identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/agusmakmun/ebayscrapper/blob/master/app_product/views.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ebayscrapper
|
agusmakmun
|
Python
|
Code
| 78
| 380
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import (get_object_or_404, redirect)
from django.views.generic import (TemplateView, DetailView)
from app_scraper.utils.scraper import scrape_product_info
from app_product.models import Product
class ProductScrape(TemplateView):
template_name = 'app_product/product_scrape.html'
def post(self, request, *args, **kwargs):
if 'url' in request.POST:
ebay_url = request.POST.get('url')
product_info = scrape_product_info(ebay_url)
product = Product(item_id=product_info.get('item_id'),
name=product_info.get('name'),
price=product_info.get('current_price'),
color=product_info.get('item_specific').get('color'),
size=product_info.get('item_specific').get('size'))
product.save()
return redirect('product_cart_detail', pk=product.pk)
return super().post(request, *args, **kwargs)
class ProductCartDetail(DetailView):
template_name = 'app_product/product_cart_detail.html'
context_object_name = 'product'
model = Product
class ProductPaymentDetail(ProductCartDetail):
template_name = 'app_product/product_payment_detail.html'
| 10,452
|
https://github.com/read0nly/hms-flutter-plugin/blob/master/flutter-hms-ml/android/src/main/java/com/huawei/hms/flutter/ml/permissions/PermissionHandler.java
|
Github Open Source
|
Open Source
|
Apache-2.0, MIT, BSD-3-Clause
| 2,021
|
hms-flutter-plugin
|
read0nly
|
Java
|
Code
| 486
| 2,087
|
/*
Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.huawei.hms.flutter.ml.permissions;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import com.huawei.hms.flutter.ml.logger.HMSLogger;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;
public class PermissionHandler implements MethodChannel.MethodCallHandler, PluginRegistry.RequestPermissionsResultListener {
private Activity activity;
private MethodChannel.Result mResult;
public PermissionHandler(Activity activity) {
this.activity = activity;
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
mResult = result;
switch (call.method) {
case "checkCameraPermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("checkCameraPermission");
result.success(checkCameraPermission());
break;
case "checkWriteExternalStoragePermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("checkWriteExternalStoragePermission");
result.success(checkWriteExternalStoragePermission());
break;
case "checkReadExternalStoragePermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("checkReadExternalStoragePermission");
result.success(checkReadExternalStoragePermission());
break;
case "checkAudioPermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("checkAudioPermission");
result.success(checkAudioPermission());
break;
case "checkAccessNetworkStatePermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("checkAccessNetworkStatePermission");
result.success(checkAccessNetworkStatePermission());
break;
case "checkAccessWifiStatePermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("checkAccessWifiStatePermission");
result.success(checkAccessWifiStatePermission());
break;
case "requestCameraPermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("requestCameraPermission");
requestCameraPermission();
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("requestCameraPermission");
break;
case "requestStoragePermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("requestStoragePermission");
requestStoragePermission();
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("requestStoragePermission");
break;
case "requestAudioPermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("requestAudioPermission");
requestAudioPermission();
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("requestAudioPermission");
break;
case "requestConnectionStatePermission":
HMSLogger.getInstance(activity.getApplicationContext()).startMethodExecutionTimer("requestConnectionStatePermission");
requestConnectionStatePermission();
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("requestConnectionStatePermission");
break;
default:
break;
}
}
// CHECKING PERMISSIONS
public boolean checkCameraPermission() {
final int cameraPer = ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("checkCameraPermission");
return cameraPer == PackageManager.PERMISSION_GRANTED;
}
private boolean checkWriteExternalStoragePermission() {
final int writeExPer = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("checkWriteExternalStoragePermission");
return writeExPer == PackageManager.PERMISSION_GRANTED;
}
private boolean checkReadExternalStoragePermission() {
final int readExPer = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("checkReadExternalStoragePermission");
return readExPer == PackageManager.PERMISSION_GRANTED;
}
private boolean checkAudioPermission() {
final int audioPer = ActivityCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO);
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("checkAudioPermission");
return audioPer == PackageManager.PERMISSION_GRANTED;
}
private boolean checkAccessNetworkStatePermission() {
final int networkPer = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_NETWORK_STATE);
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("checkAccessNetworkStatePermission");
return networkPer == PackageManager.PERMISSION_GRANTED;
}
private boolean checkAccessWifiStatePermission() {
final int wifiPer = ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_WIFI_STATE);
HMSLogger.getInstance(activity.getApplicationContext()).sendSingleEvent("checkAccessWifiStatePermission");
return wifiPer == PackageManager.PERMISSION_GRANTED;
}
// REQUESTING PERMISSIONS
public void requestCameraPermission() {
final String[] permissions = {Manifest.permission.CAMERA};
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
ActivityCompat.requestPermissions(activity, permissions, 1);
} else {
ActivityCompat.requestPermissions(activity, permissions, 2);
}
}
private void requestStoragePermission() {
final String[] permissions = {
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
ActivityCompat.requestPermissions(activity, permissions, 5);
} else {
ActivityCompat.requestPermissions(activity, permissions, 6);
}
}
private void requestAudioPermission() {
final String[] permissions = {Manifest.permission.RECORD_AUDIO};
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
ActivityCompat.requestPermissions(activity, permissions, 7);
} else {
ActivityCompat.requestPermissions(activity, permissions, 8);
}
}
private void requestConnectionStatePermission() {
final String[] permissions = {
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.ACCESS_NETWORK_STATE};
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
ActivityCompat.requestPermissions(activity, permissions, 9);
} else {
ActivityCompat.requestPermissions(activity, permissions, 10);
}
}
private boolean checkGrantStatus(final int[] grantResults) {
for (final int i : grantResults) {
return !(i == -1);
}
return true;
}
@Override
public boolean onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
final MethodChannel.Result result = mResult;
mResult = null;
if (result != null) {
if (requestCode == 1 || requestCode == 5 || requestCode == 7) {
result.success(grantResults[0] == 0 && grantResults[1] == 0);
} else {
result.success(checkGrantStatus(grantResults));
}
}
return true;
}
}
| 7,625
|
https://github.com/zendesk/curlybars/blob/master/spec/dummy/app/presenters/shared/avatar_presenter.rb
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
curlybars
|
zendesk
|
Ruby
|
Code
| 19
| 74
|
class Shared::AvatarPresenter
extend Curlybars::MethodWhitelist
attr_reader :avatar
allow_methods :url
def initialize(avatar)
@avatar = avatar
end
def url
@avatar.url
end
end
| 49,051
|
https://github.com/ryanoflaherty/arduino-rgb/blob/master/src/libraries/RgbDriver.h
|
Github Open Source
|
Open Source
|
MIT
| null |
arduino-rgb
|
ryanoflaherty
|
C
|
Code
| 30
| 94
|
#ifndef RGBDRIVER_H
#define RGBDRIVER_H
class RgbDriver
{
protected:
Led red;
Led green;
Led blue;
bool ledOn;
public:
RgbDriver(int redPin, int greenPin, int bluePin);
void setColor(Rgb color);
void turnRgbOff();
};
#endif
| 21,238
|
https://github.com/jupierce/ci-tainting-webhook/blob/master/build.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ci-tainting-webhook
|
jupierce
|
Shell
|
Code
| 11
| 59
|
#!/bin/sh
sudo docker build -t quay.io/jupierce/ci-tainting-webhook:latest .
sudo docker push quay.io/jupierce/ci-tainting-webhook:latest
| 35,564
|
https://github.com/praveenpv1/ecaps-Fe/blob/master/src/app/core/components/dashboard/dashboard.component.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
ecaps-Fe
|
praveenpv1
|
TypeScript
|
Code
| 760
| 2,721
|
import { Component, OnInit, OnDestroy } from "@angular/core";
import { DataStore } from "@app/core/store/app.store";
import { CompanyReducers } from "@app/core/store/reducers/company.reducer";
import {
GET_COMPANY_WALLET,
GET_COMPANY_MAIN_TXNS,
GET_COMPANY_TXNS,
GET_CLAIMS_TXNS
} from "@app/core/store/actions";
import * as _ from "lodash";
import { environment } from "@env/environment";
import { SalaryIn, getStatusText } from "@app/core/services/utils";
import {
catchCommonData,
successCommonData
} from "@app/core/store/commonstoredata";
import { CurrencyPipe } from "@angular/common";
import { barGraphOptions } from "@app/core/services/graphoptions";
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import * as pluginDataLabels from 'chartjs-plugin-datalabels';
import { Label } from 'ng2-charts';
export interface Tile {
color: string;
cols: number;
rows: number;
text: string;
category: string;
route: string;
icon: string;
}
interface RecentTransactions {
id: number;
date: Date;
details: string;
}
enum InfoType {
amount = 1,
info = 2
}
interface InfoCards {
title: string;
text: string;
icon: string;
bgClass?: string;
desc: string;
routerLink: any;
type: InfoType;
iconImg?: string;
}
@Component({
selector: "koppr-pot",
templateUrl: "./dashboard.component.html",
styleUrls: ["./dashboard.component.scss"]
})
export class DashboardComponent implements OnInit, OnDestroy {
companyBalance: string = "0";
balanceCards: InfoCards[] = [];
mockCards: InfoCards[] = [];
pendingClaims = 0;
approvedClaims = 0;
settledClaims = 0;
claimsData: any;
pendingClaimsData: any;
approvedClaimsData: any;
settledClaimsData: any;
infoCards: InfoCards[] = [];
recentTransaction: RecentTransactions[] = [];
companyTranscations: any;
initialState: any = "";
expenseData: any = [];
allowanceData: any;
subscribers: any = [];
public barGraphOptions = barGraphOptions;
public barChartOptions: ChartOptions = {
responsive: true,
// Use these empty structures as placeholders for dynamic theming.
scales: { xAxes: [{}], yAxes: [{}] },
plugins: {
datalabels: {
anchor: 'end',
align: 'end',
}
}
};
public barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
public barChartType: ChartType = 'bar';
public barChartLegend = true;
public barChartPlugins = [pluginDataLabels];
public barChartData: ChartDataSets[] = [
{ data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A' },
// { data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B' }
];
constructor(
private cR: CompanyReducers,
private ds: DataStore,
private currencyPipe: CurrencyPipe
) {
this.initialState = ds.dataStore$.getValue();
this.clearCompanyTxnsStore();
this.clearClaimsStore();
this.subscribers = this.ds.dataStore$.subscribe(res => {
console.log(res);
if (_.get(res.company.details, "data", null)) {
this.companyBalance = _.get(res.company.details, "data.value", 0);
}
if (_.get(res.company_transactions.details, "data", null)) {
this.companyTranscations = res.company_transactions.details.data;
}
if (_.get(res.company_txns.details, "data", null)) {
this.expenseData = _.filter(res.company_txns.details.data, function(
txns
) {
return txns.amount_type === "expense";
});
this.allowanceData = _.filter(res.company_txns.details.data);
this.clearCompanyTxnsStore();
this.getClaims();
}
if (_.get(res.claims_txns.details, "data", null)) {
this.claimsData = res.claims_txns.details.data;
this.settledClaimsData = _.filter(this.claimsData, function(claims) {
if (claims.approval_status === "approved") {
return true;
}
});
this.settledClaims = this.getSettledClaimAmount(this.settledClaimsData);
this.pendingClaimsData = _.filter(this.claimsData, function(claims) {
return claims.approval_status === "pending_approval";
});
this.pendingClaims = this.pendingClaimsData.length;
this.renderCards();
this.clearClaimsStore();
}
});
}
getSettledClaimAmount(data: any): number {
let amount = 0;
data.forEach(element => {
amount = amount + element.amount;
});
return amount;
}
public showCompanyWallet() {
this.cR.cardReducer({
type: GET_COMPANY_WALLET,
payload: {}
});
}
ngOnInit() {
this.showCompanyWallet();
this.getCompanyTransactions();
this.getCompanyTxns();
//this.getClaims();
}
ngOnDestroy() {
this.subscribers.unsubscribe();
}
getCompanyTxns() {
this.cR.cardReducer({
type: GET_COMPANY_TXNS,
payload: {}
});
}
getClaims() {
this.cR.cardReducer({
type: GET_CLAIMS_TXNS,
payload: {}
});
}
getCompanyTransactions() {
this.cR.cardReducer({
type: GET_COMPANY_MAIN_TXNS,
payload: { company: this.initialState.company_id }
});
}
getStatusText(status: string): string {
return getStatusText(status);
}
getTotalSalary(amounts: any): string {
let totalSalary = 0;
amounts.forEach(element => {
totalSalary = totalSalary + element.amount;
});
return totalSalary.toString();
}
clearCompanyTxnsStore(): void {
const state = this.ds.dataStore$.getValue();
this.ds.dataStore$.next({
...state,
...successCommonData,
company_txns: {
details: {}
}
});
}
clearClaimsStore(): void {
const state = this.ds.dataStore$.getValue();
this.ds.dataStore$.next({
...state,
...successCommonData,
claims_txns: {
details: {}
}
});
}
public chartClicked({ event, active }: { event: MouseEvent, active: {}[] }): void {
console.log(event, active);
}
public chartHovered({ event, active }: { event: MouseEvent, active: {}[] }): void {
console.log(event, active);
}
public randomize(): void {
// Only Change 3 values
const data = [
Math.round(Math.random() * 100),
59,
80,
(Math.random() * 100),
56,
(Math.random() * 100),
40];
this.barChartData[0].data = data;
}
renderCards(): void {
this.balanceCards = [];
this.infoCards = [];
this.balanceCards.push(
{
title: "Enviar Account Balance",
text: this.currencyPipe.transform(this.companyBalance, "₹"),
icon: "more",
bgClass: "enviar-account-balance",
desc: "TOP UP",
routerLink: ["/", "company", "deposit"],
type: InfoType.amount
},
{
title: "Money Transferred",
text: this.currencyPipe.transform(
this.getTotalSalary(this.expenseData),
"₹"
),
icon: "more",
bgClass: "white-bg-card",
desc: "VIEW DETAILS",
routerLink: ["/", "salary"],
type: InfoType.amount
},
{
title: "Earnings",
text: this.currencyPipe.transform(this.settledClaims, "₹"),
icon: "more",
bgClass: "white-bg-card",
desc: "VIEW DETAILS",
routerLink: ["/", "claims"],
type: InfoType.amount
},
{
title: "Ledgers",
text: this.currencyPipe.transform(
this.getTotalSalary(this.allowanceData),
"₹"
),
icon: "more",
bgClass: "white-bg-card",
desc: "VIEW DETAILS",
routerLink: ["/", "allowance"],
type: InfoType.amount
}
);
this.infoCards = [
{
title: "Auto Wallet Loading in",
text: SalaryIn(),
icon: "more",
bgClass: "white-bg-card",
desc: "VIEW DETAILS",
routerLink: ["/", "salary"],
type: InfoType.info,
iconImg: "assets/images/calendar.svg"
},
{
title: "Pending Transactions",
text: this.pendingClaims + "Txns",
icon: "more",
bgClass: "white-bg-card",
desc: "VIEW DETAILS",
routerLink: ["/", "claims"],
type: InfoType.info,
iconImg: "assets/images/re-imbursement.svg"
}
];
}
}
| 2,650
|
https://github.com/kickstarter/android-oss/blob/master/app/src/main/java/com/kickstarter/ui/views/LoginPopupMenu.kt
|
Github Open Source
|
Open Source
|
Apache-2.0, ICU, MIT, LicenseRef-scancode-facebook-software-license, EPL-1.0
| 2,023
|
android-oss
|
kickstarter
|
Kotlin
|
Code
| 95
| 416
|
package com.kickstarter.ui.views
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.view.MenuItem
import android.view.View
import android.widget.PopupMenu
import androidx.appcompat.app.AppCompatActivity
import com.kickstarter.R
import com.kickstarter.libs.utils.Secrets
import com.kickstarter.ui.activities.HelpActivity
import com.kickstarter.ui.activities.HelpActivity.Terms
class LoginPopupMenu(context: Context, anchor: View) : PopupMenu(context, anchor) {
init {
menuInflater.inflate(R.menu.login_help_menu, menu)
val activity = context as? AppCompatActivity
setOnMenuItemClickListener { item: MenuItem ->
val intent: Intent
when (item.itemId) {
R.id.terms -> {
intent = Intent(context, Terms::class.java)
activity?.startActivity(intent)
}
R.id.privacy_policy -> {
intent = Intent(context, HelpActivity.Privacy::class.java)
activity?.startActivity(intent)
}
R.id.cookie_policy -> {
intent = Intent(context, HelpActivity.CookiePolicy::class.java)
activity?.startActivity(intent)
}
R.id.help -> {
intent = Intent(Intent.ACTION_VIEW, Uri.parse(Secrets.HelpCenter.ENDPOINT))
activity?.startActivity(intent)
}
}
true
}
}
}
| 18,921
|
https://github.com/ZebraRoy/ThreeKingdom/blob/master/public/src/views/naming-scene.js
|
Github Open Source
|
Open Source
|
MIT
| null |
ThreeKingdom
|
ZebraRoy
|
JavaScript
|
Code
| 107
| 355
|
import {
connect
} from 'inferno-redux';
import createElement from 'inferno-create-element';
import {
Actions
} from '../actions';
export function NamingScene ({ name, onSubmit }) {
return createElement(
'div',
{
className: 'inferno-form'
},
createElement(
'form',
{
name: 'naming',
onSubmit
},
createElement(
'input',
{
type: 'text',
name: 'name',
className: 'helium-input',
required: 'required',
placeholder: 'Name',
defaultValue: name
}
),
createElement(
'button',
{
type: 'submit',
className: 'helium-button'
},
'Confirm'
)
)
);
}
const ConnectNamingScene = connect(function mapStateToProps (state) {
return {
name: state.name
};
}, function mapDispatchToProps (dispatch) {
return {
onSubmit: (e) => {
e.preventDefault();
dispatch({
type: Actions.ConfirmName,
name: document.forms.naming.name.value
});
return false;
}
};
})(NamingScene);
export {
ConnectNamingScene
};
| 46,587
|
https://github.com/WildGoat07/LogicTable/blob/master/LogicTable/Language.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
LogicTable
|
WildGoat07
|
C#
|
Code
| 23
| 56
|
namespace LogicTable
{
public partial class MainWindow
{
#region Public Enums
public enum Language
{
FR,
EN
}
#endregion Public Enums
}
}
| 44,513
|
https://github.com/burkeac/MPS_Tool_Kit/blob/master/docs/search/all_c.js
|
Github Open Source
|
Open Source
|
MIT
| null |
MPS_Tool_Kit
|
burkeac
|
JavaScript
|
Code
| 10
| 452
|
var searchData=
[
['scopetimer_65',['ScopeTimer',['../class_m_p_s_1_1_scope_timer.html',1,'MPS::ScopeTimer'],['../class_m_p_s_1_1_scope_timer.html#a3e464bc2d89e98d7b38e91e8e50ef4d9',1,'MPS::ScopeTimer::ScopeTimer()']]],
['selectprimary_66',['selectPrimary',['../class_m_p_s_1_1color_primaries.html#ae97ba301ab9140d0825f00cdbddd1333',1,'MPS::colorPrimaries']]],
['setlab1_67',['setLab1',['../class_m_p_s_1_1_c_i_edelta_e.html#aa68a7d419fad7662488c0b641155e4b0',1,'MPS::CIEdeltaE']]],
['setlab2_68',['setLab2',['../class_m_p_s_1_1_c_i_edelta_e.html#a2e8211fa13c9deb435c429db180d07fc',1,'MPS::CIEdeltaE']]],
['showhelp_69',['showHelp',['../class_m_p_s_1_1_program_options.html#a129757a96844f7065704575d05c8824f',1,'MPS::ProgramOptions']]],
['st2084_5f2_5fy_70',['ST2084_2_Y',['../_h_d_r___tran_func_8cpp.html#a7d3a9435c135e7041bc6ecf4e9a8c66e',1,'HDR_TranFunc.cpp']]]
];
| 472
|
https://github.com/HorvatMatej/IdentityUI/blob/master/src/IdentityUI.Admin/Areas/IdentityAdmin/Controllers/Group/GroupInviteController.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
IdentityUI
|
HorvatMatej
|
C#
|
Code
| 173
| 948
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SSRD.IdentityUI.Admin.Areas.IdentityAdmin.Interfaces.Group;
using SSRD.IdentityUI.Admin.Areas.IdentityAdmin.Models.DataTable;
using SSRD.IdentityUI.Admin.Areas.IdentityAdmin.Models.Group;
using SSRD.IdentityUI.Core.Data.Models.Constants;
using SSRD.IdentityUI.Core.Helper;
using SSRD.IdentityUI.Core.Interfaces.Services;
using SSRD.IdentityUI.Core.Models.Result;
using SSRD.IdentityUI.Core.Services.User.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace SSRD.IdentityUI.Admin.Areas.IdentityAdmin.Controllers.Group
{
[Route("[area]/Group/{groupId}/[controller]/[action]")]
[GroupPermissionAuthorize(IdentityUIPermissions.GROUP_CAN_MANAGE_INVITES)]
public class GroupInviteController : BaseController
{
private readonly IGroupInviteDataService _groupInviteDataService;
private readonly IInviteService _inviteService;
public GroupInviteController(IGroupInviteDataService groupInviteDataService, IInviteService inviteService)
{
_groupInviteDataService = groupInviteDataService;
_inviteService = inviteService;
}
[HttpGet]
[ProducesResponseType(typeof(DataTableResult<GroupInviteTableModel>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(IDictionary<string, string[]>), StatusCodes.Status400BadRequest)]
public IActionResult Get([FromRoute] string groupId, [FromQuery] DataTableRequest dataTableRequest)
{
if(!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Result<DataTableResult<GroupInviteTableModel>> result = _groupInviteDataService.Get(groupId, dataTableRequest);
if(result.Failure)
{
ModelState.AddErrors(result);
return BadRequest(ModelState);
}
return Ok(result.Value);
}
[GroupPermissionAuthorize(IdentityUIPermissions.GROUP_CAN_INVITE_USERS)]
[ProducesResponseType(typeof(EmptyResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(IDictionary<string, string[]>), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Invite([FromRoute] string groupId, [FromBody] InviteToGroupRequest inviteToGroupRequest)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
Result result = await _inviteService.InviteToGroup(groupId, inviteToGroupRequest);
if (result.Failure)
{
ModelState.AddErrors(result);
return BadRequest(ModelState);
}
return Ok(new EmptyResult());
}
[HttpPost("{inviteId}")]
[ProducesResponseType(typeof(EmptyResult), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(IDictionary<string, string[]>), StatusCodes.Status400BadRequest)]
public IActionResult Remove([FromRoute] string groupId, [FromRoute] string inviteId)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
Result result = _inviteService.Remove(inviteId);
if (result.Failure)
{
ModelState.AddErrors(result);
return BadRequest(ModelState);
}
return Ok(new EmptyResult());
}
}
}
| 38,945
|
https://github.com/isomorfeus/arangodb-driver/blob/master/lib/arango/requests/replication/get_tail.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
arangodb-driver
|
isomorfeus
|
Ruby
|
Code
| 70
| 188
|
module Arango
module Requests
module Replication
class GetTail < Arango::Request
request_method :get
uri_template '{/dbcontext}/_api/wal/tail'
param :barrier_id
param :chunk_size
param :client_info
param :from
param :global
param :last_scanned
param :server_id
param :syncer_id
param :to
code 200, :success
code 204, :success
code 400, "From or to value are invalid!"
code 405, "Invalid HTTP request method!"
code 500, "A error occurred!"
code 501, "Cannot be called on a cluster coordinater!"
end
end
end
end
| 8,272
|
https://github.com/gotd/td/blob/master/_tools/go.mod
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-proprietary-license
| 2,023
|
td
|
gotd
|
Go Module
|
Code
| 19
| 129
|
module github.com/gotd/td/_tools
go 1.16
require (
github.com/dvyukov/go-fuzz v0.0.0-20210103155950-6a8e9d1f2415
github.com/elazarl/go-bindata-assetfs v1.0.1 // indirect
github.com/stephens2424/writerset v1.0.2 // indirect
golang.org/x/tools v0.12.0
)
| 13,228
|
https://github.com/mikeleber/j2html/blob/master/library/src/main/java/j2html/tags/specialized/MapTag.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
j2html
|
mikeleber
|
Java
|
Code
| 21
| 79
|
package j2html.tags.specialized;
import j2html.tags.ContainerTag;
import j2html.tags.attributes.IName;
public final class MapTag extends ContainerTag<MapTag>
implements IName<MapTag> {
public MapTag() {
super("map");
}
}
| 23,257
|
https://github.com/curtys/webprotege-attestation/blob/master/webprotege-shared/src/main/java/edu/stanford/bmir/protege/web/shared/issues/mention/EntityMention.java
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,023
|
webprotege-attestation
|
curtys
|
Java
|
Code
| 72
| 291
|
package edu.stanford.bmir.protege.web.shared.issues.mention;
import edu.stanford.bmir.protege.web.shared.annotations.GwtSerializationConstructor;
import edu.stanford.bmir.protege.web.shared.issues.Mention;
import org.semanticweb.owlapi.model.OWLEntity;
import javax.annotation.Nonnull;
import static com.google.common.base.MoreObjects.toStringHelper;
/**
* Matthew Horridge
* Stanford Center for Biomedical Informatics Research
* 27 Sep 16
*/
public class EntityMention extends Mention {
@Nonnull
private OWLEntity entity;
public EntityMention(@Nonnull OWLEntity entity) {
this.entity = entity;
}
@GwtSerializationConstructor
private EntityMention() {
}
@Nonnull
public OWLEntity getEntity() {
return entity;
}
@Override
public String toString() {
return toStringHelper("EntityMention")
.addValue(entity)
.toString();
}
}
| 28,055
|
https://github.com/BasiqueEvangelist/allium/blob/master/src/main/java/me/hugeblank/allium/lua/api/JavaLib.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
allium
|
BasiqueEvangelist
|
Java
|
Code
| 693
| 2,378
|
package me.hugeblank.allium.lua.api;
import me.basiqueevangelist.enhancedreflection.api.EClass;
import me.basiqueevangelist.enhancedreflection.api.EMethod;
import me.basiqueevangelist.enhancedreflection.api.typeuse.EClassUse;
import me.hugeblank.allium.Allium;
import me.hugeblank.allium.lua.type.*;
import me.hugeblank.allium.lua.type.annotation.*;
import org.squiddev.cobalt.*;
import java.lang.reflect.InaccessibleObjectException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@LuaWrapped(name = "java")
public class JavaLib implements WrappedLuaLibrary {
private static final String[] AUTO_COMPLETE = new String[]{
"",
"java.util.",
"java.lang.",
"net.minecraft.",
"net.minecraft.item.",
"net.minecraft.block.",
"net.minecraft.entity.",
"net.minecraft.entity.player.",
"net.minecraft.inventory.",
"net.minecraft.nbt.",
"net.minecraft.potion.",
"net.minecraft.sound.",
"net.minecraft.text.",
"net.minecraft.tag.",
"net.minecraft.village.",
"net.minecraft.world.",
"net.minecraft.util.",
"net.minecraft.util.registry.",
"net.minecraft.server.",
"net.minecraft.server.command.",
"net.minecraft.server.world.",
"net.minecraft.server.network.",
"com.mojang."
};
private static final Map<String, String> CACHED_AUTO_COMPLETE = new HashMap<>();
@LuaWrapped(name = "import")
public static LuaValue importClass(EClass<?> clazz) {
return StaticBinder.bindClass(clazz);
}
private static Varargs invokeStatic(EClass<?> clazz, String name, EMethod[] methods, LuaState state, Varargs args) throws LuaError {
List<String> paramList = new ArrayList<>(); // String for displaying errors more smartly
StringBuilder error = new StringBuilder("Could not find parameter match for called function \"" +
name + "\" for \"" + clazz.name() + "\"" +
"\nThe following are correct argument types:\n"
);
for (var method : methods) {
var parameters = method.parameters();
try {
var jargs = ArgumentUtils.toJavaArguments(state, args, 1, parameters);
if (jargs.length == parameters.size()) { // Found a match!
try { // Get the return type, invoke method, cast returned value, cry.
EClassUse<?> ret = method.returnTypeUse().upperBound();
// method.setAccessible(true); // throws InaccessibleObjectException | SecurityException
Object out = method.invoke(null, jargs);
return TypeCoercions.toLuaValue(out, ret);
} catch (InaccessibleObjectException | SecurityException | IllegalAccessException e) {
throw new LuaError(e);
} catch (InvocationTargetException e) {
if (e.getTargetException() instanceof LuaError err)
throw err;
throw new LuaError(e);
}
}
} catch (InvalidArgumentException e) {
paramList.add(ArgumentUtils.paramsToPrettyString(parameters));
}
}
for (String headers : paramList) {
error.append(headers).append("\n");
}
throw new LuaError(error.toString());
}
// TODO: merge this with the Lua string library
@LuaWrapped
public static String[] split(String strToSplit, String delimiter) {
return strToSplit.split(delimiter);
}
@LuaWrapped
public static String toYarn(String string) {
return Allium.MAPPINGS.getYarn(string);
}
@LuaWrapped
public static @CoerceToNative List<String> fromYarn(String string) {
return Allium.MAPPINGS.getIntermediary(string);
}
private static Varargs createInstance(LuaState state, EClass<?> clazz, Varargs args) throws LuaError {
List<String> paramList = new ArrayList<>();
for (var constructor : clazz.constructors()) {
if (AnnotationUtils.isHiddenFromLua(constructor)) continue;
var parameters = constructor.parameters();
try {
var jargs = ArgumentUtils.toJavaArguments(state, args, 1, parameters);
try { // Get the return type, invoke method, cast returned value, cry.
EClassUse<?> ret = (EClassUse<?>) constructor.receiverTypeUse();
if (ret == null) ret = clazz.asEmptyUse();
Object out = constructor.invoke(jargs);
return TypeCoercions.toLuaValue(out, ret);
} catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
throw new LuaError(e);
}
} catch (InvalidArgumentException e) {
paramList.add(ArgumentUtils.paramsToPrettyString(parameters));
}
}
StringBuilder error = new StringBuilder("Could not find parameter match for called constructor " +
clazz.name() +
"\nThe following are correct argument types:\n"
);
for (String headers : paramList) {
error.append(headers).append("\n");
}
throw new LuaError(error.toString());
}
@LuaWrapped
public static LuaValue cast(@LuaStateArg LuaState state, EClass<?> klass, LuaUserdata object) throws LuaError {
try {
return TypeCoercions.toLuaValue(TypeCoercions.toJava(state, object, klass), klass);
} catch (InvalidArgumentException e) {
e.printStackTrace();
return Constants.NIL;
}
}
@LuaWrapped
public static boolean exists(String string, @OptionalArg Class<?>[] value) {
try {
var parts = string.split("#");
var clazz = getRawClass(parts[0]);
if (parts.length != 2) {
return true;
}
if (value != null) {
return clazz.method(parts[1], value) != null;
} else {
for (var method : clazz.methods()) {
if (method.name().equals(parts[1])) {
return true;
}
}
return clazz.field(parts[1]) != null;
}
} catch (Throwable t) {
return false;
}
}
@LuaWrapped
public static ClassBuilder extendClass(@LuaStateArg LuaState state, EClass<?> superclass, List<EClass<?>> interfaces) {
return new ClassBuilder(superclass, interfaces, state);
}
@LuaWrapped
public static EClass<?> getRawClass(String className) throws LuaError {
var cachedClassName = CACHED_AUTO_COMPLETE.get(className);
if (cachedClassName != null) {
try {
return EClass.fromJava(Class.forName(cachedClassName));
} catch (ClassNotFoundException e1) {
}
}
for (var auto : AUTO_COMPLETE) {
try {
cachedClassName = Allium.MAPPINGS.getIntermediary(auto + className).get(0);
var clazz = EClass.fromJava(Class.forName(cachedClassName));
CACHED_AUTO_COMPLETE.put(className, cachedClassName);
return clazz;
} catch (ClassNotFoundException e1) {
}
try {
cachedClassName = auto + className;
var clazz = EClass.fromJava(Class.forName(cachedClassName));
CACHED_AUTO_COMPLETE.put(className, cachedClassName);
return clazz;
} catch (ClassNotFoundException e) {
}
}
throw new LuaError("Couldn't find class \"" + className + "\"");
}
@SuppressWarnings("unchecked")
public static EClass<?> asClass(LuaValue value) throws LuaError {
if (value.isString()) {
return getRawClass(value.checkString());
} else if (value.isUserdata(EClass.class)) {
return value.checkUserdata(EClass.class);
} else if (value.isUserdata(Class.class)) {
return EClass.fromJava(value.checkUserdata(Class.class));
} else if (value.isUserdata()) {
return EClass.fromJava(value.checkUserdata().getClass());
} else if (value.isTable() && value.checkTable().rawget("allium_java_class") != Constants.NIL) {
return value.checkTable().rawget("allium_java_class").checkUserdata(EClass.class);
} else if (value.isNil()) {
return null;
}
throw new LuaError(new ClassNotFoundException());
}
}
| 39,517
|
https://github.com/MaximTiberiu/OOProject/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
OOProject
|
MaximTiberiu
|
Ignore List
|
Code
| 12
| 75
|
CMakeCache.txt
CMakeFiles
CMakeScripts
Testing
Makefile
cmake_install.cmake
install_manifest.txt
compile_commands.json
CTestTestfile.cmake
_deps
/**/cmake-build-debug/
/**/cmake-build-release
| 1,475
|
https://github.com/blackcoffeexbt/lnbits-legend/blob/master/lnbits/core/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
lnbits-legend
|
blackcoffeexbt
|
Python
|
Code
| 33
| 83
|
from fastapi.routing import APIRouter
from lnbits.db import Database
db = Database("database")
core_app: APIRouter = APIRouter()
from .views.api import * # noqa
from .views.generic import * # noqa
from .views.public_api import * # noqa
| 21,968
|
https://github.com/Songllgons/uni-app/blob/master/src/platforms/app-plus/view/elements/index.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
uni-app
|
Songllgons
|
JavaScript
|
Code
| 9
| 18
|
import View from './view'
export default {
View
}
| 46,777
|
https://github.com/markodjunev/E-Diary/blob/master/EDiary/Data/EDiary.Data.Models/Mark.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
E-Diary
|
markodjunev
|
C#
|
Code
| 57
| 137
|
namespace EDiary.Data.Models
{
using EDiary.Data.Common.Models;
public class Mark : BaseDeletableModel<int>
{
public double Score { get; set; }
public string NameOfExam { get; set; }
public string StudentId { get; set; }
public virtual ApplicationUser Student { get; set; }
public int SubjectClassTeacherId { get; set; }
public virtual SubjectClassTeacher SubjectClassTeacher { get; set; }
}
}
| 22,208
|
https://github.com/Simulalex/have-you-considered/blob/master/db/database.go
|
Github Open Source
|
Open Source
|
MIT
| null |
have-you-considered
|
Simulalex
|
Go
|
Code
| 140
| 430
|
package db
import (
"fmt"
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/Simulalex/haveyouconsidered/models"
)
const dbConnectionString = "%v:%v@%v"
type Database interface {
GetSummary(name string) (*models.Technology, error)
}
type database struct{
mysql *sql.DB
}
type Config struct {
Username string
Password string
Database string
}
func NewDatabase(cfg *Config) (Database, error) {
// "user:password@/dbname"
db, err := sql.Open("mysql", fmt.Sprintf(dbConnectionString, cfg.Username, cfg.Password, cfg.Database))
if err != nil {
return nil, err
}
outgoing := database{db}
return outgoing, nil
}
func (db database) GetSummary(name string) (*models.Technology, error) {
var technologyId, authorId int
var summary, username, title string
err := db.mysql.QueryRow("SELECT technologies.id, title, summary, authors.id, authors.username FROM technologies JOIN authors ON authors.id = technologies.author_id WHERE technologies.name = ?", name).Scan(&technologyId, &title, &summary, &authorId, &username)
if err != nil{ //sql.ErrNoRows
return nil, err
}
author := models.Author{authorId, username}
technology := models.Technology{
technologyId,
name,
title,
summary,
&author,
}
return &technology, nil
}
| 44,281
|
https://github.com/sjdlloyd/tsai/blob/master/tsai/metrics.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
tsai
|
sjdlloyd
|
Python
|
Code
| 92
| 339
|
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/007_metrics.ipynb (unless otherwise specified).
__all__ = ['MatthewsCorrCoefBinary', 'get_task_metrics']
# Cell
from .imports import *
from fastai.metrics import *
# Cell
mk_class('ActivationType', **{o:o.lower() for o in ['No', 'Sigmoid', 'Softmax', 'BinarySoftmax']},
doc="All possible activation classes for `AccumMetric")
# Cell
def MatthewsCorrCoefBinary(thresh=.5, sample_weight=None):
"Matthews correlation coefficient for single-label classification problems"
return skm_to_fastai(skm.matthews_corrcoef, activation=ActivationType.BinarySoftmax, thresh=thresh, sample_weight=sample_weight)
# Cell
def get_task_metrics(dls, binary_metrics=None, multi_class_metrics=None, regression_metrics=None, verbose=True):
if dls.c == 2:
pv('binary-classification task', verbose)
return binary_metrics
elif dls.c > 2:
pv('multi-class task', verbose)
return multi_class_metrics
else:
pv('regression task', verbose)
return regression_metrics
| 18,356
|
https://github.com/alifffahmi/checks-api-plugin/blob/master/src/test/java/io/jenkins/plugins/checks/status/BuildStatusChecksPublisherITest.java
|
Github Open Source
|
Open Source
|
MIT
| null |
checks-api-plugin
|
alifffahmi
|
Java
|
Code
| 361
| 1,178
|
package io.jenkins.plugins.checks.status;
import hudson.model.Job;
import hudson.model.Run;
import io.jenkins.plugins.checks.util.LoggingChecksPublisher;
import io.jenkins.plugins.util.IntegrationTestWithJenkinsPerTest;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.TestExtension;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests that the {@link BuildStatusChecksPublisher} listens to the status of a {@link Run} and publishes status
* accordingly.
*/
public class BuildStatusChecksPublisherITest extends IntegrationTestWithJenkinsPerTest {
private static final String STATUS_TEMPLATE = "Published Checks (name: %s, status: %s, conclusion %s)%n";
/**
* Provide a {@link io.jenkins.plugins.checks.util.LoggingChecksPublisher} to log details.
*/
@TestExtension
public static final LoggingChecksPublisher.Factory PUBLISHER_FACTORY =
new LoggingChecksPublisher.Factory(details -> String.format(STATUS_TEMPLATE,
details.getName().orElseThrow(() -> new IllegalStateException("Empty check name")),
details.getStatus(), details.getConclusion()));
/**
* Provide inject an implementation of {@link AbstractStatusChecksProperties} to control the checks.
*/
@TestExtension
public static final ChecksProperties PROPERTIES = new ChecksProperties();
/**
* Tests when the implementation of {@link AbstractStatusChecksProperties} is not applicable,
* a status checks should not be published.
*
* @throws IOException if failed getting log from {@link Run}
*/
@Test
public void shouldNotPublishStatusWhenNotApplicable() throws IOException {
PROPERTIES.setApplicable(false);
assertThat(JenkinsRule.getLog(buildSuccessfully(createFreeStyleProject())))
.doesNotContain(String.format(STATUS_TEMPLATE, "Test Status", "IN_PROGRESS", "NONE"))
.doesNotContain(String.format(STATUS_TEMPLATE, "Test Status", "COMPLETED", "SUCCESS"));
}
/**
* Tests when status checks is skipped, a status checks should not be published.
*
* @throws IOException if failed getting log from {@link Run}
*/
@Test
public void shouldNotPublishStatusWhenSkipped() throws IOException {
PROPERTIES.setApplicable(true);
PROPERTIES.setSkipped(true);
PROPERTIES.setName("Test Status");
assertThat(JenkinsRule.getLog(buildSuccessfully(createFreeStyleProject())))
.doesNotContain(String.format(STATUS_TEMPLATE, "Test Status", "IN_PROGRESS", "NONE"))
.doesNotContain(String.format(STATUS_TEMPLATE, "Test Status", "COMPLETED", "SUCCESS"));
}
/**
* Tests when an implementation of {@link AbstractStatusChecksProperties} is applicable and not skipped,
* a status checks using the specified name should be published.
*
* @throws IOException if failed getting log from {@link Run}
*/
@Test
public void shouldPublishStatusWithProperties() throws IOException {
PROPERTIES.setApplicable(true);
PROPERTIES.setSkipped(false);
PROPERTIES.setName("Test Status");
Run<?, ?> run = buildSuccessfully(createFreeStyleProject());
assertThat(JenkinsRule.getLog(run))
.contains(String.format(STATUS_TEMPLATE, "Test Status", "IN_PROGRESS", "NONE"))
.contains(String.format(STATUS_TEMPLATE, "Test Status", "COMPLETED", "SUCCESS"));
}
static class ChecksProperties extends AbstractStatusChecksProperties {
private boolean applicable;
private boolean skipped;
private String name;
public void setApplicable(final boolean applicable) {
this.applicable = applicable;
}
public void setSkipped(final boolean skipped) {
this.skipped = skipped;
}
public void setName(final String name) {
this.name = name;
}
@Override
public boolean isApplicable(final Job<?, ?> job) {
return applicable;
}
@Override
public String getName(final Job<?, ?> job) {
return name;
}
@Override
public boolean isSkipped(final Job<?, ?> job) {
return skipped;
}
}
}
| 19,268
|
https://github.com/justinribeiro/lighthouse-action/blob/master/node_modules/axe-core/lib/checks/aria/aria-hidden-body-evaluate.js
|
Github Open Source
|
Open Source
|
MPL-2.0, Apache-2.0
| 2,022
|
lighthouse-action
|
justinribeiro
|
JavaScript
|
Code
| 43
| 99
|
/**
* Check that the element does not have the `aria-hidden` attribute.
*
* @memberof checks
* @return {Boolean} True if the `aria-hidden` attribute is not present. False otherwise.
*/
function ariaHiddenBodyEvaluate(node, options, virtualNode) {
return virtualNode.attr('aria-hidden') !== 'true';
}
export default ariaHiddenBodyEvaluate;
| 19,233
|
https://github.com/AlexRogalskiy/DevArtifacts/blob/master/master/javascript-tutorial-ru/javascript-tutorial-ru/1-js/6-objects-more/8-decorators/3-caching-decorator/_js.view/solution.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
DevArtifacts
|
AlexRogalskiy
|
JavaScript
|
Code
| 24
| 65
|
function makeCaching(f) {
var cache = {};
return function(x) {
if (!(x in cache)) {
cache[x] = f.call(this, x);
}
return cache[x];
};
}
| 6,788
|
https://github.com/daydream05/another-dev-swag/blob/master/web/src/components/convert-kit-signup.js
|
Github Open Source
|
Open Source
|
0BSD
| 2,021
|
another-dev-swag
|
daydream05
|
JavaScript
|
Code
| 103
| 332
|
import React from "react"
/** @jsx jsx */
import { jsx, Container } from "theme-ui"
import ConvertKitForm from 'convertkit-react'
import { SectionHeading } from "./section-heading"
import { mediaQueries } from "../gatsby-plugin-theme-ui/media-queries"
import { breakpoints } from "../gatsby-plugin-theme-ui/breakpoints"
const inputStyle = {
height: `56px`,
borderColor: `buttonBorder`,
borderRadius: `4px`,
borderStyle: `solid`,
borderWidth: `1px`,
width: `100%`,
fontSize: 1,
px: 3,
my: 2,
}
export const ConvertKitSignup = () => {
return (
<ConvertKitForm
formId={2071704}
sx={{
display: `flex`,
flexDirection: `column`,
justifyContent: `center`,
input: {
...inputStyle,
},
button: {
...inputStyle,
cursor: `pointer`,
bg: `primary`,
border: `none`,
},
[mediaQueries.md]: {
maxWidth: breakpoints.md,
mx: `auto`,
},
}}
/>
)
}
| 19,380
|
https://github.com/djh-A/java/blob/master/design/src/local/design/singleton/Singletondemo3.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
java
|
djh-A
|
Java
|
Code
| 45
| 221
|
package local.design.singleton;
public class Singletondemo3 {
/*
定义私有无参构造
*/
private Singletondemo3() {
}
/*
私有静态属性
*/
private static Singletondemo3 instance;
public static Singletondemo3 getInstance() {
if (instance == null) {
/**
* todo:多线程资源抢占时,会导致null判断失效,第一个线程进入null值区间,但还未来得及实例化对象,另一个线程也进入null值区间
* 导致null判断无效
*/
instance = new Singletondemo3();
}
return instance;
}
}
| 32,027
|
https://github.com/marlonnardi/alcinoe/blob/master/references/UIB/misc/ShellExtention/Shutdown.dfm
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, LicenseRef-scancode-proprietary-license, MPL-1.0, LicenseRef-scancode-unknown, MPL-1.1, Apache-2.0, LicenseRef-scancode-free-unknown
| 2,020
|
alcinoe
|
marlonnardi
|
Pascal
|
Code
| 235
| 552
|
object ShutDownForm: TShutDownForm
Left = 379
Top = 327
Width = 325
Height = 244
Caption = 'Shutdown database'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
Position = poDefaultPosOnly
OnClose = FormClose
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object Label1: TLabel
Left = 48
Top = 128
Width = 48
Height = 13
Caption = 'Wait (sec)'
end
object edWait: TEdit
Left = 120
Top = 128
Width = 121
Height = 21
TabOrder = 0
Text = '0'
end
object GroupBox1: TGroupBox
Left = 48
Top = 16
Width = 225
Height = 105
Caption = 'Options '
TabOrder = 1
object rbForced: TRadioButton
Left = 16
Top = 24
Width = 113
Height = 17
Caption = 'Forced'
Checked = True
TabOrder = 0
TabStop = True
end
object rbDenyTransaction: TRadioButton
Left = 16
Top = 48
Width = 113
Height = 17
Caption = 'Deny Transaction'
TabOrder = 1
end
object rbDenyAttachment: TRadioButton
Left = 16
Top = 72
Width = 113
Height = 17
Caption = 'Deny Attachment'
TabOrder = 2
end
end
object btShutdown: TButton
Left = 120
Top = 176
Width = 75
Height = 25
Caption = 'Shutdown'
TabOrder = 2
OnClick = btShutdownClick
end
object Config: TUIBConfig
LibraryName = 'gds32.dll'
Left = 8
Top = 8
end
end
| 38,802
|
https://github.com/juszhc/CodeArts/blob/master/src/CodeArts.Db.Lts/DatabaseFactory.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
CodeArts
|
juszhc
|
C#
|
Code
| 2,067
| 6,680
|
using CodeArts.Db.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace CodeArts.Db.Lts
{
/// <summary>
/// 数据库工厂。
/// </summary>
public class DatabaseFactory
{
private static readonly Type DbConnectionType = typeof(System.Data.Common.DbConnection);
/// <summary>
/// 创建库。
/// </summary>
/// <param name="connectionConfig"></param>
/// <returns></returns>
public static IDatabase Create(IReadOnlyConnectionConfig connectionConfig)
{
if (connectionConfig is null)
{
throw new ArgumentNullException(nameof(connectionConfig));
}
var adapter = DbConnectionManager.Get(connectionConfig.ProviderName);
if (DbConnectionType.IsAssignableFrom(adapter.DbConnectionType))
{
return new DbDatabase(connectionConfig, adapter);
}
return new Database(connectionConfig, adapter);
}
private class Transaction : IDbTransaction
{
private readonly Database database;
public Transaction(Database database, IDbTransaction transaction)
{
this.database = database;
DbTransaction = transaction;
}
public IDbConnection Connection => database;
public IsolationLevel IsolationLevel => DbTransaction.IsolationLevel;
public IDbTransaction DbTransaction { get; }
public void Commit() => DbTransaction.Commit();
public void Rollback() => DbTransaction.Rollback();
private bool disposedValue = false;
public void Dispose()
{
if (!disposedValue)
{
database.CheckTransaction(this);
disposedValue = true;
}
DbTransaction.Dispose();
}
}
private class Database : IDatabase
{
private IDbConnection connection;
private readonly IDatabaseFor databaseFor;
private readonly IDbConnectionLtsAdapter adapter;
private readonly IReadOnlyConnectionConfig connectionConfig;
private readonly Stack<Transaction> transactions = new Stack<Transaction>();
public Database(IReadOnlyConnectionConfig connectionConfig, IDbConnectionLtsAdapter adapter)
{
this.connectionConfig = connectionConfig;
this.adapter = adapter;
this.databaseFor = DbConnectionManager.GetOrCreate(adapter);
}
public string Name => connectionConfig.Name;
public string ProviderName => adapter.ProviderName;
public ISQLCorrectSettings Settings => adapter.Settings;
public string Format(SQL sql) => sql?.ToString(adapter.Settings);
public string ConnectionString { get => Connection.ConnectionString; set => Connection.ConnectionString = value; }
public int ConnectionTimeout => Connection.ConnectionTimeout;
string IDbConnection.Database => Connection.Database;
public ConnectionState State => Connection.State;
#if NETSTANDARD2_1_OR_GREATER
private IDbConnection Connection => connection ??= TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true);
#else
private IDbConnection Connection => connection ?? (connection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true));
#endif
public void CheckTransaction(Transaction transaction)
{
if (transactions.Count == 0 || !ReferenceEquals(transactions.Pop(), transaction))
{
throw new DException("事务未有序释放!");
}
}
public IDbTransaction BeginTransaction()
{
var transaction = new Transaction(this, Connection.BeginTransaction());
transactions.Push(transaction);
return transaction;
}
public IDbTransaction BeginTransaction(IsolationLevel il)
{
var transaction = new Transaction(this, Connection.BeginTransaction(il));
transactions.Push(transaction);
return transaction;
}
public void Close() => connection?.Close();
public void ChangeDatabase(string databaseName) => Connection.ChangeDatabase(databaseName);
public IDbCommand CreateCommand()
{
var command = Connection.CreateCommand();
if (transactions.Count > 0)
{
var transaction = transactions.Pop();
command.Transaction = transaction.DbTransaction;
}
return command;
}
public void Open() => Connection.Open();
public void Dispose() => connection?.Dispose();
public T Read<T>(Expression expression)
{
return Read(databaseFor.Read<T>(expression));
}
public IEnumerable<T> Query<T>(Expression expression)
{
return Query<T>(databaseFor.Read<T>(expression));
}
public int Execute(Expression expression)
{
return Execute(databaseFor.Execute(expression));
}
#if NET45_OR_GREATER || NETSTANDARD2_0_OR_GREATER
public Task<T> ReadAsync<T>(Expression expression, CancellationToken cancellationToken = default)
{
return ReadAsync(databaseFor.Read<T>(expression), cancellationToken);
}
public IAsyncEnumerable<T> QueryAsync<T>(Expression expression)
{
return QueryAsync<T>(databaseFor.Read<T>(expression));
}
public Task<int> ExecuteAsync(Expression expression, CancellationToken cancellationToken = default)
{
return ExecuteAsync(databaseFor.Execute(expression), cancellationToken);
}
#endif
public T Read<T>(CommandSql<T> commandSql)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.Read<T>(dbConnection, commandSql);
}
}
if (transactions.Count == 0)
{
return databaseFor.Read<T>(connection, commandSql);
}
return databaseFor.Read<T>(this, commandSql);
}
public T Single<T>(string sql, object param = null, string missingMsg = null, int? commandTimeout = null)
{
return Read(new CommandSql<T>(sql, param, RowStyle.Single, missingMsg, commandTimeout));
}
public T SingleOrDefault<T>(string sql, object param = null, int? commandTimeout = null, T defaultValue = default)
{
return Read(new CommandSql<T>(sql, param, RowStyle.SingleOrDefault, defaultValue, commandTimeout));
}
public T First<T>(string sql, object param = null, string missingMsg = null, int? commandTimeout = null)
{
return Read(new CommandSql<T>(sql, param, RowStyle.First, missingMsg, commandTimeout));
}
public T FirstOrDefault<T>(string sql, object param = null, int? commandTimeout = null, T defaultValue = default)
{
return Read(new CommandSql<T>(sql, param, RowStyle.FirstOrDefault, defaultValue, commandTimeout));
}
public IEnumerable<T> Query<T>(CommandSql commandSql)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.Query<T>(dbConnection, commandSql);
}
}
if (transactions.Count == 0)
{
return databaseFor.Query<T>(connection, commandSql);
}
return databaseFor.Query<T>(this, commandSql);
}
public IEnumerable<T> Query<T>(string sql, object param = null, int? commandTimeout = null)
{
return Query<T>(new CommandSql(sql, param, commandTimeout));
}
public int Execute(CommandSql commandSql)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.Execute(dbConnection, commandSql);
}
}
if (transactions.Count == 0)
{
return databaseFor.Execute(connection, commandSql);
}
return databaseFor.Execute(this, commandSql);
}
public int Execute(string sql, object param = null, int? commandTimeout = null)
{
return Execute(new CommandSql(sql, param, commandTimeout));
}
#if NET45_OR_GREATER || NETSTANDARD2_0_OR_GREATER
public Task<T> ReadAsync<T>(CommandSql<T> commandSql, CancellationToken cancellationToken = default)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.ReadAsync(dbConnection, commandSql, cancellationToken);
}
}
if (transactions.Count == 0)
{
return databaseFor.ReadAsync(connection, commandSql, cancellationToken);
}
return databaseFor.ReadAsync(this, commandSql, cancellationToken);
}
public Task<T> SingleAsync<T>(string sql, object param = null, string missingMsg = null, int? commandTimeout = null, CancellationToken cancellationToken = default)
{
return ReadAsync(new CommandSql<T>(sql, param, RowStyle.Single, missingMsg, commandTimeout), cancellationToken);
}
public Task<T> SingleOrDefaultAsync<T>(string sql, object param = null, int? commandTimeout = null, T defaultValue = default, CancellationToken cancellationToken = default)
{
return ReadAsync(new CommandSql<T>(sql, param, RowStyle.SingleOrDefault, defaultValue, commandTimeout), cancellationToken);
}
public Task<T> FirstAsync<T>(string sql, object param = null, string missingMsg = null, int? commandTimeout = null, CancellationToken cancellationToken = default)
{
return ReadAsync(new CommandSql<T>(sql, param, RowStyle.First, missingMsg, commandTimeout), cancellationToken);
}
public Task<T> FirstOrDefaultAsync<T>(string sql, object param = null, int? commandTimeout = null, T defaultValue = default, CancellationToken cancellationToken = default)
{
return ReadAsync(new CommandSql<T>(sql, param, RowStyle.FirstOrDefault, defaultValue, commandTimeout), cancellationToken);
}
public IAsyncEnumerable<T> QueryAsync<T>(CommandSql commandSql)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.QueryAsync<T>(dbConnection, commandSql);
}
}
if (transactions.Count == 0)
{
return databaseFor.QueryAsync<T>(connection, commandSql);
}
return databaseFor.QueryAsync<T>(this, commandSql);
}
public IAsyncEnumerable<T> QueryAsync<T>(string sql, object param = null, int? commandTimeout = null)
{
return QueryAsync<T>(new CommandSql(sql, param, commandTimeout));
}
public Task<int> ExecuteAsync(CommandSql commandSql, CancellationToken cancellationToken = default)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.ExecuteAsync(dbConnection, commandSql, cancellationToken);
}
}
if (transactions.Count == 0)
{
return databaseFor.ExecuteAsync(connection, commandSql, cancellationToken);
}
return databaseFor.ExecuteAsync(this, commandSql, cancellationToken);
}
public Task<int> ExecuteAsync(string sql, object param = null, int? commandTimeout = null, CancellationToken cancellationToken = default)
{
return ExecuteAsync(new CommandSql(sql, param, commandTimeout), cancellationToken);
}
#endif
}
private class DbTransaction : System.Data.Common.DbTransaction
{
private readonly DbDatabase database;
public DbTransaction(DbDatabase database, System.Data.Common.DbTransaction transaction)
{
this.database = database;
Transaction = transaction;
}
public System.Data.Common.DbTransaction Transaction { get; }
public override IsolationLevel IsolationLevel => Transaction.IsolationLevel;
protected override System.Data.Common.DbConnection DbConnection => database;
public override void Commit() => Transaction.Commit();
public override void Rollback() => Transaction.Rollback();
private bool disposedValue = false;
protected override void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
database.CheckTransaction(this);
}
disposedValue = true;
}
Transaction.Dispose();
}
#if NETSTANDARD2_1_OR_GREATER
public override Task CommitAsync(CancellationToken cancellationToken = default) => Transaction.CommitAsync(cancellationToken);
public override Task RollbackAsync(CancellationToken cancellationToken = default) => Transaction.RollbackAsync(cancellationToken);
public override ValueTask DisposeAsync()
{
if (!disposedValue)
{
database.CheckTransaction(this);
disposedValue = true;
}
return Transaction.DisposeAsync();
}
#endif
}
private class DbDatabase : System.Data.Common.DbConnection, IDatabase
{
private System.Data.Common.DbConnection connection;
private readonly IDatabaseFor databaseFor;
private readonly IDbConnectionLtsAdapter adapter;
private readonly IReadOnlyConnectionConfig connectionConfig;
private readonly Stack<DbTransaction> transactions = new Stack<DbTransaction>();
public DbDatabase(IReadOnlyConnectionConfig connectionConfig, IDbConnectionLtsAdapter adapter)
{
this.connectionConfig = connectionConfig;
this.adapter = adapter;
this.databaseFor = DbConnectionManager.GetOrCreate(adapter);
}
public string Name => connectionConfig.Name;
public string ProviderName => adapter.ProviderName;
public ISQLCorrectSettings Settings => adapter.Settings;
public string Format(SQL sql) => sql?.ToString(adapter.Settings);
public override string ConnectionString { get => Connection.ConnectionString; set => Connection.ConnectionString = value; }
public override string Database => Connection.Database;
public override string DataSource => Connection.DataSource;
public override string ServerVersion => Connection.ServerVersion;
public override ConnectionState State => Connection.State;
public override ISite Site { get => Connection.Site; set => Connection.Site = value; }
#if NETSTANDARD2_1_OR_GREATER
private System.Data.Common.DbConnection Connection => connection ??= (System.Data.Common.DbConnection)(TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true));
#else
private System.Data.Common.DbConnection Connection => connection ?? (connection = (System.Data.Common.DbConnection)(TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true)));
#endif
public override void ChangeDatabase(string databaseName) => Connection.ChangeDatabase(databaseName);
public override void Close() => connection.Close();
public override void Open() => Connection.Open();
public void CheckTransaction(DbTransaction transaction)
{
if (transactions.Count == 0 || !ReferenceEquals(transactions.Pop(), transaction))
{
throw new DException("事务未有序释放!");
}
}
protected override System.Data.Common.DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
var transaction = new DbTransaction(this, connection.BeginTransaction(isolationLevel));
transactions.Push(transaction);
return transaction;
}
protected override System.Data.Common.DbCommand CreateDbCommand()
{
var command = Connection.CreateCommand();
if (transactions.Count > 0)
{
var transaction = transactions.Peek();
command.Transaction = transaction.Transaction;
}
return command;
}
public override DataTable GetSchema(string collectionName) => Connection.GetSchema(collectionName);
public override DataTable GetSchema(string collectionName, string[] restrictionValues) => Connection.GetSchema(collectionName, restrictionValues);
public override DataTable GetSchema() => Connection.GetSchema();
#if NET45_OR_GREATER || NETSTANDARD2_0_OR_GREATER
public override Task OpenAsync(CancellationToken cancellationToken) => Connection.OpenAsync(cancellationToken);
#endif
#if NETSTANDARD2_1_OR_GREATER
public override ValueTask DisposeAsync() => connection?.DisposeAsync() ?? new ValueTask();
public override Task CloseAsync() => connection.CloseAsync();
public override Task ChangeDatabaseAsync(string databaseName, CancellationToken cancellationToken = default) => Connection.ChangeDatabaseAsync(databaseName, cancellationToken);
protected override async ValueTask<System.Data.Common.DbTransaction> BeginDbTransactionAsync(IsolationLevel isolationLevel, CancellationToken cancellationToken)
{
var transaction = new DbTransaction(this, await Connection.BeginTransactionAsync(isolationLevel, cancellationToken).ConfigureAwait(false));
transactions.Push(transaction);
return transaction;
}
#endif
public override event StateChangeEventHandler StateChange
{
add { Connection.StateChange += value; }
remove { Connection.StateChange -= value; }
}
public override void EnlistTransaction(System.Transactions.Transaction transaction) => Connection.EnlistTransaction(transaction);
protected override void Dispose(bool disposing)
{
if (disposing)
{
connection?.Dispose();
}
base.Dispose(disposing);
}
public T Read<T>(Expression expression)
{
return Read(databaseFor.Read<T>(expression));
}
public IEnumerable<T> Query<T>(Expression expression)
{
return Query<T>(databaseFor.Read<T>(expression));
}
public int Execute(Expression expression)
{
return Execute(databaseFor.Execute(expression));
}
#if NET45_OR_GREATER || NETSTANDARD2_0_OR_GREATER
public Task<T> ReadAsync<T>(Expression expression, CancellationToken cancellationToken = default)
{
return ReadAsync(databaseFor.Read<T>(expression), cancellationToken);
}
public IAsyncEnumerable<T> QueryAsync<T>(Expression expression)
{
return QueryAsync<T>(databaseFor.Read<T>(expression));
}
public Task<int> ExecuteAsync(Expression expression, CancellationToken cancellationToken = default)
{
return ExecuteAsync(databaseFor.Execute(expression), cancellationToken);
}
#endif
public T Read<T>(CommandSql<T> commandSql)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.Read<T>(dbConnection, commandSql);
}
}
if (transactions.Count == 0)
{
return databaseFor.Read<T>(connection, commandSql);
}
return databaseFor.Read<T>(this, commandSql);
}
public T Single<T>(string sql, object param = null, string missingMsg = null, int? commandTimeout = null)
{
return Read(new CommandSql<T>(sql, param, RowStyle.Single, missingMsg, commandTimeout));
}
public T SingleOrDefault<T>(string sql, object param = null, int? commandTimeout = null, T defaultValue = default)
{
return Read(new CommandSql<T>(sql, param, RowStyle.SingleOrDefault, defaultValue, commandTimeout));
}
public T First<T>(string sql, object param = null, string missingMsg = null, int? commandTimeout = null)
{
return Read(new CommandSql<T>(sql, param, RowStyle.First, missingMsg, commandTimeout));
}
public T FirstOrDefault<T>(string sql, object param = null, int? commandTimeout = null, T defaultValue = default)
{
return Read(new CommandSql<T>(sql, param, RowStyle.FirstOrDefault, defaultValue, commandTimeout));
}
public IEnumerable<T> Query<T>(CommandSql commandSql)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.Query<T>(dbConnection, commandSql);
}
}
if (transactions.Count == 0)
{
return databaseFor.Query<T>(connection, commandSql);
}
return databaseFor.Query<T>(this, commandSql);
}
public IEnumerable<T> Query<T>(string sql, object param = null, int? commandTimeout = null)
{
return Query<T>(new CommandSql(sql, param, commandTimeout));
}
public int Execute(CommandSql commandSql)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.Execute(dbConnection, commandSql);
}
}
if (transactions.Count == 0)
{
return databaseFor.Execute(connection, commandSql);
}
return databaseFor.Execute(this, commandSql);
}
public int Execute(string sql, object param = null, int? commandTimeout = null)
{
return Execute(new CommandSql(sql, param, commandTimeout));
}
#if NET45_OR_GREATER || NETSTANDARD2_0_OR_GREATER
public Task<T> ReadAsync<T>(CommandSql<T> commandSql, CancellationToken cancellationToken = default)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.ReadAsync(dbConnection, commandSql, cancellationToken);
}
}
if (transactions.Count == 0)
{
return databaseFor.ReadAsync(connection, commandSql, cancellationToken);
}
return databaseFor.ReadAsync(this, commandSql, cancellationToken);
}
public Task<T> SingleAsync<T>(string sql, object param = null, string missingMsg = null, int? commandTimeout = null, CancellationToken cancellationToken = default)
{
return ReadAsync(new CommandSql<T>(sql, param, RowStyle.Single, missingMsg, commandTimeout), cancellationToken);
}
public Task<T> SingleOrDefaultAsync<T>(string sql, object param = null, int? commandTimeout = null, T defaultValue = default, CancellationToken cancellationToken = default)
{
return ReadAsync(new CommandSql<T>(sql, param, RowStyle.SingleOrDefault, defaultValue, commandTimeout), cancellationToken);
}
public Task<T> FirstAsync<T>(string sql, object param = null, string missingMsg = null, int? commandTimeout = null, CancellationToken cancellationToken = default)
{
return ReadAsync(new CommandSql<T>(sql, param, RowStyle.First, missingMsg, commandTimeout), cancellationToken);
}
public Task<T> FirstOrDefaultAsync<T>(string sql, object param = null, int? commandTimeout = null, T defaultValue = default, CancellationToken cancellationToken = default)
{
return ReadAsync(new CommandSql<T>(sql, param, RowStyle.FirstOrDefault, defaultValue, commandTimeout), cancellationToken);
}
public IAsyncEnumerable<T> QueryAsync<T>(CommandSql commandSql)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.QueryAsync<T>(dbConnection, commandSql);
}
}
if (transactions.Count == 0)
{
return databaseFor.QueryAsync<T>(connection, commandSql);
}
return databaseFor.QueryAsync<T>(this, commandSql);
}
public IAsyncEnumerable<T> QueryAsync<T>(string sql, object param = null, int? commandTimeout = null)
{
return QueryAsync<T>(new CommandSql(sql, param, commandTimeout));
}
public Task<int> ExecuteAsync(CommandSql commandSql, CancellationToken cancellationToken = default)
{
if (connection is null)
{
using (var dbConnection = TransactionConnections.GetConnection(connectionConfig.ConnectionString, adapter) ?? DispatchConnections.Instance.GetConnection(connectionConfig.ConnectionString, adapter, true))
{
return databaseFor.ExecuteAsync(dbConnection, commandSql, cancellationToken);
}
}
if (transactions.Count == 0)
{
return databaseFor.ExecuteAsync(connection, commandSql, cancellationToken);
}
return databaseFor.ExecuteAsync(this, commandSql, cancellationToken);
}
public Task<int> ExecuteAsync(string sql, object param = null, int? commandTimeout = null, CancellationToken cancellationToken = default)
{
return ExecuteAsync(new CommandSql(sql, param, commandTimeout), cancellationToken);
}
#endif
}
}
}
| 6,929
|
https://github.com/LLNL/Tool-Gear/blob/master/src/boost/mpl/set/aux_/begin_end_impl.hpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause, LicenseRef-scancode-unknown-license-reference, BSL-1.0
| 2,018
|
Tool-Gear
|
LLNL
|
C++
|
Code
| 156
| 408
|
#ifndef BOOST_MPL_SET_AUX_BEGIN_END_IMPL_HPP_INCLUDED
#define BOOST_MPL_SET_AUX_BEGIN_END_IMPL_HPP_INCLUDED
// + file: boost/mpl/aux_/begin_end_impl.hpp
// + last modified: 03/may/03
// Copyright (c) 2002-03
// David Abrahams, Aleksey Gurtovoy
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appears in all copies and
// that both the copyright notice and this permission notice appear in
// supporting documentation. No representations are made about the
// suitability of this software for any purpose. It is provided "as is"
// without express or implied warranty.
//
// See http://www.boost.org/libs/mpl for documentation.
#include "boost/mpl/begin_end_fwd.hpp"
#include "boost/mpl/set/aux_/iterator.hpp"
namespace boost { namespace mpl {
template<>
struct begin_traits< aux::set_tag >
{
template< typename Set > struct algorithm
{
typedef set_iter<Set,Set> type;
};
};
template<>
struct end_traits< aux::set_tag >
{
template< typename Set > struct algorithm
{
typedef set_iter< Set,set0<> > type;
};
};
}}
#endif // BOOST_MPL_SET_AUX_BEGIN_END_IMPL_HPP_INCLUDED
| 12,361
|
https://github.com/toniferr/PeeperPattern/blob/master/src/main/java/com/toni/peeper/pattern/structural/flyweight/Private.java
|
Github Open Source
|
Open Source
|
MIT
| null |
PeeperPattern
|
toniferr
|
Java
|
Code
| 52
| 143
|
package com.toni.peeper.pattern.structural.flyweight;
public class Private implements Enemy {
private String weapon;
private final String LIFE;
public Private() {
LIFE = "200";
}
public void setWeapon(String weapon) {
this.weapon = weapon;
System.out.println("El arma del soldado es: "+ weapon);
}
public void lifePoints() {
System.out.println("La vida de un soldado es: "+ LIFE);
}
}
| 46,660
|
https://github.com/ShayBox/ChanceCubeTimer/blob/master/src/main/java/com/shaybox/straymod/CustomTask.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ChanceCubeTimer
|
ShayBox
|
Java
|
Code
| 76
| 334
|
package com.shaybox.straymod;
import com.shaybox.straymod.proxy.ClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.text.TextComponentString;
import java.util.TimerTask;
public class CustomTask extends TimerTask {
@Override
public void run() {
ClientProxy proxy = (ClientProxy) Main.PROXY;
EntityPlayerMP player = proxy.getPlayer();
if (proxy.getQueue().size() == 0) {
proxy.timer.stop();
player.sendMessage(new TextComponentString("Queue ran out"));
return;
}
Utilities.spawnBat(player);
proxy.timer.updateTime();
proxy.getQueue().remove();
if (proxy.getQueue().size() == 0) {
proxy.timer.stop();
player.sendMessage(new TextComponentString("Queue ran out"));
return;
}
if (Minecraft.getMinecraft().isGamePaused()) {
proxy.timer.pause();
player.sendMessage(new TextComponentString("You were paused, I paused the timer for you"));
}
}
}
| 48,668
|
https://github.com/KnowledgeCaptureAndDiscovery/organicdatascience/blob/master/js/core/util/WTUtil.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
organicdatascience
|
KnowledgeCaptureAndDiscovery
|
JavaScript
|
Code
| 332
| 1,243
|
var WTUtil = function(title, api) {
this.title = title;
this.api = api;
// Initialize some event handlers
this.initEventHandlers();
};
WTUtil.prototype.initEventHandlers = function() {
var me = this;
$(document).ready(function() {
});
};
// TODO for now, assumes HTTP or HTTPS
WTUtil.prototype.getdomain = function( uri ) {
var protlength = 0;
if (uri.indexOf('http://')==-1) protlength = 'http://'.length-1;
if (uri.indexOf('https://')==-1) protlength = 'https://'.length-1;
var domain = uri.slice(protlength);
if (domain.indexOf('/')!=-1) domain = domain.slice(0, domain.indexOf('/'));
var parts = domain.split('.');
if (parts.length == 1) return domain;
if (parts.length == 2) return parts[0];
if ((parts[parts.length-2] == 'ac') || (parts[parts.length-2] == 'co')) return parts[parts.length-3];
return parts[parts.length-2];
};
WTUtil.prototype.checkevent = function( chkbox, item, tr, link, linkstr, linkstrs ) {
var num = item.data('numchecked');
var checked_data = item.data('checked_data');
var trdata = tr.data('data');
if($(chkbox).attr("checked")) {
tr.addClass('lodselected'); num++;
checked_data.push(trdata);
} else {
tr.removeClass('lodselected'); num--;
checked_data = $.grep(checked_data, function(v) { return v != trdata; });
}
if(num) {
if(num > 1) link.html(linkstrs);
else link.html(linkstr);
link.removeClass('lodinvisible');
}
else {
link.addClass('lodinvisible');
}
item.data('checked_data', checked_data);
item.data('numchecked', num);
};
WTUtil.prototype.hideFacts = function( striples ) {
$.each(striples, function(i, t) {
$.each(t.sources, function(m, s) {
var ident = $('.lodentity[title="' + s + '"]');
var table = ident.data('table');
$.each(table.children().children('tr'), function(i, tr) {
if($(tr).data('pid') == t.p && $(tr).data('oid')==t.o)
$(tr).hide();
});
});
});
};
WTUtil.prototype.showFacts = function( striples ) {
$.each(striples, function(i, t) {
$.each(t.sources, function(m, s) {
var ident = $('.lodentity[title="' + s + '"]');
var table = ident.data('table');
$.each(table.children().children('tr'), function(i, tr) {
if($(tr).data('pid') == t.p && $(tr).data('oid')==t.o)
$(tr).show();
});
});
});
};
WTUtil.prototype.removeDuplicateTriples = function( triples ) {
var seen = {};
var newarr = [];
$.each(triples, function() {
if (seen[this.property]!=this.object)
newarr.push(this);
seen[this.property] = this.object;
});
return newarr;
};
WTUtil.prototype.getHelpButton = function( msg ) {
var win = $('<div class="jqmWindow"></div>');
win.append('<h2 style="float:left">' + lpMsg('Help Window') +'</h2><a href="#" style="float:right" class="jqmClose">' + lpMsg('Close') + '</a><hr style="clear:both"/>');
win.append(lpMsg('help-' + msg));
$(document.body).append(win);
win.jqm();
var ah = $('<a class="helpbutton lodlink"></a>');
ah.click(function(){ win.jqmShow();});
return ah;
};
WTUtil.prototype.registerSuggestions = function(item, category, api) {
item.autocomplete({
delay:300,
minLength:1,
source: function(request, response) {
api.getSuggestions(request.term, category, function(sug) {
response.call(this, sug.wtsuggest.suggestions);
});
}
});
};
| 9,003
|
https://github.com/tanzu-mkondo/storefront/blob/master/src/app/home/home.component.scss
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
storefront
|
tanzu-mkondo
|
SCSS
|
Code
| 38
| 134
|
:host { width: 100%;}
.card {
.card-body:hover {
background-color: rgb(248, 249, 250);
}
svg, .article-image {
height: 160px;
}
.card-text {
min-height: 50px;
}
.article-image {
background-size: cover;
}
.add-to-cart {
img {
height: 1.8em;
}
}
}
| 8,586
|
https://github.com/Remi05/uial/blob/master/Uial.UnitTests/Scenarios/Scenario.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
uial
|
Remi05
|
C#
|
Code
| 113
| 399
|
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Uial.Interactions;
using Uial.Scenarios;
using Uial.UnitTests.Interactions;
namespace Uial.UnitTests.Scenarios
{
[TestClass]
public class ScenarioTests
{
[TestMethod]
public void VerifyNameIsSet()
{
string expectedName = "TestScenario";
var scenario= new Scenario(expectedName, new List<IInteraction>());
Assert.AreEqual(expectedName, scenario.Name);
}
[TestMethod]
public void VerifyAllInteractionsAreRunOnceInCorrectOrder()
{
var interactionsToCall = new List<string>() { "MockInteraction1", "MockInteraction2", "MockInteraction3", };
var interactionsCalled = new List<string>();
List<MockInteraction> mockInteractions = interactionsToCall.Select(
(interactionName) => new MockInteraction(interactionName, () => interactionsCalled.Add(interactionName))
).ToList();
var scenario = new Scenario("TestScenario", mockInteractions);
scenario.Do();
Assert.IsTrue(mockInteractions.All((interaction) => interaction.WasRun), "All the interactions should be run.");
Assert.IsTrue(mockInteractions.All((interaction) => interaction.WasRunOnce), "All the interactions should be run exactly once.");
Assert.IsTrue(interactionsToCall.SequenceEqual(interactionsCalled), "All the interactions should be run in the order they were given.");
}
}
}
| 17,588
|
https://github.com/SimeonRaykov/Programming-Basics-2018-March/blob/master/JAVA Basics/exercises/zadachi2/fo.java
|
Github Open Source
|
Open Source
|
MIT
| null |
Programming-Basics-2018-March
|
SimeonRaykov
|
Java
|
Code
| 76
| 217
|
package zadachi2;
import java.util.Scanner;
public class fo {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int n = Integer.parseInt(Scanner.nextLine());
int sum=0;
for (int i = 1; i <=9 ; i++) {
for (int j = 1; j <= 9; j++) {
for (int k = 1; k <=9 ; k++) {
for (int l =1; l <=9 ; l++) {
if(i+j==k+l){
if(n%(i+j)==0){
System.out.printf("%d%d%d%d ",i,j,k,l);
}
}
}
}
}
}
}
}
| 35,845
|
https://github.com/QQtufu/news/blob/master/网易新闻/ChannelLabel.h
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
news
|
QQtufu
|
Objective-C
|
Code
| 28
| 81
|
//
// ChannelLabel.h
// 网易新闻
//
// Created by iMac on 16/7/22.
// Copyright © 2016年 iMac. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ChannelLabel : UILabel
@end
| 7,235
|
https://github.com/DHS009/HackerRankSolutions/blob/master/Practice/AllDomains/CoreCS/DataStructures/Arrays/2DArray-DS.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
HackerRankSolutions
|
DHS009
|
JavaScript
|
Code
| 161
| 455
|
/* author:@shivkrthakur */
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function main() {
var arr = [];
for(arr_i = 0; arr_i < 6; arr_i++){
arr[arr_i] = readLine().split(' ');
arr[arr_i] = arr[arr_i].map(Number);
}
var highestSum = Number.MIN_SAFE_INTEGER;
for(var row = 0; row + 2 < arr.length; row++){
for(var col = 0; col + 2 < arr[row].length; col++){
var sum = 0;
for(var r = row, d = 1; r <= row + 2 && r < arr.length; d++, r++){
for(var c = col, e = 1; c <= col + 2 && c < arr[r].length; e++, c++){
if((d % 2) == 0){
if((e % 2) == 0){
sum += arr[r][c];
}
}
else sum += arr[r][c];
}
}
highestSum = Math.max(highestSum, sum);
}
}
console.log(highestSum);
}
| 47,080
|
https://github.com/agalbrai/PIMS/blob/master/frontend/src/actions/genericActions.spec.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
PIMS
|
agalbrai
|
TypeScript
|
Code
| 204
| 671
|
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { request, success, error } from 'actions/genericActions';
import * as ActionTypes from 'constants/actionTypes';
const createMockStore = configureMockStore([thunk]);
const store = createMockStore({
rootReducer: {
parcels: [],
parcelDetail: null,
pid: 0,
},
});
describe('genericActions', () => {
afterEach(() => {
store.clearActions();
});
it('`request action` returns `type: REQUEST`', () => {
const expectedActions = [
{ name: ActionTypes.GET_PARCELS, type: ActionTypes.REQUEST, isFetching: true },
];
store.dispatch<any>(request(ActionTypes.GET_PARCELS));
expect(store.getActions()).toEqual(expectedActions);
});
describe('after a `request` action', () => {
it('when an API endpoint has been successful, the `success` action returns `type: SUCCESS`', () => {
const mockData = {};
const expectedActions = [
{ name: ActionTypes.GET_PARCELS, type: ActionTypes.REQUEST, isFetching: true },
{
name: ActionTypes.GET_PARCELS,
type: ActionTypes.SUCCESS,
data: mockData,
isFetching: false,
status: 200,
},
];
store.dispatch<any>(request(ActionTypes.GET_PARCELS));
store.dispatch(success(ActionTypes.GET_PARCELS, 200, mockData));
expect(store.getActions()).toEqual(expectedActions);
});
it('when an API endpoint has failed, the `error` action returns `type: ERROR`', () => {
const mockError = {
response: { status: 400, error: { error: undefined, message: 'Error' }, data: undefined },
};
const expectedActions = [
{
name: ActionTypes.GET_PARCELS,
type: ActionTypes.REQUEST,
isFetching: true,
error: undefined,
status: undefined,
},
{
name: ActionTypes.GET_PARCELS,
type: ActionTypes.ERROR,
error: mockError,
isFetching: false,
status: 400,
data: undefined,
},
];
store.dispatch<any>(request(ActionTypes.GET_PARCELS));
store.dispatch(error(ActionTypes.GET_PARCELS, 400, mockError));
expect(store.getActions()).toEqual(expectedActions);
});
});
});
| 44,840
|
https://github.com/petrofcikmatus/simple-todo/blob/master/_app/views/pages/login.php
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
simple-todo
|
petrofcikmatus
|
PHP
|
Code
| 90
| 386
|
<?php
if (is_logged_in()){
redirect();
}
if (is_post()) {
if (do_login()) {
redirect();
}
}
if (isset($_COOKIE["email"])) {
$_POST["email"] = $_COOKIE["email"];
}
include_header(array("title" => "login"));
?>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form id="login-form" method="post">
<div class="form-group">
<label for="inputEmail" class="sr-only">email address</label>
<input type="email" name="email" id="inputEmail" class="form-control" placeholder="email address"
value="<?= (isset($_POST["email"]) ? plain($_POST["email"]) : "") ?>" required autofocus>
</div>
<div class="form-group">
<label for="inputPassword" class="sr-only">password</label>
<input type="password" name="password" id="inputPassword" class="form-control"
placeholder="password"
required>
</div>
<div class="form-group">
<button class="btn btn-sm btn-primary" type="submit">login</button>
<a href="<?= url() ?>/registration" class="btn btn-sm btn-default">registration</a>
</div>
</form>
</div>
</div>
<?php include_footer(); ?>
| 22,678
|
https://github.com/nikkelma/harvester/blob/master/pkg/controller/master/backup/util.go
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-warranty-disclaimer
| 2,021
|
harvester
|
nikkelma
|
Go
|
Code
| 285
| 1,130
|
package backup
import (
"fmt"
"time"
snapshotv1 "github.com/kubernetes-csi/external-snapshotter/v2/pkg/apis/volumesnapshot/v1beta1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
harvesterv1 "github.com/harvester/harvester/pkg/apis/harvesterhci.io/v1beta1"
)
func vmBackupReady(vmBackup *harvesterv1.VirtualMachineBackup) bool {
return vmBackup.Status != nil && vmBackup.Status.ReadyToUse != nil && *vmBackup.Status.ReadyToUse
}
func vmBackupProgressing(vmBackup *harvesterv1.VirtualMachineBackup) bool {
return vmBackupError(vmBackup) == nil &&
(vmBackup.Status == nil || vmBackup.Status.ReadyToUse == nil || !*vmBackup.Status.ReadyToUse)
}
func vmBackupError(vmBackup *harvesterv1.VirtualMachineBackup) *harvesterv1.Error {
if vmBackup.Status != nil && vmBackup.Status.Error != nil {
return vmBackup.Status.Error
}
return nil
}
func vmBackupContentReady(vmBackupContent *harvesterv1.VirtualMachineBackupContent) bool {
return vmBackupContent.Status != nil && vmBackupContent.Status.ReadyToUse != nil && *vmBackupContent.Status.ReadyToUse
}
func getVMBackupContentName(vmBackup *harvesterv1.VirtualMachineBackup) string {
if vmBackup.Status != nil && vmBackup.Status.VirtualMachineBackupContentName != nil {
return *vmBackup.Status.VirtualMachineBackupContentName
}
return fmt.Sprintf("%s-%s", vmBackup.Name, "backupcontent")
}
func newReadyCondition(status corev1.ConditionStatus, message string) harvesterv1.Condition {
return harvesterv1.Condition{
Type: harvesterv1.BackupConditionReady,
Status: status,
Message: message,
LastTransitionTime: currentTime().Format(time.RFC3339),
}
}
func newProgressingCondition(status corev1.ConditionStatus, message string) harvesterv1.Condition {
return harvesterv1.Condition{
Type: harvesterv1.BackupConditionProgressing,
Status: status,
Message: message,
LastTransitionTime: currentTime().Format(time.RFC3339),
}
}
func updateBackupCondition(ss *harvesterv1.VirtualMachineBackup, c harvesterv1.Condition) {
ss.Status.Conditions = updateCondition(ss.Status.Conditions, c, false)
}
func updateCondition(conditions []harvesterv1.Condition, c harvesterv1.Condition, includeReason bool) []harvesterv1.Condition {
found := false
for i := range conditions {
if conditions[i].Type == c.Type {
if conditions[i].Status != c.Status || (includeReason && conditions[i].Reason != c.Reason) {
conditions[i] = c
}
found = true
break
}
}
if !found {
conditions = append(conditions, c)
}
return conditions
}
func translateError(e *snapshotv1.VolumeSnapshotError) *harvesterv1.Error {
if e == nil {
return nil
}
return &harvesterv1.Error{
Message: e.Message,
Time: e.Time,
}
}
// variable so can be overridden in tests
var currentTime = func() *metav1.Time {
t := metav1.Now()
return &t
}
func isContentReady(content *harvesterv1.VirtualMachineBackupContent) bool {
return content.Status != nil && content.Status.ReadyToUse != nil && *content.Status.ReadyToUse
}
func isContentError(content *harvesterv1.VirtualMachineBackupContent) bool {
return content.Status != nil && content.Status.Error != nil
}
| 45,779
|
https://github.com/pvgennip/sensor-data-portal/blob/master/portal/app/Http/Controllers/UserController.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
sensor-data-portal
|
pvgennip
|
PHP
|
Code
| 694
| 2,478
|
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use App\Role;
use App\Sensor;
use DB;
use Hash;
use Image;
use Auth;
class UserController extends Controller
{
// Helpers
private function checkRoleAuthorization($request=null, $permission=null, $id=null)
{
if ($id && Auth::user()->id == $id) // edit self is allowed
return true;
if ($permission && Auth::user()->can($permission) == false) // check permissions
return false;
// Check for unauthorized role editing
if ($request)
{
$superId = Role::where('name','=','superadmin')->pluck('id','id')->toArray();
$reqIsSup= count(array_diff($request->input('roles'), $superId)) == 0 ? true : false; // check if super admin id role is requested
$roleIds = $this->getMyPermittedRoles(true);
$reqMatch= count(array_diff($request->input('roles'), $roleIds)) == 0 ? true : false; // check if all roles match
if ($reqMatch == false || ($reqIsSup && Auth::user()->hasRole('superadmin') == false)){
return false;
}
}
return true;
}
private function getMyPermittedRoles($returnIdArray=false)
{
//die($user->roles->pluck('id'));
if (Auth::user()->hasRole('superadmin'))
{
$roles = Role::all();
}
else if (Auth::user()->hasRole('admin'))
{
$roles = Role::where('name','!=','superadmin');
}
else
{
$roles = Auth::user()->roles;
}
//die($roles);
if ($returnIdArray)
{
return $roles->pluck('id','id')->toArray();
}
else
{
return $roles->pluck('display_name','id');
}
}
private function getMyPermittedSensors()
{
if (Auth::user()->hasRole('superadmin'))
{
$sensors = Sensor::orderBy('name', 'ASC')->get();
}
else
{
$sensors = Auth::user()->sensors();
}
return $sensors;
}
private function checkIfUserMayEditUser($user)
{
//die($user->roles->pluck('id'));
if (Auth::user()->id == $user->id)
{
return true; // you may edit yourself
}
else if (Auth::user()->hasRole('superadmin'))
{
return true;
}
else if (Auth::user()->hasRole('admin') && $user->hasRole('superadmin') == false && $user->hasRole('admin') == false) // only edit users of a 'lower' role
{
return true;
}
return false;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$data = User::all()->sortBy('name', SORT_NATURAL|SORT_FLAG_CASE, false);
return view('users.index',compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$roles = $this->getMyPermittedRoles();
$sensors = Sensor::all()->pluck('name','id');
return view('users.create',compact('roles','sensors'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if ($this->checkRoleAuthorization($request, "user-create") == false)
return redirect()->route('users.index')->with('error', 'You are not allowed to create this type of user');
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$input['api_token'] = str_random(60);
// Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save( public_path('uploads/avatars/' . $filename ) );
$user->avatar = $filename;
}
$user = User::create($input);
// Handle role assignment, only store permitted role
$roleIds = $this->getMyPermittedRoles(true);
foreach ($request->input('roles') as $key => $value)
{
if (in_array($value, $roleIds))
{
$user->attachRole($value);
}
}
// Edit sensors
$user->sensors()->sync($request->input('sensors'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id);
$sensors = $user->sensors()->orderBy('name','asc')->pluck('name','id');
return view('users.show',compact('user','sensors'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id);
$editAllowed= $this->checkIfUserMayEditUser($user);
if ($editAllowed)
{
$roles = $this->getMyPermittedRoles();
$userRole = $user->roles->pluck('id','id')->toArray();
$sensors = $this->getMyPermittedSensors()->pluck('name','id');
$userSensor = $user->sensors()->pluck('sensor_id','sensor_id')->toArray();
return view('users.edit',compact('user','roles','userRole','sensors','userSensor'));
}
return redirect()->route('users.index')
->with('error','You are not allowed to edit this user');
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
if ($this->checkRoleAuthorization($request, "user-edit", $id) == false)
return redirect()->route('users.index')->with('error', 'You are not allowed to edit users');
$user = User::find($id);
if ($this->checkIfUserMayEditUser($user) == false)
return redirect()->route('users.index')->with('error', 'You are not allowed to edit this user');
// Do normal validation
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required',
'avatar' => 'mimes:jpeg,gif,png'
]);
$input = $request->all();
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
// Handle the user upload of avatar
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->fit(300, 300)->save( public_path('uploads/avatars/' . $filename ) );
$user->avatar = $filename;
}
$user->update($input);
// Edit role
DB::table('role_user')->where('user_id',$id)->delete();
foreach ($request->input('roles') as $key => $value) {
$user->attachRole($value);
}
// Edit sensors
$user->sensors()->sync($request->input('sensors'));
return redirect()->route('users.index')
->with("success", "User updated successfully");
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
if ($this->checkRoleAuthorization(null, "user-delete", $id) == false)
return redirect()->route('users.index')->with('error','User not deleted, you have no permission');
User::find($id)->delete();
return redirect()->route('users.index')
->with('success','User deleted successfully');
}
}
| 33,393
|
https://github.com/jasonody/Cloud-Native-Development-Patterns-and-Best-Practices/blob/master/Chapter07/order-service/test/unit/connectors/database.test.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Cloud-Native-Development-Patterns-and-Best-Practices
|
jasonody
|
TypeScript
|
Code
| 107
| 446
|
import 'mocha';
import { expect } from 'chai';
const AWS = require('aws-sdk-mock');
import { Connector } from '../../../src/connectors/database';
describe('database.ts', () => {
it('save', () => {
AWS.mock('DynamoDB.DocumentClient', 'put', (params, callback) => {
expect(params).to.deep.equal({
TableName: 'orders',
Item: {
id: '00000000-0000-0000-0000-000000000000',
status: 'submitted',
},
});
callback(null, {});
});
return new Connector('orders').save({
id: '00000000-0000-0000-0000-000000000000',
status: 'submitted',
})
.then(data => expect(data).to.deep.equal({}))
;
});
it('getById', () => {
AWS.mock('DynamoDB.DocumentClient', 'get', (params, callback) => {
expect(params).to.deep.equal({
TableName: 'orders',
Key: {
id: '00000000-0000-0000-0000-000000000000',
},
});
callback(null, {
Item: {
id: '00000000-0000-0000-0000-000000000000',
status: 'submitted',
},
});
});
return new Connector('orders').getById('00000000-0000-0000-0000-000000000000')
.then(data => expect(data).to.deep.equal({
id: '00000000-0000-0000-0000-000000000000',
status: 'submitted',
}));
});
afterEach(() => {
AWS.restore('DynamoDB.DocumentClient');
});
});
| 7,337
|
https://github.com/lukas-vlcek/elasticsearch-knapsack/blob/master/src/main/java/org/xbib/io/compress/lzf/LZFCompressingInputStream.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,013
|
elasticsearch-knapsack
|
lukas-vlcek
|
Java
|
Code
| 954
| 2,188
|
package org.xbib.io.compress.lzf;
import java.io.IOException;
import java.io.InputStream;
import org.xbib.io.compress.BufferRecycler;
/**
* Decorator {@link InputStream} implementation used for reading
* <b>uncompressed</b> data and <b>compressing</b> it on the fly, such that
* reads return compressed data. It is reverse of {@link LZFInputStream} (which
* instead uncompresses data).
*
* @author Tatu Saloranta
*
*/
public class LZFCompressingInputStream extends InputStream {
private final BufferRecycler _recycler;
private ChunkEncoder _encoder;
/**
* stream to be decompressed
*/
protected final InputStream _inputStream;
/**
* Flag that indicates if we have already called 'inputStream.close()' (to
* avoid calling it multiple times)
*/
protected boolean _inputStreamClosed;
/**
* Flag that indicates whether we force full reads (reading of as many bytes
* as requested), or 'optimal' reads (up to as many as available, but at
* least one). Default is false, meaning that 'optimal' read is used.
*/
protected boolean _cfgFullReads = false;
/**
* Buffer in which uncompressed input is first read, before getting encoded
* in {@link #_encodedBytes}.
*/
protected byte[] _inputBuffer;
/**
* Buffer that contains compressed data that is returned to readers.
*/
protected byte[] _encodedBytes;
/**
* The current position (next char to output) in the uncompressed bytes
* buffer.
*/
protected int _bufferPosition = 0;
/**
* Length of the current uncompressed bytes buffer
*/
protected int _bufferLength = 0;
/**
* Number of bytes read from the underlying {@link #_inputStream}
*/
protected int _readCount = 0;
/*
///////////////////////////////////////////////////////////////////////
// Construction, configuration
///////////////////////////////////////////////////////////////////////
*/
public LZFCompressingInputStream(InputStream in) {
_inputStream = in;
_recycler = BufferRecycler.instance();
_inputBuffer = _recycler.allocInputBuffer(LZFChunk.MAX_CHUNK_LEN);
// let's not yet allocate encoding buffer; don't know optimal size
}
/**
* Method that can be used define whether reads should be "full" or
* "optimal": former means that full compressed blocks are read right away
* as needed, optimal that only smaller chunks are read at a time, more
* being read as needed.
*/
public void setUseFullReads(boolean b) {
_cfgFullReads = b;
}
/*
///////////////////////////////////////////////////////////////////////
// InputStream implementation
///////////////////////////////////////////////////////////////////////
*/
@Override
public int available() {
// if closed, return -1;
if (_inputStreamClosed) {
return -1;
}
int left = (_bufferLength - _bufferPosition);
return (left <= 0) ? 0 : left;
}
@Override
public int read() throws IOException {
if (!readyBuffer()) {
return -1;
}
return _encodedBytes[_bufferPosition++] & 255;
}
@Override
public int read(final byte[] buffer) throws IOException {
return read(buffer, 0, buffer.length);
}
@Override
public int read(final byte[] buffer, int offset, int length) throws IOException {
if (length < 1) {
return 0;
}
if (!readyBuffer()) {
return -1;
}
// First let's read however much data we happen to have...
int chunkLength = Math.min(_bufferLength - _bufferPosition, length);
System.arraycopy(_encodedBytes, _bufferPosition, buffer, offset, chunkLength);
_bufferPosition += chunkLength;
if (chunkLength == length || !_cfgFullReads) {
return chunkLength;
}
// Need more data, then
int totalRead = chunkLength;
do {
offset += chunkLength;
if (!readyBuffer()) {
break;
}
chunkLength = Math.min(_bufferLength - _bufferPosition, (length - totalRead));
System.arraycopy(_encodedBytes, _bufferPosition, buffer, offset, chunkLength);
_bufferPosition += chunkLength;
totalRead += chunkLength;
} while (totalRead < length);
return totalRead;
}
@Override
public void close() throws IOException {
_bufferPosition = _bufferLength = 0;
byte[] buf = _encodedBytes;
if (buf != null) {
_encodedBytes = null;
_recycler.releaseEncodeBuffer(buf);
}
if (_encoder != null) {
_encoder.close();
}
_closeInput();
}
private void _closeInput() throws IOException {
byte[] buf = _inputBuffer;
if (buf != null) {
_inputBuffer = null;
_recycler.releaseInputBuffer(buf);
}
if (!_inputStreamClosed) {
_inputStreamClosed = true;
_inputStream.close();
}
}
/**
* Overridden to just skip at most a single chunk at a time
*/
@Override
public long skip(long n) throws IOException {
if (_inputStreamClosed) {
return -1;
}
int left = (_bufferLength - _bufferPosition);
// if none left, must read more:
if (left <= 0) {
// otherwise must read more to skip...
int b = read();
if (b < 0) { // EOF
return -1;
}
// push it back to get accurate skip count
--_bufferPosition;
left = (_bufferLength - _bufferPosition);
}
// either way, just skip whatever we have decoded
if (left > n) {
left = (int) n;
}
_bufferPosition += left;
return left;
}
/*
///////////////////////////////////////////////////////////////////////
// Internal methods
///////////////////////////////////////////////////////////////////////
*/
/**
* Fill the uncompressed bytes buffer by reading the underlying inputStream.
*
* @throws IOException
*/
protected boolean readyBuffer() throws IOException {
if (_bufferPosition < _bufferLength) {
return true;
}
if (_inputStreamClosed) {
return false;
}
// Ok: read as much as we can from input source first
int count = _inputStream.read(_inputBuffer, 0, _inputBuffer.length);
if (count < 0) { // if no input read, it's EOF
_closeInput(); // and we can close input source as well
return false;
}
int chunkLength = count;
int left = _inputBuffer.length - count;
while ((count = _inputStream.read(_inputBuffer, chunkLength, left)) > 0) {
chunkLength += count;
left -= count;
if (left < 1) {
break;
}
}
_bufferPosition = 0;
// Ok: if we don't yet have an encoder (and buffer for it), let's get one
if (_encoder == null) {
// need 7 byte header, plus regular max buffer size:
int bufferLen = chunkLength + ((chunkLength + 31) >> 5) + 7;
_encoder = ChunkEncoder.nonAllocatingEncoder(bufferLen);
_encodedBytes = _recycler.allocEncodingBuffer(bufferLen);
}
// offset of 7 so we can prepend header as necessary
int encodeEnd = _encoder.tryCompress(_inputBuffer, 0, chunkLength, _encodedBytes, 7);
// but did it compress?
if (encodeEnd < (chunkLength + 5)) { // yes! (compared to 5 byte uncomp prefix, data)
// prepend header in situ
LZFChunk.appendCompressedHeader(chunkLength, encodeEnd - 7, _encodedBytes, 0);
_bufferLength = encodeEnd;
} else { // no -- so sad...
int ptr = LZFChunk.appendNonCompressedHeader(chunkLength, _encodedBytes, 0);
// TODO: figure out a way to avoid this copy; need a header
System.arraycopy(_inputBuffer, 0, _encodedBytes, ptr, chunkLength);
_bufferLength = ptr + chunkLength;
}
if (count < 0) { // did we get end-of-input?
_closeInput();
}
return true;
}
}
| 21,542
|
https://github.com/lonkamikaze/hsk-dev-stub/blob/master/src/main.c
|
Github Open Source
|
Open Source
|
0BSD
| null |
hsk-dev-stub
|
lonkamikaze
|
C
|
Code
| 73
| 196
|
/** \file
* Device main.c Stub
*
* @author kami
*/
#include <Infineon/XC878.h>
#include <hsk_boot/hsk_boot.h>
#include "config.h"
void main(void);
void init(void);
void run(void);
/**
* Call init functions and invoke the run routine.
*/
void main(void) {
init();
run();
}
/**
* Initialize ports, timers and ISRs.
*/
void init(void) {
/* Activate external clock. */
hsk_boot_extClock(CLK);
}
/**
* The main code body.
*/
void run(void) {
while (1) {
}
}
| 35,477
|
https://github.com/rokon12/mNet/blob/master/src/main/java/org/jugbd/mnet/security/DatabaseAuthenticationProvider.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
mNet
|
rokon12
|
Java
|
Code
| 158
| 632
|
package org.jugbd.mnet.security;
import org.jugbd.mnet.domain.User;
import org.jugbd.mnet.domain.enums.Role;
import org.jugbd.mnet.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.Arrays;
/**
* Created by bazlur on 7/3/14.
*/
@Service("databaseAuthenticationProvider")
public class DatabaseAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private UserService userService;
@Autowired
private MessageDigestPasswordEncoder messageDigestPasswordEncoder;
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//ignored
}
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
logger.debug("retrieveUser() username ={}", username);
String password = (String) authentication.getCredentials();
if (!StringUtils.hasText(password)) {
throw new BadCredentialsException("Please enter password");
}
try {
User targetUser = (User) userService.loadUserByUsername(username);
String encryptedPassword = messageDigestPasswordEncoder.encodePassword(password, targetUser.getSalt());
String expectedPassword = targetUser.getHashedPassword();
if (!StringUtils.hasText(expectedPassword)) {
throw new BadCredentialsException("No password for "
+ username
+ " set in database, contact administrator");
}
if (!encryptedPassword.equals(expectedPassword)) {
throw new BadCredentialsException("Invalid Password");
}
return targetUser;
} catch (Exception ex) {
throw new BadCredentialsException("Invalid user");
}
}
}
| 20,900
|
https://github.com/gitter-badger/zimg-1/blob/master/.gitmodules
|
Github Open Source
|
Open Source
|
WTFPL
| 2,015
|
zimg-1
|
gitter-badger
|
Git Config
|
Code
| 8
| 47
|
[submodule "UnitTest/Extra/googletest"]
path = UnitTest/Extra/googletest
url = https://github.com/google/googletest.git
| 5,615
|
https://github.com/YangHao666666/hawq/blob/master/src/pl/pljava/src/java/pljava/org/postgresql/pljava/ObjectPool.java
|
Github Open Source
|
Open Source
|
Artistic-1.0-Perl, ISC, bzip2-1.0.5, TCL, Apache-2.0, BSD-3-Clause-No-Nuclear-License-2014, MIT, PostgreSQL, BSD-3-Clause
| 2,018
|
hawq
|
YangHao666666
|
Java
|
Code
| 136
| 292
|
/*
* Copyright (c) 2004, 2005, 2006 TADA AB - Taby Sweden
* Distributed under the terms shown in the file COPYRIGHT
* found in the root directory of this distribution or at
* http://eng.tada.se/osprojects/COPYRIGHT.html
*/
package org.postgresql.pljava;
import java.sql.SQLException;
public interface ObjectPool
{
/**
* Obtain a pooled object. A new instance is created if needed. The pooled
* object is removed from the pool and activated.
*
* @return A new object or an object found in the pool.
*/
PooledObject activateInstance()
throws SQLException;
/**
* Call the {@link PooledObject#passivate()} method and return the object
* to the pool.
* @param instance The instance to passivate.
*/
void passivateInstance(PooledObject instance)
throws SQLException;
/**
* Call the {@link PooledObject#remove()} method and evict the object
* from the pool.
*/
void removeInstance(PooledObject instance)
throws SQLException;
}
| 35,874
|
https://github.com/NUStreaming/LoL/blob/master/dash.js/src/streaming/net/HTTPLoader.js
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-proprietary-license, BSD-3-Clause, BSD-2-Clause, Apache-2.0
| 2,021
|
LoL
|
NUStreaming
|
JavaScript
|
Code
| 1,078
| 3,092
|
/**
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and contributor
* rights, including patent rights, and no such rights are granted under this license.
*
* Copyright (c) 2013, Dash Industry Forum.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* * Neither the name of Dash Industry Forum nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import XHRLoader from './XHRLoader';
import FetchLoader from './FetchLoader';
import { HTTPRequest } from '../vo/metrics/HTTPRequest';
import FactoryMaker from '../../core/FactoryMaker';
import Errors from '../../core/errors/Errors';
import DashJSError from '../vo/DashJSError';
/**
* @module HTTPLoader
* @ignore
* @description Manages download of resources via HTTP.
* @param {Object} cfg - dependancies from parent
*/
function HTTPLoader(cfg) {
cfg = cfg || {};
const context = this.context;
const errHandler = cfg.errHandler;
const dashMetrics = cfg.dashMetrics;
const mediaPlayerModel = cfg.mediaPlayerModel;
const requestModifier = cfg.requestModifier;
const boxParser = cfg.boxParser;
const useFetch = cfg.useFetch || false;
let instance,
requests,
delayedRequests,
retryRequests,
downloadErrorToRequestTypeMap;
function setup() {
requests = [];
delayedRequests = [];
retryRequests = [];
downloadErrorToRequestTypeMap = {
[HTTPRequest.MPD_TYPE]: Errors.DOWNLOAD_ERROR_ID_MANIFEST_CODE,
[HTTPRequest.XLINK_EXPANSION_TYPE]: Errors.DOWNLOAD_ERROR_ID_XLINK_CODE,
[HTTPRequest.INIT_SEGMENT_TYPE]: Errors.DOWNLOAD_ERROR_ID_INITIALIZATION_CODE,
[HTTPRequest.MEDIA_SEGMENT_TYPE]: Errors.DOWNLOAD_ERROR_ID_CONTENT_CODE,
[HTTPRequest.INDEX_SEGMENT_TYPE]: Errors.DOWNLOAD_ERROR_ID_CONTENT_CODE,
[HTTPRequest.BITSTREAM_SWITCHING_SEGMENT_TYPE]: Errors.DOWNLOAD_ERROR_ID_CONTENT_CODE,
[HTTPRequest.OTHER_TYPE]: Errors.DOWNLOAD_ERROR_ID_CONTENT_CODE
};
}
function internalLoad(config, remainingAttempts) {
const request = config.request;
const traces = [];
let firstProgress = true;
let needFailureReport = true;
let requestStartTime = new Date();
let lastTraceTime = requestStartTime;
let lastTraceReceivedCount = 0;
let httpRequest;
if (!requestModifier || !dashMetrics || !errHandler) {
throw new Error('config object is not correct or missing');
}
const handleLoaded = function (success) {
needFailureReport = false;
request.requestStartDate = requestStartTime;
request.requestEndDate = new Date();
request.firstByteDate = request.firstByteDate || requestStartTime;
if (!request.checkExistenceOnly) {
// may.lim: adding more data to request obj for logging
if (httpRequest.response) request.responseHeaders = httpRequest.response.responseHeaders;
dashMetrics.addHttpRequest(request, httpRequest.response ? httpRequest.response.responseURL : null,
httpRequest.response ? httpRequest.response.status : null,
httpRequest.response && httpRequest.response.getAllResponseHeaders ? httpRequest.response.getAllResponseHeaders() :
httpRequest.response ? httpRequest.response.responseHeaders : [],
success ? traces : null);
if (request.type === HTTPRequest.MPD_TYPE) {
dashMetrics.addManifestUpdate(request.type, request.requestStartDate, request.requestEndDate);
}
}
};
const onloadend = function () {
if (requests.indexOf(httpRequest) === -1) {
return;
} else {
requests.splice(requests.indexOf(httpRequest), 1);
}
if (needFailureReport) {
handleLoaded(false);
if (remainingAttempts > 0) {
remainingAttempts--;
let retryRequest = { config: config };
retryRequests.push(retryRequest);
retryRequest.timeout = setTimeout(function () {
if (retryRequests.indexOf(retryRequest) === -1) {
return;
} else {
retryRequests.splice(retryRequests.indexOf(retryRequest), 1);
}
internalLoad(config, remainingAttempts);
}, mediaPlayerModel.getRetryIntervalsForType(request.type));
} else {
errHandler.error(new DashJSError(downloadErrorToRequestTypeMap[request.type], request.url + ' is not available', {request: request, response: httpRequest.response}));
if (config.error) {
config.error(request, 'error', httpRequest.response.statusText);
}
if (config.complete) {
config.complete(request, httpRequest.response.statusText);
}
}
}
};
const progress = function (event) {
const currentTime = new Date();
if (firstProgress) {
firstProgress = false;
if (!event.lengthComputable ||
(event.lengthComputable && event.total !== event.loaded)) {
request.firstByteDate = currentTime;
}
}
if (event.lengthComputable) {
request.bytesLoaded = event.loaded;
request.bytesTotal = event.total;
}
if (!event.noTrace) {
traces.push({
s: lastTraceTime,
d: event.time ? event.time : currentTime.getTime() - lastTraceTime.getTime(),
b: [event.loaded ? event.loaded - lastTraceReceivedCount : 0]
});
lastTraceTime = currentTime;
lastTraceReceivedCount = event.loaded;
}
if (config.progress && event) {
config.progress(event);
}
};
const onload = function () {
if (httpRequest.response.status >= 200 && httpRequest.response.status <= 299) {
handleLoaded(true);
if (config.success) {
config.success(httpRequest.response.response, httpRequest.response.statusText, httpRequest.response.responseURL);
}
if (config.complete) {
config.complete(request, httpRequest.response.statusText);
}
}
};
const onabort = function () {
if (config.abort) {
config.abort(request);
}
};
let loader;
if (useFetch && window.fetch && request.responseType === 'arraybuffer' && request.type === HTTPRequest.MEDIA_SEGMENT_TYPE) {
loader = FetchLoader(context).create({
requestModifier: requestModifier,
boxParser: boxParser
});
} else {
loader = XHRLoader(context).create({
requestModifier: requestModifier
});
}
const modifiedUrl = requestModifier.modifyRequestURL(request.url);
const verb = request.checkExistenceOnly ? HTTPRequest.HEAD : HTTPRequest.GET;
const withCredentials = mediaPlayerModel.getXHRWithCredentialsForType(request.type);
httpRequest = {
url: modifiedUrl,
method: verb,
withCredentials: withCredentials,
request: request,
onload: onload,
onend: onloadend,
onerror: onloadend,
progress: progress,
onabort: onabort,
loader: loader
};
// Adds the ability to delay single fragment loading time to control buffer.
let now = new Date().getTime();
if (isNaN(request.delayLoadingTime) || now >= request.delayLoadingTime) {
// no delay - just send
requests.push(httpRequest);
loader.load(httpRequest);
} else {
// delay
let delayedRequest = { httpRequest: httpRequest };
delayedRequests.push(delayedRequest);
delayedRequest.delayTimeout = setTimeout(function () {
if (delayedRequests.indexOf(delayedRequest) === -1) {
return;
} else {
delayedRequests.splice(delayedRequests.indexOf(delayedRequest), 1);
}
try {
requestStartTime = new Date();
lastTraceTime = requestStartTime;
requests.push(delayedRequest.httpRequest);
loader.load(delayedRequest.httpRequest);
} catch (e) {
delayedRequest.httpRequest.onerror();
}
}, (request.delayLoadingTime - now));
}
}
/**
* Initiates a download of the resource described by config.request
* @param {Object} config - contains request (FragmentRequest or derived type), and callbacks
* @memberof module:HTTPLoader
* @instance
*/
function load(config) {
if (config.request) {
internalLoad(
config,
mediaPlayerModel.getRetryAttemptsForType(
config.request.type
)
);
} else {
if (config.error) {
config.error(config.request, 'error');
}
}
}
/**
* Aborts any inflight downloads
* @memberof module:HTTPLoader
* @instance
*/
function abort() {
retryRequests.forEach(t => {
clearTimeout(t.timeout);
// abort request in order to trigger LOADING_ABANDONED event
if (t.config.request && t.config.abort) {
t.config.abort(t.config.request);
}
});
retryRequests = [];
delayedRequests.forEach(x => clearTimeout(x.delayTimeout));
delayedRequests = [];
requests.forEach(x => {
// abort will trigger onloadend which we don't want
// when deliberately aborting inflight requests -
// set them to undefined so they are not called
x.onloadend = x.onerror = x.onprogress = undefined;
x.loader.abort(x);
});
requests = [];
}
instance = {
load: load,
abort: abort
};
setup();
return instance;
}
HTTPLoader.__dashjs_factory_name = 'HTTPLoader';
const factory = FactoryMaker.getClassFactory(HTTPLoader);
export default factory;
| 30,973
|
https://github.com/jexenberger/codestreamparent/blob/master/codestream-di/src/test/kotlin/io/codestream/di/runtime/ComponentDefinitionTest.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
codestreamparent
|
jexenberger
|
Kotlin
|
Code
| 156
| 428
|
/*
* Copyright 2018 Julian Exenberger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* `* `[`http://www.apache.org/licenses/LICENSE-2.0`](http://www.apache.org/licenses/LICENSE-2.0)
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.codestream.di.runtime
import io.codestream.di.api.*
import io.codestream.di.sample.AnotherObject
import io.codestream.di.sample.SampleObject
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class ComponentDefinitionTest {
private val ctx = DefaultApplicationContext()
private val anotherObject = AnotherObject()
@BeforeEach
fun beforeAll() {
SingletonScope.clear()
InstanceScope.clear()
bind(theInstance(anotherObject)) into ctx
}
@Test
fun testCreate() {
val def = ComponentDefinition<SampleObject>(ConstructorInjection(SampleObject::class), id(SampleObject::class))
val result = def.instance(ctx)
assertNotNull(result)
assertEquals(anotherObject, result.anotherObject)
assertEquals(anotherObject, result.injected)
}
}
| 36,805
|
https://github.com/thinkdolabs/tailwindui-crawler/blob/master/output-vue/components/application-ui/elements/avatars/circular_avatars_with_placeholder_initials.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
tailwindui-crawler
|
thinkdolabs
|
Vue
|
Code
| 82
| 326
|
<template>
<span class="inline-flex items-center justify-center h-6 w-6 rounded-full bg-gray-500">
<span class="text-xs font-medium leading-none text-white">TW</span>
</span>
<span class="inline-flex items-center justify-center h-8 w-8 rounded-full bg-gray-500">
<span class="text-sm font-medium leading-none text-white">TW</span>
</span>
<span class="inline-flex items-center justify-center h-10 w-10 rounded-full bg-gray-500">
<span class="font-medium leading-none text-white">TW</span>
</span>
<span class="inline-flex items-center justify-center h-12 w-12 rounded-full bg-gray-500">
<span class="text-lg font-medium leading-none text-white">TW</span>
</span>
<span class="inline-flex items-center justify-center h-14 w-14 rounded-full bg-gray-500">
<span class="text-xl font-medium leading-none text-white">TW</span>
</span>
</template>
<script>
export default {
data: () => ({
})
}
</script>
| 48,500
|
https://github.com/nikitabu/drudeLorentz/blob/master/node_modules/mathjs/lib/function/construction/string.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
drudeLorentz
|
nikitabu
|
JavaScript
|
Code
| 182
| 471
|
'use strict';
module.exports = function (math) {
var util = require('../../util/index'),
collection = require('../../type/collection'),
number = util.number,
isNumber = util.number.isNumber,
isCollection = collection.isCollection;
/**
* Create a string or convert any object into a string.
* Elements of Arrays and Matrices are processed element wise.
*
* Syntax:
*
* math.string(value)
*
* Examples:
*
* math.string(4.2); // returns string '4.2'
* math.string(math.complex(3, 2); // returns string '3 + 2i'
*
* var u = math.unit(5, 'km');
* math.string(u.to('m')); // returns string '5000 m'
*
* math.string([true, false]); // returns ['true', 'false']
*
* See also:
*
* bignumber, boolean, complex, index, matrix, number, unit
*
* @param {* | Array | Matrix | null} [value] A value to convert to a string
* @return {String | Array | Matrix} The created string
*/
math.string = function string (value) {
switch (arguments.length) {
case 0:
return '';
case 1:
if (isNumber(value)) {
return number.format(value);
}
if (isCollection(value)) {
return collection.deepMap(value, string);
}
if (value === null) {
return 'null';
}
return value.toString();
default:
throw new math.error.ArgumentsError('string', arguments.length, 0, 1);
}
};
};
| 32,425
|
https://github.com/SaeedAhmadSD7/muscleUp/blob/master/resources/views/muscle-up-app/trainee/workoutProgram/workoutProgram.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
muscleUp
|
SaeedAhmadSD7
|
PHP
|
Code
| 157
| 862
|
@extends('layouts.backend-main')
@section('title','Progress')
@section('style-sheet')
@stop
@section('page-heading')
<h2>Workout Program</h2>
<p>View Workout Program</p>
@stop
@section('content')
<div class="panel">
<div class="panel-body">
<div class="example-box-wrapper">
<div class="form-wizard" id="form-wizard-3">
@if($phase_daycount)
<form class="workout-program form-horizontal bordered-row" action="">
<div class="tab-content">
<h3 class="content-box-header bg-default">Activity Mark Progress</h3>
<div class="form-group first-group">
<label class="col-sm-3 control-label">Program Name</label>
<div class="col-sm-6">
<span class="form-control">{{$trainee->allocation->program->title}}</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Phase Name</label>
<div class="col-sm-6">
<select class="phase_list form-control" name="">
@for($i = 0; $i < count($trainee->allocation->program->phase); $i++)
<option value="{{$trainee->allocation->program->phase[$i]->id}}" data-value="{{$phase_daycount[$i]}}" data-order="{{$i}}">{{$trainee->allocation->program->phase[$i]->title}}</option>
@endfor
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Day Name</label>
<div class="col-sm-6">
<select class="day_list form-control" name="">
@foreach($p_day as $day)
<option>{{$day}}</option>
@endforeach </select>
</div>
</div>
<div class="form-group date-div">
<label class="col-sm-3 control-label">Date</label>
<div class="col-sm-6">
<input type="hidden" class="start_date" value="{{$trainee->allocation->start_date}}">
<input class="calc_date" type="hidden" value="">
<span class="form-control date-span"> {{$trainee->allocation->start_date}} </span>
</div>
</div>
<div class="form-group wbs"></div>
</div>
</form>
@else
<div class="tab-content">
<h3 class="content-box-header bg-default">Workout Program</h3>
<fieldset>
<div class="form-group first-group">
<div class="col-sm-6 col-sm-offset-3">
No Workout program has been allocated.
</div>
</div>
</fieldset>
</div>
@endif
</div>
</div>
</div>
</div>
@stop
@section('script')
<script src="{{url('/admin-assets/js/workoutProgramView.js')}}" type="text/javascript"></script>
@stop
| 46,714
|
https://github.com/GEOS-ESM/MAPL/blob/master/generic/StringCompositeMap.F90
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-warranty-disclaimer, LicenseRef-scancode-unknown-license-reference
| 2,023
|
MAPL
|
GEOS-ESM
|
Fortran Free Form
|
Code
| 28
| 115
|
module mapl_StringCompositeMap
use mapl_AbstractComposite
#include "types/key_deferredLengthString.inc"
#define _value class(AbstractComposite)
#define _value_allocatable class(AbstractComposite)
#define _map StringCompositeMap
#define _iterator StringCompositeMapIterator
#define _pair StringCompositePair
#define _alt
#include "templates/map.inc"
end module mapl_StringCompositeMap
| 25,694
|
https://github.com/didi/daedalus/blob/master/daedalus-server/src/main/java/com/didichuxing/daedalus/dal/InstanceDal.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
daedalus
|
didi
|
Java
|
Code
| 289
| 1,389
|
package com.didichuxing.daedalus.dal;
import com.didichuxing.daedalus.common.enums.InstanceTypeEnum;
import com.didichuxing.daedalus.common.enums.StatusEnum;
import com.didichuxing.daedalus.entity.instance.InstanceEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.List;
/**
* @author : jiangxinyu
* @date : 2020/4/16
*/
@Repository
public class InstanceDal {
@Autowired
private MongoTemplate mongoTemplate;
public Page<InstanceEntity> list(String instanceType, int page, int pageSize, String name, String ip) {
PageRequest pageRequest = PageRequest.of(page, pageSize);
Query query = basicQuery().addCriteria(typeCriteria(instanceType)).with(pageRequest).with(sortByTime());
if (StringUtils.isNotBlank(name)) {
query.addCriteria(like("name", name));
}
if (StringUtils.isNotBlank(ip)) {
if ("http".equalsIgnoreCase(instanceType)) {
query.addCriteria(like("url", ip));
} else {
query.addCriteria(like("ip", ip));
}
}
List<InstanceEntity> instanceEntities = mongoTemplate.find(query, InstanceEntity.class);
return new PageImpl<>(instanceEntities, pageRequest, countByType(instanceType));
}
public long countByType(String insType) {
return mongoTemplate.count(basicQuery().addCriteria(typeCriteria(insType)), InstanceEntity.class);
}
public void delete(String instanceId) {
Update update = Update.update("status", StatusEnum.DELETED);
mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(instanceId)), update, InstanceEntity.class);
}
public InstanceEntity save(InstanceEntity entity) {
if (entity.getId() != null) {
return update(entity);
}
return mongoTemplate.insert(entity);
}
public InstanceEntity findById(String instanceId) {
return mongoTemplate.findById(instanceId, InstanceEntity.class);
}
public List<InstanceEntity> findByIds(Collection<String> instanceIds) {
Query query = Query.query(Criteria.where("_id").in(instanceIds));
return mongoTemplate.find(query, InstanceEntity.class);
}
public InstanceEntity update(InstanceEntity entity) {
Query query = Query.query(Criteria.where("_id").is(entity.getId()));
Update update = Update.update("name", entity.getName())
.set("ip", entity.getIp())
.set("port", entity.getPort())
.set("username", entity.getUsername())
.set("database", entity.getDatabase())
.set("protocol", entity.getProtocol())
.set("method", entity.getMethod())
.set("url", entity.getUrl())
.set("timeout", entity.getTimeout())
.set("body", entity.getBody())
.set("bodyType", entity.getBodyType())
.set("formData", entity.getFormData())
.set("headers", entity.getHeaders())
.set("cookies", entity.getCookies())
.set("urlParams", entity.getUrlParams())
.set("cookieText", entity.getCookieText());
if (entity.getPassword() != null && StringUtils.isNotBlank(entity.getPassword().replace("*", ""))) {
update.set("password", entity.getPassword());
}
return mongoTemplate.update(InstanceEntity.class)
.matching(query).apply(update)
.withOptions(FindAndModifyOptions.options().upsert(true))
.findAndModifyValue();
}
public InstanceEntity findByIdAndType(String instanceId, InstanceTypeEnum instanceType) {
final Query query = basicQuery().addCriteria(Criteria.where("_id").is(instanceId)).addCriteria(typeCriteria(instanceType.name()));
return mongoTemplate.findOne(query, InstanceEntity.class);
}
private Sort sortByTime() {
return Sort.by(Sort.Order.desc("createTime"));
}
private Query basicQuery() {
Criteria criteria = Criteria.where("status").is(StatusEnum.OK);
return new Query(criteria);
}
private Criteria typeCriteria(String instanceType) {
return Criteria.where("instanceType").is(instanceType);
}
private Criteria like(String filed, String value) {
return Criteria.where(filed).regex(".*" + value + ".*");
}
}
| 49,023
|
https://github.com/christocs/ICT397/blob/master/shader/default.vert
|
Github Open Source
|
Open Source
|
ISC
| null |
ICT397
|
christocs
|
GLSL
|
Code
| 60
| 158
|
#version 410 core
layout (location = 0) in vec3 in_pos;
layout (location = 1) in vec3 in_normal;
layout (location = 2) in vec2 in_uvs;
uniform struct Matrices {
mat4 model;
mat4 view;
mat4 projection;
} u_matrices;
out VertexData {
vec2 uvs;
} o;
void main() {
o.uvs = in_uvs;
gl_Position = u_matrices.projection * u_matrices.view * u_matrices.model * vec4(in_pos, 1.0);
}
| 12,468
|
https://github.com/adityavs/ant/blob/master/src/tests/junit/org/apache/tools/ant/types/PathTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
ant
|
adityavs
|
Java
|
Code
| 1,871
| 6,329
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.tools.ant.types;
import java.io.File;
import java.util.Locale;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.condition.Os;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.Matchers.endsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* JUnit testcases for org.apache.tools.ant.types.Path
*
*/
public class PathTest {
public static boolean isUnixStyle = File.pathSeparatorChar == ':';
public static boolean isNetWare = Os.isFamily("netware");
private Project project;
private Path p;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void setUp() {
project = new Project();
if (System.getProperty("root") != null) {
project.setBasedir(System.getProperty("root"));
}
p = new Path(project);
}
// actually tests constructor as well as setPath
@Test
public void testConstructorUnixStyle() {
p = new Path(project, "/a:/b");
String[] l = p.list();
assertEquals("two items, Unix style", 2, l.length);
if (isUnixStyle) {
assertEquals("/a", l[0]);
assertEquals("/b", l[1]);
} else if (isNetWare) {
assertEquals("\\a", l[0]);
assertEquals("\\b", l[1]);
} else {
String base = new File(File.separator).getAbsolutePath();
assertEquals(base + "a", l[0]);
assertEquals(base + "b", l[1]);
}
}
@Test
public void testRelativePathUnixStyle() {
project.setBasedir(new File(project.getBaseDir(), "src/etc").getAbsolutePath());
p = new Path(project, "..:testcases");
String[] l = p.list();
assertEquals("two items, Unix style", 2, l.length);
if (isUnixStyle) {
assertThat("test resolved relative to src/etc",
l[0], endsWith("/src"));
assertThat("test resolved relative to src/etc",
l[1], endsWith("/src/etc/testcases"));
} else if (isNetWare) {
assertThat("test resolved relative to src/etc",
l[0], endsWith("\\src"));
assertThat("test resolved relative to src/etc",
l[1], endsWith("\\src\\etc\\testcases"));
} else {
assertThat("test resolved relative to src/etc",
l[0], endsWith("\\src"));
assertThat("test resolved relative to src/etc",
l[1], endsWith("\\src\\etc\\testcases"));
}
}
@Test
public void testConstructorWindowsStyleTwoItemsNoDrive() {
p = new Path(project, "\\a;\\b");
String[] l = p.list();
assertEquals("two items, DOS style", 2, l.length);
if (isUnixStyle) {
assertEquals("/a", l[0]);
assertEquals("/b", l[1]);
} else if (isNetWare) {
assertEquals("\\a", l[0]);
assertEquals("\\b", l[1]);
} else {
String base = new File(File.separator).getAbsolutePath();
assertEquals(base + "a", l[0]);
assertEquals(base + "b", l[1]);
}
}
@Test
public void testConstructorWindowsStyle() {
p = new Path(project, "c:\\test");
String[] l = p.list();
if (isUnixStyle) {
assertEquals("no drives on Unix", 2, l.length);
assertThat("c resolved relative to project\'s basedir",
l[0], endsWith("/c"));
assertEquals("/test", l[1]);
} else if (isNetWare) {
assertEquals("volumes on NetWare", 1, l.length);
assertEquals("c:\\test", l[0].toLowerCase(Locale.US));
} else {
assertEquals("drives on DOS", 1, l.length);
assertEquals("c:\\test", l[0].toLowerCase(Locale.US));
}
}
@Test
public void testConstructorWindowsStyleTwoItems() {
p = new Path(project, "c:\\test;d:\\programs");
String[] l = p.list();
if (isUnixStyle) {
assertEquals("no drives on Unix", 4, l.length);
assertThat("c resolved relative to project\'s basedir",
l[0], endsWith("/c"));
assertEquals("/test", l[1]);
assertThat("d resolved relative to project\'s basedir",
l[2], endsWith("/d"));
assertEquals("/programs", l[3]);
} else if (isNetWare) {
assertEquals("volumes on NetWare", 2, l.length);
assertEquals("c:\\test", l[0].toLowerCase(Locale.US));
assertEquals("d:\\programs", l[1].toLowerCase(Locale.US));
} else {
assertEquals("drives on DOS", 2, l.length);
assertEquals("c:\\test", l[0].toLowerCase(Locale.US));
assertEquals("d:\\programs", l[1].toLowerCase(Locale.US));
}
}
@Test
public void testConstructorWindowsStyleUnixFS() {
p = new Path(project, "c:/test");
String[] l = p.list();
if (isUnixStyle) {
assertEquals("no drives on Unix", 2, l.length);
assertThat("c resolved relative to project\'s basedir",
l[0], endsWith("/c"));
assertEquals("/test", l[1]);
} else if (isNetWare) {
assertEquals("volumes on NetWare", 1, l.length);
assertEquals("c:\\test", l[0].toLowerCase(Locale.US));
} else {
assertEquals("drives on DOS", 1, l.length);
assertEquals("c:\\test", l[0].toLowerCase(Locale.US));
}
}
@Test
public void testConstructorWindowsStyleUnixFSTwoItems() {
p = new Path(project, "c:/test;d:/programs");
String[] l = p.list();
if (isUnixStyle) {
assertEquals("no drives on Unix", 4, l.length);
assertThat("c resolved relative to project\'s basedir",
l[0], endsWith("/c"));
assertEquals("/test", l[1]);
assertThat("d resolved relative to project\'s basedir",
l[2], endsWith("/d"));
assertEquals("/programs", l[3]);
} else if (isNetWare) {
assertEquals("volumes on NetWare", 2, l.length);
assertEquals("c:\\test", l[0].toLowerCase(Locale.US));
assertEquals("d:\\programs", l[1].toLowerCase(Locale.US));
} else {
assertEquals("drives on DOS", 2, l.length);
assertEquals("c:\\test", l[0].toLowerCase(Locale.US));
assertEquals("d:\\programs", l[1].toLowerCase(Locale.US));
}
}
// try a netware-volume length path, see how it is handled
@Test
public void testConstructorNetWareStyle() {
p = new Path(project, "sys:\\test");
String[] l = p.list();
if (isUnixStyle) {
assertEquals("no drives on Unix", 2, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("/sys"));
assertEquals("/test", l[1]);
} else if (isNetWare) {
assertEquals("sys:\\test", l[0].toLowerCase(Locale.US));
assertEquals("volumes on NetWare", 1, l.length);
} else {
assertEquals("no multiple character-length volumes on Windows", 2, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("\\sys"));
assertThat("test resolved relative to project\'s basedir",
l[1], endsWith("\\test"));
}
}
// try a multi-part netware-volume length path, see how it is handled
@Test
public void testConstructorNetWareStyleTwoItems() {
p = new Path(project, "sys:\\test;dev:\\temp");
String[] l = p.list();
if (isUnixStyle) {
assertEquals("no drives on Unix", 4, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("/sys"));
assertEquals("/test", l[1]);
assertThat("dev resolved relative to project\'s basedir",
l[2], endsWith("/dev"));
assertEquals("/temp", l[3]);
} else if (isNetWare) {
assertEquals("volumes on NetWare", 2, l.length);
assertEquals("sys:\\test", l[0].toLowerCase(Locale.US));
assertEquals("dev:\\temp", l[1].toLowerCase(Locale.US));
} else {
assertEquals("no multiple character-length volumes on Windows", 4, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("\\sys"));
assertThat("test resolved relative to project\'s basedir",
l[1], endsWith("\\test"));
assertThat("dev resolved relative to project\'s basedir",
l[2], endsWith("\\dev"));
assertThat("temp resolved relative to project\'s basedir",
l[3], endsWith("\\temp"));
}
}
// try a netware-volume length path w/forward slash, see how it is handled
@Test
public void testConstructorNetWareStyleUnixFS() {
p = new Path(project, "sys:/test");
String[] l = p.list();
if (isUnixStyle) {
assertEquals("no drives on Unix", 2, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("/sys"));
assertEquals("/test", l[1]);
} else if (isNetWare) {
assertEquals("volumes on NetWare", 1, l.length);
assertEquals("sys:\\test", l[0].toLowerCase(Locale.US));
} else {
assertEquals("no multiple character-length volumes on Windows", 2, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("\\sys"));
assertThat("test resolved relative to project\'s basedir",
l[1], endsWith("\\test"));
}
}
// try a multi-part netware-volume length path w/forward slash, see how it is handled
@Test
public void testConstructorNetWareStyleUnixFSTwoItems() {
p = new Path(project, "sys:/test;dev:/temp");
String[] l = p.list();
if (isUnixStyle) {
assertEquals("no drives on Unix", 4, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("/sys"));
assertEquals("/test", l[1]);
assertThat("dev resolved relative to project\'s basedir",
l[2], endsWith("/dev"));
assertEquals("/temp", l[3]);
} else if (isNetWare) {
assertEquals("volumes on NetWare", 2, l.length);
assertEquals("sys:\\test", l[0].toLowerCase(Locale.US));
assertEquals("dev:\\temp", l[1].toLowerCase(Locale.US));
} else {
assertEquals("no multiple character-length volumes on Windows", 4, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("\\sys"));
assertThat("test resolved relative to project\'s basedir",
l[1], endsWith("\\test"));
assertThat("dev resolved relative to project\'s basedir",
l[2], endsWith("\\dev"));
assertThat("temp resolved relative to project\'s basedir",
l[3], endsWith("\\temp"));
}
}
// try a multi-part netware-volume length path with UNIX
// separator (this testcase if from an actual bug that was
// found, in AvailableTest, which uses PathTokenizer)
@Test
public void testConstructorNetWareStyleUnixPS() {
p = new Path(project, "SYS:\\JAVA/lib/rt.jar:SYS:\\JAVA/lib/classes.zip");
String[] l = p.list();
if (isUnixStyle) {
assertEquals("no drives on Unix", 3, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("/SYS"));
assertEquals("/JAVA/lib/rt.jar", l[1]);
assertEquals("/JAVA/lib/classes.zip", l[2]);
} else if (isNetWare) {
assertEquals("volumes on NetWare", 2, l.length);
assertEquals("sys:\\java\\lib\\rt.jar", l[0].toLowerCase(Locale.US));
assertEquals("sys:\\java\\lib\\classes.zip", l[1].toLowerCase(Locale.US));
} else {
assertEquals("no multiple character-length volumes on Windows", 3, l.length);
assertThat("sys resolved relative to project\'s basedir",
l[0], endsWith("\\SYS"));
assertThat("java/lib/rt.jar resolved relative to project\'s basedir",
l[1], endsWith("\\JAVA\\lib\\rt.jar"));
assertThat("java/lib/classes.zip resolved relative to project\'s basedir",
l[2], endsWith("\\JAVA\\lib\\classes.zip"));
}
}
@Test
public void testConstructorMixedStyle() {
p = new Path(project, "\\a;\\b:/c");
String[] l = p.list();
assertEquals("three items, mixed style", 3, l.length);
if (isUnixStyle) {
assertEquals("/a", l[0]);
assertEquals("/b", l[1]);
assertEquals("/c", l[2]);
} else if (isNetWare) {
assertEquals("\\a", l[0]);
assertEquals("\\b", l[1]);
assertEquals("\\c", l[2]);
} else {
String base = new File(File.separator).getAbsolutePath();
assertEquals(base + "a", l[0]);
assertEquals(base + "b", l[1]);
assertEquals(base + "c", l[2]);
}
}
@Test
public void testSetLocation() {
p.setLocation(new File(File.separatorChar + "a"));
String[] l = p.list();
if (isUnixStyle) {
assertEquals(1, l.length);
assertEquals("/a", l[0]);
} else if (isNetWare) {
assertEquals(1, l.length);
assertEquals("\\a", l[0]);
} else {
assertEquals(1, l.length);
assertEquals(":\\a", l[0].substring(1));
}
}
@Test
public void testAppending() {
p = new Path(project, "/a:/b");
String[] l = p.list();
assertEquals("2 after construction", 2, l.length);
p.setLocation(new File("/c"));
l = p.list();
assertEquals("3 after setLocation", 3, l.length);
p.setPath("\\d;\\e");
l = p.list();
assertEquals("5 after setPath", 5, l.length);
p.append(new Path(project, "\\f"));
l = p.list();
assertEquals("6 after append", 6, l.length);
p.createPath().setLocation(new File("/g"));
l = p.list();
assertEquals("7 after append", 7, l.length);
}
@Test
public void testEmptyPath() {
p = new Path(project, "");
String[] l = p.list();
assertEquals("0 after construction", 0, l.length);
p.setPath("");
l = p.list();
assertEquals("0 after setPath", 0, l.length);
p.append(new Path(project));
l = p.list();
assertEquals("0 after append", 0, l.length);
p.createPath();
l = p.list();
assertEquals("0 after append", 0, l.length);
}
@Test
public void testUnique() {
p = new Path(project, "/a:/a");
String[] l = p.list();
assertEquals("1 after construction", 1, l.length);
String base = new File(File.separator).getAbsolutePath();
p.setLocation(new File(base, "a"));
l = p.list();
assertEquals("1 after setLocation", 1, l.length);
p.setPath("\\a;/a");
l = p.list();
assertEquals("1 after setPath", 1, l.length);
p.append(new Path(project, "/a;\\a:\\a"));
l = p.list();
assertEquals("1 after append", 1, l.length);
p.createPath().setPath("\\a:/a");
l = p.list();
assertEquals("1 after append", 1, l.length);
}
@Test
public void testEmptyElementSetRefid() {
thrown.expect(BuildException.class);
thrown.expectMessage("You must not specify more than one attribute when using refid");
p = new Path(project, "/a:/a");
p.setRefid(new Reference(project, "dummyref"));
}
@Test
public void testEmptyElementSetLocationThenRefid() {
thrown.expect(BuildException.class);
thrown.expectMessage("You must not specify more than one attribute when using refid");
p.setLocation(new File("/a"));
p.setRefid(new Reference(project, "dummyref"));
}
@Test
public void testUseExistingRefid() {
thrown.expect(BuildException.class);
thrown.expectMessage("You must not specify more than one attribute when using refid");
Path another = new Path(project, "/a:/a");
project.addReference("dummyref", another);
p.setRefid(new Reference(project, "dummyref"));
p.setLocation(new File("/a"));
}
@Test
public void testEmptyElementIfIsReferenceAttr() {
thrown.expect(BuildException.class);
thrown.expectMessage("You must not specify more than one attribute when using refid");
p.setRefid(new Reference(project, "dummyref"));
p.setPath("/a;\\a");
}
@Test
public void testEmptyElementCreatePath() {
thrown.expect(BuildException.class);
thrown.expectMessage("You must not specify nested elements when using refid");
p.setRefid(new Reference(project, "dummyref"));
p.createPath();
}
@Test
public void testEmptyElementCreatePathElement() {
thrown.expect(BuildException.class);
thrown.expectMessage("You must not specify nested elements when using refid");
p.setRefid(new Reference(project, "dummyref"));
p.createPathElement();
}
@Test
public void testEmptyElementAddFileset() {
thrown.expect(BuildException.class);
thrown.expectMessage("You must not specify nested elements when using refid");
p.setRefid(new Reference(project, "dummyref"));
p.addFileset(new FileSet());
}
@Test
public void testEmptyElementAddFilelist() {
thrown.expect(BuildException.class);
thrown.expectMessage("You must not specify nested elements when using refid");
p.setRefid(new Reference(project, "dummyref"));
p.addFilelist(new FileList());
}
@Test
public void testEmptyElementAddDirset() {
thrown.expect(BuildException.class);
thrown.expectMessage("You must not specify nested elements when using refid");
p.setRefid(new Reference(project, "dummyref"));
p.addDirset(new DirSet());
}
@Test
public void testCircularReferenceCheck() {
thrown.expect(BuildException.class);
thrown.expectMessage("This data type contains a circular reference.");
project.addReference("dummy", p);
p.setRefid(new Reference(project, "dummy"));
p.list();
}
@Test
public void testLoopReferenceCheck() {
// dummy1 --> dummy2 --> dummy3 --> dummy1
thrown.expect(BuildException.class);
thrown.expectMessage("This data type contains a circular reference.");
project.addReference("dummy1", p);
Path pa = p.createPath();
project.addReference("dummy2", pa);
Path pb = pa.createPath();
project.addReference("dummy3", pb);
pb.setRefid(new Reference(project, "dummy1"));
p.list();
}
@Test
public void testLoopReferenceCheckWithLocation() {
// dummy1 --> dummy2 --> dummy3 (with Path "/a")
project.addReference("dummy1", p);
Path pa = p.createPath();
project.addReference("dummy2", pa);
Path pb = pa.createPath();
project.addReference("dummy3", pb);
pb.setLocation(new File("/a"));
String[] l = p.list();
assertEquals("One element buried deep inside a nested path structure",
1, l.length);
if (isUnixStyle) {
assertEquals("/a", l[0]);
} else if (isNetWare) {
assertEquals("\\a", l[0]);
} else {
assertEquals(":\\a", l[0].substring(1));
}
}
@Test
public void testFileList() {
FileList f = new FileList();
f.setProject(project);
f.setDir(project.resolveFile("."));
f.setFiles("build.xml");
p.addFilelist(f);
String[] l = p.list();
assertEquals(1, l.length);
assertEquals(project.resolveFile("build.xml").getAbsolutePath(), l[0]);
}
@Test
public void testFileSet() {
FileSet f = new FileSet();
f.setProject(project);
f.setDir(project.resolveFile("."));
f.setIncludes("build.xml");
p.addFileset(f);
String[] l = p.list();
assertEquals(1, l.length);
assertEquals(project.resolveFile("build.xml").getAbsolutePath(), l[0]);
}
@Test
public void testDirSet() {
DirSet d = new DirSet();
d.setProject(project);
d.setDir(project.resolveFile("."));
d.setIncludes("build");
p.addDirset(d);
String[] l = p.list();
assertEquals(1, l.length);
assertEquals(project.resolveFile("build").getAbsolutePath(), l[0]);
}
@Test
public void testRecursion() {
thrown.expect(BuildException.class);
thrown.expectMessage("circular");
try {
p.append(p);
} finally {
assertEquals(0, p.list().length);
}
}
}
| 33,387
|
https://github.com/millerf1234/OpenGL_Windows_Projects/blob/master/OpenGL_GLFW_Project/FSMRenderEngine.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
OpenGL_Windows_Projects
|
millerf1234
|
C++
|
Code
| 9
| 51
|
#include "FSMRenderEngine.h"
//FSMRenderEngine::FSMRenderEngine() {
//
//}
FSMRenderEngine::~FSMRenderEngine() {
}
| 36,160
|
https://github.com/ArtiomKolesnikov/WomanInterest/blob/master/app/Http/Controllers/CosmeticsController.php
|
Github Open Source
|
Open Source
|
MIT
| null |
WomanInterest
|
ArtiomKolesnikov
|
PHP
|
Code
| 106
| 493
|
<?php
namespace App\Http\Controllers;
use App\Post;
use Falur\Breadcrumbs\BreadcrumbsItem;
use Falur\Breadcrumbs\Contracts\Breadcrumbs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Symfony\Component\HttpFoundation\Session\Session;
class CosmeticsController extends Controller
{
public function index()
{
$all_posts = Post::all();
return view('cosmetics.index',compact('all_posts'));
}
public function post(Post $post, Breadcrumbs $breadcrumbs)
{
$breadcrumbs->addArray([
new BreadcrumbsItem('Главная', route('main')),
new BreadcrumbsItem('Косметика', route('cosmetics')),
]);
return view('cosmetics.post',compact('post'));
}
public function create(Breadcrumbs $breadcrumbs)
{
$breadcrumbs->addArray([
new BreadcrumbsItem('Главная', route('main')),
new BreadcrumbsItem('Личный кабинет', route('home')),
]);
$post = new Post;
return view('cosmetics.create',compact('post'));
}
public function post_create(Request $request)
{
$newPost = new Post;
// $newPost->fill(Input::all());
$newPost->company_name = $request->company_name;
$newPost->title = $request->title;
$newPost->content = $request->content;
$newPost->save();
Session::flash('success','Пост добавлен');
return redirect(route('cosmetics'));
}
public function post_edit(Request $request, Post $post)
{
return view('cosmetics.update',compact('post'));
}
}
| 43,872
|
https://github.com/delaco/Argo/blob/master/src/Argo/Commands/CommandInvokerCache.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Argo
|
delaco
|
C#
|
Code
| 98
| 302
|
using System.Collections.Concurrent;
namespace Argo.Commands
{
public class CommandInvokerCache
{
private readonly ICommandDescriptorCollectionProvider _collectionProvider;
private volatile InnerCache _currentCache;
public CommandInvokerCache(ICommandDescriptorCollectionProvider collectionProvider)
{
_collectionProvider = collectionProvider;
}
private InnerCache CurrentCache
{
get
{
var current = _currentCache;
_ = _collectionProvider.CommandDescriptors;
if (current == null)
{
current = new InnerCache();
_currentCache = current;
}
return current;
}
}
public object Get(CommandContext commandContext)
{
var cache = CurrentCache;
var commandDescriptor = commandContext?.CommandDescriptor;
if (!cache.Entries.TryGetValue(commandDescriptor, out _))
{
}
else
{
}
return null;
}
private class InnerCache
{
public ConcurrentDictionary<CommandDescriptor, CommandInvokerCacheEntry> Entries { get; } =
new ConcurrentDictionary<CommandDescriptor, CommandInvokerCacheEntry>();
}
}
}
| 26,357
|
https://github.com/callpraths/explore-georust/blob/master/harness/src/bin/area_numerical_stability.rs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
explore-georust
|
callpraths
|
Rust
|
Code
| 450
| 1,648
|
use geo::{
algorithm::area::Area, map_coords::MapCoords, CoordFloat, CoordNum, Coordinate, LineString,
Polygon,
};
use geos::{Geom, Geometry};
use serde::Serialize;
use std::f64::consts::PI;
fn main() {
let polygon = {
const NUM_VERTICES: usize = 10;
const ANGLE_INC: f64 = 2. * PI / NUM_VERTICES as f64;
const RADIUS: f64 = 10.;
Polygon::new(
(0..NUM_VERTICES)
.map(|i| {
let angle = i as f64 * ANGLE_INC;
Coordinate {
x: RADIUS * angle.cos(),
y: RADIUS * angle.sin(),
}
})
.collect::<Vec<_>>()
.into(),
vec![],
)
};
let shifts = (0..64)
.map(f64::from)
.map(|i| 1.5 * i.exp2())
.collect::<Vec<f64>>();
let shift_angles = [0., PI / 8., PI / 4., PI * 3. / 8., PI / 2.];
let series = compute_series(&polygon, &shifts, &shift_angles);
println!("{}", serde_json::to_string_pretty(&series).unwrap());
}
#[derive(Serialize)]
struct Series {
pub angle: f64,
pub data: Vec<Datum>,
}
#[derive(Serialize)]
struct Datum {
pub shift: f64,
pub geo: ComputedArea,
pub geos: ComputedArea,
pub naive: ComputedArea,
pub geo_shift_relative_error: f64,
pub naive_geo_relative_error: ComputedArea,
pub geos_geo_relative_error: ComputedArea,
pub geo_geos_relative_error: ComputedArea,
}
#[derive(Serialize)]
struct ComputedArea {
pub original: f64,
pub shifted: f64,
}
fn compute_series(polygon: &Polygon<f64>, shifts: &[f64], angles: &[f64]) -> Vec<Series> {
let mut series: Vec<Series> = Vec::with_capacity(angles.len());
for angle in angles {
let mut data: Vec<Datum> = Vec::with_capacity(shifts.len());
for shift in shifts {
data.push(compute_datum(polygon, *angle, *shift));
}
series.push(Series {
angle: *angle,
data,
})
}
series
}
fn compute_datum(polygon: &Polygon<f64>, angle: f64, shift: f64) -> Datum {
let xshift = shift * angle.cos();
let yshift = shift * angle.sin();
let shifted_polygon = polygon.map_coords(|&(x, y)| (x + xshift, y + yshift));
Datum {
shift,
geo: ComputedArea {
original: geo_area(polygon),
shifted: geo_area(&shifted_polygon),
},
geos: ComputedArea {
original: geos_area(polygon),
shifted: geos_area(&shifted_polygon),
},
naive: ComputedArea {
original: naive_area(polygon),
shifted: naive_area(&shifted_polygon),
},
geo_shift_relative_error: (geo_area(&shifted_polygon) - geo_area(polygon)).abs()
/ geo_area(polygon),
naive_geo_relative_error: ComputedArea {
original: (geo_area(polygon) - naive_area(polygon)).abs() / geo_area(polygon),
shifted: (geo_area(&shifted_polygon) - naive_area(&shifted_polygon)).abs()
/ geo_area(&shifted_polygon),
},
geos_geo_relative_error: ComputedArea {
original: (geo_area(polygon) - geos_area(polygon)).abs() / geo_area(polygon),
shifted: (geo_area(&shifted_polygon) - geos_area(&shifted_polygon)).abs()
/ geos_area(&shifted_polygon),
},
geo_geos_relative_error: ComputedArea {
original: (geo_area(polygon) - geos_area(polygon)).abs() / geos_area(polygon),
shifted: (geo_area(&shifted_polygon) - geos_area(&shifted_polygon)).abs()
/ geos_area(&shifted_polygon),
},
}
}
fn geo_area(polygon: &Polygon<f64>) -> f64 {
polygon.signed_area()
}
fn geos_area(polygon: &Polygon<f64>) -> f64 {
let g: Geometry = polygon.try_into().unwrap();
g.area().unwrap()
}
fn naive_area(polygon: &Polygon<f64>) -> f64 {
get_linestring_area_naive(polygon.exterior())
}
fn get_linestring_area_naive<T>(linestring: &LineString<T>) -> T
where
T: CoordFloat,
{
twice_signed_ring_area(linestring) / (T::one() + T::one())
}
fn twice_signed_ring_area<T>(linestring: &LineString<T>) -> T
where
T: CoordNum,
{
// LineString with less than 3 points is empty, or a
// single point, or is not closed.
if linestring.0.len() < 3 {
return T::zero();
}
// Above test ensures the vector has at least 2 elements.
// We check if linestring is closed, and return 0 otherwise.
if linestring.0.first().unwrap() != linestring.0.last().unwrap() {
return T::zero();
}
let mut tmp = T::zero();
for line in linestring.lines() {
tmp = tmp + line.determinant();
}
tmp
}
| 29,532
|
https://github.com/kubilaycaglayan/Personal-Projects/blob/master/5-javascript/PubSub/user_a.js
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Personal-Projects
|
kubilaycaglayan
|
JavaScript
|
Code
| 38
| 141
|
const PubSub = require('PubSub');
const pubsub = new PubSub();
const onUserAdd = pubsub.subscribe('user_add', (data, topic) => {
console.log('User added');
console.log('user data:', data);
console.log(topic);
});
const published = pubsub.publish('user_add', {
firstName: 'John',
lastName: 'Doe',
email: 'johndoe@gmail.com',
});
console.log(onUserAdd);
console.log(published);
| 24,242
|
https://github.com/ask-community/ask-community-decorators/blob/master/dist/lib/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ask-community-decorators
|
ask-community
|
JavaScript
|
Code
| 36
| 218
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var CanHandleIntentRequest_1 = require("./decorators/CanHandleIntentRequest");
exports.CanHandleIntentRequest = CanHandleIntentRequest_1.CanHandleIntentRequest;
var CanHandleLaunchRequest_1 = require("./decorators/CanHandleLaunchRequest");
exports.CanHandleLaunchRequest = CanHandleLaunchRequest_1.CanHandleLaunchRequest;
var CanHandleSessionEndedRequest_1 = require("./decorators/CanHandleSessionEndedRequest");
exports.CanHandleSessionEndedRequest = CanHandleSessionEndedRequest_1.CanHandleSessionEndedRequest;
var CanHandleSkillEventRequests_1 = require("./decorators/CanHandleSkillEventRequests");
exports.CanHandleSkillEventRequests = CanHandleSkillEventRequests_1.CanHandleSkillEventRequests;
| 28,041
|
https://github.com/PARAGJYOTI/instabuy/blob/master/node_modules/oauth20-provider/test/authorizationCode_checkRefreshTokenGrant.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
instabuy
|
PARAGJYOTI
|
JavaScript
|
Code
| 284
| 1,052
|
var
query = require('querystring'),
request = require('supertest'),
data = require('./server/model/data.js'),
app = require('./server/app.js');
describe('Authorization Code Grant Type ',function() {
before(function() {
app.get('oauth2').model.client.checkGrantType = function(client, grant){
return grant != 'refresh_token';
};
});
after(function(){
app.get('oauth2').model.client.checkGrantType = function(client, grant){
return [];
};
});
var
loginUrl,
authorizationUrl,
cookie,
code,
accessToken;
var cookiePattern = new RegExp('connect.sid=(.*?);');
it('GET /authorization with response_type="code" expect login form redirect', function(done) {
request(app)
.get('/authorization?' + query.stringify({
redirect_uri: data.clients[1].redirectUri,
client_id: data.clients[1].id,
response_type: 'code'
}))
.expect('Location', new RegExp('login'))
.expect(302, function(err, res) {
if (err) return done(err);
loginUrl = res.headers.location;
done();
});
});
it('POST /login expect authorized', function(done) {
request(app)
.post(loginUrl)
.send({ username: data.users[0].username, password: data.users[0].password })
.expect('Location', new RegExp('authorization'))
.expect(302, function(err, res) {
if (err) return done(err);
authorizationUrl = res.headers.location;
cookie = cookiePattern.exec(res.headers['set-cookie'][0])[0];
done();
});
});
it('GET /authorize with response_type="code" expect decision', function(done) {
request(app)
.get(authorizationUrl)
.set('Cookie', cookie)
.expect(200, function(err, res) {
if (err) return done(err);
done();
});
});
it('POST /authorize with response_type="code" and decision="1" expect code redirect', function(done) {
request(app)
.post(authorizationUrl)
.send({ decision: 1 })
.set('Cookie', cookie)
.expect(302, function(err, res) {
if (err) return done(err);
var uri = res.headers.location;
if (uri.indexOf('?') == -1) return done(new Error('Failed to parse redirect uri'));
var q = query.parse(uri.substr(uri.indexOf('?') + 1));
if (!q['code']) return done(new Error('No code value found in redirect uri'));
code = q['code'];
done();
})
});
it('POST /token with grant_type="authorization_code" expect token but not refresh_token', function(done) {
request(app)
.post('/token')
.set('Authorization', 'Basic ' + new Buffer(data.clients[1].id + ':' + data.clients[1].secret, 'ascii').toString('base64'))
.send({grant_type: 'authorization_code', code: code, redirectUri: data.clients[1].redirectUri})
.expect(200)
.expect(function check_no_refresh_token(res){
if(res.body.refresh_token){
throw new Error('refresh_token received')
}
})
.end(function(err, res) {
if (err) return done(err);
accessToken = res.body.access_token;
done();
});
});
it('POST /secure expect authorized', function(done) {
request(app)
.get('/secure')
.set('Authorization', 'Bearer ' + accessToken)
.expect(200, new RegExp(data.users[0].id, 'i'), done);
});
});
| 33,049
|
https://github.com/jpaw/jpaw/blob/master/jpaw-xml/src/main/java/de/jpaw/xml/jaxb/AbstractScaledDecimalAdapter.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
jpaw
|
jpaw
|
Java
|
Code
| 90
| 298
|
package de.jpaw.xml.jaxb;
import java.math.BigDecimal;
import java.math.RoundingMode;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
public abstract class AbstractScaledDecimalAdapter extends XmlAdapter<String, BigDecimal> {
private final boolean allowRounding;
private final int scale;
protected AbstractScaledDecimalAdapter(final int scale, final boolean allowRounding) {
this.scale = scale;
this.allowRounding = allowRounding;
}
private BigDecimal scaleAndRound(final BigDecimal decimal) {
return decimal.setScale(scale, allowRounding ? RoundingMode.HALF_EVEN : RoundingMode.UNNECESSARY);
}
@Override
public BigDecimal unmarshal(final String value) throws Exception {
final BigDecimal decimal = new BigDecimal(value);
if (decimal.signum() == 0)
return BigDecimal.ZERO;
return scaleAndRound(decimal);
}
@Override
public String marshal(final BigDecimal value) throws Exception {
return scaleAndRound(value).toPlainString();
}
}
| 27,869
|
https://github.com/Mifrill/data/blob/master/packages/-ember-data/tests/integration/record-data/record-data-state-test.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
data
|
Mifrill
|
TypeScript
|
Code
| 694
| 2,256
|
import EmberObject from '@ember/object';
import Ember from 'ember';
import { module, test } from 'qunit';
import { Promise } from 'rsvp';
import Model from 'ember-data/model';
import Store from 'ember-data/store';
import { setupTest } from 'ember-qunit';
import { RECORD_DATA_STATE } from '@ember-data/canary-features';
import { attr } from '@ember-data/model';
import JSONAPISerializer from '@ember-data/serializer/json-api';
type RecordData = import('@ember-data/store/-private/ts-interfaces/record-data').RecordData;
type NewRecordIdentifier = import('@ember-data/store/-private/ts-interfaces/identifier').NewRecordIdentifier;
class Person extends Model {
// TODO fix the typing for naked attrs
@attr('string', {})
name;
@attr('string', {})
lastName;
}
class TestRecordIdentifier implements NewRecordIdentifier {
constructor(public id: string | null, public lid: string, public type: string) {}
}
class TestRecordData implements RecordData {
id: string | null = '1';
clientId: string | null = 'test-record-data-1';
modelName = 'tst';
getResourceIdentifier() {
if (this.clientId !== null) {
return new TestRecordIdentifier(this.id, this.clientId, this.modelName);
}
}
commitWasRejected(): void {}
// Use correct interface once imports have been fix
_storeWrapper: any;
pushData(data, calculateChange?: boolean) {}
clientDidCreate() {}
willCommit() {}
isRecordInUse() {
return false;
}
unloadRecord() {}
rollbackAttributes() {
return [];
}
changedAttributes(): any {}
hasChangedAttributes(): boolean {
return false;
}
setDirtyAttribute(key: string, value: any) {}
getAttr(key: string): string {
return 'test';
}
hasAttr(key: string): boolean {
return false;
}
getHasMany(key: string) {
return {};
}
isNew() {
return false;
}
isDeleted() {
return false;
}
addToHasMany(key: string, recordDatas: RecordData[], idx?: number) {}
removeFromHasMany(key: string, recordDatas: RecordData[]) {}
setDirtyHasMany(key: string, recordDatas: RecordData[]) {}
getBelongsTo(key: string) {
return {};
}
setDirtyBelongsTo(name: string, recordData: RecordData | null) {}
didCommit(data) {}
isAttrDirty(key: string) {
return false;
}
removeFromInverseRelationships() {}
_initRecordCreateOptions(options) {
return {};
}
}
let CustomStore = Store.extend({
createRecordDataFor(modelName, id, clientId, storeWrapper) {
return new TestRecordData();
},
});
module('integration/record-data - Record Data State', function (hooks) {
if (!RECORD_DATA_STATE) {
return;
}
setupTest(hooks);
let store;
hooks.beforeEach(function () {
let { owner } = this;
owner.register('model:person', Person);
owner.unregister('service:store');
owner.register('service:store', CustomStore);
owner.register('serializer:application', JSONAPISerializer);
});
test('Record Data state saving', async function (assert) {
assert.expect(3);
let isDeleted, isNew, isDeletionCommitted;
let calledDelete = false;
let calledUpdate = false;
let calledCreate = false;
const personHash = {
type: 'person',
id: '1',
attributes: {
name: 'Scumbag Dale',
},
};
let { owner } = this;
class LifecycleRecordData extends TestRecordData {
isNew(): boolean {
return isNew;
}
isDeleted(): boolean {
return isDeleted;
}
isDeletionCommitted(): boolean {
return isDeletionCommitted;
}
setIsDeleted(identifier, isDeleted): void {}
}
let TestStore = Store.extend({
createRecordDataFor(modelName, id, clientId, storeWrapper) {
return new LifecycleRecordData();
},
});
let TestAdapter = EmberObject.extend({
deleteRecord() {
calledDelete = true;
return Promise.resolve();
},
updateRecord() {
calledUpdate = true;
return Promise.resolve();
},
createRecord() {
calledCreate = true;
return Promise.resolve();
},
});
owner.register('service:store', TestStore);
owner.register('adapter:application', TestAdapter, { singleton: false });
store = owner.lookup('service:store');
store.push({
data: [personHash],
});
let person = store.peekRecord('person', '1');
isNew = true;
await person.save();
assert.true(calledCreate, 'called create if record isNew');
isNew = false;
isDeleted = true;
await person.save();
assert.true(calledDelete, 'called delete if record isDeleted');
isNew = false;
isDeleted = false;
await person.save();
assert.true(calledUpdate, 'called update if record isnt deleted or new');
});
test('Record Data state record flags', async function (assert) {
assert.expect(9);
let isDeleted, isNew, isDeletionCommitted;
let calledSetIsDeleted = false;
let storeWrapper;
const personHash = {
type: 'person',
id: '1',
attributes: {
name: 'Scumbag Dale',
},
};
let { owner } = this;
class LifecycleRecordData extends TestRecordData {
constructor(sw) {
super();
storeWrapper = sw;
}
isNew(): boolean {
return isNew;
}
isDeleted(): boolean {
return isDeleted;
}
isDeletionCommitted(identifier): boolean {
return isDeletionCommitted;
}
setIsDeleted(identifier, isDeleted: boolean): void {
calledSetIsDeleted = true;
}
}
let TestStore = Store.extend({
createRecordDataFor(modelName, id, clientId, storeWrapper) {
return new LifecycleRecordData(storeWrapper);
},
});
owner.register('service:store', TestStore);
store = owner.lookup('service:store');
store.push({
data: [personHash],
});
let person = store.peekRecord('person', '1');
let people = store.peekAll('person');
isNew = true;
storeWrapper.notifyStateChange('person', '1', null, 'isNew');
assert.true(person.get('isNew'), 'person is new');
isNew = false;
isDeleted = true;
storeWrapper.notifyStateChange('person', '1', null, 'isDeleted');
storeWrapper.notifyStateChange('person', '1', null, 'isNew');
assert.false(person.get('isNew'), 'person is not new');
assert.true(person.get('isDeleted'), 'person is deleted');
isNew = false;
isDeleted = false;
storeWrapper.notifyStateChange('person', '1', null, 'isDeleted');
assert.false(person.get('isNew'), 'person is not new');
assert.false(person.get('isDeleted'), 'person is not deleted');
person.deleteRecord();
assert.false(person.get('isDeleted'), 'calling deleteRecord does not automatically set isDeleted flag to true');
assert.true(calledSetIsDeleted, 'called setIsDeleted');
assert.equal(people.get('length'), 1, 'live array starting length is 1');
isDeletionCommitted = true;
Ember.run(() => {
storeWrapper.notifyStateChange('person', '1', null, 'isDeletionCommitted');
});
assert.equal(people.get('length'), 0, 'commiting a deletion updates the live array');
});
});
| 43,606
|
https://github.com/whitemike889/libmonetra/blob/master/examples/run_sale/run_sale.c
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
libmonetra
|
whitemike889
|
C
|
Code
| 322
| 1,323
|
/* Usage example for libmonetra.
*
* Runs a sale through the public TranSafe test server (test.transafe.com).
*
* To build, see instructions at top of CMakeLists.txt.
*/
#include <monetra_api.h>
static void trans_callback(LM_conn_t *conn, M_event_t *event, LM_event_type_t type, LM_trans_t *trans)
{
switch (type) {
case LM_EVENT_CONN_CONNECTED:
M_printf("Connected successfully\n");
break;
case LM_EVENT_CONN_DISCONNECT:
case LM_EVENT_CONN_ERROR:
M_printf("%s received: %s\n", (type == LM_EVENT_CONN_DISCONNECT)?"Disconnect":"Connection Error", LM_conn_error(conn));
LM_conn_destroy(conn);
M_event_done(event);
break;
case LM_EVENT_TRANS_DONE:
M_printf("Transaction %p complete:\n", trans);
if (LM_trans_response_type(trans) == LM_TRANS_RESPONSE_KV) {
M_list_str_t *params = LM_trans_response_keys(trans);
size_t i;
for (i=0; i<M_list_str_len(params); i++) {
const char *key = M_list_str_at(params, i);
M_printf("\t'%s' = '%s'\n", key, LM_trans_response_param(trans, key));
}
M_list_str_destroy(params);
} else {
const M_csv_t *csv = LM_trans_response_csv(trans);
size_t i;
M_printf("\t%zu rows, %zu cols\n", M_csv_get_numrows(csv), M_csv_get_numcols(csv));
/* Print headers */
for (i=0; i<M_csv_get_numcols(csv); i++) {
if (i != 0)
M_printf("|");
M_printf("%s", M_csv_get_header(csv, i));
}
M_printf("\n");
/* Print data */
for (i=0; i<M_csv_get_numrows(csv); i++) {
size_t j;
for (j=0; j<M_csv_get_numcols(csv); j++) {
if (j != 0)
M_printf("|");
M_printf("%s", M_csv_get_cellbynum(csv, i, j));
}
M_printf("\n");
}
}
LM_trans_delete(trans);
// We're only running a single transaction, issue a graceful disconnect.
// Actually, wait, we set a 5s idle timeout, lets do that instead :)
//M_printf("Initiating disconnect\n");
//LM_conn_disconnect(conn);
break;
case LM_EVENT_TRANS_ERROR:
case LM_EVENT_TRANS_NOCONNECT:
M_printf("Transaction %p error (connectivity): %s\n", trans, LM_conn_error(conn));
LM_trans_delete(trans);
// We should still get an LM_EVENT_CONN_ERROR after this event for additional cleanup.
break;
}
}
int main(int argc, char *argv[])
{
M_event_t *event = M_event_create(M_EVENT_FLAG_NONE);
LM_conn_t *conn = LM_conn_init(event, trans_callback, "test.transafe.com", 8665);
LM_trans_t *trans;
/* Set 2s idle timeout. This is how we want to exit the script to verify this works */
LM_conn_set_idle_timeout(conn, 2);
trans = LM_trans_new(conn);
LM_trans_set_param(trans, "username", "test_retail:public");
LM_trans_set_param(trans, "password", "publ1ct3st");
LM_trans_set_param(trans, "action", "sale");
LM_trans_set_param(trans, "account", "4012888888881881");
LM_trans_set_param(trans, "expdate", "1220");
LM_trans_set_param(trans, "zip", "32606");
LM_trans_set_param(trans, "cv", "999");
LM_trans_set_param(trans, "amount", "12.00");
LM_trans_send(trans);
M_printf("Enqueued transaction %p\n", trans);
M_event_loop(event, M_TIMEOUT_INF);
// NOTE: we cleaned up 'conn' within the trans_callback. We can't have
// exited the event loop otherwise.
conn = NULL;
M_event_destroy(event);
M_library_cleanup();
return 0;
}
| 12,898
|
https://github.com/aschampion/raveler-utils/blob/master/libstack/libstack.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,015
|
raveler-utils
|
aschampion
|
C++
|
Code
| 4,034
| 11,286
|
#include <stdio.h>
#include "HdfStack.h"
#include "util.h"
#include "timers.h"
#include "util.h"
#include "BodyColorTable.h"
//
// libstack.cpp
//
// This is the C interface to HdfStack.
//
// HdfStack is a C++ class. C++ code can use HdfStack directly
// and not use the below. But Python code can use ctypes to call the
// below functions. Raveler has a class LibStack which uses ctypes
// and has Python versions of the below functions.
//
// NOTE ABOUT CTYPES AND OTHER OPTIONS
// aka "don't do this"
//
// We do a two-step allocation process which leaves allocating
// completely on the Python code. Every call that needs to return
// an array is split in two: queue and then get.
//
// There are supposedly ways to setup ctypes/numpy such that we could do
// allocation from C, and then pass back that buffer such that
// Python would own it and free it. This would be much simpler/cleaner
// once working, but it looked complex to initially setup.
//
// Another option that might be cleaner is Cython instead of cytypes.
// Ctypes has a fair amount of boilerplate on the Python side and
// the C side and my impression is Cython would be cleaner.
//
// Boost.Python and pypluslus is another option, which Christopher is
// using for wrapping the V3D plugin API.
//
// The below works fine but it's ugly with all the queue/get pairs.
//
extern "C"
{
//
// Functions
//
// The const char* return values work the same:
// 1) return NULL on success
// 2) return an error string on failure
//
// Call at library setup time, return NULL if no errors
const char* init();
// Load the HDF-STACK from disk
const char* load(const char* path);
// Save the HDF-STACK to disk
const char* save(const char* path, uint isbackup);
// Create from old session format
const char* create(
uint32 bounds_rows, uint32* bounds_data,
uint32 segment_rows, uint32* segment_data,
uint32 bodies_rows, uint32* bodies_data);
// Get the count of bodies for getnewbodies
const char* queuenewbodies(uint32* count);
// Get all bodies using count from queunewbodies().
const char* getnewbodies(uint32 count, uint32* data);
// Get the lowest numbered plane
const char* getzmin(uint32* retval);
// Get the highest numbered plane
const char* getzmax(uint32* retval);
// Get count of all the superpixels on a given plane
const char* getnumsuperpixelsinplane(uint32 plane, uint32* retval);
// Get the number of superpixels in the given body
const char* getnumsuperpixelsinbody(uint32 bodyid, uint32 *count);
// Return 1 if superpixel exists
const char* hassuperpixel(uint32 plane, uint32 spid, uint32* retval);
// Create a new superpixel, return the new spid
const char* createsuperpixel(uint32 plane, uint32 *retval);
// Add superpixel to the given segment
const char* addsuperpixel(uint32 plane, uint32 spid, uint32 segid);
// Get the count of superpixels for getsuperpixelsinplane()
const char* queuesuperpixelsinplane(uint32 plane, uint32 *count);
// Get superpixels on a given plane, using count from queuesuperpixelsinplane
const char* getsuperpixelsinplane(uint32 plane, uint32 count, uint32* data);
// Get the count of bodyids for getsuperpixelbodiesinplane()
const char* queuesuperpixelbodiesinplane(uint32 plane, uint32 *count);
// Get bodies for all superpixels on a given plane, count from queuesuperpixelbodiesinplane
const char* getsuperpixelbodiesinplane(uint32 plane, uint32 count, uint32* data);
// Get the count of superpixels for getsuperpixelsinsegment()
const char* queuesuperpixelsinsegment(uint32 segid, uint32* count);
// Get the superpixels using count from queuesuperpixelsinsegment().
const char* getsuperpixelsinsegment(uint32 segid, uint32 count, uint32* data);
// Get the count of superpixels for getsuperpixelsinbody()
const char* queuesuperpixelsinbody(uint32 bodyid, uint32* count);
// Get the superpixels using count from queuesuperpixelsinbody().
const char* getsuperpixelsinbody(uint32 bodyid, uint32 count,
uint32* planes, uint32* spids);
// Get the count of superpixels for getsuperpixelsinbodyinplane()
const char* queuesuperpixelsinbodyinplane(uint32 segid, uint32 plane, uint32* count);
// Get the superpixels using count from queuesuperpixelsinbodyinplane().
const char* getsuperpixelsinbodyinplane(uint32 bodyid, uint32 plane, uint32 count, uint32* spids);
// Get highest numbered superpixel on a given plane
const char* getmaxsuperpixelid(uint32 plane, uint32 *retval);
// Return (x, y, width, height) bounding area of this superpixel
const char* getbounds(uint32 plane, uint32 spid, uint32* bounds);
// Return exact volume of the superpixel
const char* getvolume(uint32 plane, uint32 spid, uint32* retval);
// Set the bounds and volume of a given superpixel
const char* setboundsandvolume(uint32 plane, uint32 spid, Bounds bounds,
uint32 volume);
// Return 1 if segment exists
const char* hassegment(uint32 segid, uint32* retval);
// Get the segment id for the given (plane, spid)
const char* getsegmentid(uint32 plane, uint32 spid, uint32* retval);
// Set the segment id for the given (plane, spid)
const char* setsegmentid(uint32 plane, uint32 spid, uint32 segid);
// Get the plane for the given segment
const char* getplane(uint32 segid, uint32* retval);
// Set the superpixels for a given segment
const char* setsuperpixels(uint32 segid, uint32 plane, uint32 count, uint32* data);
// Create a new empty segment and return the id
const char* createsegment(uint32* retval);
// Get the body id for a given segment
const char* getsegmentbodyid(uint32 segid, uint32* retval);
// Get the count of segments for getsegments()
const char* queuesegments(uint32 bodyid, uint32* count);
// Get the segments using count from queuesegments().
const char* getsegments(uint32 bodyid, uint32 count, uint32* data);
// Set the segments for a given body
const char* setsegments(uint32 bodyid, uint32 count, uint32* segments);
// Create a new empty body and return the id
const char* createbody(uint32 *retval);
// Return 1 if body exists
const char* hasbody(uint32 bodyid, uint32* retval);
// Add the segments to the given body
const char* addsegments(uint32 count, uint32* segments, uint32 bodyid);
// Delete segment completely
const char* deletesegment(uint32 segid);
// Get count of all bodies
const char* getnumbodies(uint32* count);
// Get count of all bodies, not including the zero body
const char* getnumbodiesnonzero(uint32* count);
// Get the count of bodies for getallbodies
const char* queueallbodies(uint32* count);
// Get all bodies using count from queueallbodies().
const char* getallbodies(uint32 count, uint32* data);
// Return count of all segments
const char* getnumsegments(uint32* count);
// Get the count of segments for getallsegments
const char* queueallsegments(uint32* count);
// Get all segments using count from queueallsegments().
const char* getallsegments(uint32 count, uint32* data);
// Get min and max plane extents which the body occupies
const char* getplanelimits(uint32 bodyid, uint32* zmin, uint32* zmax);
// Get the count of plane limits for getallplanelimits
const char* queueallplanelimits(uint32* count);
// Return a table of with 3 values in each row (bodyid, zmins, and zmaxs),
// one row for each of count bodies.
const char* getallplanelimits(uint32 count, uint32* table);
//
// volume API
//
// Compute the volume of every body in the stack
const char* initbodyvolumes();
// Get the given body's volume
const char* getbodyvolume(uint32 bodyid, uint64* volume);
// Get the count of body/volume pairs for getallbodyvolumes
const char* queueallbodyvolumes(uint32* count);
// Get all bodyids and associated volumes
const char* getallbodyvolumes(uint32 count, uint32* bodyids, uint64* volumes);
// Recalculate the volume of each given body
const char* updatebodyvolumes(uint32 count, uint32* bodyids);
// Queue the "n" largest bodies for getlargestbodies
const char* queuelargestbodies(uint32 n, uint32* count);
// Get the bodies previously queued by queuelargestbodies, note these
// are returned in an arbitrary order right now
const char* getlargestbodies(uint32 count, uint32 *data);
//
// colormap API
//
// Assign a random color to every body in the stack
const char* initbodycolormap();
// Build a single plane's colormap, return the count of entries
const char* queueplanecolormap(uint32 plane, uint32* count);
// Get previously queued colormap
const char* getplanecolormap(uint32 plane, uint32 count, uint32* data);
// Create new random color for this body if it doesn't have one already
const char* addbodycolor(uint32 bodyid);
// Get packed RGBA value for a single body
const char* getbodycolor(uint32 bodyid, uint32* color);
//
// sideview/mapview APIs
//
// Prepare geometry to represent a single body in the XZ side view
const char* queuebodygeometryXZ(uint32 bodyid, uint32* count);
// Get previously queued geometry
const char* getbodygeometryXZ(uint32 bodyid, uint32 count, uint32* data);
// Prepare geometry to represent a single body in the ZY side view
const char* queuebodygeometryZY(uint32 bodyid, uint32* count);
// Get previously queued geometry
const char* getbodygeometryZY(uint32 bodyid, uint32 count, uint32* data);
// Prepare geometry to represent a single body in the YZ side view
const char* queuebodygeometryYZ(uint32 bodyid, uint32* count);
// Get previously queued geometry
const char* getbodygeometryYZ(uint32 bodyid, uint32 count, uint32* data);
// Prepare bounding boxes for a single body
const char* queuebodybounds(uint32 bodyid, uint32* count);
// Get previously queued bounding boxes
const char* getbodybounds(uint32 bodyid, uint32 count, uint32* data);
// Prepare vtk bounding boxes for a single body
const char* queuebodyboundsvtk(uint32 bodyid, float zaspect, uint32* countverts, uint32* counttris);
// Get previously queued vtk bounding boxes
const char* getbodyboundsvtk(uint32 bodyid, uint32 countverts, uint32 counttris, float* verts, int64* tris);
// Export a single body as a binary STL file
const char* exportstl(uint32 bodyid, const char* path, float zaspect);
} // extern 'C'
// Single global stack. This C api is not thread-safe and
// doesn't support having multiple stacks open.
HdfStack* g_stack = NULL;
// Get safely
HdfStack* getStack()
{
if (!g_stack)
{
throw std::string("No stack loaded");
}
return g_stack;
}
// TRY_CATCH
//
// All our C API functions return "const char *". We return NULL on
// success, or we return a string describing the error on an error.
//
// So this macro does 3 things:
// 1) runs the given code
// 2) returns NULL on success
// 3) returns error string on failure
//
// Note: using the HDF5-DIAG stuff it would be possible to get the
// entire HDF5 "error stack" and return it in some form. But we just
// return a single short error string right now.
//
#define TRY_CATCH(code_) \
try \
{ \
code_ \
return NULL; \
} \
catch (std::string& error) \
{ \
return error.c_str(); \
} \
catch (std::exception& e) \
{ \
return e.what(); \
}
//
// To allow memory allocation to stay on the Python side any API
// which needs to return an array is broken up into two calls:
// 1) queue
// 2) get
// The queue does the real work, it queues up all the values and
// returns a count of values. The Python side then allocates
// space for those values. Then the get is called with the
// allocated space, and we copy in the queued values.
//
template <class T>
class ValueQueue
{
public:
ValueQueue();
// Call this to start queuing, add values to the returned
// vector. Key is optional way to detect if queue/get
// calls are not paired properly.
std::vector<T>& start(uint32 key = 0);
// Get reference to our values
std::vector<T>& values() { return m_values; }
// How many values are queued
uint32 size() const { return m_values.size(); }
// Get data that was previously queued
// Key and count are checked against previous queue call.
// Data is cleared to free up memory, can only get() once.
void get(uint32 count, T* data, uint32 key = 0);
// Add one value
void push_back(T value) { m_values.push_back(value); }
// Clear everything
void clear() { m_values.clear(); }
private:
std::vector<T> m_values;
uint32 m_key;
};
template <class T>
ValueQueue<T>::ValueQueue() :
m_key(0)
{}
template <class T>
std::vector<T>& ValueQueue<T>::start(uint32 key)
{
// Should always be empty from last get, but just to be sure
m_values.clear();
// Optional key
m_key = key;
return m_values;
}
template <class T>
void ValueQueue<T>::get(uint32 count, T* data, uint32 key)
{
if (m_key != key)
{
throw std::string("wrong key");
}
if (m_values.size() != count)
{
throw std::string("wrong count");
}
for (uint32 i = 0; i < m_values.size(); ++i)
{
data[i] = m_values[i];
}
m_values.clear();
m_key = 0;
}
typedef ValueQueue<uint32> IntQueue;
typedef ValueQueue<uint64> Int64Queue;
typedef ValueQueue<Bounds> BoundsQueue;
typedef ValueQueue<float3> Float3Queue;
// Global queue used for multiple operations
static IntQueue g_intqueue;
//
// Like ValueQueue but specifically for getsuperpixelsinbody
// which needs to return two arrays.
//
class SuperpixelGetter
{
public:
// Returns a count of items queued
uint32 queue(uint32 bodyid);
// Get data that was previously queued
void get(uint32 bodyid, uint32 count, uint32* planes, uint32* spids);
private:
IntQueue m_planes;
IntQueue m_spids;
};
uint32 SuperpixelGetter::queue(uint32 bodyid)
{
IntVec& planes = m_planes.start(bodyid);
IntVec& spids = m_spids.start(bodyid);
getStack()->getsuperpixelsinbody(bodyid, planes, spids);
assert(planes.size() == spids.size());
return planes.size();
}
void SuperpixelGetter::get(uint32 bodyid, uint32 count,
uint32* planes, uint32* spids)
{
m_planes.get(count, planes, bodyid);
m_spids.get(count, spids, bodyid);
}
// Global queue
static SuperpixelGetter g_spgetter;
//
// Magic macro for compile-time asserts from linux kernel
// as described here:
// http://www.pixelbeat.org/programming/gcc/static_assert.html
// for example:
// ct_assert(sizeof(size_t) == 8);
// must be placed in a function.
//
#define ct_assert(e) ((void)sizeof(char[1 - 2*!(e)]))
const char* init()
{
// ct_assert must be in a function
ct_assert(sizeof(uint32) == 4);
ct_assert(sizeof(uint64) == 8);
#ifndef __APPLE__
ct_assert(sizeof(size_t) == 8);
#endif
// Nothing to init right now... no errors possible
return NULL;
}
const char* load(const char* path)
{
TRY_CATCH(
delete g_stack;
g_stack = new HdfStack();
getStack()->load(path);
)
}
const char* create(
uint32 bounds_rows, uint32* bounds_data,
uint32 segment_rows, uint32* segment_data,
uint32 bodies_rows, uint32* bodies_data)
{
// The Tables create copies of the incoming data, we could re-use
// the memory but Table normally wants to control its own memory,
// so we just make the copy to keep it simple.
Table bounds(bounds_rows, 7, bounds_data);
Table segments(segment_rows, 3, segment_data);
Table bodies(bodies_rows, 2, bodies_data);
TRY_CATCH(
delete g_stack;
g_stack = new HdfStack();
g_stack->create(&bounds, &segments, &bodies);
)
}
const char* save(const char* path, uint isbackup)
{
TRY_CATCH(
getStack()->save(path, isbackup);
)
}
const char* close()
{
TRY_CATCH(
delete g_stack;
g_stack = NULL;
)
}
const char* getzmin(uint32* retval)
{
TRY_CATCH(
*retval = getStack()->getzmin();
)
}
const char* getzmax(uint32* retval)
{
TRY_CATCH(
*retval = getStack()->getzmax();
)
}
const char* getplane(uint32 segid, uint32* retval)
{
TRY_CATCH(
*retval = getStack()->getplane(segid);
)
}
const char* getnumsuperpixelsinplane(uint32 plane, uint32* retval)
{
TRY_CATCH(
*retval = getStack()->getnumsuperpixelsinplane(plane);
)
}
const char* getnumsuperpixelsinbody(uint32 bodyid, uint32 *count)
{
TRY_CATCH(
*count = getStack()->getnumsuperpixelsinbody(bodyid);
)
}
const char* hassuperpixel(uint32 plane, uint32 spid, uint32* retval)
{
TRY_CATCH(
*retval = getStack()->hassuperpixel(plane, spid);
)
}
const char* createsuperpixel(uint32 plane, uint32 *retval)
{
TRY_CATCH(
*retval = getStack()->createsuperpixel(plane);
)
}
const char* addsuperpixel(uint32 plane, uint32 spid, uint32 segid)
{
TRY_CATCH(
getStack()->addsuperpixel(plane, spid, segid);
)
}
const char* queuesuperpixelsinplane(uint32 plane, uint32 *count)
{
TRY_CATCH(
IntVec& spids = g_intqueue.start(plane);
getStack()->getsuperpixelsinplane(plane, spids);
*count = g_intqueue.size();
)
}
const char* getsuperpixelsinplane(uint32 plane, uint32 count, uint32* data)
{
TRY_CATCH(
g_intqueue.get(count, data, plane);
)
}
const char* queuesuperpixelbodiesinplane(uint32 plane, uint32 *count)
{
TRY_CATCH(
IntVec& bodies = g_intqueue.start(plane);
getStack()->getsuperpixelbodiesinplane(plane, bodies);
*count = g_intqueue.size();
)
}
const char* getsuperpixelbodiesinplane(uint32 plane, uint32 count, uint32* data)
{
TRY_CATCH(
g_intqueue.get(count, data, plane);
)
}
const char* getmaxsuperpixelid(uint32 plane, uint32 *retval)
{
TRY_CATCH(
*retval = getStack()->getmaxsuperpixelid(plane);
)
}
const char* getbounds(uint32 plane, uint32 spid, uint32* retval)
{
TRY_CATCH(
Bounds bounds = getStack()->getbounds(plane, spid);
retval[0] = bounds.x;
retval[1] = bounds.y;
retval[2] = bounds.width;
retval[3] = bounds.height;
)
}
const char* getvolume(uint32 plane, uint32 spid, uint32* retval)
{
TRY_CATCH(
*retval = getStack()->getvolume(plane, spid);
)
}
const char* setboundsandvolume(uint32 plane, uint32 spid, Bounds bounds,
uint32 volume)
{
TRY_CATCH(
getStack()->setboundsandvolume(plane, spid, bounds, volume);
)
}
const char* hassegment(uint32 segid, uint32* retval)
{
TRY_CATCH(
*retval = getStack()->hassegment(segid);
)
}
const char* getsegmentid(uint32 plane, uint32 spid, uint32* retval)
{
TRY_CATCH(
*retval = getStack()->getsegmentid(plane, spid);
)
}
const char* setsegmentid(uint32 plane, uint32 spid, uint32 segid)
{
TRY_CATCH(
getStack()->setsegmentid(plane, spid, segid);
)
}
const char* queuesuperpixelsinsegment(uint32 segid, uint32* count)
{
TRY_CATCH(
IntVec& spids = g_intqueue.start(segid);
getStack()->getsuperpixelsinsegment(segid, spids);
*count = g_intqueue.size();
)
}
const char* getsuperpixelsinsegment(uint32 segid, uint32 count, uint32* data)
{
TRY_CATCH(
g_intqueue.get(count, data, segid);
)
}
const char* queuesuperpixelsinbody(uint32 bodyid, uint32* count)
{
TRY_CATCH(
*count = g_spgetter.queue(bodyid);
)
}
const char* getsuperpixelsinbody(uint32 bodyid, uint32 count,
uint32* planes, uint32* spids)
{
TRY_CATCH(
g_spgetter.get(bodyid, count, planes, spids);
)
}
const char* queuesuperpixelsinbodyinplane(uint32 bodyid, uint32 plane, uint32* count)
{
TRY_CATCH(
IntVec& spids = g_intqueue.start(bodyid);
getStack()->getsuperpixelsinbodyinplane(bodyid, plane, spids);
*count = g_intqueue.size();
)
}
const char* getsuperpixelsinbodyinplane(uint32 bodyid, uint32 plane, uint32 count, uint32* spids)
{
TRY_CATCH(
g_intqueue.get(count, spids, bodyid);
)
}
const char* setsuperpixels(uint32 segid, uint32 plane, uint32 count,
uint32* spids)
{
IntVec spidvec;
for (uint32 i = 0; i < count; i++)
{
spidvec.push_back(spids[i]);
}
TRY_CATCH(
getStack()->setsuperpixels(segid, plane, spidvec);
)
}
const char* createsegment(uint32* retval)
{
TRY_CATCH(
*retval = getStack()->createsegment();
)
}
const char* getsegmentbodyid(uint32 segid, uint32* retval)
{
TRY_CATCH(
*retval = getStack()->getsegmentbodyid(segid);
)
}
const char* queuesegments(uint32 bodyid, uint32* count)
{
TRY_CATCH(
IntVec& segments = g_intqueue.start(bodyid);
getStack()->getsegments(bodyid, segments);
*count = g_intqueue.size();
)
}
const char* getsegments(uint32 bodyid, uint32 count, uint32* data)
{
TRY_CATCH(
g_intqueue.get(count, data, bodyid);
)
}
const char* setsegments(uint32 bodyid, uint32 count, uint32* segments)
{
IntVec segvec;
for (uint32 i = 0; i < count; i++)
{
segvec.push_back(segments[i]);
}
TRY_CATCH(
getStack()->setsegments(bodyid, segvec);
)
}
const char* createbody(uint32 *retval)
{
TRY_CATCH(
*retval = getStack()->createbody();
)
}
const char* hasbody(uint32 bodyid, uint32* retval)
{
TRY_CATCH(
*retval = getStack()->hasbody(bodyid);
)
}
const char* addsegments(uint32 count, uint32* segments, uint32 bodyid)
{
IntVec segvec;
for (uint32 i = 0; i < count; i++)
{
segvec.push_back(segments[i]);
}
TRY_CATCH(
getStack()->addsegments(segvec, bodyid);
)
}
const char* deletesegment(uint32 segid)
{
TRY_CATCH(
getStack()->deletesegment(segid);
)
}
const char* getnumbodies(uint32* count)
{
TRY_CATCH(
*count = getStack()->getnumbodies();
)
}
const char* getnumbodiesnonzero(uint32* count)
{
TRY_CATCH(
*count = getStack()->getnumbodiesnonzero();
)
}
// These are just random keys we use to check that "queue" and "get"
// calls are paired. We don't want someone queuing up one type
// of value then getting something else, they would be getting
// the wrong thing.
static const int KEY_NEW_BODIES = 1001;
static const int KEY_ALL_BODIES = 1002;
static const int KEY_ALL_SEGMENTS = 1003;
static const int KEY_LARGEST_BODIES = 1004;
const char* queuenewbodies(uint32* count)
{
TRY_CATCH(
IntVec& bodies = g_intqueue.start(KEY_NEW_BODIES);
getStack()->getnewbodies(bodies);
*count = g_intqueue.size();
)
}
const char* getnewbodies(uint32 count, uint32* data)
{
TRY_CATCH(
g_intqueue.get(count, data, KEY_NEW_BODIES);
)
}
const char* queueallbodies(uint32* count)
{
TRY_CATCH(
IntVec& bodies = g_intqueue.start(KEY_ALL_BODIES);
getStack()->getallbodies(bodies);
*count = g_intqueue.size();
)
}
const char* getallbodies(uint32 count, uint32* data)
{
TRY_CATCH(
g_intqueue.get(count, data, KEY_ALL_BODIES);
)
}
const char* getnumsegments(uint32* count)
{
TRY_CATCH(
*count = getStack()->getnumsegments();
)
}
const char* queueallsegments(uint32* count)
{
TRY_CATCH(
IntVec& segments = g_intqueue.start(KEY_ALL_SEGMENTS);
getStack()->getallsegments(segments);
*count = g_intqueue.size();
)
}
const char* getallsegments(uint32 count, uint32* data)
{
TRY_CATCH(
g_intqueue.get(count, data, KEY_ALL_SEGMENTS);
)
}
const char* getplanelimits(uint32 bodyid, uint32* zmin, uint32* zmax)
{
TRY_CATCH(
getStack()->getplanelimits(bodyid, *zmin, *zmax);
)
}
// For queue/get all plane limits
IntQueue g_bodyids;
IntQueue g_zmin;
IntQueue g_zmax;
const char* queueallplanelimits(uint32* count)
{
TRY_CATCH(
IntVec& bodies = g_bodyids.start();
IntVec& zmin = g_zmin.start();
IntVec& zmax = g_zmax.start();
getStack()->getallplanelimits(bodies, zmin, zmax);
assert(bodies.size() == zmin.size());
assert(bodies.size() == zmax.size());
*count = bodies.size();
)
}
// Return bodyids, zmins, and zmaxs for all bodies
const char* getallplanelimits(
uint32 count, uint32* table)
{
TRY_CATCH(
IntVec& bodies = g_bodyids.values();
IntVec& zmin = g_zmin.values();
IntVec& zmax = g_zmax.values();
for (uint32 i = 0; i < bodies.size(); ++i)
{
table[i*3 + 0] = bodies[i];
table[i*3 + 1] = zmin[i];
table[i*3 + 2] = zmax[i];
}
)
}
static BodyColorTable* g_bodycolors = NULL;
const char* initbodycolormap()
{
TRY_CATCH(
delete(g_bodycolors);
g_bodycolors = new BodyColorTable(getStack());
)
}
const char* queueplanecolormap(uint32 plane, uint32* count)
{
TRY_CATCH(
IntVec& colors = g_intqueue.start(plane);
g_bodycolors->getplanecolormap(plane, colors);
*count = g_intqueue.size();
)
}
const char* getplanecolormap(uint32 plane, uint32 count, uint32* data)
{
TRY_CATCH(
g_intqueue.get(count, data, plane);
)
}
const char* addbodycolor(uint32 bodyid)
{
TRY_CATCH(
g_bodycolors->addbodycolor(bodyid);
)
}
const char* getbodycolor(uint32 bodyid, uint32* color)
{
TRY_CATCH(
*color = g_bodycolors->getbodycolor(bodyid);
)
}
IntQueue g_x;
IntQueue g_y;
IntQueue g_z;
const char* queuebodygeometryXZ(uint32 bodyid, uint32* count)
{
TRY_CATCH(
IntVec& x = g_x.start(bodyid);
IntVec& z = g_z.start(bodyid);
getStack()->getBodyGeometryXZ(bodyid, x, z);
// Should be the same size
assert(x.size() == z.size());
*count = x.size();
)
}
const char* getbodygeometryXZ(uint32 bodyid, uint32 count, uint32* data)
{
TRY_CATCH(
IntVec& x = g_x.values();
IntVec& z = g_z.values();
for (uint32 i = 0; i < count; ++i)
{
data[i*2 + 0] = x[i];
data[i*2 + 1] = z[i];
}
)
}
const char* queuebodygeometryZY(uint32 bodyid, uint32* count)
{
TRY_CATCH(
IntVec& z = g_z.start(bodyid);
IntVec& y = g_y.start(bodyid);
getStack()->getBodyGeometryYZ(bodyid, y, z);
// Should be the same size
assert(y.size() == z.size());
*count = y.size();
)
}
const char* getbodygeometryZY(uint32 bodyid, uint32 count, uint32* data)
{
TRY_CATCH(
IntVec& y = g_y.values();
IntVec& z = g_z.values();
for (uint32 i = 0; i < count; ++i)
{
data[i*2 + 0] = z[i];
data[i*2 + 1] = y[i];
}
)
}
const char* queuebodygeometryYZ(uint32 bodyid, uint32* count)
{
TRY_CATCH(
IntVec& y = g_y.start(bodyid);
IntVec& z = g_z.start(bodyid);
getStack()->getBodyGeometryYZ(bodyid, y, z);
// Should be the same size
assert(y.size() == z.size());
*count = y.size();
)
}
const char* getbodygeometryYZ(uint32 bodyid, uint32 count, uint32* data)
{
TRY_CATCH(
IntVec& y = g_y.values();
IntVec& z = g_z.values();
for (uint32 i = 0; i < count; ++i)
{
data[i*2 + 0] = y[i];
data[i*2 + 1] = z[i];
}
)
}
BoundsQueue g_bounds;
const char* queuebodybounds(uint32 bodyid, uint32* count)
{
TRY_CATCH(
IntVec& z = g_intqueue.start(bodyid);
BoundsVec& bounds = g_bounds.start(bodyid);
getStack()->getBodyBounds(bodyid, z, bounds);
assert(z.size() == bounds.size());
*count = z.size();
)
}
const char* getbodybounds(uint32 bodyid, uint32 count, uint32* data)
{
TRY_CATCH(
IntVec& z = g_intqueue.values();
BoundsVec& bounds = g_bounds.values();
for (uint32 i = 0; i < count; ++i)
{
uint32 j = i * 5;
Bounds &b = bounds[i];
data[j + 0] = z[i];
data[j + 1] = b.x0();
data[j + 2] = b.y0();
data[j + 3] = b.x1();
data[j + 4] = b.y1();
}
)
}
Float3Queue g_verts;
const char* queuebodyboundsvtk(uint32 bodyid, float zaspect, uint32* countverts, uint32* counttris)
{
TRY_CATCH(
Float3Vec& verts = g_verts.start(bodyid);
IntVec& tris = g_intqueue.start(bodyid);
getStack()->getBodyBoundsVTK(bodyid, zaspect, verts, tris);
*countverts = verts.size();
*counttris = tris.size();
)
}
// Get previously queued vtk bounding boxes
const char* getbodyboundsvtk(uint32 bodyid, uint32 countverts, uint32 counttris,
float* verts, int64* tris)
{
TRY_CATCH(
Float3Vec& vertvec = g_verts.values();
IntVec& trivec = g_intqueue.values();
for (uint32 i = 0; i < countverts; ++i)
{
uint32 j = i * 3;
float3 &v = vertvec[i];
verts[j + 0] = v.x;
verts[j + 1] = v.y;
verts[j + 2] = v.z;
}
for (uint32 i = 0; i < counttris; ++i)
{
tris[i] = trivec[i];
}
g_verts.clear();
g_intqueue.clear();
)
}
static Int64Map s_volumes;
const char* initbodyvolumes()
{
TRY_CATCH(
s_volumes.clear();
HdfStack* stack = getStack();
IntVec bodies;
stack->getallbodies(bodies);
// For each body
for (IntVecIt bodyIt = bodies.begin();
bodyIt != bodies.end(); ++bodyIt)
{
uint64 volume = stack->getbodyvolume(*bodyIt);
s_volumes[*bodyIt] = volume;
}
)
}
const char* getbodyvolume(uint32 bodyid, uint64* volume)
{
TRY_CATCH(
*volume = s_volumes[bodyid];
)
}
const char* updatebodyvolumes(uint32 count, uint32* bodyids)
{
TRY_CATCH(
HdfStack* stack = getStack();
for (uint32 i = 0; i < count; ++i)
{
uint32 bodyid = bodyids[i];
uint64 volume = stack->getbodyvolume(bodyid);
s_volumes[bodyids[i]] = volume;
}
)
}
// For getnlargest heap
struct BodyVolume
{
BodyVolume(uint32 bodyid, uint64 volume) :
m_bodyid(bodyid),
m_volume(volume)
{}
bool operator>(const BodyVolume& other) const
{
return m_volume > other.m_volume;
}
uint32 m_bodyid;
uint64 m_volume;
};
static void getnlargest(uint32 n, IntVec& result)
{
// Don't trust the bodies in s_volumes, they might include stale
// entries, bodies that have been removed. Instead get a trusted
// list of all bodies from the stack, then lookup each volume
// in s_volumes
IntVec bodies;
getStack()->getallbodies(bodies);
// Create a heap of the n biggest bodies
std::vector<BodyVolume> heap;
for (uint32 i = 0; i < bodies.size(); ++i)
{
uint32 bodyid = bodies[i];
if (bodyid == 0)
continue;
uint64 volume = s_volumes[bodyid];
if (heap.size() < n)
{
// Heap is not even full, so add every body at this point
heap.push_back(BodyVolume(bodyid, volume));
push_heap(heap.begin(), heap.end(), std::greater<BodyVolume>());
}
else if (volume > heap[0].m_volume)
{
// Heap is full but this body is bigger than the smallest one
// in the heap. So add it and remove the smallest.
heap.push_back(BodyVolume(bodyid, volume));
push_heap(heap.begin(), heap.end(), std::greater<BodyVolume>());
pop_heap(heap.begin(), heap.end(), std::greater<BodyVolume>());
heap.pop_back();
}
}
result.clear();
// Copy just the bodyids out of the heap (in heap order, NOT sorted)
for (std::vector<BodyVolume>::iterator it = heap.begin();
it != heap.end(); ++it)
{
result.push_back(it->m_bodyid);
}
}
const char* queuelargestbodies(uint32 n, uint32* count)
{
TRY_CATCH(
IntVec& bodies = g_intqueue.start(KEY_LARGEST_BODIES);
getnlargest(n, bodies);
*count = g_intqueue.size();
)
}
const char* getlargestbodies(uint32 count, uint32 *data)
{
TRY_CATCH(
g_intqueue.get(count, data, KEY_LARGEST_BODIES);
)
}
class BodyVolumeQueue
{
public:
// Return count of elements queued
uint32 queue();
// Get previously queued values
void get(uint32 count, uint32* bodyids, uint64* volumes);
private:
IntQueue m_bodyids;
Int64Queue m_volumes;
};
uint32 BodyVolumeQueue::queue()
{
IntVec& bodies = m_bodyids.start();
Int64Vec& volumes = m_volumes.start();
HdfStack* stack = getStack();
stack->getallbodies(bodies);
// For each body, look up the volume
for (IntVecIt bodyIt = bodies.begin();
bodyIt != bodies.end(); ++bodyIt)
{
volumes.push_back(s_volumes[*bodyIt]);
}
assert(m_bodyids.size() == m_volumes.size());
return m_bodyids.size();
}
void BodyVolumeQueue::get(uint32 count, uint32* bodyids, uint64* volumes)
{
m_bodyids.get(count, bodyids);
m_volumes.get(count, volumes);
}
BodyVolumeQueue g_bodyVolumeQueue;
const char* queueallbodyvolumes(uint32* count)
{
TRY_CATCH(
*count = g_bodyVolumeQueue.queue();
)
}
const char* getallbodyvolumes(uint32 count, uint32* bodyids, uint64* volumes)
{
TRY_CATCH(
g_bodyVolumeQueue.get(count, bodyids, volumes);
)
}
const char* exportstl(uint32 bodyid, const char* path, float zaspect)
{
TRY_CATCH(
getStack()->exportstl(bodyid, path, zaspect);
)
}
| 10,405
|
https://github.com/OpusSoluttio/iExpo-backend/blob/master/iExpo/Dominios/Interfaces/ISensores.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
iExpo-backend
|
OpusSoluttio
|
C#
|
Code
| 155
| 380
|
using Dominios.Classes;
using System;
using System.Collections.Generic;
using System.Text;
namespace Dominios.Interfaces
{
public interface ISensores
{
/// <summary>
/// Lista todos sensores vindos do Banco de Dados
/// </summary>
/// <returns>Retorna uma lista com todos os sensores</returns>
List<Sensores> Listar();
/// <summary>
/// Cadastra um novo sensor no Banco de Dados
/// </summary>
/// <param name="produto">Recebe um sensor com todas informações preenchidas</param>
/// <returns>Retorna o sensor cadastrado caso tenha sucesso ou null caso haja falha</returns>
Sensores Cadastrar(Sensores sensor);
/// <summary>
/// Altera as informações de um determinado sensor
/// </summary>
/// <param name="produto">Recebe as informações do sensor a serem mudadas</param>
/// <returns>Retorna o sensor alterado caso tenha sucesso ou null caso haja falha</returns>
Sensores Alterar(Sensores sensor);
/// <summary>
/// Altera o Status do Sensor
/// </summary>
/// <param name="IdProduto">Recebe o ID do sensor a ter sua sua informação alterada<//param>
/// <returns>Retorna o sensor com a nova informação ou null caso haja falha</returns>
Sensores AlterarStatus(int IdSensor);
}
}
| 20,091
|
https://github.com/sahabi/OpenAMASE/blob/master/OpenAMASE/src/Core/avtas/map/image/DDSDecoder.java
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, LicenseRef-scancode-us-govt-public-domain, LicenseRef-scancode-warranty-disclaimer
| 2,017
|
OpenAMASE
|
sahabi
|
Java
|
Code
| 1,099
| 2,838
|
// ===============================================================================
// Authors: AFRL/RQQD
// Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
//
// Copyright (c) 2017 Government of the United State of America, as represented by
// the Secretary of the Air Force. No copyright is claimed in the United States under
// Title 17, U.S. Code. All Other Rights Reserved.
// ===============================================================================
package avtas.map.image;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
* Reads a Direct-X texture file (usually a .dds extension) and returns a buffered image with its contents. Currently,
* this class will read DXT1 and DXT3 style files, but has not been thoroughly tested.
*
* This is based on work found in the WorldWind forums (www.forum.worldwindcentral.com) posted by remleduff on 12 Jun 2009.
*
* @author AFRL/RQQD
*/
public class DDSDecoder {
private static final int DDPF_FOURCC = 0x0004;
private static final int DDSCAPS_TEXTURE = 0x1000;
protected static final int HEADER_SIZE = 128;
/** Reads the file header. This is here to help understand what is contained in the header. The whole header is not
* read since the extraction depends only on DXT type and image size.
* @param buffer
* @return size of image
*/
protected static Dimension readHeaderDxt(ByteBuffer buffer) {
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.rewind();
byte[] magic = new byte[4];
buffer.get(magic);
assert new String(magic).equals("DDS ");
int version = buffer.getInt();
assert version == 124;
int flags = buffer.getInt();
int height = buffer.getInt();
int width = buffer.getInt();
int pixels = buffer.getInt(); // ???
int depth = buffer.getInt();
int mipmaps = buffer.getInt();
buffer.position(buffer.position() + 44); // 11 unused double-words
int pixelFormatSize = buffer.getInt(); // ???
int fourCC = buffer.getInt();
assert fourCC == DDPF_FOURCC;
byte[] format = new byte[4];
buffer.get(format);
//System.out.println(new String(format));
int bpp = buffer.getInt(); // bits per pixel for RGB (non-compressed) formats
buffer.getInt(); // rgb bit masks for RGB formats
buffer.getInt(); // rgb bit masks for RGB formats
buffer.getInt(); // rgb bit masks for RGB formats
buffer.getInt(); // alpha mask for RGB formats
int unknown = buffer.getInt();
assert unknown == DDSCAPS_TEXTURE;
int ddsCaps = buffer.getInt(); // ???
buffer.position(buffer.position() + 12);
return new Dimension(width, height);
}
protected static int getDXTVersion(ByteBuffer buf) {
char verChar = buf.getChar(87);
if (verChar == '1') return 1;
if (verChar == '3') return 3;
return 0;
}
protected static Dimension getImageSize(ByteBuffer buf) {
int h = buf.getInt(12);
int w = buf.getInt(16);
return new Dimension(w, h);
}
/** Reads a DDS image file and returns a buffered image.
*
* @param file the file to read from
* @return a buffered image containing the image data, or null if there is an error.
*/
public static BufferedImage readDxt(File file) {
try {
ByteBuffer buf = ByteBuffer.allocate((int)file.length());
FileInputStream fis = new FileInputStream(file);
int len = fis.read(buf.array());
if (len != (int) file.length()) {
throw new IOException("File reading error.");
}
return readDxt(buf);
} catch (Exception ex) {
Logger.getLogger(DDSDecoder.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
/** Method for extracting an image from a byte buffer that contains the entire image file (header + image data) */
public static BufferedImage readDxt(ByteBuffer buffer) {
buffer.order(ByteOrder.LITTLE_ENDIAN);
int dxtVer = getDXTVersion(buffer);
Dimension dimension = getImageSize(buffer);
buffer.position(HEADER_SIZE);
if (dxtVer == 1)
return readDxt1Buffer(buffer, dimension.width, dimension.height);
else if (dxtVer == 3) {
return readDxt3Buffer(buffer, dimension.width, dimension.height);
}
return null;
}
protected static BufferedImage readDxt3(ByteBuffer buffer) {
buffer.order(ByteOrder.LITTLE_ENDIAN);
Dimension dimension = readHeaderDxt(buffer);
return readDxt3Buffer(buffer, dimension.width, dimension.height);
}
protected static BufferedImage readDxt1(ByteBuffer buffer) {
buffer.order(ByteOrder.LITTLE_ENDIAN);
Dimension dimension = readHeaderDxt(buffer);
return readDxt1Buffer(buffer, dimension.width, dimension.height);
}
protected static BufferedImage readDxt3Buffer(ByteBuffer buffer, int width, int height) {
buffer.order(ByteOrder.LITTLE_ENDIAN);
int[] pixels = new int[16];
int[] alphas = new int[16];
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
Color24[] lookupTable = new Color24[] {new Color24(),new Color24(),new Color24(),new Color24()} ;
int numTilesWide = width / 4;
int numTilesHigh = height / 4;
for (int i = 0; i < numTilesHigh; i++) {
for (int j = 0; j < numTilesWide; j++) {
// Read the alpha table.
long alphaData = buffer.getLong();
for (int k = alphas.length - 1; k >= 0; k--) {
alphas[k] = (int) (alphaData >>> (k * 4)) & 0xF; // Alphas are just 4 bits per pixel
alphas[k] <<= 4;
}
short minColor = buffer.getShort();
short maxColor = buffer.getShort();
expandLookupTable(lookupTable, minColor, maxColor);
int colorData = buffer.getInt();
for (int k = pixels.length - 1; k >= 0; k--) {
int colorCode = (colorData >>> k * 2) & 0x03;
pixels[k] = (alphas[k] << 24) | getPixel888(multiplyAlpha(lookupTable[colorCode], alphas[k]));
}
result.setRGB(j * 4, i * 4, 4, 4, pixels, 0, 4);
}
}
return result;
}
protected static BufferedImage readDxt1Buffer(ByteBuffer buffer, int width, int height) {
buffer.order(ByteOrder.LITTLE_ENDIAN);
int[] pixels = new int[16];
BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Color24[] lookupTable = new Color24[] {new Color24(),new Color24(),new Color24(),new Color24()} ;
int numTilesWide = width / 4;
int numTilesHigh = height / 4;
for (int i = 0; i < numTilesHigh; i++) {
for (int j = 0; j < numTilesWide; j++) {
short minColor = buffer.getShort();
short maxColor = buffer.getShort();
expandLookupTable(lookupTable, minColor, maxColor);
int colorData = buffer.getInt();
for (int k = pixels.length - 1; k >= 0; k--) {
int colorCode = (colorData >>> k * 2) & 0x03;
//pixels[k] = (alphas[k] << 24) | getPixel888(multiplyAlpha(lookupTable[colorCode], 256));
pixels[k] = getPixel888(lookupTable[colorCode]);
}
result.setRGB(j * 4, i * 4, 4, 4, pixels, 0, 4);
}
}
return result;
}
private static Color24 multiplyAlpha(Color24 color, int alpha) {
//Color result = new Color();
double alphaF = alpha / 256.0;
Color24 c = new Color24();
c.r = (int) (color.r * alphaF);
c.g = (int) (color.g * alphaF);
c.b = (int) (color.b * alphaF);
return c;
}
protected static Color24 getColor565(Color24 color, int pixel) {
//Color color = new Color();
color.r = (int) (((long) pixel) & 0xf800) >>> 8;
color.g = (int) (((long) pixel) & 0x07e0) >>> 3;
color.b = (int) (((long) pixel) & 0x001f) << 3;
return color;
}
private static void expandLookupTable(Color24[] result, short minColor, short maxColor) {
getColor565(result[0], minColor);
getColor565(result[1], maxColor);
result[2].r = (2 * result[0].r + result[1].r + 1) / 3;
result[2].g = (2 * result[0].g + result[1].g + 1) / 3;
result[2].b = (2 * result[0].b + result[1].b + 1) / 3;
result[3].r = (result[0].r + 2 * result[1].r + 1) / 3;
result[3].g = (result[0].g + 2 * result[1].g + 1) / 3;
result[3].b = (result[0].b + 2 * result[1].b + 1) / 3;
}
protected static int getPixel888(Color24 color) {
return color.r << 16 | color.g << 8 | color.b;
}
static class Color24 {
int r, g, b;
}
}
/* Distribution A. Approved for public release.
* Case: #88ABW-2015-4601. Date: 24 Sep 2015. */
| 42,785
|
https://github.com/gb-nick/PagerSlidingTabStrip/blob/master/app/src/main/java/com/example/tabstrip/MainActivity.java
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
PagerSlidingTabStrip
|
gb-nick
|
Java
|
Code
| 94
| 392
|
package com.example.tabstrip;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button button, button2, button3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button2 = findViewById(R.id.button2);
button3 = findViewById(R.id.button3);
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent();
if (v.getId() == R.id.button) {
intent.setClass(this, TextTabActivity.class);
} else if (v.getId() == R.id.button2) {
intent.setClass(this, IconTabActivity.class);
} else if (v.getId() == R.id.button3) {
intent.setClass(this, TabActivity.class);
}
startActivity(intent);
}
}
| 12,908
|
https://github.com/roth-andreas/NeurIPS2021-traffic4cast/blob/master/baselines/naive_weighted_average_from_stats.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
NeurIPS2021-traffic4cast
|
roth-andreas
|
Python
|
Code
| 946
| 3,151
|
# Copyright 2021 Institute of Advanced Research in Artificial Intelligence (IARAI) GmbH.
# IARAI licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import logging
from functools import partial
from multiprocessing import Pool
from pathlib import Path
from typing import List
from typing import Optional
from typing import Tuple
import numpy as np
import torch
import tqdm
from baselines.naive_weighted_average import NaiveWeightedAverage
from util.data_range import generate_date_range
from util.data_range import weekday_parser
from util.h5_util import load_h5_file
from util.h5_util import write_data_to_h5
from util.logging import t4c_apply_basic_logging_config
spatio_temporal_cities = ["VIENNA", "CHICAGO"]
temporal_cities = ["BERLIN", "ISTANBUL", "MOSCOW", "NEWYORK"]
class NaiveWeightedAverageWithStats(NaiveWeightedAverage):
def __init__(self, stats_dir: Path, w_stats: float = 0.0, w_random: float = 0.5):
"""
Parameters
----------
stats_dir: Path
where CITY_WEEKDAY_[means|zeros].h5 are stored
w_stats: float
weight `w_stats` given to hourly and daily mean from stats and `1-w_stats` given to mean in test input for each channel.
w_random
scale fraction of no volume by `w_random` when sampling no data.
"""
super(NaiveWeightedAverageWithStats, self).__init__()
self.w_stats = w_stats
self.w_random = w_random
self.means = {}
self.zeros = {}
for city in spatio_temporal_cities + temporal_cities:
for weekday in range(7):
self.means[(city, weekday)] = load_h5_file(str(stats_dir / f"{city}_{weekday}_means.h5"))
self.zeros[(city, weekday)] = load_h5_file(str(stats_dir / f"{city}_{weekday}_zeros.h5"))
if logging.getLogger().isEnabledFor(logging.DEBUG):
logging.debug("%s on %s has means %s", city, weekday, np.unique(self.means[(city, weekday)]))
logging.debug("%s on %s has zeros %s", city, weekday, np.unique(self.zeros[(city, weekday)]))
def forward(self, x: torch.Tensor, additional_data: torch.Tensor, city: str, *args, **kwargs):
x = x.numpy()
additional_data = additional_data.numpy()
batch_size = x.shape[0]
y = np.zeros(shape=(batch_size, 6, 495, 436, 8))
for b in range(batch_size):
weekday, slot = additional_data[b]
y_b = (1 - self.w_stats) * np.mean(x[b], axis=0) + self.w_stats * self.means[(city, weekday)][slot % 24]
assert y_b.shape == (495, 436, 8)
y_b = np.expand_dims(y_b, axis=0)
y_b = np.repeat(y_b, repeats=6, axis=0)
assert y_b.shape == (6, 495, 436, 8), y_b.shape
for t in range(6):
# volume channels
for ch in [0, 2, 4, 6]:
# mask: put pixel to zero with the same probability as in the stats scaled by `w_random`
mask = np.where(np.random.random(size=(495, 436)) * 12 * self.w_random < self.zeros[(city, weekday)][slot % 24][:, :, ch], 0, 1)
assert mask.shape == (495, 436)
# apply mask to volume and corresponding speed channel
y_b[t, :, :, ch] = y_b[t, :, :, ch] * mask
y_b[t, :, :, ch + 1] = y_b[t, :, :, ch + 1] * mask
if logging.getLogger().isEnabledFor(logging.DEBUG):
logging.debug("unique values in forward item %s: %s ", b, np.unique(y_b))
y[b] = y_b
y = torch.from_numpy(y).float()
return y
def process_hourly_means_and_zero_fraction_by_weekday(
task: Tuple[str, int, List[str]], data_raw_dir: Path, output_dir: Path, max_num_files: Optional[int] = None
):
try:
city, weekday, dates = task
logging.debug(f"start for {task}")
files = list(itertools.chain(*[(data_raw_dir / city).rglob(f"{date}_*8ch.h5",) for date in dates]))
if max_num_files is not None:
files = files[:max_num_files]
num_files = len(files)
if num_files == 0:
logging.error(f"no files for {city} {weekday} {dates} in {data_raw_dir}")
data = np.zeros(shape=(num_files, 288, 495, 436, 8), dtype=np.uint8)
for c, f in enumerate(files):
logging.debug(f"{city} {weekday} {c}/{num_files}")
data[c] = load_h5_file(f)
logging.debug(f"{city} {weekday} reshape")
data = np.reshape(data, newshape=(num_files, 24, 12, 495, 436, 8))
logging.debug(f"{city} {weekday} mean/std")
# aggregate over files and within-hour slots to get hourly mean/std
mean = np.mean(data, axis=(0, 2),)
std = np.std(data, axis=(0, 2))
average_non_zero_volume_counts = np.count_nonzero(data, axis=(0, 2)) / (num_files * 12)
for ch in [1, 3, 5, 7]:
average_non_zero_volume_counts[:, :, :, ch] = average_non_zero_volume_counts[:, :, :, ch - 1]
logging.debug(f"{city} {weekday} stacking")
stats = []
stats.append(mean)
stats.append(std)
stats.append(average_non_zero_volume_counts)
stacked_stats = np.stack(stats)
logging.debug(f"{city} {weekday} stacked {stacked_stats.shape}")
logging.debug(f"writing for {task}")
write_data_to_h5(data=stacked_stats, filename=str(output_dir / f"{city}_{weekday}_distribution.h5"), compression_level=6, dtype=stacked_stats.dtype)
logging.debug(f"done for {task}")
logging.debug(f"{city} {weekday} mean/std normalized for non-zero volume")
for ch in [1, 3, 5, 7]:
speed_data = data[:, :, :, :, :, ch]
volume_data = data[:, :, :, :, :, ch - 1]
# `np.mean(..., where=....)` and `np.std(..., where=...)` do not work for too many dimensions, grr...
# mean over all speeds where volume > 0, aggregated by file (all files have same weekday) and hour
s = np.sum(speed_data, axis=(0, 2))
c = np.count_nonzero(volume_data, axis=(0, 2))
speed_normalized_mean = np.zeros_like(s)
non_zero = c != 0
speed_normalized_mean[non_zero] = s[non_zero] / c[non_zero]
mean[:, :, :, ch] = speed_normalized_mean
# std by putting normalized mean speed instead of 0 where volume is zero
# move axis for broadcasting to work...
speed_data = np.moveaxis(speed_data, 1, 2)
volume_data = np.moveaxis(volume_data, 1, 2)
assert speed_data.shape == (num_files, 12, 24, 495, 436), f"{speed_data.shape}"
std[:, :, :, ch] = np.sqrt(np.mean(np.square(np.where(volume_data > 0, speed_data, speed_normalized_mean) - speed_normalized_mean), axis=(0, 1)))
stats = []
stats.append(mean)
stats.append(std)
stats.append(average_non_zero_volume_counts)
logging.debug(f"{city} {weekday} stacking")
stacked_stats = np.stack(stats)
logging.debug(f"{city} {weekday} stacked {stacked_stats.shape}")
logging.debug(f"writing for {task}")
write_data_to_h5(
data=stacked_stats,
filename=str(output_dir / f"{city}_{weekday}_distribution_normalized_nonzeros.h5"),
compression_level=6,
dtype=stacked_stats.dtype,
)
logging.debug(f"done for {task}")
except BaseException as e:
logging.error("something went wrong...", exc_info=e)
def generate_stats_files(city: str, dates: List[str], data_raw_dir: Path, stats_dir: Path, max_num_files: Optional[int] = 3, pool_size: int = 2):
date2weekday = {d: weekday_parser(d) for d in dates}
logging.debug(dates)
logging.debug(date2weekday)
weekday2dates = {}
for date, weekday in sorted(date2weekday.items()):
weekday2dates.setdefault(weekday, []).append(date)
tasks = [(city, weekday, dates) for city in [city] for weekday, dates in weekday2dates.items()]
with Pool(processes=pool_size) as pool:
for _ in tqdm.tqdm(
pool.imap_unordered(
partial(process_hourly_means_and_zero_fraction_by_weekday, data_raw_dir=data_raw_dir, output_dir=stats_dir, max_num_files=max_num_files), tasks,
),
total=len(tasks),
):
pass
def main():
t4c_apply_basic_logging_config(loglevel="DEBUG")
data_raw_dir = Path("privat/competition_prep/01_normalized-less-compressed")
stats_dir = Path("privat/competition_prep/stats")
stats_dir.mkdir(parents=True, exist_ok=True)
pool_size = 2
max_num_files = 4
all_cities = spatio_temporal_cities + temporal_cities
for city in tqdm.tqdm(all_cities):
if city in spatio_temporal_cities:
dates = generate_date_range(f"2019-04-01", f"2019-05-31") + generate_date_range(f"2020-04-01", f"2020-05-31")
else:
dates = generate_date_range(f"2020-04-01", f"2020-05-31")
generate_stats_files(city=city, dates=dates, data_raw_dir=data_raw_dir, stats_dir=stats_dir, max_num_files=max_num_files, pool_size=pool_size)
if __name__ == "__main__":
main()
| 27,397
|
https://github.com/HaoweiCh/bin-html-template/blob/master/go.mod
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
bin-html-template
|
HaoweiCh
|
Go Module
|
Code
| 7
| 42
|
module github.com/HaoweiCh/bin-html-template
go 1.15
require github.com/arschles/assert v1.0.0
| 37,796
|
https://github.com/ch1seL/EverCraft/blob/master/shared/src/main/kotlin/com/mazekine/libs/Cryptography.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
EverCraft
|
ch1seL
|
Kotlin
|
Code
| 440
| 1,384
|
package com.mazekine.libs
import org.slf4j.LoggerFactory
import java.nio.ByteBuffer
import java.security.NoSuchAlgorithmException
import java.security.SecureRandom
import java.security.spec.InvalidKeySpecException
import java.security.spec.KeySpec
import java.util.*
import javax.crypto.Cipher
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
/**
* A Kotlin adaptation of the library for ChaCha20 / Poly1305 encryption/decryption
*
* @author Mkyong, https://mkyong.com/java/java-11-chacha20-poly1305-encryption-examples/
*/
class ChaCha20Poly1305 (
salt: String? = null
) {
init {
salt?.let { Companion.salt = it }
}
//private val logger by lazy { LoggerFactory.getLogger(this::class.java) }
/**
* Encrypt a byte array using the secret key
*
* @param pText Data to encrypt
* @param key Secret key
* @param nonce (Random) nonce
* @return Encoded byte array
*/
@JvmOverloads
@Throws(Exception::class)
fun encrypt(
pText: ByteArray?,
key: SecretKey?,
nonce: ByteArray? = Companion.nonce // if no nonce, generate a random 12 bytes nonce
): ByteArray {
val cipher = Cipher.getInstance(ENCRYPT_ALGO)
// IV, initialization value with nonce
val iv = IvParameterSpec(nonce)
cipher.init(Cipher.ENCRYPT_MODE, key, iv)
val encryptedText = cipher.doFinal(pText)
// append nonce to the encrypted text
return ByteBuffer.allocate(encryptedText.size + NONCE_LEN)
.put(encryptedText)
.put(nonce)
.array()
}
fun encryptStringWithPassword (
data: String? = "",
password: String,
nonce: ByteArray? = Companion.nonce
): String {
return encrypt(
data?.toByteArray(),
secretKeyFromString(password),
nonce
).toHex()
}
@Throws(Exception::class)
fun decrypt(cText: ByteArray, key: SecretKey?): ByteArray {
val bb = ByteBuffer.wrap(cText)
// split cText to get the appended nonce
val encryptedText = ByteArray(cText.size - NONCE_LEN)
val nonce = ByteArray(NONCE_LEN)
bb[encryptedText]
bb[nonce]
val cipher = Cipher.getInstance(ENCRYPT_ALGO)
val iv = IvParameterSpec(nonce)
cipher.init(Cipher.DECRYPT_MODE, key, iv)
// decrypted text
return cipher.doFinal(encryptedText)
}
fun decryptStringWithPassword(
data: String,
password: String
): String {
return String(decrypt(
data.hexToByteArray(),
secretKeyFromString(password)
))
}
/**
* Generates a secret key from a password
* Uses a concept proposed by Baeldung: https://www.baeldung.com/java-secret-key-to-string
*
* @param input User's arbitrary string
* @return SecretKey
* @throws NoSuchAlgorithmException In case the library doesn't support ChaCha20
*/
@Throws(NoSuchAlgorithmException::class, InvalidKeySpecException::class)
fun secretKeyFromString(input: String): SecretKey {
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
val spec: KeySpec = PBEKeySpec(input.toCharArray(), salt.toByteArray(), 65536, 256)
return SecretKeySpec(factory.generateSecret(spec).encoded, "AES")
}
companion object {
private const val ENCRYPT_ALGO = "ChaCha20-Poly1305"
private const val NONCE_LEN = 12 // 96 bits, 12 bytes
// 96-bit nonce (12 bytes)
private val nonce: ByteArray
get() {
val newNonce = ByteArray(NONCE_LEN)
SecureRandom().nextBytes(newNonce)
return newNonce
}
var salt: String = "EverCraft"
}
}
/**
* Converts a byte array to a hex view
*
* @return String
*/
fun ByteArray.toHex(): String {
val result = StringBuilder()
for (temp in this) {
result.append(String.format("%02x", temp))
}
return result.toString()
}
fun String.hexToByteArray(): ByteArray {
check(length % 2 == 0) {
try {
ResourceBundle
.getBundle("messages", Locale.ENGLISH)
.getString("error.hex.odd")
} catch (e: Exception) {
"String length must be even"
}
}
return ByteArray(length / 2) {
Integer.parseInt(this, it * 2, (it + 1) * 2, 16).toByte()
}
}
| 44,798
|
https://github.com/Shiguang-Guo/fairseq/blob/master/fairseq/benchmark/dummy_masked_lm.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
fairseq
|
Shiguang-Guo
|
Python
|
Code
| 275
| 955
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from dataclasses import dataclass, field
from typing import Optional
import torch
from omegaconf import II
from .dummy_dataset import DummyDataset
from fairseq.data import Dictionary
from fairseq.dataclass import FairseqDataclass
from fairseq.tasks import FairseqTask, register_task
logger = logging.getLogger(__name__)
@dataclass
class DummyMaskedLMConfig(FairseqDataclass):
dict_size: int = 49996
dataset_size: int = 100000
tokens_per_sample: int = field(
default=512,
metadata={
"help": "max number of total tokens over all"
" segments per sample for BERT dataset"
},
)
batch_size: Optional[int] = II("dataset.batch_size")
max_tokens: Optional[int] = II("dataset.max_tokens")
max_target_positions: int = II("task.tokens_per_sample")
@register_task("dummy_masked_lm", dataclass=DummyMaskedLMConfig)
class DummyMaskedLMTask(FairseqTask):
def __init__(self, cfg: DummyMaskedLMConfig):
super().__init__(cfg)
self.dictionary = Dictionary()
for i in range(cfg.dict_size):
self.dictionary.add_symbol("word{}".format(i))
logger.info("dictionary: {} types".format(len(self.dictionary)))
# add mask token
self.mask_idx = self.dictionary.add_symbol("<mask>")
self.dictionary.pad_to_multiple_(8) # often faster if divisible by 8
mask_idx = 0
pad_idx = 1
seq = torch.arange(cfg.tokens_per_sample) + pad_idx + 1
mask = torch.arange(2, cfg.tokens_per_sample, 7) # ~15%
src = seq.clone()
src[mask] = mask_idx
tgt = torch.full_like(seq, pad_idx)
tgt[mask] = seq[mask]
self.dummy_src = src
self.dummy_tgt = tgt
def load_dataset(self, split, epoch=1, combine=False, **kwargs):
"""Load a given dataset split.
Args:
split (str): name of the split (e.g., train, valid, test)
"""
if self.cfg.batch_size is not None:
bsz = self.cfg.batch_size
else:
bsz = max(1, self.cfg.max_tokens // self.cfg.tokens_per_sample)
self.datasets[split] = DummyDataset(
{
"id": 1,
"net_input": {
"src_tokens": torch.stack([self.dummy_src for _ in range(bsz)]),
"src_lengths": torch.full(
(bsz,), self.cfg.tokens_per_sample, dtype=torch.long
),
},
"target": torch.stack([self.dummy_tgt for _ in range(bsz)]),
"nsentences": bsz,
"ntokens": bsz * self.cfg.tokens_per_sample,
},
num_items=self.cfg.dataset_size,
item_size=self.cfg.tokens_per_sample,
)
@property
def source_dictionary(self):
return self.dictionary
@property
def target_dictionary(self):
return self.dictionary
| 46,432
|
https://github.com/opendatafit/sasview/blob/master/src/sas/sascalc/simulation/geoshapespy/libgeoshapespy/ellipsoid.cc
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
sasview
|
opendatafit
|
C++
|
Code
| 389
| 1,437
|
/** \file Ellipsoid.cc */
#include <cmath>
#include <cassert>
#include <algorithm>
//MS library does not define min max in algorithm
//#include "minmax.h"
#include "ellipsoid.h"
#include "myutil.h"
using namespace std;
Ellipsoid::Ellipsoid()
{
rx_ = 0;
ry_ = 0;
rz_ = 0;
}
Ellipsoid::Ellipsoid(double rx, double ry, double rz)
{
rx_ = rx;
ry_ = ry;
rz_ = rz;
xedge_plus_ = Point3D(rx,0,0);
xedge_minus_ = Point3D(-rx,0,0);
yedge_plus_ = Point3D(0,ry,0);
yedge_minus_ = Point3D(0,-ry,0);
zedge_plus_ = Point3D(0,0,rz);
zedge_minus_ = Point3D(0,0,-rz);
}
Ellipsoid::~Ellipsoid()
{
}
void Ellipsoid::SetRadii(double rx, double ry, double rz)
{
rx_ = rx;
ry_ = ry;
rz_ = rz;
}
double Ellipsoid::GetRadiusX()
{
return rx_;
}
double Ellipsoid::GetRadiusY()
{
return ry_;
}
double Ellipsoid::GetRadiusZ()
{
return rz_;
}
double Ellipsoid::GetMaxRadius()
{
double maxr = max(max(rx_,ry_),max(ry_,rz_));
return maxr;
}
ShapeType Ellipsoid::GetShapeType() const
{
return ELLIPSOID;
}
double Ellipsoid::GetVolume()
{
double V = (4./3.)*pi*rx_*ry_*rz_;
return V;
}
void Ellipsoid::GetFormFactor(IQ * iq)
{
/** number of I for output, equal to the number of rows of array IQ*/
/** to be finished */
}
Point3D Ellipsoid::GetAPoint(double sld)
{
static int max_try = 100;
for (int i = 0; i < max_try; ++i) {
double x = (ran1()-0.5) * 2 * rx_;
double y = (ran1()-0.5) * 2 * ry_;
double z = (ran1()-0.5) * 2 * rz_;
if ((square(x/rx_) + square(y/ry_) + square(z/rz_)) <= 1){
Point3D apoint(x,y,z,sld);
return apoint;
}
}
std::cerr << "Max try "
<< max_try
<< " is reached while generating a point in ellipsoid" << std::endl;
return Point3D(0, 0, 0);
}
bool Ellipsoid::IsInside(const Point3D& point) const
{
//x, y, z axis are internal axis
bool isOutsideX = false;
Point3D pointOnX = point.getInterPoint(GetXaxisPlusEdge(),GetXaxisMinusEdge(),&isOutsideX);
bool isOutsideY = false;
Point3D pointOnY = point.getInterPoint(GetYaxisPlusEdge(),GetYaxisMinusEdge(),&isOutsideY);
bool isOutsideZ = false;
Point3D pointOnZ = point.getInterPoint(GetZaxisPlusEdge(),GetZaxisMinusEdge(),&isOutsideZ);
if (isOutsideX || isOutsideY || isOutsideZ){
//one is outside axis is true -> the point is not inside
return false;
}
else{
Point3D pcenter = GetCenterP();
double distX = pointOnX.distanceToPoint(pcenter);
double distY = pointOnY.distanceToPoint(pcenter);
double distZ = pointOnZ.distanceToPoint(pcenter);
return ((square(distX/rx_)+square(distY/ry_)+square(distZ/rz_)) <= 1);
}
}
Point3D Ellipsoid::GetXaxisPlusEdge() const
{
Point3D new_edge(xedge_plus_);
new_edge.Transform(GetOrientation(),GetCenter());
return new_edge;
}
Point3D Ellipsoid::GetXaxisMinusEdge() const
{
Point3D new_edge(xedge_minus_);
new_edge.Transform(GetOrientation(),GetCenter());
return new_edge;
}
Point3D Ellipsoid::GetYaxisPlusEdge() const
{
Point3D new_edge(yedge_plus_);
new_edge.Transform(GetOrientation(),GetCenter());
return new_edge;
}
Point3D Ellipsoid::GetYaxisMinusEdge() const
{
Point3D new_edge(yedge_minus_);
new_edge.Transform(GetOrientation(),GetCenter());
return new_edge;
}
Point3D Ellipsoid::GetZaxisPlusEdge() const
{
Point3D new_edge(zedge_plus_);
new_edge.Transform(GetOrientation(),GetCenter());
return new_edge;
}
Point3D Ellipsoid::GetZaxisMinusEdge() const
{
Point3D new_edge(zedge_minus_);
new_edge.Transform(GetOrientation(),GetCenter());
return new_edge;
}
| 12,018
|
https://github.com/vyuldashev/minter-console-web/blob/master/components/CoinCreateForm.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
minter-console-web
|
vyuldashev
|
Vue
|
Code
| 1,423
| 6,545
|
<script>
import {validationMixin} from 'vuelidate';
import required from 'vuelidate/lib/validators/required.js';
import minValue from 'vuelidate/lib/validators/minValue.js';
import maxValue from 'vuelidate/lib/validators/maxValue.js';
import minLength from 'vuelidate/lib/validators/minLength.js';
import maxLength from 'vuelidate/lib/validators/maxLength.js';
import withParams from 'vuelidate/lib/withParams.js';
import {COIN_MIN_MAX_SUPPLY, COIN_MAX_MAX_SUPPLY} from "minterjs-util/src/variables.js";
import {TX_TYPE} from 'minterjs-util/src/tx-types.js';
import {sellCoin} from 'minterjs-util/src/coin-math';
import {FeePrice} from 'minterjs-util/src/fee.js';
import {getCommissionPrice} from '~/api/gate.js';
import checkEmpty from '~/assets/v-check-empty.js';
import {prettyExact, prettyExactDecrease, prettyPreciseFloor, prettyRound, coinSymbolValidator} from "~/assets/utils.js";
import BaseAmount from '~/components/common/BaseAmount.vue';
import TxForm from '~/components/common/TxForm.vue';
import InputUppercase from '~/components/common/InputUppercase.vue';
import InputMaskedAmount from '~/components/common/InputMaskedAmount.vue';
import FieldPercentage from '~/components/common/FieldPercentage.vue';
const MIN_CRR = 10;
const MAX_CRR = 100;
const MIN_CREATE_RESERVE = 10000;
const constantReserveRatioValidator = withParams({type: 'constantReserveRatio'}, function(value) {
let constantReserveRatio = parseInt(value, 10);
return constantReserveRatio === 0 || (MIN_CRR <= constantReserveRatio && MAX_CRR >= constantReserveRatio);
});
function minValueOrZero(val) {
return parseInt(val) === 0 || minValue(MIN_CREATE_RESERVE)(val);
}
/**
* @param {Object} form
* @return {number}
*/
function calculatePrice(form) {
const sellAmount = 1;
const price = sellCoin(formToCoin(form), sellAmount);
return price >= 0 ? price : 0;
}
/**
* @param {Object} form
* @return {Coin}
*/
function formToCoin(form) {
return {
supply: form.initialAmount,
reserve: form.initialReserve,
crr: form.constantReserveRatio / 100,
};
}
export default {
// first key not handled by webstorm intelliSense
ideFix: true,
TX_TYPE,
MIN_CREATE_RESERVE,
MIN_CRR,
MAX_CRR,
COIN_MIN_MAX_SUPPLY,
COIN_MAX_MAX_SUPPLY,
prettyRound,
prettyPreciseFloor,
prettyExact,
prettyExactDecrease,
components: {
BaseAmount,
FieldPercentage,
TxForm,
InputUppercase,
InputMaskedAmount,
},
directives: {
checkEmpty,
},
mixins: [validationMixin],
fetch() {
return getCommissionPrice()
.then((commissionPriceData) => {
this.commissionPriceData = commissionPriceData;
});
},
data() {
return {
form: {
name: '',
symbol: '',
initialAmount: '',
constantReserveRatio: null,
initialReserve: '',
maxSupply: '',
mintable: false,
burnable: false,
},
txType: TX_TYPE.CREATE_COIN,
/** @type CommissionPriceData|null */
commissionPriceData: null,
};
},
validations() {
const form = {
name: {
maxLength: maxLength(64),
},
symbol: {
required,
minLength: minLength(3),
maxLength: maxLength(10),
valid: coinSymbolValidator,
},
initialAmount: {
required,
minValue: minValue(1),
maxValue: maxValue(this.form.maxSupply || COIN_MAX_MAX_SUPPLY),
},
constantReserveRatio: {
required: this.txType === TX_TYPE.CREATE_COIN ? required : () => true,
between: this.txType === TX_TYPE.CREATE_COIN ? constantReserveRatioValidator : () => true,
},
initialReserve: {
required: this.txType === TX_TYPE.CREATE_COIN ? required : () => true,
minValue: this.txType === TX_TYPE.CREATE_COIN ? minValueOrZero : () => true,
},
maxSupply: {
minValue: this.form.maxSupply ? minValue(COIN_MIN_MAX_SUPPLY) : () => true,
maxValue: this.form.maxSupply ? maxValue(COIN_MAX_MAX_SUPPLY) : () => true,
},
};
return {
form,
};
},
computed: {
coinPrice() {
return calculatePrice(this.form);
},
feePriceCoin() {
return this.commissionPriceData?.coin.symbol || '';
},
},
methods: {
getFee(length) {
if (!this.commissionPriceData) {
return false;
}
const feePrice = new FeePrice(this.commissionPriceData);
return prettyRound(feePrice.getFeeValue(this.txType, {
coinSymbolLength: length,
}));
},
clearForm() {
this.form.name = '';
this.form.symbol = '';
this.form.initialAmount = '';
this.form.constantReserveRatio = null;
this.form.initialReserve = '';
this.form.maxSupply = '';
this.form.mintable = false;
this.form.burnable = false;
this.$v.$reset();
this.txType = TX_TYPE.CREATE_COIN;
},
},
};
</script>
<template>
<TxForm
:txData="form"
:$txData="$v.form"
:txType="txType"
@clear-form="clearForm()"
>
<template v-slot:panel-header>
<h1 class="panel__header-title">
{{ $td('Create coin or token', 'coiner.create-title') }}
</h1>
<p class="panel__header-description">
{{ $td('Create your own coin from scratch. It is completely up to you to decide what role it will play — that of a currency, a security, a utility token, a right, a vote, or something else.', 'coiner.create-description') }}
</p>
</template>
<template v-slot:default="{fee, addressBalance}">
<div class="u-cell">
<div class="form-check-label">Type</div>
<label class="form-check">
<input type="radio" class="form-check__input" name="convert-type" :value="$options.TX_TYPE.CREATE_COIN" v-model="txType">
<span class="form-check__label form-check__label--radio">{{ $td('Coin', 'form.coiner-type-coin') }}</span>
</label>
<label class="form-check">
<input type="radio" class="form-check__input" name="convert-type" :value="$options.TX_TYPE.CREATE_TOKEN" v-model="txType">
<span class="form-check__label form-check__label--radio">{{ $td('Token', 'form.coiner-type-token') }}</span>
</label>
</div>
<div class="u-cell u-cell--medium--1-2">
<label class="form-field" :class="{'is-error': $v.form.name.$error}">
<input class="form-field__input" type="text" v-check-empty
v-model.trim="form.name"
@blur="$v.form.name.$touch()"
>
<span class="form-field__label">{{ $td('Coin name (optional)', 'form.coiner-create-name') }}</span>
</label>
<span class="form-field__error" v-if="$v.form.name.$dirty && !$v.form.name.maxLength">{{ $td('Max 64 letters', 'form.coiner-create-name-error-max') }}</span>
<div class="form-field__help" v-html="$td('The full name or description of your coin (for example, <strong>Bitcoin</strong>). Arbitrary string up to 64 letters long.', 'form.coiner-create-name-help')"></div>
</div>
<div class="u-cell u-cell--medium--1-2">
<label class="form-field" :class="{'is-error': $v.form.symbol.$error}">
<InputUppercase class="form-field__input" type="text" autocapitalize="off" spellcheck="false" v-check-empty
v-model.trim="form.symbol"
@blur="$v.form.symbol.$touch()"
/>
<span class="form-field__label">{{ $td('Coin symbol', 'form.coiner-create-symbol') }}</span>
</label>
<span class="form-field__error" v-if="$v.form.symbol.$dirty && !$v.form.symbol.required">{{ $td('Enter coin symbol', 'form.coiner-create-symbol-error-required') }}</span>
<span class="form-field__error" v-else-if="$v.form.symbol.$dirty && !$v.form.symbol.minLength">{{ $td('Min 3 letters', 'form.coin-error-min') }}</span>
<span class="form-field__error" v-else-if="$v.form.symbol.$dirty && !$v.form.symbol.maxLength">{{ $td('Max 10 letters', 'form.coin-error-max') }}</span>
<span class="form-field__error" v-else-if="$v.form.symbol.$dirty && !$v.form.symbol.valid">{{ $td('Invalid coin ticker', 'form.coin-error-name') }}</span>
<div class="form-field__help" v-html="$td('Ticker symbol (for example, <strong>BTC</strong>). Must be unique, alphabetic, uppercase, and 3 to 10 symbols long.', 'form.coiner-create-symbol-help')"></div>
</div>
<div class="u-cell u-cell--medium--1-2">
<label class="form-field" :class="{'is-error': $v.form.initialAmount.$error}">
<InputMaskedAmount class="form-field__input" type="text" inputmode="decimal" v-check-empty
v-model="form.initialAmount"
@blur="$v.form.initialAmount.$touch()"
/>
<span class="form-field__label">{{ $td('Initial amount', 'form.coiner-create-amount') }}</span>
</label>
<span class="form-field__error" v-if="$v.form.initialAmount.$dirty && !$v.form.initialAmount.required">{{ $td('Enter amount', 'form.amount-error-required') }}</span>
<span class="form-field__error" v-else-if="$v.form.initialAmount.$dirty && !$v.form.initialAmount.minValue">{{ $td(`Min amount is 1`, 'form.coiner-create-amount-error-min') }}</span>
<span class="form-field__error" v-else-if="$v.form.initialAmount.$dirty && !$v.form.initialAmount.maxValue">
{{ $td(`Initial amount should be less or equal of Max supply`, 'form.coiner-create-amount-error-max') }}:
<span v-if="form.maxSupply">{{ $options.prettyExactDecrease(form.maxSupply) }}</span>
<span v-else>10<sup>15</sup></span>
</span>
</div>
<div class="u-cell u-cell--medium--1-2" v-show="txType === $options.TX_TYPE.CREATE_COIN">
<label class="form-field" :class="{'is-error': $v.form.initialReserve.$error}">
<InputMaskedAmount class="form-field__input" type="text" inputmode="decimal" v-check-empty
v-model.number="form.initialReserve"
@blur="$v.form.initialReserve.$touch()"
/>
<span class="form-field__label">{{ $td('Initial reserve', 'form.coiner-create-reserve') }}</span>
</label>
<span class="form-field__error" v-if="$v.form.initialReserve.$dirty && !$v.form.initialReserve.required">{{ $td('Enter reserve', 'form.coiner-create-reserve-error-required') }}</span>
<span class="form-field__error" v-else-if="$v.form.initialReserve.$dirty && !$v.form.initialReserve.minValue">{{ $td(`Min reserve is ${$store.getters.COIN_NAME} ${$options.prettyRound($options.MIN_CREATE_RESERVE)}`, 'form.coiner-create-reserve-error-min', {coin: $store.getters.COIN_NAME, min: $options.MIN_CREATE_RESERVE}) }}</span>
</div>
<div class="u-cell u-cell--medium--1-2" v-show="txType === $options.TX_TYPE.CREATE_COIN">
<FieldPercentage
v-model="form.constantReserveRatio"
:$value="$v.form.constantReserveRatio"
:label="$td('Constant reserve ratio', 'form.coiner-create-crr')"
:min-value="$options.MIN_CRR"
:max-value="$options.MAX_CRR"
/>
<span class="form-field__error" v-if="$v.form.constantReserveRatio.$dirty && !$v.form.constantReserveRatio.required">{{ $td('Enter CRR', 'form.coiner-create-crr-error-required') }}</span>
<span class="form-field__error" v-else-if="$v.form.constantReserveRatio.$dirty && !$v.form.constantReserveRatio.between">{{ $td('CRR should be between 10 and 100', 'form.coiner-create-crr-error-between') }}</span>
<div class="form-field__help">{{ $td('CRR reflects the volume of BIP reserves backing a newly issued coin. The higher the coefficient, the higher the reserves and thus the lower the volatility. And vice versa. The value should be integer and fall in the range from 10 to 100.', 'form.coiner-create-crr-help') }}</div>
</div>
<div class="u-cell u-cell--medium--1-2">
<label class="form-field" :class="{'is-error': $v.form.maxSupply.$error}">
<InputMaskedAmount class="form-field__input" type="text" inputmode="decimal" v-check-empty
v-model="form.maxSupply"
@blur.native="$v.form.maxSupply.$touch()"
/>
<span class="form-field__label">{{ $td('Max supply (optional)', 'form.coiner-create-max-supply') }}</span>
</label>
<span class="form-field__error" v-if="$v.form.maxSupply.$dirty && !$v.form.maxSupply.minValue">{{ $td(`Min value is ${$options.COIN_MIN_MAX_SUPPLY}`, 'form.coiner-create-max-supply-error-min', {value: $options.COIN_MIN_MAX_SUPPLY}) }}</span>
<span class="form-field__error" v-else-if="$v.form.maxSupply.$dirty && !$v.form.maxSupply.maxValue">{{ $td(`Max value is ${$options.COIN_MAX_MAX_SUPPLY}`, 'form.coiner-create-max-supply-error-max', {value: $options.COIN_MAX_MAX_SUPPLY}) }}</span>
<div class="form-field__help">
{{ $td('Some txs will be not accepted by blockchain if they will lead to exceeding the limit.', 'form.coiner-create-max-supply-help') }}
<br>
{{ $td('Default:', 'form.help-default') }} 10^15
</div>
</div>
<div class="u-cell" v-show="txType === $options.TX_TYPE.CREATE_TOKEN">
<div class="form-check-label">Allow edit token supply</div>
<label class="form-check">
<input class="form-check__input" type="checkbox" v-model="form.mintable">
<span class="form-check__label form-check__label--checkbox">{{ $td('Mintable', 'form.coiner-create-token-mintable') }}</span>
</label>
<label class="form-check">
<input class="form-check__input" type="checkbox" v-model="form.burnable">
<span class="form-check__label form-check__label--checkbox">{{ $td('Burnable', 'form.coiner-create-token-burnalbe') }}</span>
</label>
</div>
</template>
<template v-slot:panel-footer>
<div class="u-grid u-grid--small u-mb-10" v-if="txType === $options.TX_TYPE.CREATE_COIN">
<div class="u-cell u-cell--large--1-2">
<label class="form-field form-field--dashed">
<input class="form-field__input is-not-empty" type="text" readonly
:value="$options.prettyPreciseFloor(coinPrice)"
>
<span class="form-field__label">{{ $td('Initial price', 'form.coiner-create-price') }}</span>
</label>
</div>
</div>
<!--@see https://github.com/MinterTeam/minter-go-node/blob/master/core/transaction/create_coin.go#L93-->
<template v-if="$i18n.locale === 'en'">
<template v-if="txType === $options.TX_TYPE.CREATE_COIN">
<p><span class="u-emoji">⚠️</span> Coin liquidation is not allowed. One can't sell coin if it reserve goes lower than 10 000 {{ $store.getters.COIN_NAME }}.</p>
<p>See how coin reserve works: <a class="link--default" href="https://calculator.minter.network" target="_blank">calculator.minter.network</a></p>
</template>
<p>Ticker symbol fees:</p>
<p>
3 letters — {{ feePriceCoin }} {{ getFee(3) }}<br>
4 letters — {{ feePriceCoin }} {{ getFee(4) }}<br>
5 letters — {{ feePriceCoin }} {{ getFee(5) }}<br>
6 letters — {{ feePriceCoin }} {{ getFee(6) }}<br>
7-10 letters — {{ feePriceCoin }} {{ getFee(7) }}<br>
</p>
</template>
<template v-if="$i18n.locale === 'ru'">
<template v-if="txType === $options.TX_TYPE.CREATE_COIN">
<p><span class="u-emoji">⚠️</span> Внимание! Ликвидация монеты будет невозможна. <br> Нельзя продать монету, если это понизит её резерв ниже 10 000 {{ $store.getters.COIN_NAME }}.</p>
<p>Вы можете проверить как работает связь между выпуском, резервом и CRR в нашем калькуляторе: <a class="link--default" href="https://calculator.minter.network" target="_blank">calculator.minter.network</a></p>
</template>
<p class="u-text-muted">Комиссии на длину тикера:</p>
<p class="u-text-muted">
3 буквы — {{ feePriceCoin }} {{ getFee(3) }}<br>
4 буквы — {{ feePriceCoin }} {{ getFee(4) }}<br>
5 букв — {{ feePriceCoin }} {{ getFee(5) }}<br>
6 букв — {{ feePriceCoin }} {{ getFee(6) }}<br>
7-10 букв — {{ feePriceCoin }} {{ getFee(7) }}<br>
</p>
</template>
</template>
<template v-slot:submit-title>
{{ $td('Create', 'form.coiner-create-button') }}
</template>
<template v-slot:confirm-modal-header>
<h1 class="panel__header-title">
<img class="panel__header-title-icon" :src="`${BASE_URL_PREFIX}/img/icon-feature-coin-creation.svg`" alt="" role="presentation" width="40" height="40">
{{ $td('Create', 'coiner.create-title') }}
</h1>
</template>
<template v-slot:confirm-modal-body>
<div class="u-grid u-grid--small u-grid--vertical-margin u-text-left">
<div class="u-cell">
<div class="form-field form-field--dashed">
<BaseAmount tag="div" class="form-field__input is-not-empty" :coin="form.symbol" :amount="form.initialAmount" :exact="true"/>
<div class="form-field__label">{{ $td('You issue', 'form.coiner-create-confirm-amount') }}</div>
</div>
</div>
<div class="u-cell" v-if="txType === $options.TX_TYPE.CREATE_COIN">
<label class="form-field form-field--dashed">
<input class="form-field__input is-not-empty" autocapitalize="off" spellcheck="false" readonly tabindex="-1"
:value="form.constantReserveRatio + '%'"
/>
<span class="form-field__label">{{ $td('With CRR', 'form.coiner-create-confirm-crr') }}</span>
</label>
</div>
<div class="u-cell" v-if="txType === $options.TX_TYPE.CREATE_COIN">
<div class="form-field form-field--dashed">
<BaseAmount tag="div" class="form-field__input is-not-empty" :coin="$store.getters.COIN_NAME" :amount="form.initialReserve" :exact="true"/>
<div class="form-field__label">{{ $td('By reserving', 'form.coiner-create-confirm-reserve') }}</div>
</div>
</div>
<div class="u-cell u-text-left" v-if="txType === $options.TX_TYPE.CREATE_TOKEN">
<div>
Mintable:
<span v-if="form.mintable">✅ {{ $td('Yes', 'common.yes') }}</span>
<span v-else>🚫 {{ $td('No', 'common.no') }}</span>
</div>
<div>
Burnable:
<span v-if="form.burnable">✅ {{ $td('Yes', 'common.yes') }}</span>
<span v-else>🚫 {{ $td('No', 'common.no') }}</span>
</div>
</div>
</div>
</template>
<template v-slot:confirm-modal-footer v-if="txType === $options.TX_TYPE.CREATE_COIN">
<div class="u-text-left">
<p v-if="$i18n.locale === 'en'">
Coin liquidation is not allowed. <br> One can't sell coin if it reserve goes lower than <strong class="u-display-ib">10 000 {{ $store.getters.COIN_NAME }}</strong>.
</p>
<p v-if="$i18n.locale === 'ru'">
Ликвидация монеты будет невозможна. <br> Нельзя продать монету, если это понизит её резерв ниже <strong class="u-display-ib">10 000 {{ $store.getters.COIN_NAME }}</strong>.
</p>
</div>
</template>
</TxForm>
</template>
| 47,153
|
https://github.com/anugraha07/HoNoSoFt.BadgeIt.SonarQube/blob/master/HoNoSoFt.BadgeIt.SonarQube.Web/Logics/SonarQubeColorsSteps/FinalBestValueColorStep.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
HoNoSoFt.BadgeIt.SonarQube
|
anugraha07
|
C#
|
Code
| 105
| 407
|
using HoNoSoFt.BadgeIt.SonarQube.Web.Models;
using System;
namespace HoNoSoFt.BadgeIt.SonarQube.Web.Logics.SonarQubeColorsSteps
{
internal class FinalBestValueColorStep : IColorStep
{
private IColorStep _successorTrue;
private IColorStep _successorFalse;
public FinalBestValueColorStep() { }
public void SetSuccessor(IColorStep successorTrue, IColorStep successorFalse)
{
_successorTrue = successorTrue;
_successorFalse = successorFalse;
}
public ShieldsColors Handle(Measure measure, SonarQubeMetric metric)
{
var isThisTrue = metric.SmallerThanValue(measure.Value ?? measure.Periods[0].Value, metric.BestValue ?? "0");
if (string.IsNullOrEmpty(metric.BestValue) || !isThisTrue.HasValue)
{
return ShieldsColors.LightGrey;
}
// We could also invert in case of higherIsBetter
if (!metric.HigherValuesAreBetter)
{
return isThisTrue.Value || measure.Value.Equals(metric.BestValue, StringComparison.OrdinalIgnoreCase)
? ShieldsColors.YellowGreen
: ShieldsColors.Red;
}
return isThisTrue.Value
? ShieldsColors.Red
: ShieldsColors.YellowGreen;
}
public bool ValidateSetup()
{
return _successorTrue == null
&& _successorFalse == null;
}
}
}
| 6,923
|
https://github.com/relinkt/shipping-company-tier3/blob/master/resources/js/views/sample-pages/two-step-verification.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
shipping-company-tier3
|
relinkt
|
Vue
|
Code
| 172
| 697
|
<script>
import CodeInput from "vue-verification-code-input";
export default {
data() {
return {};
},
components: { CodeInput },
methods: {},
};
</script>
<template>
<div class="account-pages my-5 pt-sm-5">
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="text-center mb-5 text-muted">
<a href="/" class="d-block auth-logo">
<img
src="/images/logo-dark.png"
alt=""
height="20"
class="auth-logo-dark mx-auto"
/>
<img
src="/images/logo-light.png"
alt=""
height="20"
class="auth-logo-light mx-auto"
/>
</a>
<p class="mt-3">Responsive Bootstrap 5 Admin Dashboard</p>
</div>
</div>
</div>
<!-- end row -->
<div class="row justify-content-center">
<div class="col-md-8 col-lg-6 col-xl-5">
<div class="card">
<div class="card-body">
<div class="p-2">
<div class="text-center">
<div class="avatar-md mx-auto">
<div class="avatar-title rounded-circle bg-light">
<i class="bx bxs-envelope h1 mb-0 text-primary"></i>
</div>
</div>
<div class="p-2 mt-4">
<h4>Verify your email</h4>
<p class="mb-5">
Please enter the 6 digit code sent to
<span class="fw-semibold">example@abc.com</span>
</p>
<CodeInput :loading="false" class="input" />
<div class="mt-4">
<a href="/" class="btn btn-success w-md">Confirm</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="mt-5 text-center">
<p>
Did't receive a code ?
<a href="#" class="fw-medium text-primary"> Resend </a>
</p>
<p>
©
{{ new Date().getFullYear() }}
Skote. Crafted with <i class="mdi mdi-heart text-danger"></i> by
Themesbrand
</p>
</div>
</div>
</div>
</div>
</div>
</template>
| 11,588
|
https://github.com/Ichcodealsobinich/Test/blob/master/Seminar/src/Quest856/Movie.java
|
Github Open Source
|
Open Source
|
MIT
| null |
Test
|
Ichcodealsobinich
|
Java
|
Code
| 116
| 312
|
package Quest856;
import java.util.Arrays;
public class Movie {
private String title = "";
private String[] actors = {"", "", ""};
public void setTitle(String name) {
this.title=name;
}
public boolean setActors(String[] someActors) {
if (someActors.length==actors.length) {
actors = someActors;
return true;
}
return false;
}
public String getTitle() {
return title;
}
public String[] getActors() {
return actors;
}
public Movie(String name, String[] actors) {
this.title=name;
this.actors=actors;
}
public String toString() {
String ret = "In the movie " + this.title + ", the main actors are: ";
for (String actor : actors) {
ret = ret + actor + ", ";
}
ret = ret.trim();
if (ret.endsWith(",")){
ret = ret.substring(0, ret.length()-1);
}
return ret;
}
}
| 18,728
|
https://github.com/c0ding/survey/blob/master/SPV/Home/controller/DRReportVC/DRReportViewController.m
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
survey
|
c0ding
|
Objective-C
|
Code
| 311
| 1,496
|
//
// DRReportViewController.m
// SPV
//
// Created by 黄梦炜 on 2019/2/21.
// Copyright © 2019 训机. All rights reserved.
//
#import "DRReportViewController.h"
#import "DRReportLeftTableViewCell.h"
#import "DRReportRightTableViewCell.h"
#import "DRReportModel.h"
@interface DRReportViewController ()<UITableViewDelegate, UITableViewDataSource>
@end
@implementation DRReportViewController
{
DRBaseTableView *leftTable;
DRBaseTableView *rightTable;
DRReportModel *model;
NSInteger selectCell;
}
- (void)viewDidLoad {
[super viewDidLoad];
selectCell = 0;
[self setTitleView:@"尽调报告" color:YES];
[self createTableleftAndRight];
// Do any additional setup after loading the view.
}
-(void)getData
{
@weakify(self)
DRCollectListModel *modelCollectList = _modelCollect.list[0];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:_obligatoryRightId forKey:@"obligatoryRightId"];
[params setObject:modelCollectList.guaranteeId forKey:@"guaranteeId"];
[[request new] getReportModel:params net:^(id data, RequestResult *result) {
model = data;
[self createTableleftAndRight];
} error:^(RequestResult *result) {
} handleErrorCode:^(NSUInteger errorCode) {
}];
}
-(void)createTableleftAndRight
{
leftTable = [DRBaseTableView new] ;
[self.view addSubview:leftTable];
[leftTable mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.offset(0);
make.top.offset(0);
make.bottom.offset(0);
make.width.offset(kWidth(92.5));
}];
leftTable.dataSource = self;
leftTable.delegate = self;
[leftTable registerClass:[DRReportLeftTableViewCell class] forCellReuseIdentifier:@"left"];
[leftTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
leftTable.estimatedRowHeight=1000.0;
leftTable.rowHeight=UITableViewAutomaticDimension;
UIView *lineView = [UIView new];
[self.view addSubview:lineView];
[lineView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(leftTable.mas_right).offset(0);
make.top.offset(0);
make.bottom.offset(0);
make.width.offset(0.5);
}];
[lineView setBackgroundColor:getUIColor(0xA9A9A9)];
rightTable = [DRBaseTableView new] ;
[self.view addSubview:rightTable];
[rightTable mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(lineView.mas_right).offset(0);
make.top.offset(0);
make.bottom.offset(0);
make.right.offset(0);
}];
rightTable.estimatedRowHeight=1000.0;
rightTable.rowHeight=UITableViewAutomaticDimension;
[rightTable registerClass:[DRReportRightTableViewCell class] forCellReuseIdentifier:@"right"];
rightTable.dataSource = self;
rightTable.delegate = self;
[rightTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (scrollView == leftTable) {
[leftTable mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.offset(kWidth(92.5));
}];
} else {
[leftTable mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.offset(kWidth(62));
}];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tableView == leftTable? 5 :100;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *reCell;
if (tableView == leftTable) {
DRReportLeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"left" forIndexPath:indexPath];
cell.tag = indexPath.row + 1;
cell.selectTag = selectCell;
cell.model =_modelCollect.list[indexPath.row];
reCell = cell;
} else {
DRReportRightTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"right" forIndexPath:indexPath];
reCell = cell;
}
return reCell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (tableView == leftTable) {
selectCell = indexPath.row;
[leftTable mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.offset(kWidth(92.5));
}];
[leftTable reloadData];
} else {
[leftTable mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.offset(kWidth(62));
}];
}
}
@end
| 48,047
|
https://github.com/Ellie-Yen/demo_project/blob/master/Other/bst_builder/bst_builder_serialize_deserializer.cs
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| null |
demo_project
|
Ellie-Yen
|
C#
|
Code
| 1,626
| 4,252
|
/*------
C#
Elie yen
bst builder
@value of node: int (range between (+/-)2^31 - 1), duplicate is not allowed
@the format of string input/ output is a level-order representation eg:
[5 | 3, 8 | 2, 4, 7, 9 | 1, null, null, null, 6, null, null, null]
which '|' is a separator of different level and show null
------*/
// constructor of node
public class TNode {
public int val;
public int height = 1;
public TNode left;
public TNode right;
public TNode(int x) { val = x; }
}
public class BSTbuilder {
private TNode _root;
private int _count = 0; // number of non-null elements
// caculation for creating BST and maintaining AVL tree
private int GetHeight(TNode node) { return (node == null)? 0: node.height; }
private int UpdateHeightbychild(TNode node){
// use height of node's children to calculate height
return Math.Max(GetHeight(node.left), GetHeight(node.right)) + 1;
}
private TNode RightRotate(TNode node){
// rotate right by use node.left as new _root
TNode L = node.left;
TNode LR = L.right;
L.right = node;
node.left = LR;
// update height
node.height = UpdateHeightbychild(node);
L.height = UpdateHeightbychild(L);
return L;
}
private TNode LeftRotate(TNode node){
// same as RightRotate
TNode R = node.right;
TNode RL = R.left;
R.left = node;
node.right = RL;
node.height = UpdateHeightbychild(node);
R.height = UpdateHeightbychild(R);
return R;
}
private int GetDifference(TNode node){
return (node == null)? 0:
GetHeight(node.left) - GetHeight(node.right);
}
private bool ValidBST(){
// set boundary by int64 to avoid false judgement
// made of comparing a node's val to int.MaxValue
bool helper(TNode node, long max, long min){
if (node == null){
return true;
}
if (node.val <= min || node.val >= max){
return false;
}
bool L = helper(node.left, node.val, min);
bool R = helper(node.right, max, node.val);
if (L && R){
return true;
}
return false;
}
return helper(_root, long.MaxValue, long.MinValue);
}
private TNode RebuildBST(int startidx, int endidx, List<int> sortedvalue){
// this is for constructors failed to build a valid BST
// as a result of duplicates or violation BST rules
// array must be preprocessed to become sorted and has only unique elements.
// build balanced BST recursively
// bottom-up, use its children to calculate height
if (endidx == startidx){
return null;
}
if (endidx - startidx == 1){
TNode res1 = new TNode(sortedvalue[startidx]);
return res1;
}
int m = (int)(startidx + (endidx - startidx) * 0.5);
TNode res = new TNode(sortedvalue[m]);
res.left = RebuildBST(startidx, m, sortedvalue);
res.right = RebuildBST(m + 1, endidx, sortedvalue);
res.height = UpdateHeightbychild(res);
return res;
}
private List<int> ToList(SortedSet<int> vset){
// turn into List which is indexed for rebuild
List<int> res = new List<int>();
foreach (int v in vset){
res.Add(v);
}
return res;
}
// properties
public TNode root { get => _root; }
public int count { get => _count; }
public int height { get{ return GetHeight(_root); } }
public override string ToString(){
// represented by level order, shows null
string res = "[";
if (_root == null){
res += "null]";
}
else {
Queue<TNode> que = new Queue<TNode>();
que.Enqueue(_root);
bool notonlynull = true; // trim the level that only has null
while (notonlynull){
notonlynull = false;
int m = que.Count;
string thislevel = "";
for (int i = 0; i < m; i++){
TNode node = que.Dequeue();
if (node != null){
notonlynull = true;
thislevel += $"{node.val}, ";
que.Enqueue(node.left);
que.Enqueue(node.right);
}
else{
thislevel += "null, ";
}
}
res += (notonlynull)? thislevel.TrimEnd(',', ' ') + " | " : "";
}
res = res.TrimEnd(',', ' ', '|') + "]";
}
return res;
}
// other operations
public bool Insert(int _value){
// return true if no duplicate in _root
bool helper(int v, ref TNode node){
if (node == null){
node = new TNode(v);
_count ++;
return true;
}
if (v == node.val){
return false;
}
// get the boolean and update children first
bool res = (v > node.val)? helper(v, ref node.right): helper(v, ref node.left);
// update height
node.height = UpdateHeightbychild(node);
int dif = GetDifference(node);
// rightrotate when left is higher (has less depth)
if (dif > 1){
node.left = (node.left.val < v)? LeftRotate(node.left): node.left;
node = RightRotate(node);
}
else if (dif < -1){
node.right = (node.right.val > v)? RightRotate(node.right): node.right;
node = LeftRotate(node);
}
return res;
}
return helper(_value, ref _root);
}
public void Delete(int _value){
// it will be ok if the deletion target isn't in root.
TNode helper(int v, TNode node){
if (node == null){
return node;
}
// reach the target
if (node.val == v){
// when has 0 or 1 child
if (node.left == null && node.right == null){
_count --;
node = null;
return node;
}
else if (node.left == null){
_count --;
node = node.right;
}
else if (node.right == null){
_count --;
node = node.left;
}
// has 2 children
else {
// replace it with its inorder successor
TNode successor = node.right;
while (successor.left != null){
successor = successor.left;
}
// replace
node.val = successor.val;
// delete successor
node.right = helper(node.val, node.right);
}
}
// continue to find target
else if (node.val > v){
node.left = helper(v, node.left);
}
else {
node.right = helper(v, node.right);
}
// update height & rotate, resemble to insertion
node.height = UpdateHeightbychild(node);
int diff = GetDifference(node);
if (diff > 1){
node.left = (GetDifference(node.left) < 0)?
LeftRotate(node.left): node.left;
return RightRotate(node);
}
if (diff < -1){
node.right = (GetDifference(node.right) > 0)?
RightRotate(node.right): node.right;
return LeftRotate(node);
}
return node;
}
_root = helper(_value, _root);
}
public bool Contains(int _value){
// like insert, but looking for value only
bool helper(int v, TNode node){
if (node == null){
return false;
}
if (v == node.val){
return true;
}
if (v > node.val){
return helper(v, node.right);
}
return helper(v, node.left);
}
return helper(_value, _root);
}
// serialize, by different traversal way (ignore null)
public int[] GetInOrder(){
// get recursively
List<int> inorder_traversal(TNode node){
List<int> res = new List<int>();
if (node == null){
return res;
}
res.AddRange(inorder_traversal(node.left));
res.Add(node.val);
res.AddRange(inorder_traversal(node.right));
return res;
}
return inorder_traversal(_root).ToArray();
}
public int[] GetPreOrder(){
List<int> preorder_traversal(TNode node){
List<int> res = new List<int>();
if (node == null){
return res;
}
res.Add(node.val);
res.AddRange(preorder_traversal(node.left));
res.AddRange(preorder_traversal(node.right));
return res;
}
return preorder_traversal(_root).ToArray();
}
public int[] GetPostOrder(){
List<int> postorder_traversal(TNode node){
List<int> res = new List<int>();
if (node == null){
return res;
}
res.AddRange(postorder_traversal(node.left));
res.AddRange(postorder_traversal(node.right));
res.Add(node.val);
return res;
}
return postorder_traversal(_root).ToArray();
}
public int[][] GetLevelOrder(){
List<int[]> res = new List<int[]>();
if (_root == null){
return res.ToArray();
}
Queue<TNode> que = new Queue<TNode>();
que.Enqueue(_root);
while (que.Count > 0){
int m = que.Count;
List<int> thislevel = new List<int>();
for (int i = 0; i < m; i++){
TNode node = que.Dequeue();
thislevel.Add(node.val);
if (node.left != null){
que.Enqueue(node.left);
}
if (node.right != null){
que.Enqueue(node.right);
}
}
res.Add(thislevel.ToArray());
}
return res.ToArray();
}
public string OrderVisualize(string order){
// this is for all traversal way, but won't show null
int[] values;
string res = "";
switch (order.ToLower()){
case "inorder": values = this.GetInOrder(); break;
case "preorder": values = this.GetPreOrder(); break;
case "postorder": values = this.GetPostOrder(); break;
case "levelorder":
res = $"{order} : {this.ToString()} , height: {this.height}, non-null elements: {this.count}";
return ;
default: Console.WriteLine("Error, invalid input."); return res;
}
foreach (int v in values){
res += $"{v}, ";
}
res = $"{order} : [ {res.TrimEnd(',', ' ')} ] , height: {this.height}, non-null elements: {this.count}";
return res;
}
// constructors
public BSTbuilder(int[] values){
// remove duplicates and sort
SortedSet<int> vset = new SortedSet<int>(values);
List<int> sortedvalue = ToList(vset);
_count = sortedvalue.Count;
_root = RebuildBST(0, _count, sortedvalue);
}
public BSTbuilder(TNode rt){
// this rebuilds a BST if rt is not a valid BST
_root = rt;
if (! ValidBST()){
Console.WriteLine("this is not a BST, but we will fix it");
SortedSet<int> vset = new SortedSet<int>(this.GetInOrder());
List<int> sortedvalue = ToList(vset);
_count = sortedvalue.Count;
_root = RebuildBST(0, _count, sortedvalue);
}
}
public BSTbuilder(string s){
// can also be seem as deserializer
// use the same format as ToString()
s = s.Replace(" ", "").Trim('[', ']');
if (s.Length == 0 || s == "null"){
_root = null;
return ;
}
string[] subs = s.Split('|');
int n = subs.Length - 1;
Queue<TNode> bottomlevel = new Queue<TNode>();
SortedSet<int> vset = new SortedSet<int>(); // for rebuilt if it's not a BST
// build by bottom-up to calculate height
for (int i = n; i > -1; i--){
Queue<TNode> upperlevel = new Queue<TNode>();
foreach (string v in subs[i].Split(',')){
try {
TNode tmp = (v == "null")? null: new TNode(int.Parse(v));
if (tmp != null){
if (i < n){
tmp.left = bottomlevel.Dequeue();
tmp.right = bottomlevel.Dequeue();
tmp.height = UpdateHeightbychild(tmp);
}
vset.Add(tmp.val);
_count ++;
}
upperlevel.Enqueue(tmp);
}
catch (System.FormatException){
Console.WriteLine("Error, value must be an integer or null");
}
catch (InvalidOperationException){
Console.WriteLine("Error, do you miss [ null ] ?" +
" Ensure it's an level order and every parent node should have 2 child node");
}
}
bottomlevel = upperlevel;
}
if (bottomlevel.Count == 1){
_root = bottomlevel.Dequeue();
if (! ValidBST()){
Console.WriteLine("this is not a BST, but we will fix it");
List<int> sortedvalue = ToList(vset);
_count = sortedvalue.Count;
_root = RebuildBST(0, _count, sortedvalue);
}
}
else{
throw new System.FormatException("Error, the first level must contain only one value" +
" which must be an integer, not null");
}
}
}
class Test {
static void Main() {
int[] values = new int[]{1,2,3,4,5,6,7,8,9};
var ex = new BSTbuilder(values);
Console.WriteLine(ex);
// [5 / 3, 8 / 2, 4, 7, 9 / 1, null, null, null, 6, null, null, null]
var ex2 = new BSTbuilder("[5|5,99|42,4,78,9|1,null,null,null,6,null,null,null]"); // not valid, rebuild
Console.WriteLine(ex2);
// [9 | 5, 78 | 4, 6, 42, 99 | 1, null, null, null, null, null, null, null]
ex2.Delete(11); // this would do nothing since 11 is not in root
ex2.Delete(4);
Console.WriteLine(ex2.Insert(5)); // false, since 5 already in root
ex2.Insert(55);
Console.WriteLine(ex2);
// [9 | 5, 78 | 1, 6, 42, 99 | null, null, null, null, null, 55, null, null]
Console.WriteLine(ex2.OrderVisualize("preorder"));
// preorder : [ 9, 5, 1, 6, 78, 42, 55, 99 ] , height: 4, non-null elements: 8
}
}
| 26,831
|
https://github.com/My-Novel-Management/storybuilderunite/blob/master/builder/core/formatter.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
storybuilderunite
|
My-Novel-Management
|
Python
|
Code
| 252
| 832
|
# -*- coding: utf-8 -*-
'''
Formatter Object
================
'''
from __future__ import annotations
__all__ = ('Reducer',)
from enum import Enum, auto
from builder.core.executer import Executer
from builder.datatypes.builderexception import BuilderError
from builder.datatypes.formatmode import FormatMode
from builder.datatypes.formattag import FormatTag
from builder.datatypes.rawdata import RawData
from builder.datatypes.resultdata import ResultData
from builder.datatypes.textlist import TextList
from builder.utils import assertion
from builder.utils.logger import MyLogger
# logger
LOG = MyLogger.get_logger(__name__)
LOG.set_file_handler()
class FormatModeError(BuilderError):
''' Exception class for Format
'''
pass
class Formatter(Executer):
''' Formatter Executer class.
'''
def __init__(self):
super().__init__()
LOG.info('FORMATTER: initialize')
#
# methods
#
def execute(self, src: RawData, mode: FormatMode) -> ResultData:
LOG.info(f'FORMATTER: start exec on [{mode}] mode')
LOG.debug(f'-- src: {src}')
is_succeeded = True
tmp = []
error = None
if mode is FormatMode.DEFAULT:
tmp = assertion.is_instance(self._to_default(src), TextList)
elif mode is FormatMode.PLAIN:
tmp = src
elif mode is FormatMode.WEB:
tmp = assertion.is_instance(self._to_web(src), TextList)
elif mode is FormatMode.SMARTPHONE:
tmp = src
else:
msg = f'Invalid format-mode! {mode}'
LOG.critical(msg)
is_succeeded = False
error = FormatModeError(msg)
return ResultData(
tmp,
is_succeeded,
error)
#
# private methods
#
def _to_default(self, src: RawData) -> TextList:
LOG.info('FORMAT: to_default')
tmp = []
for line in assertion.is_instance(src, RawData).data:
if isinstance(line, FormatTag):
continue
else:
tmp.append(line)
return TextList(*tmp)
def _to_web(self, src: RawData) -> TextList:
LOG.info('FORMAT: to_web')
tmp = []
in_dialogue = False
for line in assertion.is_instance(src, RawData).data:
if isinstance(line, FormatTag):
if line is FormatTag.DESCRIPTION_HEAD:
if in_dialogue:
tmp.append('\n')
in_dialogue = False
elif line is FormatTag.DIALOGUE_HEAD:
if not in_dialogue:
tmp.append('\n')
in_dialogue = True
elif line is FormatTag.SYMBOL_HEAD:
pass
elif line is FormatTag.TAG_HEAD:
pass
else:
pass
else:
assertion.is_str(line)
tmp.append(line)
return TextList(*tmp)
| 48,866
|
https://github.com/xDanielus/SmallPets/blob/master/smallpets-1.15/src/main/java/it/smallcode/smallpets/v1_15/listener/experience/EntityDeathListener.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
SmallPets
|
xDanielus
|
Java
|
Code
| 126
| 688
|
package it.smallcode.smallpets.v1_15.listener.experience;
/*
Class created by SmallCode
25.08.2020 22:10
*/
import it.smallcode.smallpets.core.SmallPetsCommons;
import it.smallcode.smallpets.core.manager.ExperienceManager;
import it.smallcode.smallpets.core.manager.UserManager;
import it.smallcode.smallpets.core.manager.types.User;
import it.smallcode.smallpets.core.worldguard.SmallFlags;
import it.smallcode.smallpets.core.worldguard.WorldGuardImp;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDeathEvent;
public class EntityDeathListener implements Listener {
private double xpMultiplier;
public EntityDeathListener(double xpMultiplier){
this.xpMultiplier = xpMultiplier;
}
@EventHandler
public void onEntityKill(EntityDeathEvent e){
Player p = e.getEntity().getKiller();
if(p != null) {
if(SmallPetsCommons.getSmallPetsCommons().isUseWorldGuard()){
if(!WorldGuardImp.checkStateFlag(p, SmallFlags.GIVE_EXP))
return;
}
UserManager userManager = SmallPetsCommons.getSmallPetsCommons().getUserManager();
ExperienceManager experienceManager = SmallPetsCommons.getSmallPetsCommons().getExperienceManager();
User user = userManager.getUser(p.getUniqueId().toString());
if (user != null) {
if (user.getSelected() != null) {
String type = e.getEntityType().name().toLowerCase();
if(experienceManager.getExperienceTableAll().containsKey(type)){
double extraMultiplier = 1;
if(SmallPetsCommons.getSmallPetsCommons().isUseWorldGuard())
extraMultiplier = WorldGuardImp.getDoubleFlagValue(p, SmallFlags.EXP_MODIFIER, 1D);
int exp = experienceManager.getExperienceTableAll().get(type);
if(experienceManager.getPetTypeOfType(type) != user.getSelected().getPetType()) {
exp /= 2;
}
user.getSelected().giveExp((int) (exp * xpMultiplier * extraMultiplier), SmallPetsCommons.getSmallPetsCommons().getJavaPlugin());
}
}
}
}
}
}
| 49,902
|
https://github.com/riccardone/MySelfLog.Ui/blob/master/src/Diary/Diary.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
MySelfLog.Ui
|
riccardone
|
JavaScript
|
Code
| 257
| 826
|
import React, { Component } from 'react';
import NavBarTop from '../navbar.top';
import Footer from '../footer';
import Bus from '../bus';
import DiaryLog from './DiaryLog';
import DiaryLink from './DiaryLink';
import DiaryReport from './DiaryReport';
import CreateDiary from './CreateDiary';
import { ToastContainer, toast } from 'react-toastify';
var bus = Bus();
class Diary extends Component {
constructor(props) {
super(props);
this.state = {
diaryName: ''
};
// preserve the initial state in a new object
this.baseState = this.state;
this.subscribeForEvents();
}
componentDidMount() {
if (this.props.auth) {
bus.publish("GetDiaryName");
}
}
subscribeForEvents = () => {
var _this = this;
bus.subscribe("DiaryFound", (diaryName) => {
_this.setState({
diaryName: diaryName
});
});
bus.subscribe("DiaryNotFound", (data) => {
//toast.error("Diary not found " + data)
});
bus.subscribe("error", (err) => {
if (err && err.message) {
toast.error(err.message);
} else {
toast.error(err);
}
});
}
// redux action (TODO)
addLog(log) {
return { type: 'LogValue', title: log.title };
}
login() {
this.props.auth.login();
}
render() {
const { isAuthenticated } = this.props.auth;
function ShowDiaryLog(props) {
if (props.diaryName) {
return <DiaryLog />;
} else {
return <p />;
}
}
function ShowCreateDiary(props) {
if (props.diaryName) {
return (<div>
<DiaryLink diaryName={props.diaryName} />
<DiaryReport diaryName={props.diaryName} />
</div>);
} else {
return <CreateDiary />;
}
}
return (
<div>
<NavBarTop auth={this.props.auth} {...this.props} />
<div className="container">
<ToastContainer
hideProgressBar
newestOnTop
/>
{
isAuthenticated() &&
<div>
<ShowDiaryLog diaryName={this.state.diaryName} />
<ShowCreateDiary diaryName={this.state.diaryName} />
<br />
</div>
}
{
!isAuthenticated() &&
<h4>
You are not logged in! Please{' '}
<a
style={{ cursor: 'pointer' }}
onClick={this.login.bind(this)}
>
Log In
</a>
{' '}to continue.
</h4>
}
</div>
<Footer />
</div>
);
}
}
export default Diary;
| 25,758
|
https://github.com/fdietz/whistler_news_reader/blob/master/client/js/components/ClickOutside.js
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
whistler_news_reader
|
fdietz
|
JavaScript
|
Code
| 77
| 250
|
import React, { Component, PropTypes } from 'react';
export default class ClickOutside extends Component {
static propTypes = {
children: PropTypes.node,
onClickOutside: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
document.addEventListener('click', this.handleClick);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick);
}
handleClick(e) {
const { onClickOutside } = this.props;
const el = this.containerRef;
if (!el.contains(e.target)) onClickOutside(e);
}
render() {
const { children } = this.props;
return <div {...this.props} ref={(c) => { this.containerRef = c; }}>{children}</div>;
}
}
| 3,970
|
https://github.com/Jimmy2027/MMVAE_mnist_svhn_text/blob/master/tests/test_functions.py
|
Github Open Source
|
Open Source
|
MIT
| null |
MMVAE_mnist_svhn_text
|
Jimmy2027
|
Python
|
Code
| 520
| 1,838
|
import tempfile
import pytest
from mmvae_hub.networks.FlowVaes import PlanarMixtureMMVae
from mmvae_hub.networks.MixtureVaes import MOEMMVae
from mmvae_hub.networks.utils.mixture_component_selection import mixture_component_selection
from mmvae_hub.utils.Dataclasses.Dataclasses import *
from tests.utils import set_me_up
from matplotlib import pyplot as plt
DATASET = 'polymnist'
# @pytest.mark.tox
def test_fuse_modalities_1():
"""
With 3 experts and a batch size of 1, the mixture selection should select one of the experts randomly.
"""
class_dim = 3
batch_size = 1
num_mods = 3
with tempfile.TemporaryDirectory() as tmpdirname:
mst = set_me_up(tmpdirname, method='planar_mixture',
attributes={'num_mods': num_mods, 'class_dim': class_dim, 'device': 'cpu',
'batch_size': batch_size, 'weighted_mixture': False}, dataset=DATASET)
model: PlanarMixtureMMVae = mst.mm_vae
enc_mods: Mapping[str, EncModPlanarMixture] = {
mod_str: EncModPlanarMixture(None, None, z0=None,
zk=torch.ones((batch_size, class_dim)) * numbr) for numbr, mod_str
in zip(range(num_mods), mst.modalities)}
joint_zk = model.mixture_component_selection(enc_mods, 'm0_m1_m2', weight_joint=False)
assert torch.all(joint_zk == Tensor([[1., 1., 1.]]))
# @pytest.mark.tox
def test_fuse_modalities_2():
"""
With 3 experts and a batch size of 3, the mixture selection should select each of the experts one time.
"""
class_dim = 3
batch_size = 3
num_mods = 3
with tempfile.TemporaryDirectory() as tmpdirname:
mst = set_me_up(tmpdirname, method='planar_mixture',
attributes={'num_mods': num_mods, 'class_dim': class_dim, 'device': 'cpu',
'batch_size': batch_size, 'weighted_mixture': False}, dataset=DATASET)
model: PlanarMixtureMMVae = mst.mm_vae
enc_mods: Mapping[str, EncModPlanarMixture] = {
mod_str: EncModPlanarMixture(None, None, z0=None,
zk=torch.ones((batch_size, class_dim)) * numbr) for numbr, mod_str
in zip(range(num_mods), mst.modalities)}
joint_zk = model.mixture_component_selection(enc_mods, 'm0_m1_m2', weight_joint=False)
assert torch.all(joint_zk ==
Tensor([[0., 0., 0.],
[1., 1., 1.],
[2., 2., 2.]]))
# @pytest.mark.tox
def test_fuse_modalities_3():
"""
test that during the mixture selection, the batches don't get mixed up.
If 3 experts have a zk of:
Tensor([[0., 0., 0.],
[1., 1., 1.],
[2., 2., 2.]])
(of shape (batch_size, class dim)).
Then the mixture selection should select the first batch from expert 1, the second batch from expert 2 and the
third batch from expert 3, giving the same result.
"""
class_dim = 3
batch_size = 3
num_mods = 3
with tempfile.TemporaryDirectory() as tmpdirname:
mst = set_me_up(tmpdirname, method='planar_mixture',
attributes={'num_mods': num_mods, 'class_dim': class_dim, 'device': 'cpu',
'batch_size': batch_size, 'weighted_mixture': False}, dataset=DATASET)
model: PlanarMixtureMMVae = mst.mm_vae
enc_mod_zk = torch.ones((batch_size, class_dim))
enc_mod_zk[0] = enc_mod_zk[0] * 0
enc_mod_zk[2] = enc_mod_zk[2] * 2
enc_mods: Mapping[str, EncModPlanarMixture] = {
mod_str: EncModPlanarMixture(None, None, z0=None, zk=enc_mod_zk) for mod_str in mst.modalities}
joint_zk = model.mixture_component_selection(enc_mods, 'm0_m1_m2', weight_joint=False)
assert torch.all(joint_zk ==
Tensor([[0., 0., 0.],
[1., 1., 1.],
[2., 2., 2.]]))
# @pytest.mark.tox
def test_fuse_modalities_4():
"""
With 3 experts and a batch size of 3, the mixture selection should select each of the experts one time.
"""
class_dim = 3
batch_size = 3
num_mods = 3
with tempfile.TemporaryDirectory() as tmpdirname:
mst = set_me_up(tmpdirname, method='moe',
attributes={'num_mods': num_mods, 'class_dim': class_dim, 'device': 'cpu',
'batch_size': batch_size, 'weighted_mixture': False}, dataset=DATASET)
model: MOEMMVae = mst.mm_vae
mus = torch.ones((num_mods, batch_size, class_dim))
mus[0] = mus[0] * 0
mus[2] = mus[2] * 2
logvars = torch.zeros((num_mods, batch_size, class_dim))
w_modalities = torch.ones((num_mods,)) * (1 / 3)
joint_distr = mixture_component_selection(mst.flags, mus, logvars, w_modalities)
assert torch.all(joint_distr.mu ==
Tensor([[0., 0., 0.],
[1., 1., 1.],
[2., 2., 2.]]))
def text_beta_warmup():
"""Verify the beta warmup function."""
min_beta = 0
max_beta = 10
beta_start_epoch = 50
beta_warmup = 50
epochs = [ep for ep in range(150)]
betas = [
min(
[
max([min_beta, ((epoch - beta_start_epoch) * (max_beta - min_beta)) / max([beta_warmup, 1.0])]),
max_beta,
]
)
for epoch in epochs
]
plt.plot(epochs, betas)
plt.show()
if __name__ == '__main__':
text_beta_warmup()
| 967
|
https://github.com/ylhoony/fs-final-react/blob/master/src/containers/navs/Product.js
|
Github Open Source
|
Open Source
|
MIT
| null |
fs-final-react
|
ylhoony
|
JavaScript
|
Code
| 88
| 306
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { Link, withRouter } from "react-router-dom";
import { Card, Segment } from "semantic-ui-react";
import BreadcrumbDisplay from "../../components/BreadcrumbDisplay";
class Product extends Component {
render() {
return (
<React.Fragment>
<main>
<Segment.Group>
<BreadcrumbDisplay
breadcrumbList={[{ name: "Product", url: "/product" }]}
/>
<Segment>
<Card.Group className="">
<Card>
<Card.Content as={Link} to="/products" header="Products" />
<Card.Content description="Manage Products" />
</Card>
<Card>
<Card.Content
as={Link}
to="/products"
header="Product Family"
/>
<Card.Content description="sales orders" />
</Card>
</Card.Group>
</Segment>
</Segment.Group>
</main>
</React.Fragment>
);
}
}
export default withRouter(connect()(Product));
| 30,183
|
https://github.com/Maxopoly/cards-database/blob/master/data/Diamond & Pearl/Stormfront/100.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
cards-database
|
Maxopoly
|
TypeScript
|
Code
| 298
| 697
|
import { Card } from '../../../interfaces'
import Set from '../Stormfront'
const card: Card = {
name: {
en: "Regigigas",
fr: "Regigigas LV.X",
},
illustrator: "Shizurow",
rarity: "Rare",
category: "Pokemon",
set: Set,
dexId: [
486,
],
hp: 150,
types: [
"Colorless",
],
evolveFrom: {
fr: "Regigigas LV.X",
},
stage: "LEVEL-UP",
abilities: [
{
type: "Poke-POWER",
name: {
en: "Sacrifice",
fr: "Sacrifice",
},
effect: {
en: "Once during your turn (before your attack), you may choose 1 of your Pokémon in play and that Pokémon is Knocked Out. Then, search your discard pile for up to 2 basic Energy cards, attach them to Regigigas, and remove 8 damage counters from Regigigas. This power can't be used if Regigigas is affected by a Special Condition.",
fr: "Une seule fois lors de votre tour (avant votre attaque), vous pouvez choisir 1 des Pokémon que vous avez en jeu. Ce Pokémon est mis K.O. Ensuite, choisissez dans votre pile de défausse jusqu'à 2 cartes Énergie de base, attachez-les à Regigigas et retirez-lui 8 marqueurs de dégât. Ce pouvoir ne peut pas être utilisé si Regigigas est affecté par un État Spécial.",
},
},
],
attacks: [
{
cost: [
"Water",
"Fighting",
"Metal",
"Colorless",
],
name: {
en: "Giga Blaster",
fr: "Giga blaster",
},
effect: {
en: "Discard the top card from your opponent's deck. Then, choose 1 card from your opponent's hand without looking and discard it. Regigigas can't use Giga Blaster during your next turn.",
fr: "Défaussez la carte du dessus du deck de votre adversaire. Ensuite, choisissez sans regarder 1 carte de la main de votre adversaire et défaussez-la. Regigigas ne peut pas utiliser Giga blaster lors de votre prochain tour.",
},
damage: 100,
},
],
weaknesses: [
{
type: "Fighting",
value: "×2"
},
],
retreat: 4,
}
export default card
| 28,359
|
https://github.com/ProjectBlackFalcon/DatBot/blob/master/DatBot.ProtocolBuilder/Utils/messages/game/context/roleplay/job/JobDescriptionMessage.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
DatBot
|
ProjectBlackFalcon
|
Java
|
Code
| 135
| 569
|
package protocol.network.messages.game.context.roleplay.job;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import protocol.utils.ProtocolTypeManager;
import protocol.network.util.types.BooleanByteWrapper;
import protocol.network.NetworkMessage;
import protocol.network.util.DofusDataReader;
import protocol.network.util.DofusDataWriter;
import protocol.network.Network;
import protocol.network.NetworkMessage;
import protocol.network.types.game.context.roleplay.job.JobDescription;
@SuppressWarnings("unused")
public class JobDescriptionMessage extends NetworkMessage {
public static final int ProtocolId = 5655;
private List<JobDescription> jobsDescription;
public List<JobDescription> getJobsDescription() { return this.jobsDescription; }
public void setJobsDescription(List<JobDescription> jobsDescription) { this.jobsDescription = jobsDescription; };
public JobDescriptionMessage(){
}
public JobDescriptionMessage(List<JobDescription> jobsDescription){
this.jobsDescription = jobsDescription;
}
@Override
public void Serialize(DofusDataWriter writer) {
try {
writer.writeShort(this.jobsDescription.size());
int _loc2_ = 0;
while( _loc2_ < this.jobsDescription.size()){
this.jobsDescription.get(_loc2_).Serialize(writer);
_loc2_++;
}
} catch (Exception e){
e.printStackTrace();
}
}
@Override
public void Deserialize(DofusDataReader reader) {
try {
int _loc2_ = reader.readShort();
int _loc3_ = 0;
this.jobsDescription = new ArrayList<JobDescription>();
while( _loc3_ < _loc2_){
JobDescription _loc15_ = new JobDescription();
_loc15_.Deserialize(reader);
this.jobsDescription.add(_loc15_);
_loc3_++;
}
} catch (Exception e){
e.printStackTrace();
}
}
}
| 50,058
|
https://github.com/aravindhsampath/Grad_school_course_Projects/blob/master/Custom_Disk_Scheduler_822_Operating_Systems/822statspy.py
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
Grad_school_course_Projects
|
aravindhsampath
|
Python
|
Code
| 286
| 803
|
import matplotlib.pyplot as plt
# Read the stats as string from all three input files
f = open("stats_serv_time_optimal.csv","r") # optimal scheduler
f1 = open("stats2.csv","r") # deadline scheduler
f2 = open("stats_serv_time_cfq.csv","r") #CFQ scheduler
s = f.read()
s1 = f1.read()
s2 = f2.read()
# list of individual service times
# optimal
l = []
t = s.split(";;") # to chuck off the averages
l = t[0][0:-1].split(",")
# for deadline
l1 = []
l1 = s1[0:-1].split(",")
# for cfq
l2 = []
t2 = s2.split(";;")
l2 = t2[0][0:-1].split(",")
l = l[500:] # ignore the first 500 requests
l1 = l1[500:] # ignore the first 500 requests
l2 = l2[500:] # ignore the first 500 requests
print "total records from optimal is "+str(len(l))
print str(t[1])
print "total records from deadline is "+str(len(l1))
print "total records from cfq is "+str(len(l2))
print str(t2[1])
no_of_reqs = len(l)
# plot the results for Optimal Scheduler
intlist = []
sortlist = []
for item in l:
intlist.append(int(item))
sortlist.append(int(item))
sortlist.sort()
max = max(sortlist)
result = [0]*max
for timeres in intlist:
for i in range(timeres,max):
result[i] += 1
x = []
for num in range(len(result)):
x.append(num)
test = []
for r in result:
test.append(r-300)
plt.plot(x,result,'r',label = 'Optimal scheduler')
# plot the results for the deadline scheduler
intlist1 = []
for item in l1:
intlist1.append(int(item))
result1 = [0]*max
for timeres in intlist1:
for i in range(timeres,max):
result1[i] += 1
plt.plot(x,result1,'g',label = 'deadline scheduler')
# plot the results for the cfq scheduler
intlist2 = []
for item in l2:
intlist2.append(int(item))
result2 = [0]*max
for timeres in intlist2:
for i in range(timeres,max):
result2[i] += 1
plt.plot(x,result2,'b',label = 'CFQ scheduler')
plt.axis([0,max,0,no_of_reqs+500])
plt.title("Service Distribution of Disk scheduling alorithms")
plt.xlabel("Service time(t) in milliseconds")
plt.ylabel("no.of requests served under time (t)")
plt.legend(loc='lower right')
plt.savefig("diskschedplot.png",bbox_inches=0)
plt.show()
| 44,666
|
https://github.com/Gillani0/hazelcastcustomised/blob/master/hazelcast-jet-core/src/main/java/com/hazelcast/jet/application/Application.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
hazelcastcustomised
|
Gillani0
|
Java
|
Code
| 417
| 906
|
/*
* Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.application;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.jet.impl.statemachine.application.ApplicationState;
import com.hazelcast.jet.impl.application.LocalizationResourceType;
import com.hazelcast.jet.container.CounterKey;
import com.hazelcast.jet.counters.Accumulator;
import com.hazelcast.jet.dag.DAG;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.Future;
/**
* Represents abstract application
*/
public interface Application {
/**
* Submit dag to the cluster
*
* @param dag Direct acyclic graph, which describes calculation flow
* @param classes Classes which will be used during calculation process
* @throws IOException if application could not be submitted
*/
void submit(DAG dag, Class... classes) throws IOException;
/**
* Add classes to the calculation's classLoader
*
* @param classes classes, which will be used during calculation
* @throws IOException if resource could not be added
*/
void addResource(Class... classes) throws IOException;
/**
* Add all bytecode for url to the calculation classLoader
*
* @param url source url with classes
* @throws IOException if resource could not be added
*/
void addResource(URL url) throws IOException;
/**
* Add all bytecode for url to the calculation classLoader
*
* @param inputStream source inputStream with bytecode
* @param name name of the source
* @param localizationResourceType type of data stored in inputStream (JAR,CLASS,DATA)
* @throws IOException if resource could not be added
*/
void addResource(InputStream inputStream, String name, LocalizationResourceType localizationResourceType) throws IOException;
/**
* Clear all submitted resources
*/
void clearResources();
/**
* @return state for the application's state-machine
*/
ApplicationState getApplicationState();
/**
* @return Returns name for the application
*/
String getName();
/**
* Execute application
*
* @return Future which will return execution's result
*/
Future execute();
/**
* Interrupts application
*
* @return Future which will return interruption's result
*/
Future interrupt();
/**
* Finalizes application
*
* @return Future which will return finalization's result
*/
Future finalizeApplication();
/**
* Returns map with statistic counters info for the certain application
*
* @return map with accumulators
*/
Map<CounterKey, Accumulator> getAccumulators();
/**
* @return Hazelcast instance corresponding for application
*/
HazelcastInstance getHazelcastInstance();
}
| 42,170
|
https://github.com/collinsigeh-briigo/Paysupplier/blob/master/application/views/pages/success.php
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, MIT
| 2,019
|
Paysupplier
|
collinsigeh-briigo
|
PHP
|
Code
| 57
| 265
|
<div class="container">
<div class="card page-content">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-9">
<h2>Success</h2>
</div>
<div class="col-3 text-right">
<a class="btn btn-sm btn-secondary" href="<?php echo base_url(); ?>dashboard/">Home</a>
</div>
</div><br>
<div>
<div class="alert alert-success">
<h3>Report:</h3>
<h5>Hurray! Action was successful.</h5>
</div><br>
<div class=" text-center">
<a class="btn btn-primary" href="<?php echo base_url(); ?>dashboard/">← Dashboard</a>
</div>
<pre>
</pre>
</div>
</div>
</div>
</div>
</div>
| 25,422
|
https://github.com/globalnaturesoft-erp/erp-stock-transfers/blob/master/README.rdoc
|
Github Open Source
|
Open Source
|
MIT
| null |
erp-stock-transfers
|
globalnaturesoft-erp
|
RDoc
|
Code
| 8
| 19
|
= Erp::StockTransfers
This project rocks and uses MIT-LICENSE.
| 20,858
|
https://github.com/Marcus-Rise/labwork/blob/master/src/services/AppService.ts
|
Github Open Source
|
Open Source
|
0BSD
| null |
labwork
|
Marcus-Rise
|
TypeScript
|
Code
| 31
| 77
|
export class AppService {
private readonly _env: string;
get isDevMode(): boolean {
return this._env === "development";
}
constructor() {
this._env = process.env.NODE_ENV;
}
}
export const app: AppService = new AppService();
| 26,602
|
https://github.com/outtaspace/jip_debug/blob/master/lib/JIP/Debug.pm
|
Github Open Source
|
Open Source
|
Artistic-2.0
| null |
jip_debug
|
outtaspace
|
Perl
|
Code
| 1,356
| 3,862
|
package JIP::Debug;
use base qw(Exporter);
use 5.006;
use strict;
use warnings;
use Term::ANSIColor 3.00 ();
use Devel::StackTrace;
use Carp qw(croak);
use Data::Dumper qw(Dumper);
use Fcntl qw(LOCK_EX LOCK_UN);
use English qw(-no_match_vars);
our $VERSION = '0.03';
our @EXPORT_OK = qw(
to_debug
to_debug_raw
to_debug_empty
to_debug_count
to_debug_trace
to_debug_truncate
);
our $HANDLE = \*STDERR;
our $MSG_FORMAT = qq{%s\n%s\n\n};
our $MSG_DELIMITER = q{-} x 80;
our $MSG_EMPTY_LINES = qq{\n} x 18;
our $DUMPER_INDENT = 1;
our $DUMPER_DEEPCOPY = 1;
our $DUMPER_SORTKEYS = 1;
our $DUMPER_TRAILING_COMMA = 1;
our %TRACE_PARAMS = (
skip_frames => 1, # skip to_debug_trace
);
our %TRACE_AS_STRING_PARAMS;
our $COLOR = 'bright_green';
our $MAYBE_COLORED = sub {
my $text = shift;
return defined $text && defined $COLOR
? Term::ANSIColor::colored($text, $COLOR) : $text;
};
our $MAKE_MSG_HEADER = sub {
# $MAKE_MSG_HEADER=0, to_debug=1
my ($package, undef, $line) = caller 1;
# $MAKE_MSG_HEADER=0, to_debug=1, subroutine=2
my $subroutine = (caller 2)[3];
$subroutine = resolve_subroutine_name($subroutine);
my $text = join q{, }, (
sprintf('package=%s', $package),
(defined $subroutine ? sprintf('subroutine=%s', $subroutine) : ()),
sprintf('line=%d', $line),
);
$text = qq{[$text]:};
{
my $msg_delimiter = defined $MSG_DELIMITER ? $MSG_DELIMITER : q{};
$text = sprintf qq{%s\n%s\n%s}, $msg_delimiter, $text, $msg_delimiter;
}
return $MAYBE_COLORED->($text);
};
our $NO_LABEL_KEY = '<no label>';
our %COUNT_OF_LABEL = ($NO_LABEL_KEY => 0);
# Supported on Perl 5.22+
eval {
require Sub::Util;
if (my $set_subname = Sub::Util->can('set_subname')) {
$set_subname->('MAYBE_COLORED', $MAYBE_COLORED);
$set_subname->('MAKE_MSG_HEADER', $MAKE_MSG_HEADER);
}
};
sub to_debug {
my $msg_body = do {
local $Data::Dumper::Indent = $DUMPER_INDENT;
local $Data::Dumper::Deepcopy = $DUMPER_DEEPCOPY;
local $Data::Dumper::Sortkeys = $DUMPER_SORTKEYS;
local $Data::Dumper::Trailingcomma = $DUMPER_TRAILING_COMMA;
Dumper(\@ARG);
};
my $msg = sprintf $MSG_FORMAT, $MAKE_MSG_HEADER->(), $msg_body;
return send_to_output($msg);
}
sub to_debug_raw {
my $msg_text = shift;
my $msg = sprintf $MSG_FORMAT, $MAKE_MSG_HEADER->(), $msg_text;
return send_to_output($msg);
}
sub to_debug_empty {
my $msg = sprintf $MSG_FORMAT, $MAKE_MSG_HEADER->(), $MSG_EMPTY_LINES;
return send_to_output($msg);
}
sub to_debug_count {
my ($label, $cb);
if (@ARG == 2 && ref $ARG[1] eq 'CODE') {
($label, $cb) = @ARG;
}
elsif (@ARG == 1 && ref $ARG[0] eq 'CODE') {
$cb = $ARG[0];
}
elsif (@ARG == 1) {
$label = $ARG[0];
}
$label = defined $label && length $label ? $label : $NO_LABEL_KEY;
my $count = $COUNT_OF_LABEL{$label} || 0;
$count++;
$COUNT_OF_LABEL{$label} = $count;
my $msg_body = sprintf '%s: %d', $label, $count;
my $msg = sprintf $MSG_FORMAT, $MAKE_MSG_HEADER->(), $msg_body;
$cb->($label, $count) if defined $cb;
return send_to_output($msg);
}
sub to_debug_trace {
my $cb = shift;
my $trace = Devel::StackTrace->new(%TRACE_PARAMS);
my $msg_body = $trace->as_string(%TRACE_AS_STRING_PARAMS);
$msg_body =~ s{\n+$}{}x;
my $msg = sprintf $MSG_FORMAT, $MAKE_MSG_HEADER->(), $msg_body;
$cb->($trace) if defined $cb;
return send_to_output($msg);
}
sub to_debug_truncate {
return unless $HANDLE;
flock $HANDLE, LOCK_EX;
truncate $HANDLE, 0;
flock $HANDLE, LOCK_UN;
return 1;
}
sub send_to_output {
my $msg = shift;
return unless $HANDLE;
flock $HANDLE, LOCK_EX;
$HANDLE->print($msg) or croak(sprintf q{Can't write to output: %s}, $OS_ERROR);
flock $HANDLE, LOCK_UN;
return 1;
}
sub resolve_subroutine_name {
my $subroutine = shift;
return unless defined $subroutine;
my ($subroutine_name) = $subroutine =~ m{::(\w+)$}x;
return $subroutine_name;
}
1;
__END__
=head1 NAME
JIP::Debug - provides a convenient way to attach debug print statements anywhere in a program.
=head1 VERSION
This document describes C<JIP::Debug> version C<0.03>.
=head1 SYNOPSIS
For complex data structures (references, arrays and hashes) you can use the
use JIP::Debug qw(to_debug);
to_debug(
an_array => [],
a_hash => {},
a_reference => \42,
);
C<to_debug({a =E<gt> 1, b =E<gt> 1})> will produce the output:
--------------------------------------------------------------------------------
[package=main, subroutine=tratata, line=1]:
--------------------------------------------------------------------------------
$VAR1 = [
{
'a' => 1,
'b' => 1
}
];
Prints a string
use JIP::Debug qw(to_debug_raw);
to_debug_raw('Hello');
C<to_debug_raw('Hello')> will produce the output:
--------------------------------------------------------------------------------
[package=main, subroutine=tratata, line=1]:
--------------------------------------------------------------------------------
Hello
Prints empty lines
use JIP::Debug qw(to_debug_empty);
to_debug_empty();
Prints the number of times that this particular call to to_debug_count() has been called
use JIP::Debug qw(to_debug_count);
to_debug_count('tratata label');
C<to_debug_count('tratata label')> will produce the output:
--------------------------------------------------------------------------------
[package=main, subroutine=tratata, line=1]:
--------------------------------------------------------------------------------
tratata label: 1
Prints a stack trace
use JIP::Debug qw(to_debug_trace);
to_debug_trace();
C<to_debug_trace()> will produce the output:
--------------------------------------------------------------------------------
[package=main, subroutine=tratata, line=1]:
--------------------------------------------------------------------------------
Trace begun at -e line 1
main::tratata at -e line 1
=head1 DESCRIPTION
Each debug message is added a header with useful data during debugging, such as a C<package> (package name), a C<subroutine> (function name/method), a C<line> (line number).
All debug messages are output via a file descriptor. Default is C<STDERR>. Value can be changed by editing the variable C<$JIP::Debug::HANDLE>.
The list of exporting functions by default is empty, all functions of this module are exported explicitly.
=head1 SUBROUTINES/METHODS
=head2 to_debug(I<LIST>)
A wrapper for C<Dumper> method of the C<Data::Dumper> module. The list of parameters passed to C<to_debug>, without any changes, is passed to C<Dumper>.
Parameters for C<Data::Dumper> can be changed, here are their analogues (and default values) in this module:
=over 4
=item *
$JIP::Debug::DUMPER_INDENT = 1 I<or> $Data::Dumper::Indent = 1
Mild pretty print.
=item *
$JIP::Debug::DUMPER_DEEPCOPY = 1 I<or> $Data::Dumper::Deepcopy = 1
Avoid cross-refs.
=item *
$JIP::Debug::DUMPER_SORTKEYS = 1 I<or> $Data::Dumper::Sortkeys = 1
Hash keys are dumped in sorted order.
=item *
$JIP::Debug::DUMPER_TRAILING_COMMA = 1 I<or> $Data::Dumper::Trailingcomma = 1
Controls whether a comma is added after the last element of an array or hash.
=back
=head2 to_debug_raw(I<[STRING]>)
Logs a string without any changes.
=head2 to_debug_empty()
Logs 18 empty lines. The content can be changed, there is a parameter for this C<$JIP::Debug::MSG_EMPTY_LINES>.
=head2 to_debug_count(I<[LABEL, CODE]>)
Logs the number of times that this particular call to C<to_debug_count()> has been called.
This function takes an optional argument C<label>. If C<label> is supplied, this function
logs the number of times C<to_debug_count()> has been called with that particular C<label>.
C<label> - a string. If this is supplied, C<to_debug_count()> outputs the number of times
it has been called at this line and with that label.
to_debug_count('label');
If C<label> is omitted, the function logs the number of times C<to_debug_count()> has been
called at this particular line.
to_debug_count();
This function takes an optional argument C<callback>:
to_debug_count('label', sub {
my ($label, $count) = @_;
});
or
to_debug_count(sub {
my ($label, $count) = @_;
});
=head2 to_debug_trace(I<[CODE]>)
Logs a stack trace from the point where the method was called.
This function takes an optional argument C<callback>:
to_debug_trace(sub {
my ($trace) = @_;
});
=head2 to_debug_truncate()
Truncates the file opened on C<$JIP::Debug::HANDLE>. In fact it's just a wrapper for the built-in function C<truncate>.
=head1 CODE SNIPPET
use JIP::Debug qw(to_debug to_debug_raw to_debug_empty to_debug_count to_debug_trace to_debug_truncate);
BEGIN { $JIP::Debug::HANDLE = IO::File->new('/home/my_dir/debug.log', '>>'); }
=head1 DIAGNOSTICS
None.
=head1 CONFIGURATION AND ENVIRONMENT
C<JIP::Debug> requires no configuration files or environment variables.
=head1 SEE ALSO
L<Debuggit>, L<Debug::Simple>, L<Debug::Easy>
=head1 AUTHOR
Vladimir Zhavoronkov, C<< <flyweight at yandex.ru> >>
=head1 LICENSE AND COPYRIGHT
Copyright 2018 Vladimir Zhavoronkov.
This program is free software; you can redistribute it and/or modify it
under the terms of the the Artistic License (2.0). You may obtain a
copy of the full license at:
L<http://www.perlfoundation.org/artistic_license_2_0>
Any use, modification, and distribution of the Standard or Modified
Versions is governed by this Artistic License. By using, modifying or
distributing the Package, you accept this license. Do not use, modify,
or distribute the Package, if you do not accept this license.
If your Modified Version has been derived from a Modified Version made
by someone other than you, you are nevertheless required to ensure that
your Modified Version complies with the requirements of this license.
This license does not grant you the right to use any trademark, service
mark, tradename, or logo of the Copyright Holder.
This license includes the non-exclusive, worldwide, free-of-charge
patent license to make, have made, use, offer to sell, sell, import and
otherwise transfer the Package with respect to any patent claims
licensable by the Copyright Holder that are necessarily infringed by the
Package. If you institute patent litigation (including a cross-claim or
counterclaim) against any party alleging that the Package constitutes
direct or contributory patent infringement, then this Artistic License
to you shall terminate on the date that such litigation is filed.
Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=cut
| 5,977
|
https://github.com/rbb-data/airbnb-ratings/blob/master/src/components/_shared/BalanceGauge/BalanceGauge.module.sass
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
airbnb-ratings
|
rbb-data
|
Sass
|
Code
| 116
| 336
|
$red: #e31818
$grey: #D8D8D8
.balanceGauge
display: inline-block
position: relative
margin: .3em 0
.bar
width: 80px
margin-right: 10px
height: 3px
top: 50%
transform: translateY(-50%)
display: inline-block
.leftBarPart,
.rightBarPart
display: inline-block
height: 100%
.leftBarPart
// width is calculated dynamically (see .jsx)
background: $red
.rightBarPart
// width is calculated dynamically (see .jsx)
background: $grey
.caret
$size: 3px
display: block
position: absolute
// left is calculated dynamically (see .jsx)
top: 5px
// this is a 4px downwards pointing triangle:
width: 0
height: 0
border-left: $size solid transparent
border-right: $size solid transparent
border-top: $size solid $red
// the rotation is supposed to help with anti-aliasing issues in webkit browsers
transform: rotate(360deg) translateX(-$size)
.text
display: inline-block
width: calc(100% - 90px)
vertical-align: middle
| 29,669
|
https://github.com/atveit/vespa/blob/master/document/src/main/java/com/yahoo/document/json/readers/StructReader.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
vespa
|
atveit
|
Java
|
Code
| 142
| 412
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.json.readers;
import com.yahoo.document.Field;
import com.yahoo.document.datatypes.FieldValue;
import com.yahoo.document.datatypes.StructuredFieldValue;
import com.yahoo.document.json.JsonReaderException;
import com.yahoo.document.json.TokenBuffer;
import static com.yahoo.document.json.readers.SingleValueReader.readSingleValue;
public class StructReader {
public static void fillStruct(TokenBuffer buffer, StructuredFieldValue parent) {
// do note the order of initializing initNesting and token is relevant for empty docs
int initNesting = buffer.nesting();
buffer.next();
while (buffer.nesting() >= initNesting) {
Field f = getField(buffer, parent);
try {
FieldValue v = readSingleValue(buffer, f.getDataType());
parent.setFieldValue(f, v);
buffer.next();
} catch (IllegalArgumentException e) {
throw new JsonReaderException(f, e);
}
}
}
public static Field getField(TokenBuffer buffer, StructuredFieldValue parent) {
Field f = parent.getField(buffer.currentName());
if (f == null) {
throw new NullPointerException("Could not get field \"" + buffer.currentName() +
"\" in the structure of type \"" + parent.getDataType().getDataTypeName() + "\".");
}
return f;
}
}
| 47,960
|
https://github.com/ddwivedi08/ats/blob/master/src/constitutive_relations/ewc/permafrost_model.cc
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,017
|
ats
|
ddwivedi08
|
C++
|
Code
| 871
| 4,037
|
/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/*
Ugly hackjob to enable direct evaluation of the full model, on a single
WRM/region. This is bypassing much of the "niceness" of the framework, but
seems necessary for solving a cell-wise correction equation.
Uses intensive, not extensive, forms.
Authors: Ethan Coon (ecoon@lanl.gov)
*/
#include "exceptions.hh"
#include "State.hh"
#include "eos_evaluator.hh"
#include "eos.hh"
#include "wrm_partition.hh"
#include "wrm_permafrost_evaluator.hh"
#include "wrm_permafrost_model.hh"
#include "molar_fraction_gas_evaluator.hh"
#include "vapor_pressure_relation.hh"
#include "pc_liquid_evaluator.hh"
#include "pc_ice_evaluator.hh"
#include "pc_ice_water.hh"
#include "pc_liq_atm.hh"
#include "iem_evaluator.hh"
#include "iem.hh"
#include "iem_water_vapor_evaluator.hh"
#include "iem_water_vapor.hh"
#include "compressible_porosity_evaluator.hh"
#include "compressible_porosity_model.hh"
#include "compressible_porosity_leijnse_evaluator.hh"
#include "compressible_porosity_leijnse_model.hh"
#include "permafrost_model.hh"
namespace Amanzi {
#define DEBUG_FLAG 0
void PermafrostModel::InitializeModel(const Teuchos::Ptr<State>& S,
Teuchos::ParameterList& plist) {
// these are not yet initialized
rho_rock_ = -1.;
p_atm_ = -1.e12;
domain = plist.get<std::string>("domain key", "");
if (!domain.empty()) {
mesh_ = S->GetMesh(domain);
} else {
mesh_ = S->GetMesh("domain");
}
// Grab the models.
// get the WRM models and their regions
Teuchos::RCP<FieldEvaluator> me = S->GetFieldEvaluator(getKey(domain, "saturation_gas"));
Teuchos::RCP<Flow::FlowRelations::WRMPermafrostEvaluator> wrm_me =
Teuchos::rcp_dynamic_cast<Flow::FlowRelations::WRMPermafrostEvaluator>(me);
ASSERT(wrm_me != Teuchos::null);
wrms_ = wrm_me->get_WRMPermafrostModels();
// -- liquid EOS
me = S->GetFieldEvaluator(getKey(domain, "molar_density_liquid"));
Teuchos::RCP<Relations::EOSEvaluator> eos_liquid_me =
Teuchos::rcp_dynamic_cast<Relations::EOSEvaluator>(me);
ASSERT(eos_liquid_me != Teuchos::null);
liquid_eos_ = eos_liquid_me->get_EOS();
// -- ice EOS
me = S->GetFieldEvaluator(getKey(domain, "molar_density_ice"));
Teuchos::RCP<Relations::EOSEvaluator> eos_ice_me =
Teuchos::rcp_dynamic_cast<Relations::EOSEvaluator>(me);
ASSERT(eos_ice_me != Teuchos::null);
ice_eos_ = eos_ice_me->get_EOS();
// -- gas EOS
me = S->GetFieldEvaluator(getKey(domain, "molar_density_gas"));
Teuchos::RCP<Relations::EOSEvaluator> eos_gas_me =
Teuchos::rcp_dynamic_cast<Relations::EOSEvaluator>(me);
ASSERT(eos_gas_me != Teuchos::null);
gas_eos_ = eos_gas_me->get_EOS();
// -- gas vapor pressure
me = S->GetFieldEvaluator(getKey(domain, "mol_frac_gas"));
Teuchos::RCP<Relations::MolarFractionGasEvaluator> mol_frac_me =
Teuchos::rcp_dynamic_cast<Relations::MolarFractionGasEvaluator>(me);
ASSERT(mol_frac_me != Teuchos::null);
vpr_ = mol_frac_me->get_VaporPressureRelation();
// -- capillary pressure for ice/water
me = S->GetFieldEvaluator(getKey(domain, "capillary_pressure_liq_ice"));
Teuchos::RCP<Flow::FlowRelations::PCIceEvaluator> pc_ice_me =
Teuchos::rcp_dynamic_cast<Flow::FlowRelations::PCIceEvaluator>(me);
ASSERT(pc_ice_me != Teuchos::null);
pc_i_ = pc_ice_me->get_PCIceWater();
// -- capillary pressure for liq/gas
me = S->GetFieldEvaluator(getKey(domain, "capillary_pressure_gas_liq"));
Teuchos::RCP<Flow::FlowRelations::PCLiquidEvaluator> pc_liq_me =
Teuchos::rcp_dynamic_cast<Flow::FlowRelations::PCLiquidEvaluator>(me);
ASSERT(pc_liq_me != Teuchos::null);
pc_l_ = pc_liq_me->get_PCLiqAtm();
// -- iem for liquid
me = S->GetFieldEvaluator(getKey(domain, "internal_energy_liquid"));
Teuchos::RCP<Energy::EnergyRelations::IEMEvaluator> iem_liquid_me =
Teuchos::rcp_dynamic_cast<Energy::EnergyRelations::IEMEvaluator>(me);
ASSERT(iem_liquid_me != Teuchos::null);
liquid_iem_ = iem_liquid_me->get_IEM();
// -- iem for ice
me = S->GetFieldEvaluator(getKey(domain, "internal_energy_ice"));
Teuchos::RCP<Energy::EnergyRelations::IEMEvaluator> iem_ice_me =
Teuchos::rcp_dynamic_cast<Energy::EnergyRelations::IEMEvaluator>(me);
ASSERT(iem_ice_me != Teuchos::null);
ice_iem_ = iem_ice_me->get_IEM();
// -- iem for gas
me = S->GetFieldEvaluator(getKey(domain, "internal_energy_gas"));
Teuchos::RCP<Energy::EnergyRelations::IEMWaterVaporEvaluator> iem_gas_me =
Teuchos::rcp_dynamic_cast<Energy::EnergyRelations::IEMWaterVaporEvaluator>(me);
ASSERT(iem_gas_me != Teuchos::null);
gas_iem_ = iem_gas_me->get_IEM();
// -- iem for rock
me = S->GetFieldEvaluator(getKey(domain, "internal_energy_rock"));
Teuchos::RCP<Energy::EnergyRelations::IEMEvaluator> iem_rock_me =
Teuchos::rcp_dynamic_cast<Energy::EnergyRelations::IEMEvaluator>(me);
ASSERT(iem_rock_me != Teuchos::null);
rock_iem_ = iem_rock_me->get_IEM();
// -- porosity
poro_leij_ = plist.get<bool>("porosity leijnse model", false);
me = S->GetFieldEvaluator(getKey(domain, "porosity"));
if(!poro_leij_){
Teuchos::RCP<Flow::FlowRelations::CompressiblePorosityEvaluator> poro_me =
Teuchos::rcp_dynamic_cast<Flow::FlowRelations::CompressiblePorosityEvaluator>(me);
ASSERT(poro_me != Teuchos::null);
poro_models_ = poro_me->get_Models();
}
else{
Teuchos::RCP<Flow::FlowRelations::CompressiblePorosityLeijnseEvaluator> poro_me =
Teuchos::rcp_dynamic_cast<Flow::FlowRelations::CompressiblePorosityLeijnseEvaluator>(me);
ASSERT(poro_me != Teuchos::null);
poro_leij_models_ = poro_me->get_Models();
}
}
void PermafrostModel::UpdateModel(const Teuchos::Ptr<State>& S, int c) {
// update scalars
p_atm_ = *S->GetScalarData("atmospheric_pressure");
rho_rock_ = (*S->GetFieldData(getKey(domain,"density_rock"))->ViewComponent("cell"))[0][c];
poro_ = (*S->GetFieldData(getKey(domain,"base_porosity"))->ViewComponent("cell"))[0][c];
wrm_ = wrms_->second[(*wrms_->first)[c]];
if(!poro_leij_)
poro_model_ = poro_models_->second[(*poro_models_->first)[c]];
else
poro_leij_model_ = poro_leij_models_->second[(*poro_leij_models_->first)[c]];
ASSERT(IsSetUp_());
}
bool PermafrostModel::IsSetUp_() {
if (wrm_ == Teuchos::null) return false;
if (!poro_leij_) {
if (poro_model_ == Teuchos::null) return false;
}
else {
if (poro_leij_model_ == Teuchos::null) return false;
}
if (liquid_eos_ == Teuchos::null) return false;
if (gas_eos_ == Teuchos::null) return false;
if (ice_eos_ == Teuchos::null) return false;
if (pc_i_ == Teuchos::null) return false;
if (pc_l_ == Teuchos::null) return false;
if (vpr_ == Teuchos::null) return false;
if (liquid_iem_ == Teuchos::null) return false;
if (gas_iem_ == Teuchos::null) return false;
if (ice_iem_ == Teuchos::null) return false;
if (rock_iem_ == Teuchos::null) return false;
if (rho_rock_ < 0.) return false;
if (p_atm_ < -1.e10) return false;
return true;
}
bool
PermafrostModel::Freezing(double T, double p) {
double eff_p = std::max(p_atm_, p);
double rho_l = liquid_eos_->MolarDensity(T,eff_p);
double mass_rho_l = liquid_eos_->MassDensity(T,eff_p);
double pc_l = pc_l_->CapillaryPressure(p,p_atm_);
double pc_i;
if (pc_i_->IsMolarBasis()) {
pc_i = pc_i_->CapillaryPressure(T, rho_l);
} else {
double mass_rho_l = liquid_eos_->MassDensity(T,eff_p);
pc_i = pc_i_->CapillaryPressure(T, mass_rho_l);
}
return wrm_->freezing(T,pc_l,pc_i);
}
int PermafrostModel::EvaluateSaturations(double T, double p, double& s_gas, double& s_liq, double& s_ice) {
int ierr = 0;
try {
double eff_p = std::max(p_atm_, p);
double rho_l = liquid_eos_->MolarDensity(T,eff_p);
double mass_rho_l = liquid_eos_->MassDensity(T,eff_p);
double pc_l = pc_l_->CapillaryPressure(p, p_atm_);
double pc_i;
if (pc_i_->IsMolarBasis()) {
pc_i = pc_i_->CapillaryPressure(T, rho_l);
} else {
double mass_rho_l = liquid_eos_->MassDensity(T,eff_p);
pc_i = pc_i_->CapillaryPressure(T, mass_rho_l);
}
double sats[3];
wrm_->saturations(pc_l, pc_i, sats);
s_gas = sats[0];
s_liq = sats[1];
s_ice = sats[2];
} catch (const Exceptions::Amanzi_exception& e) {
if (e.what() == std::string("Cut time step")) {
ierr = 1;
}
}
return ierr;
}
int PermafrostModel::EvaluateEnergyAndWaterContent_(double T, double p, AmanziGeometry::Point& result) {
if (T < 100.0 || T > 373.0) {
return 1; // invalid temperature
}
int ierr = 0;
try {
double poro;
if (!poro_leij_)
poro = poro_model_->Porosity(poro_, p, p_atm_);
else
poro = poro_leij_model_->Porosity(poro_, p, p_atm_);
double eff_p = std::max(p_atm_, p);
double rho_l = liquid_eos_->MolarDensity(T,eff_p);
double mass_rho_l = liquid_eos_->MassDensity(T,eff_p);
double rho_i = ice_eos_->MolarDensity(T,eff_p);
double rho_g = gas_eos_->MolarDensity(T,eff_p);
double omega = vpr_->SaturatedVaporPressure(T)/p_atm_;
double pc_i;
if (pc_i_->IsMolarBasis()) {
pc_i = pc_i_->CapillaryPressure(T, rho_l);
} else {
double mass_rho_l = liquid_eos_->MassDensity(T,eff_p);
pc_i = pc_i_->CapillaryPressure(T, mass_rho_l);
}
double pc_l = pc_l_->CapillaryPressure(p, p_atm_);
double sats[3];
wrm_->saturations(pc_l, pc_i, sats);
double s_g = sats[0];
double s_l = sats[1];
double s_i = sats[2];
double u_l = liquid_iem_->InternalEnergy(T);
double u_g = gas_iem_->InternalEnergy(T, omega);
double u_i = ice_iem_->InternalEnergy(T);
double u_rock = rock_iem_->InternalEnergy(T);
// water content
result[1] = poro * (rho_l * s_l + rho_i * s_i + rho_g * s_g * omega);
// energy
result[0] = poro * (u_l * rho_l * s_l + u_i * rho_i * s_i + u_g * rho_g * s_g)
+ (1.0 - poro_) * (rho_rock_ * u_rock);
} catch (const Exceptions::Amanzi_exception& e) {
if (e.what() == std::string("Cut time step")) {
ierr = 1;
}
}
return ierr;
}
}
| 46,220
|
https://github.com/Marvenlee/cheviot/blob/master/kernel/fs/write.c
|
Github Open Source
|
Open Source
|
Apache-1.1
| 2,021
|
cheviot
|
Marvenlee
|
C
|
Code
| 110
| 409
|
//#define KDEBUG
#include <kernel/dbg.h>
#include <kernel/filesystem.h>
#include <kernel/globals.h>
#include <kernel/proc.h>
#include <kernel/types.h>
#include <kernel/vm.h>
#include <sys/fsreq.h>
#include <sys/mount.h>
/*
*
*/
ssize_t Write(int fd, void *src, size_t sz) {
struct Filp *filp;
struct VNode *vnode;
ssize_t xfered;
filp = GetFilp(fd);
if (filp == NULL) {
return -EINVAL;
}
vnode = filp->vnode;
if (IsAllowed(vnode, W_OK) != 0) {
Info ("Write IsAllowed failed");
return -EACCES;
}
if (S_ISCHR(vnode->mode)) {
xfered = WriteToChar(vnode, src, sz);
} else if (S_ISBLK(vnode->mode)) {
xfered = WriteToCache(vnode, src, sz, &filp->offset);
} else if (S_ISFIFO(vnode->mode)) {
xfered = WriteToPipe(vnode, src, sz, &filp->offset);
} else {
Info ("Write to unknown file type");
xfered = -EINVAL;
}
return xfered;
}
| 38,691
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.