hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7bf5d81cb14983955e18bd915974857ed5462277
| 10,598
|
cc
|
C++
|
google/cloud/servicedirectory/internal/registration_logging_decorator.cc
|
LaudateCorpus1/google-cloud-cpp
|
a9575c5af5e3938efc71bf5822e79b73027d1f3b
|
[
"Apache-2.0"
] | 80
|
2017-11-24T00:19:45.000Z
|
2019-01-25T10:24:33.000Z
|
google/cloud/servicedirectory/internal/registration_logging_decorator.cc
|
LaudateCorpus1/google-cloud-cpp
|
a9575c5af5e3938efc71bf5822e79b73027d1f3b
|
[
"Apache-2.0"
] | 1,579
|
2017-11-24T01:01:21.000Z
|
2019-01-28T23:41:21.000Z
|
google/cloud/servicedirectory/internal/registration_logging_decorator.cc
|
LaudateCorpus1/google-cloud-cpp
|
a9575c5af5e3938efc71bf5822e79b73027d1f3b
|
[
"Apache-2.0"
] | 51
|
2017-11-24T00:56:11.000Z
|
2019-01-18T20:35:02.000Z
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/servicedirectory/v1/registration_service.proto
#include "google/cloud/servicedirectory/internal/registration_logging_decorator.h"
#include "google/cloud/internal/log_wrapper.h"
#include "google/cloud/status_or.h"
#include <google/cloud/servicedirectory/v1/registration_service.grpc.pb.h>
#include <memory>
namespace google {
namespace cloud {
namespace servicedirectory_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
RegistrationServiceLogging::RegistrationServiceLogging(
std::shared_ptr<RegistrationServiceStub> child,
TracingOptions tracing_options, std::set<std::string> components)
: child_(std::move(child)),
tracing_options_(std::move(tracing_options)),
components_(std::move(components)) {}
StatusOr<google::cloud::servicedirectory::v1::Namespace>
RegistrationServiceLogging::CreateNamespace(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::CreateNamespaceRequest const&
request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::CreateNamespaceRequest const&
request) { return child_->CreateNamespace(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::ListNamespacesResponse>
RegistrationServiceLogging::ListNamespaces(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::ListNamespacesRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::ListNamespacesRequest const&
request) { return child_->ListNamespaces(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::Namespace>
RegistrationServiceLogging::GetNamespace(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::GetNamespaceRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::GetNamespaceRequest const&
request) { return child_->GetNamespace(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::Namespace>
RegistrationServiceLogging::UpdateNamespace(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::UpdateNamespaceRequest const&
request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::UpdateNamespaceRequest const&
request) { return child_->UpdateNamespace(context, request); },
context, request, __func__, tracing_options_);
}
Status RegistrationServiceLogging::DeleteNamespace(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::DeleteNamespaceRequest const&
request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::DeleteNamespaceRequest const&
request) { return child_->DeleteNamespace(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::Service>
RegistrationServiceLogging::CreateService(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::CreateServiceRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::CreateServiceRequest const&
request) { return child_->CreateService(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::ListServicesResponse>
RegistrationServiceLogging::ListServices(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::ListServicesRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::ListServicesRequest const&
request) { return child_->ListServices(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::Service>
RegistrationServiceLogging::GetService(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::GetServiceRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::GetServiceRequest const&
request) { return child_->GetService(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::Service>
RegistrationServiceLogging::UpdateService(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::UpdateServiceRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::UpdateServiceRequest const&
request) { return child_->UpdateService(context, request); },
context, request, __func__, tracing_options_);
}
Status RegistrationServiceLogging::DeleteService(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::DeleteServiceRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::DeleteServiceRequest const&
request) { return child_->DeleteService(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::Endpoint>
RegistrationServiceLogging::CreateEndpoint(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::CreateEndpointRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::CreateEndpointRequest const&
request) { return child_->CreateEndpoint(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::ListEndpointsResponse>
RegistrationServiceLogging::ListEndpoints(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::ListEndpointsRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::ListEndpointsRequest const&
request) { return child_->ListEndpoints(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::Endpoint>
RegistrationServiceLogging::GetEndpoint(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::GetEndpointRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::GetEndpointRequest const&
request) { return child_->GetEndpoint(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::cloud::servicedirectory::v1::Endpoint>
RegistrationServiceLogging::UpdateEndpoint(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::UpdateEndpointRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::UpdateEndpointRequest const&
request) { return child_->UpdateEndpoint(context, request); },
context, request, __func__, tracing_options_);
}
Status RegistrationServiceLogging::DeleteEndpoint(
grpc::ClientContext& context,
google::cloud::servicedirectory::v1::DeleteEndpointRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::cloud::servicedirectory::v1::DeleteEndpointRequest const&
request) { return child_->DeleteEndpoint(context, request); },
context, request, __func__, tracing_options_);
}
StatusOr<google::iam::v1::Policy> RegistrationServiceLogging::GetIamPolicy(
grpc::ClientContext& context,
google::iam::v1::GetIamPolicyRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::iam::v1::GetIamPolicyRequest const& request) {
return child_->GetIamPolicy(context, request);
},
context, request, __func__, tracing_options_);
}
StatusOr<google::iam::v1::Policy> RegistrationServiceLogging::SetIamPolicy(
grpc::ClientContext& context,
google::iam::v1::SetIamPolicyRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::iam::v1::SetIamPolicyRequest const& request) {
return child_->SetIamPolicy(context, request);
},
context, request, __func__, tracing_options_);
}
StatusOr<google::iam::v1::TestIamPermissionsResponse>
RegistrationServiceLogging::TestIamPermissions(
grpc::ClientContext& context,
google::iam::v1::TestIamPermissionsRequest const& request) {
return google::cloud::internal::LogWrapper(
[this](grpc::ClientContext& context,
google::iam::v1::TestIamPermissionsRequest const& request) {
return child_->TestIamPermissions(context, request);
},
context, request, __func__, tracing_options_);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace servicedirectory_internal
} // namespace cloud
} // namespace google
| 44.158333
| 82
| 0.723816
|
a4b6d1b791eefcfd90aa0b7bf745f668203fa615
| 624
|
dart
|
Dart
|
flutter_weather/lib/blocs/settings_bloc.dart
|
AhmedMostafaElbasha/Flutter-Weather
|
4873861d82a4d03863380ede298b6bedc551626f
|
[
"Apache-2.0"
] | null | null | null |
flutter_weather/lib/blocs/settings_bloc.dart
|
AhmedMostafaElbasha/Flutter-Weather
|
4873861d82a4d03863380ede298b6bedc551626f
|
[
"Apache-2.0"
] | null | null | null |
flutter_weather/lib/blocs/settings_bloc.dart
|
AhmedMostafaElbasha/Flutter-Weather
|
4873861d82a4d03863380ede298b6bedc551626f
|
[
"Apache-2.0"
] | null | null | null |
import 'package:flutter/material.dart';
import 'package:bloc/bloc.dart';
import 'blocs.dart';
class SettingsBloc extends Bloc<SettingsEvent, SettingsState> {
SettingsBloc()
: super(SettingsState(temperatureUnits: TemperatureUnits.celsius));
@override
Stream<SettingsState> mapEventToState(SettingsEvent event) async* {
// TODO: implement mapEventToState
if (event is TemperatureUnitsToggled) {
yield SettingsState(
temperatureUnits: state.temperatureUnits == TemperatureUnits.celsius
? TemperatureUnits.fahrenheit
: TemperatureUnits.celsius,
);
}
}
}
| 28.363636
| 76
| 0.716346
|
e003d93a87bb47b335729a02d74cd446ac94a859
| 4,473
|
php
|
PHP
|
resources/views/home/districtOfficer/master.blade.php
|
arabi-kabir/Project-7-E-Governance_Project
|
65eeba04714ee99dfbc4bee92c98a8576682b400
|
[
"MIT"
] | null | null | null |
resources/views/home/districtOfficer/master.blade.php
|
arabi-kabir/Project-7-E-Governance_Project
|
65eeba04714ee99dfbc4bee92c98a8576682b400
|
[
"MIT"
] | null | null | null |
resources/views/home/districtOfficer/master.blade.php
|
arabi-kabir/Project-7-E-Governance_Project
|
65eeba04714ee99dfbc4bee92c98a8576682b400
|
[
"MIT"
] | null | null | null |
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="{{ asset('css/bootstrap.css') }}">
<link rel="stylesheet" href="{{ asset('css/style.css') }}">
<link rel="stylesheet" href="{{ asset('css/toastr.min.css') }}">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<title>e-Bazar</title>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark navbar-laravel">
<div class="container-fluid">
<a class="navbar-brand" href="">e - Bazar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<!-- Left Side Of Navbar -->
<ul class="navbar-nav mr-auto">
</ul>
<!-- Right Side Of Navbar -->
<ul class="navbar-nav ml-auto">
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle text-color" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
{{ session('user')->District }} District Officer : {{ session('user')->fullname }} <span class="caret"></span>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="">Profile</a>
<a class="dropdown-item" href="{{ route('logout') }}">Logout</a>
</div>
</li>
</ul>
</div>
</div>
</nav>
<main class="py-4">
<div class="container-fluid">
<div class="row">
<div class="col-lg-3 myNav">
<!-- <h4 class="text-center">District : {{ session('user')->District }}</h4> -->
<ul class="list-group">
<a href=""><li class="list-group-item @yield('')"> <i class="fa fa-home" aria-hidden="true"></i>Dashboard</li></a>
<a href=""><li class="list-group-item @yield('')"> <i class="far fa-folder"></i> District Market Request </li></a>
<a href=""><li class="list-group-item @yield('')"> <i class="fas fa-folder"></i> District Market Provide </li></a>
<a href="{{ route('show_add_upazila') }}"><li class="list-group-item @yield('')"> <i class="fas fa-plus"></i> Add Upazila </li></a>
<a href="{{ route('upazila_list') }}"><li class="list-group-item @yield('')"> <i class="fab fa-bity"></i> Upazila List </li></a>
<a href="{{ route('show_add_upazila_officer') }}"><li class="list-group-item @yield('')"> <i class="fas fa-user-plus"></i> Add Upazila Officer </li></a>
<a href="{{ route('show_upazila_officers') }}"><li class="list-group-item @yield('')"> <i class="fas fa-city"></i> Upazila Officer List </li></a>
</ul>
</div>
<div class="col-lg-9">
@include('include.error')
@yield('content')
</div>
</div>
</div>
</main>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="{{ asset('js/jQuery.js') }}"></script>
<script src="{{ asset('js/popper.js') }}"></script>
<script src="{{ asset('js/bootstrap.js') }}"></script>
<script src="{{ asset('js/toastr.min.js') }}"></script>
@include('include.custom')
</body>
</html>
| 53.25
| 226
| 0.492734
|
da4bc31603571d359f24ba88d6323138c20105ce
| 950
|
php
|
PHP
|
application/controllers/Devices.php
|
khoahoc/frontend
|
15ac1f28c58816cc24ff62c1604fe2677980f409
|
[
"MIT"
] | null | null | null |
application/controllers/Devices.php
|
khoahoc/frontend
|
15ac1f28c58816cc24ff62c1604fe2677980f409
|
[
"MIT"
] | null | null | null |
application/controllers/Devices.php
|
khoahoc/frontend
|
15ac1f28c58816cc24ff62c1604fe2677980f409
|
[
"MIT"
] | null | null | null |
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Devices extends CI_Controller
{
public function table_devices()
{
$devices = $this->strapi_model->getApi($this->session->userdata('account')['jwt'], 'devices', FALSE);
for ($i = 0; $i < count($devices); $i++) {
$data['data'][$i] = array(
'responsive_id' => '',
'device_id' => $devices[$i]['id'],
'device_name' => $devices[$i]['name'],
'device_model_name' => $devices[$i]['device_model']['name'],
'device_category_name' => $devices[$i]['device_category']['name'],
'device_used_reason' => $devices[$i]['device_use']['reason'],
'device_status' => $devices[$i]['device_status']['name'],
);
}
$table_data = $data;
print_r(json_encode($table_data));
}
}
/* End of file Devices.php */
| 33.928571
| 109
| 0.523158
|
ffb3fdbc4b0656d688e4d10c2d257b9353985ca9
| 818
|
py
|
Python
|
summarise_gain_loss.py
|
SongGithub/summarise-gain-loss
|
2e5c5644c83999b31f27aad74e034b14f6f2f055
|
[
"Apache-2.0"
] | null | null | null |
summarise_gain_loss.py
|
SongGithub/summarise-gain-loss
|
2e5c5644c83999b31f27aad74e034b14f6f2f055
|
[
"Apache-2.0"
] | null | null | null |
summarise_gain_loss.py
|
SongGithub/summarise-gain-loss
|
2e5c5644c83999b31f27aad74e034b14f6f2f055
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from decimal import Decimal
import sys
def handle_stdin():
return sys.stdin.readlines()
def calculate_diff(previous_data, current_data):
return round((Decimal(current_data) - Decimal(previous_data)), 2)
def summarise_prices(input_array):
gain = 0
loss = 0
for i in range(1, len(input_array)):
diff = calculate_diff(input_array[i-1], input_array[i])
if diff >=0:
gain += diff
else:
loss += diff
return {
"GAIN": str(gain),
"LOSS": str(loss)
}
def output(result_dict):
print(result_dict["GAIN"])
print(result_dict["LOSS"])
if __name__ == '__main__':
stdin_data = handle_stdin()
summary = summarise_prices(stdin_data)
output(summary)
| 19.47619
| 69
| 0.610024
|
b7ac8ed336791554465e3ec0a3097ef8fd5e260e
| 681
|
cpp
|
C++
|
acmicpc/1289.cpp
|
juseongkr/BOJ
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 7
|
2020-02-03T10:00:19.000Z
|
2021-11-16T11:03:57.000Z
|
acmicpc/1289.cpp
|
juseongkr/Algorithm-training
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 1
|
2021-01-03T06:58:24.000Z
|
2021-01-03T06:58:24.000Z
|
acmicpc/1289.cpp
|
juseongkr/Algorithm-training
|
8f10a2bf9a7d695455493fbe7423347a8b648416
|
[
"Apache-2.0"
] | 1
|
2020-01-22T14:34:03.000Z
|
2020-01-22T14:34:03.000Z
|
#include <iostream>
#include <vector>
using namespace std;
#define MAX 100001
const long long MOD = 1e9+7;
long long ans;
vector<pair<int, int>> graph[MAX];
long long dfs(int cur, int prev)
{
int ret = 1;
for (int i=0; i<graph[cur].size(); ++i) {
int next = graph[cur][i].first;
int cost = graph[cur][i].second;
if (next != prev) {
long long val = (dfs(next, cur) * cost) % MOD;
ans = (ans + val * ret) % MOD;
ret = (ret + val) % MOD;
}
}
return ret;
}
int main()
{
int n, a, b, c;
cin >> n;
for (int i=1; i<n; ++i) {
cin >> a >> b >> c;
graph[a].push_back({b, c});
graph[b].push_back({a, c});
}
dfs(1, 0);
cout << ans << '\n';
return 0;
}
| 16.214286
| 49
| 0.549192
|
df6ae86070ba702cfb48e40af40219b34b2c115a
| 2,993
|
cs
|
C#
|
src/Asv.TextConverter/Rules/RuleListViewModel.cs
|
asvol/text-converter
|
7e7f432ae76b04f044ec9b1a90e7db018ee06776
|
[
"MIT"
] | null | null | null |
src/Asv.TextConverter/Rules/RuleListViewModel.cs
|
asvol/text-converter
|
7e7f432ae76b04f044ec9b1a90e7db018ee06776
|
[
"MIT"
] | null | null | null |
src/Asv.TextConverter/Rules/RuleListViewModel.cs
|
asvol/text-converter
|
7e7f432ae76b04f044ec9b1a90e7db018ee06776
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.Composition;
using System.Linq;
using Caliburn.Micro;
using NLog;
using LogManager = NLog.LogManager;
namespace Asv.TextConverter
{
public class RuleListViewModelConfig
{
public RuleViewModelConfig[] Rules { get; set; }
}
public class RuleListViewModel:Conductor<RuleViewModel>.Collection.AllActive
{
private readonly IConfiguration _configService;
private RuleListViewModelConfig _cfg;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
[ImportingConstructor]
public RuleListViewModel(IConfiguration configService)
{
_configService = configService;
_cfg = configService.Get<RuleListViewModelConfig>();
LoadConfig();
DisplayName = "Правила";
}
public void RuleUp(RuleViewModel vm)
{
var index = Items.IndexOf(vm);
if (index > 0)
{
Items.RemoveAt(index);
Items.Insert(index-1,vm);
}
}
public void RuleDown(RuleViewModel vm)
{
var index = Items.IndexOf(vm);
if (index < (Items.Count -1))
{
Items.RemoveAt(index);
Items.Insert(index + 1, vm);
}
}
#region Config save\load
public void SaveConfig()
{
try
{
_cfg.Rules = Items.Select(_ => _.SaveConfig()).ToArray();
_configService.Set(_cfg);
}
catch (Exception e)
{
IoC.Get<IWindowManager>().ShowError("Error occured to save rules", e.Message, e);
_logger.Error(e, $"Error occured to save rules:{e.Message}");
}
}
private void LoadConfig()
{
try
{
Items.Clear();
if (_cfg != null && _cfg.Rules != null)
{
foreach (var rule in _cfg.Rules)
{
var newRule = new RuleViewModel();
newRule.Load(rule);
Items.Add(newRule);
}
}
}
catch (Exception e)
{
IoC.Get<IWindowManager>().ShowError("Error occured to load rules", e.Message, e);
_logger.Error(e, $"Error occured to load rules:{e.Message}");
}
}
#endregion
protected override void OnDeactivate(bool close)
{
if (close)
{
SaveConfig();
}
base.OnDeactivate(close);
}
public void RemoveRule(RuleViewModel vm)
{
Items.Remove(vm);
}
}
}
| 26.254386
| 97
| 0.492482
|
c492055adc885f3197e69a613bd23af8282ccb45
| 308
|
lua
|
Lua
|
test/lib/ffi/redir.lua
|
DemiMarie/LuaJIT-test-cleanup
|
014708bceb70550a3ab8d539cff14d9085ca9cb8
|
[
"MIT"
] | 1,657
|
2016-04-01T09:04:47.000Z
|
2022-03-31T18:25:24.000Z
|
test/lib/ffi/redir.lua
|
DemiMarie/LuaJIT-test-cleanup
|
014708bceb70550a3ab8d539cff14d9085ca9cb8
|
[
"MIT"
] | 700
|
2016-04-19T17:59:51.000Z
|
2020-01-13T13:03:35.000Z
|
test/lib/ffi/redir.lua
|
DemiMarie/LuaJIT-test-cleanup
|
014708bceb70550a3ab8d539cff14d9085ca9cb8
|
[
"MIT"
] | 180
|
2016-04-04T15:04:23.000Z
|
2022-02-16T23:15:33.000Z
|
local ffi = require("ffi")
do --- function
ffi.cdef[[
int redir_foo(const char *s) asm("strlen");
]]
assert(ffi.C.redir_foo("abcd") == 4)
end
do --- variable -windows
ffi.cdef[[
int redir_bar asm("errno");
]]
ffi.C.redir_bar = 14
assert(ffi.C.redir_bar == 14)
ffi.C.redir_bar = 0
end
| 15.4
| 45
| 0.616883
|
ef4e0300a99b90b56e289bbcd8f62a12925e2bae
| 760
|
rs
|
Rust
|
bee-protocol/src/message/tlv/mod.rs
|
neumoxx/bee-p
|
2a68c3c6c17bd2c8dd36d8274ef0db3a04d50b16
|
[
"Apache-2.0"
] | null | null | null |
bee-protocol/src/message/tlv/mod.rs
|
neumoxx/bee-p
|
2a68c3c6c17bd2c8dd36d8274ef0db3a04d50b16
|
[
"Apache-2.0"
] | null | null | null |
bee-protocol/src/message/tlv/mod.rs
|
neumoxx/bee-p
|
2a68c3c6c17bd2c8dd36d8274ef0db3a04d50b16
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2020 IOTA Stiftung
//
// 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.
//! Type-length-value encoding on top of the messages.
mod header;
mod tlv;
pub(crate) use header::{Header, HEADER_SIZE};
pub(crate) use tlv::{tlv_from_bytes, tlv_into_bytes};
| 40
| 118
| 0.753947
|
bb31459486c6f77b487ce9437d531d4f78fa5d3a
| 1,528
|
cs
|
C#
|
Proligence.Orchard.Testing/Mocks/ContentDefinitionManagerMock.cs
|
Lombiq/OrchardTesting
|
df1393e75f6ff769a14f1c789ea4708aa40eca6b
|
[
"MIT"
] | 6
|
2015-08-11T19:05:18.000Z
|
2017-12-02T07:20:08.000Z
|
Proligence.Orchard.Testing/Mocks/ContentDefinitionManagerMock.cs
|
Lombiq/OrchardTesting
|
df1393e75f6ff769a14f1c789ea4708aa40eca6b
|
[
"MIT"
] | 1
|
2015-10-16T14:00:27.000Z
|
2015-10-16T20:29:17.000Z
|
Proligence.Orchard.Testing/Mocks/ContentDefinitionManagerMock.cs
|
Lombiq/OrchardTesting
|
df1393e75f6ff769a14f1c789ea4708aa40eca6b
|
[
"MIT"
] | 2
|
2017-12-02T07:20:10.000Z
|
2020-05-15T10:58:59.000Z
|
namespace Proligence.Orchard.Testing.Mocks
{
using System.Linq;
using Moq;
using global::Orchard.ContentManagement.MetaData;
using global::Orchard.ContentManagement.MetaData.Models;
public class ContentDefinitionManagerMock : Mock<IContentDefinitionManager>
{
public ContentDefinitionManagerMock()
{
}
public ContentDefinitionManagerMock(MockBehavior mockBehavior)
: base(mockBehavior)
{
}
public void ExpectGetTypeDefinition(string name, ContentTypeDefinition definition)
{
Setup(x => x.GetTypeDefinition(name)).Returns(definition);
}
public void ExpectGetTypeDefinition(string name, params string[] partNames)
{
ContentTypeDefinition definition = CreateTypeDefinition(name, partNames);
Setup(x => x.GetTypeDefinition(name)).Returns(definition);
}
public void ExpectGetPartDefinition(string name, ContentPartDefinition definition)
{
Setup(x => x.GetPartDefinition(name)).Returns(definition);
}
public ContentTypeDefinition CreateTypeDefinition(string name, params string[] partNames)
{
var parts = partNames.Select(partName =>
new ContentTypePartDefinition(
new ContentPartDefinition(partName),
new SettingsDictionary()));
return new ContentTypeDefinition(name, name, parts, new SettingsDictionary());
}
}
}
| 33.955556
| 97
| 0.650524
|
cf17c6a06f49c44c44cb0e772cd0b1ff09241bfc
| 1,708
|
php
|
PHP
|
src/core/backend/components/system/programs/python.php
|
Blackoutzz/php-framework
|
b3c1a7ccffb758c25f9d206bb7c58898c4d39ac0
|
[
"MIT"
] | 1
|
2019-11-12T17:39:07.000Z
|
2019-11-12T17:39:07.000Z
|
src/core/backend/components/system/programs/python.php
|
Blackoutzz/php-framework
|
b3c1a7ccffb758c25f9d206bb7c58898c4d39ac0
|
[
"MIT"
] | null | null | null |
src/core/backend/components/system/programs/python.php
|
Blackoutzz/php-framework
|
b3c1a7ccffb758c25f9d206bb7c58898c4d39ac0
|
[
"MIT"
] | null | null | null |
<?php
namespace core\backend\components\system\programs;
use core\backend\filesystem\file;
use core\backend\system\console;
/**
* python short summary.
*
* python description.
*
* @version 1.0
* @author Mickael Nadeau
* @twitter @Mick4Secure
* @github @Blackoutzz
* @website https://Blackoutzz.me
**/
class python extends console
{
protected $installed = false;
protected function on_windows()
{
if($this->excution_path == "") $this->execution_path = "C:\\python2.7\\";
$this->application = "python.exe";
if(is_file($this->execution_path.$this->application)) $this->installed = true;
}
protected function on_unix()
{
$this->application = "python";
if(preg_match("~Python ([0-9\.\-\_A-z]+)\n~im",$this->execute(array("-V")))) $this->installed = true;
}
protected function execute_script($pscript,$pparams = array())
{
if(file::exist("{$pscript}") && file::get_extension("{$pscript}") == "py")
{
return parent::execute(array_merge(array($pscript),$pparams));
}
return "Python script not found";
}
public function get_version()
{
if($this->installed){
$full_version = $this->execute(array("-V"));
if(preg_match("~Python ([0-9\.\-\_A-z]+)\n~im",$full_version,$version)) return $version[1];
return "Unknown version";
}
return "Python isn't installed";
}
}
class python2 extends python
{
public function __construct()
{
//Python2.7 32bit
//Python2.7 64bit
}
}
class python3 extends python
{
public function __construct()
{
//Python3.6 32bit
}
}
| 22.473684
| 109
| 0.593091
|
878ff1191fa27795748c2c1ee0cb19272c574e1b
| 1,019
|
rb
|
Ruby
|
lib/pycall/pymodule_wrapper.rb
|
Atul9/pycall.rb
|
725ef990ac2a3250daff296be5d446035cedfbd1
|
[
"MIT"
] | 702
|
2017-09-08T05:21:44.000Z
|
2022-02-02T21:18:38.000Z
|
lib/pycall/pymodule_wrapper.rb
|
Atul9/pycall.rb
|
725ef990ac2a3250daff296be5d446035cedfbd1
|
[
"MIT"
] | 107
|
2017-09-08T04:56:15.000Z
|
2022-03-11T17:57:25.000Z
|
lib/pycall/pymodule_wrapper.rb
|
Atul9/pycall.rb
|
725ef990ac2a3250daff296be5d446035cedfbd1
|
[
"MIT"
] | 54
|
2017-09-08T16:16:30.000Z
|
2022-03-04T13:51:24.000Z
|
require 'pycall/pyobject_wrapper'
module PyCall
module PyModuleWrapper
include PyObjectWrapper
def [](*args)
case args[0]
when String, Symbol
PyCall.getattr(self, args[0])
else
super
end
end
end
module_function
class WrapperModuleCache < WrapperObjectCache
def initialize
super(LibPython::API::PyModule_Type)
end
def check_wrapper_object(wrapper_object)
unless wrapper_object.kind_of?(Module) && wrapper_object.kind_of?(PyObjectWrapper)
raise TypeError, "unexpected type #{wrapper_object.class} (expected Module extended by PyObjectWrapper)"
end
end
def self.instance
@instance ||= self.new
end
end
private_constant :WrapperModuleCache
def wrap_module(pymodptr)
check_ismodule(pymodptr)
WrapperModuleCache.instance.lookup(pymodptr) do
Module.new do |mod|
mod.instance_variable_set(:@__pyptr__, pymodptr)
mod.extend PyModuleWrapper
end
end
end
end
| 21.680851
| 112
| 0.689892
|
99f94c4ade98878987cd8176fd3b0700a4d9bb96
| 406
|
ps1
|
PowerShell
|
swarm-loadtest.ps1
|
mo-mann/aspnetcore-dockerswarm
|
7c10fe895fd84ac454a7df1c1fc92cdb26cf45cc
|
[
"MIT"
] | 130
|
2016-08-08T14:29:38.000Z
|
2020-02-14T15:49:05.000Z
|
swarm-loadtest.ps1
|
mo-mann/aspnetcore-dockerswarm
|
7c10fe895fd84ac454a7df1c1fc92cdb26cf45cc
|
[
"MIT"
] | 4
|
2016-08-21T11:49:07.000Z
|
2019-09-13T09:10:18.000Z
|
swarm-loadtest.ps1
|
mo-mann/aspnetcore-dockerswarm
|
7c10fe895fd84ac454a7df1c1fc92cdb26cf45cc
|
[
"MIT"
] | 21
|
2016-08-21T15:24:54.000Z
|
2020-05-15T07:25:51.000Z
|
workflow loadtest{
Param($Iterations)
$array = 1..$Iterations
$startTime = get-date
foreach -Parallel -ThrottleLimit 10 ($i in $array){
$null = Invoke-RestMethod http://localhost:5000/api/token
}
"elapsed time " + ((get-date) - $startTime).TotalSeconds + "sec"
# display load
Invoke-RestMethod http://localhost:5000/api/issuer
}
# run load test
loadtest 1000
| 20.3
| 68
| 0.650246
|
fa157b271ec389010412d34a87211fb4f202816b
| 1,287
|
cpp
|
C++
|
src/main.cpp
|
ishuah/simdexp
|
ed099ed472431e220c3642490f209663081bf72a
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
ishuah/simdexp
|
ed099ed472431e220c3642490f209663081bf72a
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
ishuah/simdexp
|
ed099ed472431e220c3642490f209663081bf72a
|
[
"MIT"
] | null | null | null |
#include <addition.h>
#include <multiplication.h>
#include <dotproduct.h>
#include <iostream>
using namespace std;
static const char *const HEADER = "\nSIMD Experiments\nContol output\n\n";
int main(int argc, const char *argv[]) {
cout << HEADER;
float a[8] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};
float b[8] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8};
float c[8] = {};
float d[8] = {};
float e[4] = {0.1, 0.2, 0.3, 0.4};
float f[4] = {0.5, 0.6, 0.7, 0.8};
float g[4] = {};
add_float32_avx2(a, b, c);
for (float i: c)
cout << i << '\t';
cout << '\n';
add_float32_SIMD(e, f, g);
for (float i: g)
cout << i << '\t';
cout << '\n';
add_float32(a, b, d);
for (float i: d)
cout << i << '\t';
cout << '\n';
mul_float32_avx2(a, b, c);
for (float i: c)
cout << i << '\t';
cout << '\n';
mul_float32_SIMD(e, f, g);
for (float i: g)
cout << i << '\t';
cout << '\n';
mul_float32(a, b, d);
for (float i: d)
cout << i << '\t';
cout << '\n';
size_t size = 786432;
float aa[size];
float bb[size];
fill_vectors(aa, bb, size);
dot_product(aa, bb, size);
dot_product_avx2(aa, bb, size);
dot_product_avx2_multiple_accumulators(aa, bb, size, 2);
cout << "\n\nsize: " << size;
return 0;
}
| 19.8
| 74
| 0.526807
|
e84fb494802daae219ad3bdec170362a29c9b35d
| 3,948
|
cs
|
C#
|
Runtime/Scripts/LoadingTimeMetadata.cs
|
AndyYudkin/tuningfork
|
9be99b0fd8c898f883608bb69c370d2c1b72cfe6
|
[
"Apache-2.0"
] | 30
|
2020-01-29T14:47:49.000Z
|
2022-02-22T08:32:11.000Z
|
Runtime/Scripts/LoadingTimeMetadata.cs
|
AndyYudkin/tuningfork
|
9be99b0fd8c898f883608bb69c370d2c1b72cfe6
|
[
"Apache-2.0"
] | 17
|
2020-09-22T20:57:12.000Z
|
2022-03-16T15:57:29.000Z
|
Runtime/Scripts/LoadingTimeMetadata.cs
|
AndyYudkin/tuningfork
|
9be99b0fd8c898f883608bb69c370d2c1b72cfe6
|
[
"Apache-2.0"
] | 17
|
2020-02-08T16:15:21.000Z
|
2022-02-10T12:11:35.000Z
|
//-----------------------------------------------------------------------
// <copyright file="LoadingTimeMetadata.cs" company="Google">
//
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
using System.Runtime.InteropServices;
// ReSharper disable InconsistentNaming.
namespace Google.Android.PerformanceTuner
{
/// <summary>
/// Metadata recorded with a loading time event.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class LoadingTimeMetadata
{
public enum LoadingState
{
Unknown = 0,
/// <summary>
/// The first time the game is run.
/// </summary>
FirstRun = 1,
/// <summary>
/// App is not backgrounded.
/// </summary>
ColdStart = 2,
/// <summary>
/// App is backgrounded.
/// </summary>
WarmStart = 3,
/// <summary>
/// App is backgrounded, least work needed.
/// </summary>
HotStart = 4,
/// <summary>
/// Asset loading between levels.
/// </summary>
InterLevel = 5
}
public LoadingState state;
public enum LoadingSource
{
UnknownSource = 0,
/// <summary>
/// Uncompressing data.
/// </summary>
Memory = 1,
/// <summary>
/// Reading assets from APK bundle.
/// </summary>
Apk = 2,
/// <summary>
/// Reading assets from device storage.
/// </summary>
DeviceStorage = 3,
/// <summary>
/// Reading assets from external storage, for example SD card.
/// </summary>
ExternalStorage = 4,
/// <summary>
/// Loading assets from the network.
/// </summary>
Network = 5,
/// <summary>
/// Shader compilation.
/// </summary>
ShaderCompilation = 6,
/// <summary>
/// Time spent between process starting and onCreate.
/// </summary>
PreActivity = 7,
/// <summary>
/// Total time spent between process starting and first render frame.
/// </summary>
FirstTouchToFirstFrame = 8,
/// <summary>
/// Time from start to end of a group of events.
/// </summary>
TotalUserWaitForGroup = 9
}
public LoadingSource source;
/// <summary>
/// 0 = no compression, 100 = max compression
/// </summary>
public int compression_level;
public enum NetworkConnectivity
{
Unknown = 0,
Wifi = 1,
CellularNetwork = 2
}
public NetworkConnectivity network_connectivity;
/// <summary>
/// Bandwidth in bits per second.
/// </summary>
public ulong network_transfer_speed_bps;
/// <summary>
/// Latency in nanoseconds.
/// </summary>
public ulong network_latency_ns;
}
}
| 28
| 85
| 0.491135
|
c9b017748cce365083025b25ae2730b867981682
| 1,172
|
ts
|
TypeScript
|
src/pages/manager/manager.ts
|
CaesiumY/ionic-with-pwa
|
a9ad1ca0b9e88e523048a32d78f76c56a1f336ff
|
[
"MIT"
] | null | null | null |
src/pages/manager/manager.ts
|
CaesiumY/ionic-with-pwa
|
a9ad1ca0b9e88e523048a32d78f76c56a1f336ff
|
[
"MIT"
] | null | null | null |
src/pages/manager/manager.ts
|
CaesiumY/ionic-with-pwa
|
a9ad1ca0b9e88e523048a32d78f76c56a1f336ff
|
[
"MIT"
] | null | null | null |
import { Component } from "@angular/core";
import { IonicPage, NavController, NavParams } from "ionic-angular";
import { NewsPage } from "../news/news";
import { UserPage } from "../user/user";
import { CategoryPage } from "../category/category";
/**
* Generated class for the ManagerPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: "page-manager",
templateUrl: "manager.html",
})
export class ManagerPage {
private menus = [
{
code: "001",
title: "News database",
},
{
code: "002",
title: "User database",
},
{
code: "003",
title: "Category database",
},
];
constructor(public navCtrl: NavController, public navParams: NavParams) {}
ionViewDidLoad() {
console.log("ionViewDidLoad ManagerPage");
}
toMenu(menu) {
switch (menu.code) {
case "001":
return this.navCtrl.push(NewsPage);
case "002":
return this.navCtrl.push(UserPage);
case "003":
return this.navCtrl.push(CategoryPage);
default:
break;
}
}
}
| 21.309091
| 78
| 0.614334
|
6b8792a3639bf927fd1ab4989616d36749e03612
| 119
|
sql
|
SQL
|
src/main/resources/init_db/db_setup_all.sql
|
soul-craft/liquibase-templates
|
2ed215c8e474c9fae9c9675a99195fd87fd1fe60
|
[
"MIT"
] | null | null | null |
src/main/resources/init_db/db_setup_all.sql
|
soul-craft/liquibase-templates
|
2ed215c8e474c9fae9c9675a99195fd87fd1fe60
|
[
"MIT"
] | null | null | null |
src/main/resources/init_db/db_setup_all.sql
|
soul-craft/liquibase-templates
|
2ed215c8e474c9fae9c9675a99195fd87fd1fe60
|
[
"MIT"
] | null | null | null |
-- initial scripts
select 'executing initial_scripts/db_init.sql' as log from dual;
source initial_scripts/db_init.sql;
| 39.666667
| 64
| 0.823529
|
2a1c126ec4ae1ebb82883139a2172b7ecfe89380
| 4,368
|
swift
|
Swift
|
Sources/Layout/FlowLayout.swift
|
rezamagnet/CollectionKit
|
4b04bca97b24ff97a2b11e96b334c7011b2c0bf7
|
[
"MIT"
] | 4,393
|
2017-08-22T08:36:32.000Z
|
2022-03-24T05:45:02.000Z
|
Sources/Layout/FlowLayout.swift
|
rezamagnet/CollectionKit
|
4b04bca97b24ff97a2b11e96b334c7011b2c0bf7
|
[
"MIT"
] | 146
|
2017-08-23T16:07:56.000Z
|
2022-02-12T19:23:47.000Z
|
Sources/Layout/FlowLayout.swift
|
rezamagnet/CollectionKit
|
4b04bca97b24ff97a2b11e96b334c7011b2c0bf7
|
[
"MIT"
] | 274
|
2017-08-30T03:12:02.000Z
|
2022-03-06T12:47:53.000Z
|
//
// FlowLayout.swift
// CollectionKit
//
// Created by Luke Zhao on 2017-08-15.
// Copyright © 2017 lkzhao. All rights reserved.
//
import UIKit
public class FlowLayout: VerticalSimpleLayout {
public var lineSpacing: CGFloat
public var interitemSpacing: CGFloat
public var alignContent: AlignContent
public var alignItems: AlignItem
public var justifyContent: JustifyContent
public init(lineSpacing: CGFloat = 0,
interitemSpacing: CGFloat = 0,
justifyContent: JustifyContent = .start,
alignItems: AlignItem = .start,
alignContent: AlignContent = .start) {
self.lineSpacing = lineSpacing
self.interitemSpacing = interitemSpacing
self.justifyContent = justifyContent
self.alignItems = alignItems
self.alignContent = alignContent
super.init()
}
public convenience init(spacing: CGFloat,
justifyContent: JustifyContent = .start,
alignItems: AlignItem = .start,
alignContent: AlignContent = .start) {
self.init(lineSpacing: spacing,
interitemSpacing: spacing,
justifyContent: justifyContent,
alignItems: alignItems,
alignContent: alignContent)
}
public override func simpleLayout(context: LayoutContext) -> [CGRect] {
var frames: [CGRect] = []
let sizes = (0..<context.numberOfItems).map { context.size(at: $0, collectionSize: context.collectionSize) }
let (totalHeight, lineData) = distributeLines(sizes: sizes, maxWidth: context.collectionSize.width)
var (yOffset, spacing) = LayoutHelper.distribute(justifyContent: alignContent,
maxPrimary: context.collectionSize.height,
totalPrimary: totalHeight,
minimunSpacing: lineSpacing,
numberOfItems: lineData.count)
var index = 0
for (lineSize, count) in lineData {
let (xOffset, lineInteritemSpacing) =
LayoutHelper.distribute(justifyContent: justifyContent,
maxPrimary: context.collectionSize.width,
totalPrimary: lineSize.width,
minimunSpacing: interitemSpacing,
numberOfItems: count)
let lineFrames = LayoutHelper.alignItem(alignItems: alignItems,
startingPrimaryOffset: xOffset,
spacing: lineInteritemSpacing,
sizes: sizes[index..<(index+count)],
secondaryRange: yOffset...(yOffset + lineSize.height))
frames.append(contentsOf: lineFrames)
yOffset += lineSize.height + spacing
index += count
}
return frames
}
func distributeLines(sizes: [CGSize], maxWidth: CGFloat) ->
(totalHeight: CGFloat, lineData: [(lineSize: CGSize, count: Int)]) {
var lineData: [(lineSize: CGSize, count: Int)] = []
var currentLineItemCount = 0
var currentLineWidth: CGFloat = 0
var currentLineMaxHeight: CGFloat = 0
var totalHeight: CGFloat = 0
for size in sizes {
if currentLineWidth + size.width > maxWidth, currentLineItemCount != 0 {
lineData.append((lineSize: CGSize(width: currentLineWidth - CGFloat(currentLineItemCount) * interitemSpacing,
height: currentLineMaxHeight),
count: currentLineItemCount))
totalHeight += currentLineMaxHeight
currentLineMaxHeight = 0
currentLineWidth = 0
currentLineItemCount = 0
}
currentLineMaxHeight = max(currentLineMaxHeight, size.height)
currentLineWidth += size.width + interitemSpacing
currentLineItemCount += 1
}
if currentLineItemCount > 0 {
lineData.append((lineSize: CGSize(width: currentLineWidth - CGFloat(currentLineItemCount) * interitemSpacing,
height: currentLineMaxHeight),
count: currentLineItemCount))
totalHeight += currentLineMaxHeight
}
return (totalHeight, lineData)
}
}
| 40.073394
| 117
| 0.594551
|
906b4327920f474f2109189ad84e43cce07f9169
| 1,482
|
rake
|
Ruby
|
lib/tasks/reach_linters.rake
|
reachnetwork/reach_linters
|
f9844e58240c554f71a7f6e92fea669529d079be
|
[
"MIT"
] | null | null | null |
lib/tasks/reach_linters.rake
|
reachnetwork/reach_linters
|
f9844e58240c554f71a7f6e92fea669529d079be
|
[
"MIT"
] | 1
|
2019-01-18T17:25:26.000Z
|
2019-01-18T17:25:26.000Z
|
lib/tasks/reach_linters.rake
|
reachnetwork/reach_linters
|
f9844e58240c554f71a7f6e92fea669529d079be
|
[
"MIT"
] | null | null | null |
namespace :reach_linters do
desc 'Installs various components needed for the linters'
task :system_setup do
Bundler.with_clean_env do
do_installation
end
end
end
private
def do_installation
`sudo ls` # just want to get the sudo password out of the way for prettier output later :)
print "\nChecking for Homebrew..."
begin
r = `brew list`
raise "\nHomebrew not found!" if r.nil? || r.include?('No such file or directory')
print " FOUND!"
rescue StandardError => e
print e.message
puts "\n\nINSTALLATION FAILED!"
exit
end
print "\n\nUpdating Homebrew..."
`brew update`
print " DONE!"
install_node
install_linters
puts "\n\nSETUP COMPLETE!"
end
def install_node
print "\n\nChecking for Node..."
if `brew list`.include?('node')
print " FOUND, skipping..."
else
print "\n INSTALLING..."
`brew install node`
if `brew list`.include?('node')
print " FINISHED!"
else
puts "\n\nERROR: Failed to install package manager!"
return
end
end
end
def install_linters
['PostCSS', 'StyleLint', 'ESLint'].each do |lib_name|
print "\nChecking for #{lib_name}..."
lib = lib_name.downcase
if `sudo npm -g list`.include?(lib)
print " FOUND, skipping..."
else
print "\n INSTALLING..."
`sudo npm install -g #{lib}`
if `sudo npm -g list`.include?(lib)
print " FINISHED!"
else
print ' FAILED!'
end
end
end
end
| 21.478261
| 92
| 0.631579
|
a371f84356f2fea9fd92bbfda93b94c9ccd01a8a
| 841
|
java
|
Java
|
src/main/java/com/tianma/mesos/client/mesos/MesosMonitor.java
|
jieliu/mesos-client
|
74e8b9c471e2c19ee05a685004383da02ed6b8db
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/tianma/mesos/client/mesos/MesosMonitor.java
|
jieliu/mesos-client
|
74e8b9c471e2c19ee05a685004383da02ed6b8db
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/tianma/mesos/client/mesos/MesosMonitor.java
|
jieliu/mesos-client
|
74e8b9c471e2c19ee05a685004383da02ed6b8db
|
[
"Apache-2.0"
] | null | null | null |
package com.tianma.mesos.client.mesos;
import com.tianma.mesos.domain.mesos.v1.GetSlavesResponse;
import com.tianma.mesos.domain.mesos.v1.MesosVersion;
import com.tianma.mesos.domain.mesos.v1.StateSummary;
import com.tianma.mesos.domain.mesos.v1.SystemStats;
import com.tianma.mesos.support.exception.ResponseException;
import feign.RequestLine;
/**
* Created by jie on 16-11-18.
*/
public interface MesosMonitor {
// Monitor
@RequestLine("GET /version")
MesosVersion getVersion() throws ResponseException;
@RequestLine("GET /system/stats.json")
SystemStats getMasterSystemStats() throws ResponseException;
@RequestLine("GET /master/slaves")
GetSlavesResponse getMasterSlaves() throws ResponseException;
@RequestLine("GET /state-summary")
StateSummary getStateSummary() throws ResponseException;
}
| 31.148148
| 65
| 0.774078
|
89a4e55fef28562e7dc94f955ee347e9174b872f
| 1,003
|
swift
|
Swift
|
EasyBank/Helpers/QRCodeHelper.swift
|
glrmeslp/EasyBank
|
3f1c32ac7a2152b526818ee01e57619c425f988b
|
[
"MIT"
] | 1
|
2021-10-06T14:39:51.000Z
|
2021-10-06T14:39:51.000Z
|
EasyBank/Helpers/QRCodeHelper.swift
|
glrmeslp/EasyBank
|
3f1c32ac7a2152b526818ee01e57619c425f988b
|
[
"MIT"
] | 2
|
2021-10-06T13:13:43.000Z
|
2021-10-20T15:44:05.000Z
|
EasyBank/Helpers/QRCodeHelper.swift
|
glrmeslp/EasyBank
|
3f1c32ac7a2152b526818ee01e57619c425f988b
|
[
"MIT"
] | null | null | null |
import UIKit
final class QRCodeHelper {
func isQRCodeValid(value: String) -> Bool {
do {
let qrCodePattern = #"com.glrmeslp.EasyBank00X00+\S+00X00+\S+00X00?\S"#
let regex = try NSRegularExpression(pattern: qrCodePattern)
let sourceRange = NSRange(value.startIndex..<value.endIndex, in: value)
return regex.firstMatch(in: value, options: [], range: sourceRange) != nil
} catch {
return false
}
}
func generateQRCode(from string: String) -> UIImage? {
let data = string.data(using: String.Encoding.ascii)
if let filter = CIFilter(name: "CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 10, y: 10)
if let output = filter.outputImage?.transformed(by: transform) {
return UIImage(ciImage: output)
}
}
return nil
}
}
| 35.821429
| 86
| 0.577268
|
4cff85886beb7d72dbb0735051e27c0ae8c221bc
| 778
|
py
|
Python
|
Halloween_Prank.py
|
ishkapoor2000/Halloween-Prank
|
c76ea1cd018ee35ccb623d2ba502d183fe49d4bd
|
[
"MIT"
] | 3
|
2020-12-03T09:38:26.000Z
|
2021-09-17T18:47:12.000Z
|
Halloween_Prank.py
|
ishkapoor2000/Halloween-Prank
|
c76ea1cd018ee35ccb623d2ba502d183fe49d4bd
|
[
"MIT"
] | null | null | null |
Halloween_Prank.py
|
ishkapoor2000/Halloween-Prank
|
c76ea1cd018ee35ccb623d2ba502d183fe49d4bd
|
[
"MIT"
] | null | null | null |
"""
Created on Fri Oct 30 19:41:32 2020
@author: ISH KAPOOR
"""
import pygame
from pygame import mixer
from time import sleep
pygame.init()
window = pygame.display.set_mode((600, 600))
# window = pygame.display.set_mode((0, 0),pygame.FULLSCREEN)
pygame.mixer.init()
pygame.mixer_music.load('C:/Users/ISH KAPOOR/Desktop/GIT Project/Halloween Project/ratsasan.mp3') # Not so scary audio
pygame.mixer_music.play()
sleep(5)
pygame.mixer_music.load('C:/Users/ISH KAPOOR/Desktop/GIT Project/Halloween Project/scary.mp3') # Scary audio
pygame.mixer_music.play()
sleep(1)
image = pygame.image.load('C:/Users/ISH KAPOOR/Desktop/GIT Project/Halloween Project/scr2.jpg') # Scary image(size: 200x200)
window.blit(image, (10, 10))
pygame.display.update()
sleep(3)
| 31.12
| 125
| 0.736504
|
f4e6f902fb6513480d21d92a8baad359fdd67629
| 1,228
|
tsx
|
TypeScript
|
src/symbols/alphanum/Alphanum29.tsx
|
react-pakistan/react-emoji-collection
|
eeaa58b42c7c4cc6f6a11b362b48358a14716e0f
|
[
"MIT"
] | 1
|
2020-10-17T00:36:58.000Z
|
2020-10-17T00:36:58.000Z
|
src/symbols/alphanum/Alphanum29.tsx
|
react-pakistan/react-emoji-collection
|
eeaa58b42c7c4cc6f6a11b362b48358a14716e0f
|
[
"MIT"
] | null | null | null |
src/symbols/alphanum/Alphanum29.tsx
|
react-pakistan/react-emoji-collection
|
eeaa58b42c7c4cc6f6a11b362b48358a14716e0f
|
[
"MIT"
] | null | null | null |
import * as React from "react";
import { IEmojiProps } from "../../styled";
const SvgAlphanum29 = (props: IEmojiProps) => (
<svg viewBox="0 0 72 72" width="1em" height="1em" {...props}>
<rect
x={11.792}
y={11.974}
rx={1.699}
width={48.984}
height={48.984}
fill="#d0cfce"
/>
<g fill="none" stroke="#000" strokeWidth={2}>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M34.293 24.315h14.135v10.826H34.047V24.315h.246z"
/>
<path strokeMiterlimit={10} d="M34.047 29.728h14.381" />
<path
strokeLinecap="round"
strokeMiterlimit={10}
d="M31.693 40.464h19.091M31.693 45.787h19.091M34.715 51.11h3.533M21.245 36.317l7.476-3.176M20.926 28.646l7.476-3.176"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M42.521 52.493h3.533V40.696"
/>
<path
strokeLinecap="round"
strokeMiterlimit={10}
d="M25.465 34.525v17.968"
/>
<rect
x={11.792}
y={11.974}
rx={1.699}
width={48.984}
height={48.984}
strokeMiterlimit={10}
/>
</g>
</svg>
);
export default SvgAlphanum29;
| 25.061224
| 125
| 0.544788
|
ee13938aa552d603768b2668605855dd81a7a7d8
| 683
|
lua
|
Lua
|
defgamesnacks/utils/mock.lua
|
anevdashenko/defgamesnacks
|
8418968b4e2daa80f8422fde2d64cb421cd2704c
|
[
"MIT"
] | 1
|
2022-01-07T13:54:29.000Z
|
2022-01-07T13:54:29.000Z
|
defgamesnacks/utils/mock.lua
|
anevdashenko/defgamesnacks
|
8418968b4e2daa80f8422fde2d64cb421cd2704c
|
[
"MIT"
] | null | null | null |
defgamesnacks/utils/mock.lua
|
anevdashenko/defgamesnacks
|
8418968b4e2daa80f8422fde2d64cb421cd2704c
|
[
"MIT"
] | null | null | null |
local Mock = {}
Mock.state = {
is_audio_enabled = false,
is_rewarded_ad_ready = false
}
function Mock.game_ready()
-- body
end
function Mock.send_score()
-- body
end
function Mock.send_level_complete()
-- body
end
function Mock.send_game_over()
-- body
end
function Mock.is_audio_enabled()
return Mock.state.is_audio_enabled
end
function Mock.add_audio_listener()
-- body
end
function Mock.add_rewarded_ad_listener()
-- body
end
function Mock.check_rewarded_ad_opportunity()
-- body
end
function Mock.show_rewarded_ad()
-- body
end
function Mock.is_rewarded_ad_ready()
return Mock.state.is_rewarded_ad_ready
end
return Mock
| 14.229167
| 45
| 0.729136
|
051fb45df4605f6d59d9524856f5b36f650c26a1
| 10,207
|
rs
|
Rust
|
runtime/boxed/types/list.rs
|
mwatts/arret
|
3b3bae27ca7283376d420fa7d69fe5073ecf9ef0
|
[
"Apache-2.0"
] | 207
|
2018-07-22T06:35:53.000Z
|
2022-03-06T15:26:24.000Z
|
runtime/boxed/types/list.rs
|
mwatts/arret
|
3b3bae27ca7283376d420fa7d69fe5073ecf9ef0
|
[
"Apache-2.0"
] | 50
|
2019-01-10T08:02:09.000Z
|
2021-10-30T19:01:19.000Z
|
runtime/boxed/types/list.rs
|
mwatts/arret
|
3b3bae27ca7283376d420fa7d69fe5073ecf9ef0
|
[
"Apache-2.0"
] | 5
|
2019-06-23T20:22:51.000Z
|
2022-01-08T15:19:25.000Z
|
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter::FusedIterator;
use std::marker::PhantomData;
use crate::abitype::{BoxedAbiType, EncodeBoxedAbiType};
use crate::boxed::refs::Gc;
use crate::boxed::*;
/// Non-empty list
#[repr(C, align(16))]
pub struct Pair<T: Boxed = Any> {
header: Header,
list_len: i64,
pub(crate) head: Gc<T>,
pub(crate) rest: Gc<List<T>>,
}
impl<T: Boxed> Boxed for Pair<T> {}
impl<T: Boxed> EncodeBoxedAbiType for Pair<T>
where
T: EncodeBoxedAbiType,
{
const BOXED_ABI_TYPE: BoxedAbiType = BoxedAbiType::Pair(&T::BOXED_ABI_TYPE);
}
impl<T: Boxed> Pair<T> {
/// Constructs a pair with the given `head` and `rest`
pub fn new(heap: &mut impl AsHeap, head: Gc<T>, rest: Gc<List<T>>) -> Gc<Pair<T>> {
heap.as_heap_mut().place_box(Pair {
header: Pair::TYPE_TAG.to_heap_header(Self::size()),
head,
rest,
list_len: (rest.len() + 1) as i64,
})
}
/// Returns the box size for pairs
pub fn size() -> BoxSize {
BoxSize::Size32
}
/// Returns the length of the list this pair is the head of
///
/// Note that this must be at least 1.
pub fn len(&self) -> usize {
self.list_len as usize
}
/// Returns false
pub fn is_empty(&self) -> bool {
// This is to make Clippy happy since we have `len`
false
}
/// Returns the head value
pub fn head(&self) -> Gc<T> {
self.head
}
/// Returns the tail list
pub fn rest(&self) -> Gc<List<T>> {
self.rest
}
/// Casts this pair to a non-empty list
pub fn as_list_ref(&self) -> Gc<List<T>> {
unsafe { Gc::new(&*(self as *const _ as *const List<T>)) }
}
}
impl<T: Boxed> PartialEqInHeap for Pair<T> {
fn eq_in_heap(&self, heap: &Heap, rhs: &Pair<T>) -> bool {
self.head.eq_in_heap(heap, &rhs.head) && self.rest.eq_in_heap(heap, &rhs.rest)
}
}
impl<T: Boxed> HashInHeap for Pair<T> {
fn hash_in_heap<H: Hasher>(&self, task: &Heap, state: &mut H) {
TypeTag::Pair.hash(state);
self.head().hash_in_heap(task, state);
self.rest().hash_in_heap(task, state);
}
}
impl<T: Boxed> fmt::Debug for Pair<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
self.as_list_ref().fmt(formatter)
}
}
/// List of boxed values
///
/// This allows O(n) access to its elements. It has the benefit of allowing constant time prepends
/// while sharing the tail of the existing list.
#[repr(C, align(16))]
pub struct List<T: Boxed = Any> {
header: Header,
list_len: i64,
phantom: PhantomData<T>,
}
impl<T: Boxed> Boxed for List<T> {}
impl DistinctTagged for List<Any> {
fn has_tag(type_tag: TypeTag) -> bool {
[TypeTag::Pair, TypeTag::Nil].contains(&type_tag)
}
}
impl<T: Boxed> EncodeBoxedAbiType for List<T>
where
T: EncodeBoxedAbiType,
{
const BOXED_ABI_TYPE: BoxedAbiType = BoxedAbiType::List(&T::BOXED_ABI_TYPE);
}
/// Possible subtypes of [`List`]
pub enum ListSubtype<'a, T: Boxed> {
/// Non-empty list
Pair(&'a Pair<T>),
/// Empty list
Nil,
}
impl<T: Boxed> List<T> {
/// Constructs a new fixed sized list containing the passed `elems`
pub fn new(heap: &mut impl AsHeap, elems: impl ExactSizeIterator<Item = Gc<T>>) -> Gc<List<T>> {
Self::new_with_tail(heap, elems, Self::empty())
}
/// Constructs a list with a head of `elems` and the specified tail list
pub fn new_with_tail(
heap: &mut impl AsHeap,
elems: impl ExactSizeIterator<Item = Gc<T>>,
tail: Gc<List<T>>,
) -> Gc<List<T>> {
let elems_len = elems.len();
let tail_len = tail.len();
if elems_len == 0 {
return tail;
}
// Allocate the entire list at once
let heap_alloc = heap
.as_heap_mut()
.alloc_cells(Pair::<T>::size().cell_count() * elems_len);
unsafe {
let pair_alloc = heap_alloc as *mut Pair<T>;
for (i, head) in elems.enumerate() {
let elems_remaining = elems_len - i;
let rest = if elems_remaining == 1 {
tail
} else {
(&*pair_alloc.add(i + 1)).as_list_ref()
};
*pair_alloc.add(i) = Pair {
header: Pair::TYPE_TAG.to_heap_header(Pair::<T>::size()),
head,
rest,
list_len: (elems_remaining + tail_len) as i64,
};
}
Gc::new(pair_alloc as *const List<T>)
}
}
/// Returns an empty list
pub fn empty() -> Gc<List<T>> {
unsafe { Gc::new(&NIL_INSTANCE as *const Nil as *const List<T>) }
}
/// Creates a list by constructing an iterator of values
pub fn from_values<V, F>(
heap: &mut impl AsHeap,
values: impl Iterator<Item = V>,
cons: F,
) -> Gc<List<T>>
where
F: Fn(&mut Heap, V) -> Gc<T>,
{
let heap = heap.as_heap_mut();
let elems: Vec<Gc<T>> = values.map(|v| cons(heap, v)).collect();
Self::new(heap, elems.into_iter())
}
/// Returns a subtype of this list based on its type tag
pub fn as_subtype(&self) -> ListSubtype<'_, T> {
match self.header.type_tag {
TypeTag::Pair => {
ListSubtype::Pair(unsafe { &*(self as *const List<T> as *const Pair<T>) })
}
TypeTag::Nil => ListSubtype::Nil,
other => {
unreachable!("Unexpected type tag: {:?}", other);
}
}
}
/// Returns the length of the list
pub fn len(&self) -> usize {
self.list_len as usize
}
/// Returns true if the list is empty
pub fn is_empty(&self) -> bool {
self.header.type_tag == TypeTag::Nil
}
/// Returns an iterator to the list's values
pub fn iter(&self) -> ListIterator<T> {
ListIterator {
head: unsafe { Gc::new(self as *const Self) },
}
}
}
impl<T: Boxed> PartialEqInHeap for List<T> {
fn eq_in_heap(&self, heap: &Heap, other: &List<T>) -> bool {
if self.len() != other.len() {
return false;
}
self.iter()
.zip(other.iter())
.all(|(self_value, other_value)| self_value.eq_in_heap(heap, &other_value))
}
}
impl<T: Boxed> HashInHeap for List<T> {
fn hash_in_heap<H: Hasher>(&self, heap: &Heap, state: &mut H) {
match self.as_subtype() {
ListSubtype::Pair(pair) => pair.hash_in_heap(heap, state),
ListSubtype::Nil => NIL_INSTANCE.hash_in_heap(heap, state),
}
}
}
impl<T: Boxed> fmt::Debug for List<T> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
formatter.write_str("List(")?;
formatter.debug_list().entries(self.iter()).finish()?;
formatter.write_str(")")
}
}
pub struct ListIterator<T: Boxed> {
head: Gc<List<T>>,
}
impl<T: Boxed> Iterator for ListIterator<T> {
type Item = Gc<T>;
fn next(&mut self) -> Option<Gc<T>> {
// If we use `head` directly the borrow checker gets suspicious
let head = unsafe { &*(self.head.as_ptr()) };
match head.as_subtype() {
ListSubtype::Pair(pair) => {
self.head = pair.rest;
Some(pair.head)
}
ListSubtype::Nil => None,
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.head.len(), Some(self.head.len()))
}
}
impl<T: Boxed> ExactSizeIterator for ListIterator<T> {}
impl<T: Boxed> FusedIterator for ListIterator<T> {}
/// Empty list
#[repr(C, align(16))]
#[derive(Debug)]
pub struct Nil {
header: Header,
list_len: usize,
}
/// Static constant instance of [`Nil`]
#[export_name = "ARRET_NIL"]
pub static NIL_INSTANCE: Nil = Nil {
header: Header {
type_tag: TypeTag::Nil,
alloc_type: AllocType::Const,
},
list_len: 0,
};
impl Boxed for Nil {}
impl UniqueTagged for Nil {}
impl PartialEq for Nil {
fn eq(&self, _: &Nil) -> bool {
true
}
}
impl Hash for Nil {
fn hash<H: Hasher>(&self, state: &mut H) {
Self::TYPE_TAG.hash(state);
state.write_usize(&NIL_INSTANCE as *const _ as usize);
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::boxed::heap::Heap;
use crate::boxed::Int;
use std::mem;
#[test]
fn sizes() {
assert_eq!(16, mem::size_of::<Nil>());
assert_eq!(16, mem::size_of::<List<Any>>());
assert_eq!(32, mem::size_of::<Pair<Any>>());
}
#[test]
fn equality() {
use crate::boxed::Int;
let mut heap = Heap::empty();
let forward_list1 = List::from_values(&mut heap, [1, 2, 3].iter().cloned(), Int::new);
let forward_list2 = List::from_values(&mut heap, [1, 2, 3].iter().cloned(), Int::new);
let reverse_list = List::from_values(&mut heap, [3, 2, 1].iter().cloned(), Int::new);
assert!(!forward_list1.eq_in_heap(&heap, &reverse_list));
assert!(forward_list1.eq_in_heap(&heap, &forward_list2));
}
#[test]
fn fmt_debug() {
let mut heap = Heap::empty();
let forward_list = List::from_values(&mut heap, [1, 2, 3].iter().cloned(), Int::new);
assert_eq!(
"List([Int(1), Int(2), Int(3)])",
format!("{:?}", forward_list)
);
}
#[test]
fn construct_and_iter() {
let mut heap = Heap::empty();
let boxed_list = List::from_values(&mut heap, [1, 2, 3].iter().cloned(), Int::new);
let mut boxed_list_iter = boxed_list.iter();
assert_eq!(3, boxed_list_iter.len());
for expected_num in &[1, 2, 3] {
if let Some(boxed_int) = boxed_list_iter.next() {
assert_eq!(*expected_num, boxed_int.value());
} else {
panic!("Iterator unexpectedly ended");
}
}
assert_eq!(0, boxed_list_iter.len());
assert!(!boxed_list_iter.next().is_some());
}
}
| 27.146277
| 100
| 0.554717
|
14aace9c0677336726250eb3704fccb6056c001f
| 258
|
ts
|
TypeScript
|
clients/node/client-mturk-node/model/shapes/_NotifyWorkersFailureStatusList.ts
|
pravgupt/aws-sdk-js-v3
|
1fd0fab5da141d934eb98624d6c23b347806bb47
|
[
"Apache-2.0"
] | null | null | null |
clients/node/client-mturk-node/model/shapes/_NotifyWorkersFailureStatusList.ts
|
pravgupt/aws-sdk-js-v3
|
1fd0fab5da141d934eb98624d6c23b347806bb47
|
[
"Apache-2.0"
] | null | null | null |
clients/node/client-mturk-node/model/shapes/_NotifyWorkersFailureStatusList.ts
|
pravgupt/aws-sdk-js-v3
|
1fd0fab5da141d934eb98624d6c23b347806bb47
|
[
"Apache-2.0"
] | null | null | null |
import { List as _List_ } from "@aws-sdk/types";
import { _NotifyWorkersFailureStatus } from "./_NotifyWorkersFailureStatus";
export const _NotifyWorkersFailureStatusList: _List_ = {
type: "list",
member: {
shape: _NotifyWorkersFailureStatus
}
};
| 25.8
| 76
| 0.74031
|
f5bdf2652c5fa29e7965be984f358ab44668bcaa
| 118
|
css
|
CSS
|
assets/tailwind.css
|
WendahNyiawung/Neka
|
6c67392973db62dd36ceb896c58872b000c2191b
|
[
"MIT"
] | null | null | null |
assets/tailwind.css
|
WendahNyiawung/Neka
|
6c67392973db62dd36ceb896c58872b000c2191b
|
[
"MIT"
] | null | null | null |
assets/tailwind.css
|
WendahNyiawung/Neka
|
6c67392973db62dd36ceb896c58872b000c2191b
|
[
"MIT"
] | null | null | null |
@tailwind base;
@tailwind components;
@tailwind utilities;
.font-primary{
font-family: 'Bebas Neue', cursive;
}
| 16.857143
| 41
| 0.711864
|
3887c7f3eb45e4fb3eee27f59f38300866cd4fe8
| 10,687
|
php
|
PHP
|
application/views/sales_manual_approve/details.php
|
marajmmc/beeztola_2018_19
|
f6014751d16fc4bab03ab4f332bb7bb439f66177
|
[
"MIT"
] | null | null | null |
application/views/sales_manual_approve/details.php
|
marajmmc/beeztola_2018_19
|
f6014751d16fc4bab03ab4f332bb7bb439f66177
|
[
"MIT"
] | null | null | null |
application/views/sales_manual_approve/details.php
|
marajmmc/beeztola_2018_19
|
f6014751d16fc4bab03ab4f332bb7bb439f66177
|
[
"MIT"
] | null | null | null |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$CI = & get_instance();
$action_buttons=array();
$action_buttons[]=array(
'label'=>$CI->lang->line("ACTION_BACK").' to Pending List',
'href'=>site_url($CI->controller_url)
);
$action_buttons[]=array(
'label'=>$CI->lang->line("ACTION_BACK").' to All list',
'href'=>site_url($CI->controller_url.'/index/list_all')
);
$CI->load->view('action_buttons',array('action_buttons'=>$action_buttons));
?>
<div class="row widget hidden-print">
<div class="widget-header">
<div class="title">
<?php echo $title; ?>
</div>
<div class="clearfix"></div>
</div>
<table class="table table-bordered table-responsive system_table_details_view">
<tbody>
<tr>
<td class="widget-header header_caption"><label class="control-label pull-right"><?php echo $CI->lang->line('LABEL_OUTLET_NAME');?></label></td>
<td class=""><label class="control-label"><?php echo $item['outlet_name'];?></td>
<td class="widget-header header_caption"><label class="control-label pull-right"><?php echo $CI->lang->line('LABEL_CUSTOMER_NAME');?></label></td>
<td class=""><label class="control-label"><?php echo $item['farmer_name'];?></label></td>
</tr>
<tr>
<td class="widget-header header_caption"><label class="control-label pull-right">Manual Sale Id</label></td>
<td class=""><label class="control-label"><?php echo ($item['id']);?></td>
<td class="widget-header header_caption"><label class="control-label pull-right"><?php echo $CI->lang->line('LABEL_MOBILE_NO');?></label></td>
<td class=""><label class="control-label"><?php echo $item['mobile_no'];?></label></td>
</tr>
<tr>
<td class="widget-header header_caption"><label class="control-label pull-right"><?php echo $CI->lang->line('LABEL_DATE_SALE');?></label></td>
<td class=""><label class="control-label"><?php echo System_helper::display_date_time($item['date_sale']);?></td>
<td class="widget-header header_caption"><label class="control-label pull-right"><?php echo $CI->lang->line('LABEL_DISCOUNT');?></label></td>
<td class=""><label class="control-label"><?php echo $item['discount_self_percentage'];?>%</label></td>
</tr>
<tr>
<td class="widget-header header_caption"><label class="control-label pull-right">Manual Sale Approval Status</label></td>
<td class=""><label class="control-label"><?php echo $item['status_approve'];?></td>
</tr>
<tr>
<td class="widget-header header_caption"><label class="control-label pull-right">Manual Sale Requested Time</label></td>
<td class=""><label class="control-label"><?php echo System_helper::display_date_time($item['date_manual_requested']);?></td>
<td class="widget-header header_caption"><label class="control-label pull-right">Manual Sale Requested By</label></td>
<td class=""><label class="control-label"><?php echo $users[$item['user_manual_requested']]['name'];?></label></td>
</tr>
<tr>
<td class="widget-header header_caption"><label class="control-label pull-right">Manual Sale Request Remarks</label></td>
<td class="" colspan="3"><label class="control-label"><?php echo nl2br($item['remarks_manual_requested']);?></td>
</tr>
<?php
if($item['status_approve']!=$CI->config->item('system_status_pending'))
{
?>
<tr>
<td class="widget-header header_caption"><label class="control-label pull-right">Sale Approved/Rejected Time</label></td>
<td class=""><label class="control-label"><?php echo System_helper::display_date_time($item['date_manual_approved']);?></td>
<td class="widget-header header_caption"><label class="control-label pull-right">Approved/Rejected By</label></td>
<td class=""><label class="control-label"><?php echo $users[$item['user_manual_approved']]['name'];?></label></td>
</tr>
<tr>
<td class="widget-header header_caption"><label class="control-label pull-right">Approval/Reject Remarks</label></td>
<td class="" colspan="3"><label class="control-label"><?php echo nl2br($item['remarks_manual_approved']);?></td>
</tr>
<?php
}
?>
<?php
if($item['status_approve']==$CI->config->item('system_status_approved'))
{
?>
<tr>
<td class="widget-header header_caption"><label class="control-label pull-right">Invoice No:</label></td>
<td class=""><label class="control-label"><?php echo Barcode_helper::get_barcode_sales($item['sale_id']);?></td>
<td class="widget-header header_caption"><label class="control-label pull-right">Outlet For Commission</label></td>
<td class=""><label class="control-label"><?php echo $item['outlet_name_commission'];?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<div class="widget-header">
<div class="title">
Items
</div>
<div class="clearfix"></div>
</div>
<div style="overflow-x: auto;" class="row show-grid">
<table class="table table-bordered">
<thead>
<tr>
<th style="min-width: 100px;"><?php echo $CI->lang->line('LABEL_CROP_NAME'); ?></th>
<th style="min-width: 100px;"><?php echo $CI->lang->line('LABEL_CROP_TYPE_NAME'); ?></th>
<th style="min-width: 100px;"><?php echo $CI->lang->line('LABEL_VARIETY_NAME'); ?></th>
<th style="min-width: 100px;"><?php echo $CI->lang->line('LABEL_PACK_SIZE_NAME'); ?></th>
<th style="min-width: 100px;"><?php echo $CI->lang->line('LABEL_PRICE_PER_PACK'); ?></th>
<th style="min-width: 100px;"><?php echo $CI->lang->line('LABEL_QUANTITY'); ?>(Packets)</th>
<th style="min-width: 100px;"><?php echo $CI->lang->line('LABEL_WEIGHT_KG'); ?></th>
<th style="min-width: 100px;">Price</th>
<th style="min-width: 100px;">Variety Discount%</th>
<th style="min-width: 100px;">Variety Discount</th>
<th style="min-width: 100px;">Actual Price</th>
</tr>
</thead>
<tbody>
<?php
$total_quantity=0;
$total_weight_kg=0;
foreach($items as $row)
{
$total_quantity+=$row['quantity'];
$total_weight_kg+=($row['quantity']*$row['pack_size']);
?>
<tr>
<td><label><?php echo $row['crop_name'];?></label></td>
<td><label><?php echo $row['crop_type_name'];?></label></td>
<td><label><?php echo $row['variety_name'];?></label></td>
<td class="text-right"><label><?php echo $row['pack_size'];?></label></td>
<td class="text-right"><label><?php echo number_format($row['price_unit_pack'],2); ?></label></td>
<td class="text-right"><label><?php echo $row['quantity']; ?></label></td>
<td class="text-right" ><label><?php echo number_format($row['quantity']*$row['pack_size']/1000,3,'.','');?></label>
<td class="text-right"><label><?php echo number_format($row['amount_total'],2);?></label>
<td class="text-right"><label><?php echo number_format($row['discount_percentage_variety'],2);?></label>
<td class="text-right"><label><?php echo number_format($row['amount_discount_variety'],2);?></label>
<td class="text-right"><label><?php echo number_format($row['amount_payable_actual'],2);?></label>
</tr>
<?php
}
?>
</tbody>
<tfoot>
<tr>
<td colspan="4"> </td>
<td><label><?php echo $CI->lang->line('LABEL_TOTAL'); ?></label></td>
<td class="text-right"><label><?php echo $total_quantity; ?></label></td>
<td class="text-right"><label><?php echo number_format($total_weight_kg/1000,3,'.','');?></label></td>
<td class="text-right"><label><?php echo number_format($item['amount_total'],2); ?></label></td>
<td> </td>
<td class="text-right"><label><?php echo number_format($item['amount_discount_variety'],2); ?></label></td>
<td class="text-right"><label><?php echo number_format($item['amount_total']-$item['amount_discount_variety'],2); ?></label></td>
</tr>
<tr>
<td colspan="9"> </td>
<td><label><?php echo $CI->lang->line('LABEL_DISCOUNT'); ?></label></td>
<td class="text-right"><label><?php echo number_format($item['amount_discount_self'],2); ?></label></td>
</tr>
<tr>
<td colspan="9"> </td>
<td><label>Payable</label></td>
<td class="text-right"><label><?php echo number_format($item['amount_payable'],2); ?></label></td>
</tr>
<tr>
<td colspan="9"> </td>
<td><label>Payable(rounded)</label></td>
<td class="text-right"><label><?php echo number_format($item['amount_payable_actual'],2); ?></label></td>
</tr>
<tr>
<td colspan="9"> </td>
<td><label>Paid</label></td>
<td class="text-right"><label><?php echo number_format($item['amount_cash'],2); ?></label></td>
</tr>
<tr>
<td colspan="9"> </td>
<td><label>Change</label></td>
<td class="text-right"><label><?php echo number_format($item['amount_cash']-$item['amount_payable_actual'],2); ?></label></td>
</tr>
</tfoot>
</table>
</div>
</div>
| 60.039326
| 163
| 0.525311
|
1c5a39c0a81735a737e640c6a7956b9e9bb9e7da
| 4,791
|
dart
|
Dart
|
lib/ui/post/add_tag_page.dart
|
yeshu-cn/MockApp
|
7e72794c2c57477c0d07e45091699b74d6ab1503
|
[
"MIT"
] | 9
|
2022-01-17T02:29:57.000Z
|
2022-02-08T07:03:46.000Z
|
lib/ui/post/add_tag_page.dart
|
yeshu-cn/MockApp
|
7e72794c2c57477c0d07e45091699b74d6ab1503
|
[
"MIT"
] | null | null | null |
lib/ui/post/add_tag_page.dart
|
yeshu-cn/MockApp
|
7e72794c2c57477c0d07e45091699b74d6ab1503
|
[
"MIT"
] | 4
|
2022-01-23T07:58:27.000Z
|
2022-02-08T07:03:41.000Z
|
import 'package:flutter/material.dart';
import 'package:lushan/di/usecase_locator.dart';
class AddTagPage extends StatefulWidget {
const AddTagPage({Key? key}) : super(key: key);
@override
_AddTagPageState createState() => _AddTagPageState();
}
class _AddTagPageState extends State<AddTagPage> {
List<String> _tags = [];
List<String> _selectedTags = [];
TextEditingController _editingController = TextEditingController();
@override
void initState() {
_loadTags();
_editingController.addListener(() {setState(() {
});});
super.initState();
}
void _loadTags() async {
_tags = await UseCaseLocator.getPostTagListUseCase.execute();
setState(() {});
}
@override
void dispose() {
_editingController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('添加标签'),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop(_selectedTags);
},
child: Text(
'完成',
style: TextStyle(color: Colors.white),
))
],
),
body: Padding(
padding: const EdgeInsets.all(14.0),
child: ListView(
children: [
Container(
padding: EdgeInsets.all(10),
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 5,
children: _selectedTags
.map((tag) => InputChip(
backgroundColor: Colors.blue,
label: Text(tag),
onDeleted: () {
_deleteTag(tag);
},
))
.toList(),
),
Row(
children: [
Expanded(
child: Stack(children: [
TextField(
decoration:
new InputDecoration(hintText: '请输入自定义标签,最多10个字符'),
maxLength: 10,
controller: _editingController,
),
if (_editingController.text.length > 0)
Positioned(
right: 0,
child: TextButton(
onPressed: () {
_addCustomTag(_editingController.text);
},
child: Text('添加')))
])),
],
)
],
),
),
SizedBox(
height: 12,
),
Container(
padding: EdgeInsets.all(10),
color: Colors.white,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'热门标签',
style: Theme.of(context).textTheme.subtitle1,
),
),
Wrap(
spacing: 5,
children: _tags
.map((tag) => InputChip(
backgroundColor: _getChipBackgroundColor(tag),
label: Text(tag),
selected: false,
onPressed: () {
_onTagPressed(tag);
},
))
.toList(),
)
],
),
)
],
),
),
);
}
void _onTagPressed(String tag) {
if (_selectedTags.contains(tag)) {
_selectedTags.remove(tag);
} else {
_selectedTags.add(tag);
}
setState(() {});
}
void _deleteTag(String tag) {
_selectedTags.remove(tag);
setState(() {});
}
void _addCustomTag(String tag) {
if (_selectedTags.contains(tag)) {
_editingController.clear();
return;
} else {
_selectedTags.add(tag);
_editingController.clear();
setState(() {});
}
}
Color _getChipBackgroundColor(String tag) {
if (_selectedTags.contains(tag)) {
return Colors.blue;
} else {
return Colors.grey[400]!;
}
}
}
| 28.349112
| 80
| 0.416823
|
83579d7ac452baee7b1c2de80a584d3b3db0dfa6
| 20,415
|
ts
|
TypeScript
|
src/Sequence.ts
|
DreadLordMikey/jlinq
|
17c1d293eae1ceb1fc10421df02442ad4b9b912c
|
[
"Unlicense"
] | 1
|
2020-09-22T19:03:43.000Z
|
2020-09-22T19:03:43.000Z
|
src/Sequence.ts
|
DreadLordMikey/jlinq
|
17c1d293eae1ceb1fc10421df02442ad4b9b912c
|
[
"Unlicense"
] | 47
|
2020-09-14T04:50:48.000Z
|
2020-09-24T01:15:07.000Z
|
src/Sequence.ts
|
DreadLordMikey/jlinq
|
17c1d293eae1ceb1fc10421df02442ad4b9b912c
|
[
"Unlicense"
] | null | null | null |
import { Predicate, Selector } from './interfaces';
//#region from
/**
* Gets a Sequence<T> from an array.
* @param arr {Array<T>} The source array. An exception is thrown if arr is
* null or undefined.
* @returns {Sequence<T>} A Sequence<T> containing a copy of the source array.
*/
export function from<T>(arr: Array<T>): Sequence<T> {
return new Sequence<T>(arr);
}
//#endregion
/** @template T */
export class Sequence<T> {
data: Array<T>;
//#region Constructor
constructor(data: Array<T>) {
if (typeof data === 'undefined' || data === null) {
throw 'Object construction exception: The argument to the constructor of Sequence<T> cannot be null or undefined.';
}
this.data = data;
}
//#endregion
//#region all
/**
* Determines whether all elements of a sequence satisfy a condition.
* @param predicate {Predicate<T>} A function to test each element for a
* condition.
* @returns {boolean} true if every element in the sequence satisfies the
* predicate condition; otherwise, false.
*/
all(predicate: Predicate<T>): boolean {
return this.data.every(predicate);
}
//#endregion
//#region any
/**
* Determines if any elements exist in the sequence.
* @returns true if any elements exist in the sequence; otherwise, false.
*/
any(): boolean;
/**
* Determines if any elements exist in the sequence that satisfy a condition.
* @param predicate A function to test each element for a condition.
*/
any(predicate?: Predicate<T>): boolean;
any(predicate?: unknown): boolean {
if (predicate) {
const index = this.data.findIndex(<Predicate<T>>predicate);
return index > -1;
} else {
return this.data.length > 0;
}
}
//#endregion
//#region append
/**
* Appends a value to the end of the sequence.
* @param element The value to append to the sequence.
* @returns {Sequence<T>} A new sequence that ends with element.
*/
append(element: T): Sequence<T> {
return new Sequence<T>(this.data.concat([element]));
}
//#endregion
//#region concat
/**
* Concatenates two sequences.
* @param {T[]} items The sequence to concatenate to this sequence.
* @returns {Sequence} A Sequence<T> An that contains the concatenated
* elements of the two input sequences.
*/
concat(items: T[]): Sequence<T>;
/**
* Concatenates two sequences.
* @param {Sequence<T>} items The sequence to concatenate to this sequence.
* @returns {Sequence} A Sequence<T> An that contains the concatenated
* elements of the two input sequences.
*/
concat(items: Sequence<T>): Sequence<T>;
concat(items: unknown): Sequence<T> {
if (Array.isArray(items)) {
return new Sequence<T>(this.data.concat(items));
} else {
return new Sequence<T>(this.data.concat((<Sequence<T>>items).toArray()));
}
}
//#endregion
//#region count
/**
* Returns the number of elements in a sequence.
* @returns The total number of elements in the sequence.
*/
count(): number;
/**
* Returns a number that represents how many elements in the sequence
* satisfy a condition.
* @param predicate {Predicate} A function to test each element for a condition.
* @returns {number} A number that represents how many elements in the sequence
* satisfy the condition in the predicate function.
*/
count(predicate: Predicate<T>): number;
count(predicate?: unknown): number {
if (predicate) {
return this.data.filter(<Predicate<T>>predicate).length;
} else {
return this.data.length;
}
}
//#endregion
//#region elementAt
/**
* Returns the element at a specified index in a sequence.
* @param {number} index The zero-based index of the element to retrieve.
* @returns The element at the specfied index in the sequence.
*/
elementAt(index: number): T {
if (index < 0 || index >= this.data.length) {
throw 'Index out of range exception: index is less than 0 or greater than or equal to the number of elements in the sequence.';
}
return this.data[index];
}
//#endregion
//#region elementAtOrDefault
/**
* Returns the element at a specified index in a sequence or a default value
* if the index is out of range.
* @param {T} defaultValue The value to return if there are no elements in
* the sequence or if the specified element does not exist.
* @param {number} index The zero-based index of the element to retrieve.
* @returns defaultValue if the index is outside the bounds of the source
* sequence; otherwise, the element at the specified position in the source
* sequence.
*/
elementAtOrDefault(defaultValue: T, index: number): T {
if (index < 0 || index >= this.data.length) {
return defaultValue;
}
return this.data[index];
}
//#endregion
//#region empty
/**
* Returns an empty Sequence<T> that has the specified type argument.
* @param {TReturn} TReturn The type to assign to the type parameter of the
* returned generic Sequence<T>
* @returns An empty Sequence whose type argument is `TReturn`.
* @template TReturn
*/
static empty<TReturn>(): Sequence<TReturn> {
return from(new Array<TReturn>());
}
//#endregion
//#region first
/**
* Gets the first item in a sequence.
* @returns {T} The first element in the sequence.
* @throws An exception is thrown if the sequence is empty.
*/
first(): T;
/**
* Gets the first item in the sequence that satisfies a condition.
* @param {Predicate} predicate A function to test for a condition.
* @returns {T} The first element in the sequence that satisfies the
* predicate condition.
* @throws An exception is thrown if the sequence is empty or if no
* elements in the sequence satisfy the predicate condition.
*/
first(predicate: Predicate<T>): T;
first(predicate?: unknown): T {
if (this.data.length === 0) {
throw 'Invalid operation: sequence is empty.';
}
if (!predicate) {
return this.data[0];
} else {
const index: number = this.data.findIndex((e, i) =>
(<Predicate<T>>predicate)(e, i),
);
if (index === -1) {
throw 'Invalid operation: no elements satisfy predicate condition.';
}
return this.data[index];
}
}
//#endregion
//#region firstOrDefault
/**
* Gets the first element in the sequence, or a default value if there are no
* elements in the sequence.
* @param {T} defaultValue The value to return if there are no elements in the
* sequence.
* @returns {T} The first element in the sequence if one exists; otherwise,
* `defaultValue` is returned.
*/
firstOrDefault(defaultValue: T): T;
/**
* Gets the first element in the sequence that satisfies a condition, or a
* default value if no elements satisfy the condition.
* @param {T} defaultValue The value to return if either there are no elements
* in the sequence or there are no elements in the sequence that satisfy the
* predicate condition.
* @param {Predicate} predicate A function to test each element for a condition.
* @returns The first element in the sequence that satisfies the predicate
* condition; otherwise, `defaultValue` is returned.
*/
firstOrDefault(defaultValue: T, predicate: Predicate<T>): T;
firstOrDefault(defaultValue: T, predicate?: unknown): T {
if (this.data.length === 0) {
return defaultValue;
}
if (!predicate) {
return this.data[0];
} else {
const index = this.data.findIndex((e, i) =>
(<Predicate<T>>predicate)(e, i),
);
if (index === -1) {
return defaultValue;
} else {
return this.data[index];
}
}
}
//#endregion
//#region last
/**
* Gets the last element from a sequence.
* @throws An exception is thrown if the sequence is empty.
* @returns The last element in the sequence.
*/
last(): T;
/**
* Gets the last element in a sequence that satisfies the provided predicate
* condition.
* @param {Predicate} predicate A function to test each element for a
* condition.
* @throws An exception is thrown if:
* - The sequence is empty OR
* - No elements in the sequence satisfy the predicate condition.
* @returns {T} The last element in the sequence that satisfies the predicate
* condition.
*/
last(predicate: Predicate<T>): T;
last(predicate?: unknown): T {
if (this.data.length === 0) {
throw 'Invalid operation exception: sequence is empty.';
}
if (!predicate) {
return this.data[this.data.length - 1];
} else {
for (let i = this.data.length - 1; i >= 0; i--) {
const e = this.data[i];
if ((<Predicate<T>>predicate)(e, i)) {
return e;
}
}
throw 'Invalid operation exception: no elements satisfy predicate condition.';
}
}
//#endregion
//#region lastOrDefault
/**
* Gets the last element from a sequence, or a default value if the sequence
* contains no elements.
* @param {T} defaultValue The value to return if the sequence is empty.
* @returns {T} The last element in the sequence, or `defaultValue` if the sequence contains no elements.
*/
lastOrDefault(defaultValue: T): T;
/** */
lastOrDefault(defaultValue: T, predicate: Predicate<T>): T;
lastOrDefault(defaultValue: T, predicate?: unknown): T {
if (this.data.length === 0) {
return defaultValue;
}
if (!predicate) {
return this.data[this.data.length - 1];
} else {
for (let i = this.data.length - 1; i >= 0; i--) {
const e = this.data[i];
if ((<Predicate<T>>predicate)(e, i)) {
return e;
}
}
return defaultValue;
}
}
//#endregion
//#region range
/**
* Generates a sequence of integral numbers within a specified range.
* @param start The value of the first integer in the sequence.
* @param count The number of sequential integers to generate.
* @returns An Sequence<T> that contains a range of sequential integral
* numbers.
*/
static range(start: number, count: number): Sequence<number> {
const arr = new Array<number>(count);
let value = start;
for (let i = 0; i < count; i++) {
arr[i] = value;
value++;
}
return new Sequence<number>(arr);
}
//#endregion
//#region select
/**
* Projects each element of a sequence into a new form.
* @param selector {Selector} A transform function to apply to each source
* element; the second parameter of the function represents the index of the
* source element.
* @returns {Sequence<TReturn>} A new sequence containing the transformed
* data.
*/
select<TReturn>(selector: Selector<T, TReturn>): Sequence<TReturn> {
const data: Array<TReturn> = this.data.map(selector);
return from(data);
}
//#endregion
//#region single
/**
* Gets the single element from this sequence.
*
* @throws An exception is thrown if either the sequence is empty or the
* sequence contains more than one element.
* @type T
* @returns T The single element in this sequence.
*/
single(): T;
/**
* Gets the single element from this sequence that satisfies the provided
* predicate condition.
*
* @param Predicate<T> predicate A function to test each element for a
* condition.
*
* @throws An exception is thrown if either the sequence is empty or if
* multiple elements satisfy the provided predicate condition.
*
* @type T
* @returns T The single element in this sequence that satisfies the
* provided predicate condition.
*/
single(predicate: Predicate<T>): T;
single(predicate?: unknown): T {
if (this.data.length === 0) {
throw 'Invalid operation exception: sequence is empty.';
}
if (!predicate) {
if (this.data.length > 1) {
throw 'Invalid operation exception: sequence contains multiple elements.';
} else {
return this.data[0];
}
} else {
const items = this.data.filter((e, i) => (<Predicate<T>>predicate)(e, i));
if (items.length === 0) {
throw 'Invalid operation exception: no items match predicate condition.';
} else if (items.length > 1) {
throw 'Invalid operation exception: multiple items match predicate condition.';
} else {
return items[0];
}
}
}
//#endregion
//#region singleOrDefault
/**
* Gets the sole element from this sequence, or a default value if no such element
* exists.
*
* @param T defaultValue The value to return if the sequence is empty.
* @throws An exception is thrown if the sequence contains multiple items.
* @returns The single element from this sequence. If the sequence is empty,
* `defaultValue` is returned.
*/
singleOrDefault(defaultValue: T): T;
/**
* Gets the sole element from this sequence that satisfies the provided predicate
* condition, or a default value if no such element exists.
*
* @param T defaultValue The value to return if either the sequence is empty or if
* no elements in the sequence satisfy the predicate condition.
* @param Predicate predicate A function test each element in the sequence for a
* condition.
* @throws An exception is thrown if multiple elements in the sequence satisfy the
* predicate condition.
* @returns The sole element in the sequence that satisfies the predicate condition.
* If no elements satisfy the predicate condition, `defaultValue` is returned.
*/
singleOrDefault(defaultValue: T, predicate: Predicate<T>): T;
singleOrDefault(defaultValue: T, predicate?: unknown): T {
if (!predicate) {
if (this.data.length === 1) {
return this.data[0];
} else if (this.data.length === 0) {
return defaultValue;
} else {
throw 'Invalid operation exception: sequence is empty.';
}
} else {
const matches = this.data.filter((e, i) =>
(<Predicate<T>>predicate)(e, i),
);
if (matches.length === 1) {
return matches[0];
} else if (matches.length === 0) {
return defaultValue;
} else {
throw 'Invalid oepration exception: multiple elements in sequence satisfy predicate condition.';
}
}
}
//#endregion
//#region skip
/**
* Bypasses a specified number of elements in a sequence and then returns the remaining elements.
* @param {number} count The number of elements to skip.
* @returns A Sequence<T> that contains the elements that occur after the specified index
* in this sequence.
* @remarks If count is less than or equal to zero, all elements in the source sequence are
* returned. If count is greater than the number of elements in the sequence, an empty sequence
* is returned.
*/
skip(count: number): Sequence<T> {
// If count is less than or equal to zero, return all elements.
if (count <= 0) {
return new Sequence<T>(this.data);
}
// If count is greater than the number of items in the array,
// return an empty sequence.
if (count > this.data.length) {
return new Sequence<T>([]);
}
// Otherwise, get all items starting at the index specified by count to the
// end of the array.
return new Sequence<T>(this.data.splice(count));
}
//#endregion
//#region skipWhile
/**
* Bypasses elements in a sequence as long as a specified condition is true
* and then returns the remaining elements.
* @param {Predicate} predicate A function to test each element for a
* condition.
* @returns {Sequence} A sequence that contains the elements from the input
* sequence starting at the first element in the linear series that does not
* pass the test specified by `predicate`.
* @remarks This method tests each element of the source sequence by using
* `predicate` and skips the element if the result is `true`. After the
* predicate returns `false` for an element, that element and the remaining
* elements in `source` are yielded, and there are no more invocations of
* `predicate`.
*
* If `predicate` returns `true` for all elements in a sequence, an empty
* sequence is returned.
*/
skipWhile(predicate: Predicate<T>): Sequence<T> {
if (!predicate) {
throw 'Argument null or undefined: predicate';
}
const firstNonMatchingIndex = this.data.findIndex(
(v: T, i: number) => !predicate(v, i),
);
if (firstNonMatchingIndex === -1) {
return new Sequence<T>([]);
}
return new Sequence<T>(this.data.slice(firstNonMatchingIndex));
}
//#endregion
//#region take
/**
* Returns a specified number of contiguous elements from the start of a sequence.
* @param {number} count The number of elements to return.
* @returns {Sequence} A Sequence that contains the specified number of elements
* from the start of this sequence.
* @description If count is less than zero, take returns an empty sequence. If count
* is greater than the number of items in the sequence, take returns all items in
* the sequence. Otherwise, take returns the specfied number of items from the
* sequence, starting at index 0.
*/
take(count: number): Sequence<T> {
// If the count is less than 0, return an empty sequence.
if (count < 0) return new Sequence<T>(new Array<T>());
// If the count is greater than the number of items in the sequence,
// return the entire sequence.
if (count > this.data.length) return new Sequence<T>(this.data);
// If the count is greater than zero, and less than the number of
// items in the sequence, return the specified number of items from
// the sequence, beginning at index 0.
return new Sequence<T>(this.data.slice(0, count));
}
//#endregion
//#region takeWhile
/**
* Returns elements from a sequence as long as a specified condition is true,
* and then skips the remaining elements.
* @param {Predicate} predicate A function to test each element for a
* condition.
* @returns {Sequence} A sequence that contains the elements from this
* sequence that occur before the element at which the test no longer
* passes.
* @remarks `takeWhile` uses `Array.prototype.findIndex` to retrieve the
* index of the first element in the sequence that does not satisfy the
* predicate condition.
*
* If no elements satisfy this condition, the entire sequence is returned.
* Otherwise, all elements up to and excluding that element are returned.
* The order of the elements in the sequence is preserved.
* @throws An exception is thrown if `predicate` is `null` or `undefined`.
*/
takeWhile(predicate: Predicate<T>): Sequence<T> {
if (!predicate) {
throw 'Argument null or undefined: predicate';
}
const index = this.data.findIndex((e, i) => !predicate(e, i));
return this.take(index);
}
//#endregion
//#region toArray
/**
* Copies the elements of the List<T> to a new array.
* @returns An array containing copies of the elements of the Sequence<T>.
*/
toArray(): Array<T> {
return [...this.data];
}
//#endregion
//#region toString
/**
* Returns a string that represents the current object.
* @returns A string that represents the current object.
*/
toString(): string {
return JSON.stringify(this.data, null, 2);
}
//#endregion
//#region where
/**
* Filters a sequence of values based on a predicate.
* @param predicate A function to test each source element for a condition.
*
* The first argument to the predicate is the current item in the sequence.
*
* The second argument to the predicate is the index of the item in the
* sequence.
*
* @returns A Sequence<T> containing the rows that satisfy the predicate
* condition.
*/
where(predicate: Predicate<T>): Sequence<T> {
if (predicate === null || typeof predicate === 'undefined') {
throw 'Object null or undefined: predicate is required when calling "where".';
}
const items = this.data.filter(predicate);
return new Sequence([...items]);
}
//#endregion
//#region getDefaultConstructionOptions
private getDefaultConstructionOptions() {
return {
directStore: false,
};
}
//#endregion
}
| 33.688119
| 133
| 0.658927
|
148af1bec74f2d3ba6b196487ec2f685df293e54
| 38
|
ts
|
TypeScript
|
src/components/OverlayManager/Wishlist/index.ts
|
sebasalvarado/ecommerce-storefront
|
9a7d1df97b74baf3c7933015c1d5af99fc5af04c
|
[
"BSD-3-Clause"
] | 7
|
2021-05-03T01:36:32.000Z
|
2022-02-12T05:02:34.000Z
|
client/src/components/core/Wishlist/index.ts
|
mhmdjaw/PChunt
|
2cb2d9903d48d80a8f318356a4a508a2717c4335
|
[
"MIT"
] | 1
|
2019-07-26T02:40:35.000Z
|
2019-07-26T02:40:35.000Z
|
client/src/components/core/Wishlist/index.ts
|
mhmdjaw/PChunt
|
2cb2d9903d48d80a8f318356a4a508a2717c4335
|
[
"MIT"
] | 2
|
2021-07-05T07:20:33.000Z
|
2021-07-06T05:51:49.000Z
|
export { default } from "./Wishlist";
| 19
| 37
| 0.657895
|
a64f13fd9eb8207f7678ec2586e73547d2ba417c
| 74
|
rb
|
Ruby
|
app/controllers/landing_page_controller.rb
|
oscarmolivera/adr-latam
|
e0936aa523f57ecac84cda0c1911679a557fbb51
|
[
"MIT"
] | null | null | null |
app/controllers/landing_page_controller.rb
|
oscarmolivera/adr-latam
|
e0936aa523f57ecac84cda0c1911679a557fbb51
|
[
"MIT"
] | 4
|
2021-03-10T14:20:13.000Z
|
2022-03-31T01:05:20.000Z
|
app/controllers/landing_page_controller.rb
|
oscarmolivera/adr-latam
|
e0936aa523f57ecac84cda0c1911679a557fbb51
|
[
"MIT"
] | null | null | null |
class LandingPageController < ApplicationController
def Index
end
end
| 14.8
| 51
| 0.824324
|
e236e271b7644faac967016abd701e16a058a984
| 8,603
|
js
|
JavaScript
|
src/components/MarketFooter.js
|
davidbanu/dApp
|
69f5dea56dda7bd3e53f57fcb3d953e48011bdae
|
[
"Apache-2.0"
] | 1
|
2021-04-23T21:50:20.000Z
|
2021-04-23T21:50:20.000Z
|
src/components/MarketFooter.js
|
davidbanu/dApp
|
69f5dea56dda7bd3e53f57fcb3d953e48011bdae
|
[
"Apache-2.0"
] | null | null | null |
src/components/MarketFooter.js
|
davidbanu/dApp
|
69f5dea56dda7bd3e53f57fcb3d953e48011bdae
|
[
"Apache-2.0"
] | 1
|
2020-09-16T06:10:56.000Z
|
2020-09-16T06:10:56.000Z
|
import React, { Component } from 'react';
import { Button, Col, Layout, Row } from 'antd';
import { Link } from 'react-router-dom';
// Styles
import '../less/MarketFooter.less';
import logoImg from '../img/footer/logo_light.svg';
import telegram from '../img/footer/telegram.svg';
import twitter from '../img/footer/twitter.svg';
import medium from '../img/footer/medium.svg';
import github from '../img/footer/github.svg';
import youtube from '../img/footer/youtube.svg';
const { Footer } = Layout;
class MarketFooter extends Component {
render() {
return (
<Footer
style={{ color: '#fff', backgroundColor: '#11161c', padding: '0px' }}
>
<div className="footer-wrapper">
<Row type="flex" align="top">
<Col
xs={24}
sm={24}
md={12}
lg={12}
xl={12}
style={{ marginBottom: '60px' }}
className="footer-content"
>
<img alt="Bitcoin derivatives and shorting" src={logoImg} />
<p className="footer-description">
MARKET Protocol provides the open source building blocks
powering decentralized derivatives trading and exchanges on the
Ethereum blockchain.
</p>
<div style={{ marginTop: '35px' }}>
<Link to="https://t.me/Market_Protocol_Chat" target="_blank">
<Button className="icon-button" size="small" type="primary">
<img
alt="crypto derivatives telegram"
src={telegram}
width="80%"
/>
</Button>
</Link>
<Link to="https://twitter.com/MarketProtocol/" target="_blank">
<Button className="icon-button" size="small" type="primary">
<img
alt="decentralized exchange twitter"
src={twitter}
width="80%"
/>
</Button>
</Link>
<Link to="https://medium.com/market-protocol" target="_blank">
<Button className="icon-button" size="small" type="primary">
<img
alt="ethereum derivatives medium"
src={medium}
width="80%"
/>
</Button>
</Link>
<Link to="https://github.com/MARKETProtocol/" target="_blank">
<Button className="icon-button" size="small" type="primary">
<img
alt="open source ethereum dApp"
src={github}
width="80%"
/>
</Button>
</Link>
<Link
to="https://www.youtube.com/c/MARKETProtocol"
target="_blank"
>
<Button className="icon-button" size="small" type="primary">
<img
alt="trading any assets youtube"
src={youtube}
width="80%"
/>
</Button>
</Link>
</div>
<p className="copyright-text">
<span style={{ marginTop: '35px', display: 'block' }}>
©2018 Market Protocol, LLC
</span>
</p>
</Col>
<Col xs={12} sm={8} md={4} lg={4} xl={4}>
<h3 className="footer-link-category">Documentation</h3>
<p className="footer-link">
<Link
to="https://marketprotocol.io/assets/MARKET_Protocol-Whitepaper.pdf"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Whitepaper
</Link>
</p>
<p className="footer-link">
<Link
to="https://marketprotocol.io/assets/MARKET_Protocol-Summary.pdf"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Summary
</Link>
</p>
<p className="footer-link">
<Link
to="https://github.com/MARKETProtocol"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Github
</Link>
</p>
<p className="footer-link">
<Link
to="https://docs.marketprotocol.io/"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Technical Docs
</Link>
</p>
<p className="footer-link">
<Link
to="https://docs.marketprotocol.io/#faq-general"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
FAQ
</Link>
</p>
</Col>
<Col xs={12} sm={8} md={4} lg={4} xl={4}>
<h3 className="footer-link-category">Community</h3>
<p className="footer-link">
<Link
to="https://t.me/Market_Protocol_Chat"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Telegram
</Link>
</p>
<p className="footer-link">
<Link
to="https://twitter.com/MarketProtocol"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Twitter
</Link>
</p>
<p className="footer-link">
<Link
to="https://medium.com/market-protocol"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Medium
</Link>
</p>
<p className="footer-link">
<Link
to="https://discordapp.com/invite/qN8MCbq"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Discord
</Link>
</p>
<p className="footer-link">
<Link
to="https://marketprotocol.io/press"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Press
</Link>
</p>
</Col>
<Col xs={8} sm={8} md={4} lg={4} xl={4}>
<h3 className="footer-link-category">Organization</h3>
<p className="footer-link">
<Link
to="https://marketprotocol.io/team"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Team
</Link>
</p>
<p className="footer-link">
<Link
to="https://marketprotocol.io/partners"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Partners
</Link>
</p>
<p className="footer-link">
<Link
to="https://marketprotocol.io/jobs"
target="_blank"
style={{ color: 'inherit', textDecoration: 'none' }}
>
Jobs (We're hiring!)
</Link>
</p>
<p>4450 Arapahoe Ave, Suite 100 Boulder, CO 80303</p>
<p className="footer-link">
<Link
to="mailto:info@marketprotocol.io"
style={{ color: 'inherit', textDecoration: 'none' }}
>
info@marketprotocol.io
</Link>
</p>
</Col>
</Row>
</div>
</Footer>
);
}
}
export default MarketFooter;
| 35.995816
| 86
| 0.409392
|
ff88d73f36bfe9b1bf2bad88996ec12cd8789081
| 1,611
|
py
|
Python
|
day-7/solution.py
|
DallogFheir/aoc-2020
|
089bd45d5fbdf98b9729a23f3a142ca3b792567c
|
[
"MIT"
] | null | null | null |
day-7/solution.py
|
DallogFheir/aoc-2020
|
089bd45d5fbdf98b9729a23f3a142ca3b792567c
|
[
"MIT"
] | null | null | null |
day-7/solution.py
|
DallogFheir/aoc-2020
|
089bd45d5fbdf98b9729a23f3a142ca3b792567c
|
[
"MIT"
] | null | null | null |
# Advent of Code 2020
# Day 7
import functools
import re
from pathlib import Path
# input
container_template = re.compile(r"(.*?) bags contain")
content_template = re.compile(r" (\d+) (.*?) bag(?:s)?[,.]")
def parse_bag_rules(fh):
rules_dict = {}
for line in fh:
container = re.match(container_template, line).group(1)
contents = re.findall(content_template, line)
rules_dict[container] = [(int(num), bag) for num, bag in contents]
return rules_dict
with open(Path(__file__).parent / "input.txt") as f:
inp = parse_bag_rules(f)
inp_bags_only = {k: [tup[1] for tup in v] for k, v in inp.items()}
# part 1
# Find how many bags can contain a shiny gold bag.
# check if bag can contain
@functools.lru_cache
def check_if_bag_can_contain(container, target):
if target in inp_bags_only[container]:
return True
for bag in inp_bags_only[container]:
if check_if_bag_can_contain(bag, target):
return True
return False
def part_1():
return sum(check_if_bag_can_contain(bag, "shiny gold") for bag in inp_bags_only)
print(f"Part 1: {part_1()}")
# part 2
# Find how many bags a shiny gold bag has to contain.
# check how many bags a bag has to contain
def check_how_many_bags_in_a_bag(container):
content = inp[container]
if not content:
return 0
count = sum(int(num) for num, bag in content)
for num, bag in content:
count += num * check_how_many_bags_in_a_bag(bag)
return count
def part_2():
return check_how_many_bags_in_a_bag("shiny gold")
print(f"Part 2: {part_2()}")
| 21.197368
| 84
| 0.675978
|
ccb45def2d600156f5d1287f3600b73608c34242
| 9,626
|
ps1
|
PowerShell
|
deployment/deploy-aks-dapr.ps1
|
aguywithcode/distributed-az-edge-framework
|
6a99703d35d9512cd64d0032fb6807d8afc64558
|
[
"MIT"
] | null | null | null |
deployment/deploy-aks-dapr.ps1
|
aguywithcode/distributed-az-edge-framework
|
6a99703d35d9512cd64d0032fb6807d8afc64558
|
[
"MIT"
] | null | null | null |
deployment/deploy-aks-dapr.ps1
|
aguywithcode/distributed-az-edge-framework
|
6a99703d35d9512cd64d0032fb6807d8afc64558
|
[
"MIT"
] | null | null | null |
# ------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
# ------------------------------------------------------------
Param(
[string]
[Parameter(mandatory=$true)]
$ApplicationName,
[string]
$Location = 'westeurope',
[switch]
$DeleteResourceGroup
)
Function Write-Title ($text) {
$width = (Get-Host).UI.RawUI.WindowSize.Width
$title = ""
if($text.length -ne 0)
{
$title = "=[ " + $text + " ]="
}
Write-Host $title.PadRight($width, "=") -ForegroundColor green
}
$deploymentId = Get-Random
Write-Title("Start Deploying")
$startTime = Get-Date
# ----- Create AKS Service Principals
Write-Title("Create AKS Service Principals")
$aks1ServicePrincipalName = $ApplicationName + "-aks1-sp"
$aks2ServicePrincipalName = $ApplicationName + "-aks2-sp"
$aks1ServicePrincipal = (az ad sp create-for-rbac -n $aks1ServicePrincipalName) | ConvertFrom-Json
$aks2ServicePrincipal = (az ad sp create-for-rbac -n $aks2ServicePrincipalName) | ConvertFrom-Json
$aks1ClientId = $aks1ServicePrincipal.appId
$aks2ClientId = $aks2ServicePrincipal.appId
$aks1ClientSecret = $aks1ServicePrincipal.password
$aks2ClientSecret = $aks2ServicePrincipal.password
# ----- Deploy Bicep
Write-Title("Deploy Bicep files")
$r = (az deployment sub create --location $Location `
--template-file .\bicep\main.bicep --parameters applicationName=$ApplicationName `
aks1ClientId=$aks1ClientId aks1ClientSecret=$aks1ClientSecret `
aks2ClientId=$aks2ClientId aks2ClientSecret=$aks2ClientSecret `
--name "dep-$deploymentId" -o json) | ConvertFrom-Json
$acrName = $r.properties.outputs.acrName.value
$aks1Name = $r.properties.outputs.aks1Name.value
$aks2Name = $r.properties.outputs.aks2Name.value
$resourceGroupName = $r.properties.outputs.resourceGroupName.value
$storageKey = $r.properties.outputs.storageKey.Value
$storageName = $r.properties.outputs.storageName.Value
$eventHubConnectionString = $r.properties.outputs.eventHubConnectionString.value
# ----- Build and Push Containers
Write-Title("Build and Push Containers")
$deploymentDir = Get-Location
Set-Location -Path ../iotedge/Distributed.IoT.Edge
az acr build --image datagatewaymodule:$deploymentId --registry $acrName --file Distributed.IoT.Edge.DataGatewayModule/Dockerfile .
az acr build --image simulatedtemperaturesensormodule:$deploymentId --registry $acrName --file Distributed.IoT.Edge.SimulatedTemperatureSensorModule/Dockerfile .
Set-Location -Path $deploymentDir
# ----- Build and Push Containers (OPC Publisher)
Write-Title("Build and Push Containers (OPC Publisher)")
if (!(Test-Path .\..\..\Industrial-IoT-Temp))
{
git clone -b feature/dapr-adapter https://github.com/suneetnangia/Industrial-IoT .\..\..\Industrial-IoT-Temp
}
Set-Location -Path .\..\..\Industrial-IoT-Temp
git pull
$Env:BUILD_SOURCEBRANCH = "feature/dapr-adapter"
$Env:Version_Prefix = $deploymentId
.\tools\scripts\acr-build.ps1 -Path .\modules\src\Microsoft.Azure.IIoT.Modules.OpcUa.Publisher\src -Registry $acrName
Set-Location -Path $deploymentDir
# ----- Get Cluster Credentials
Write-Title("Get AKS #1 Credentials")
az aks get-credentials --admin --name $aks1Name --resource-group $resourceGroupName --overwrite-existing
#----- Proxy
Write-Title("Install Proxy")
helm install squid-proxy ./helm/squid-proxy `
--namespace edge-proxy `
--create-namespace `
--wait
#----- Dapr
Write-Title("Install Dapr")
helm repo add dapr https://dapr.github.io/helm-charts/
helm repo update
helm upgrade --install dapr dapr/dapr `
--version=1.5 `
--namespace edge-core `
--create-namespace `
--wait
#----- Redis
Write-Title("Install Redis")
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
helm install redis bitnami/redis --wait `
--namespace edge-core `
--create-namespace `
--wait
# Copy Redis secret from edge-core namesapce to edge-app1 namespace where application is deployed.
kubectl create namespace edge-app1
kubectl get secret redis --namespace=edge-core -o yaml | % {$_.replace("namespace: edge-core","namespace: edge-app1")} | kubectl apply -f -
# ----- Run Helm
Write-Title("Install Pod/Containers with Helm in Cluster")
$datagatewaymoduleimage = $acrName + ".azurecr.io/datagatewaymodule:" + $deploymentId
$simtempimage = $acrName + ".azurecr.io/simulatedtemperaturesensormodule:" + $deploymentId
$opcplcimage = "mcr.microsoft.com/iotedge/opc-plc:2.2.0"
$opcpublisherimage = $acrName + ".azurecr.io/dapr-adapter/iotedge/opc-publisher:" + $deploymentId
helm install iot-edge-accelerator ./helm/iot-edge-accelerator `
--set-string images.datagatewaymodule="$datagatewaymoduleimage" `
--set-string images.simulatedtemperaturesensormodule="$simtempimage" `
--set-string images.opcplcmodule="$opcplcimage" `
--set-string images.opcpublishermodule="$opcpublisherimage" `
--set-string dataGatewayModule.eventHubConnectionString="$eventHubConnectionString" `
--set-string dataGatewayModule.storageAccountName="$storageName" `
--set-string dataGatewayModule.storageAccountKey="$storageKey" `
--set-string dataGatewayModule.storageAccountKey="$storageKey" `
--namespace edge-app1 `
--create-namespace `
--wait
# ----- Get AKS #1 Proxy IP Address
Write-Title("Get AKS #1 Proxy IP Address")
$proxy1 = kubectl get service squid-proxy-module -n edge-proxy -o json | ConvertFrom-Json
$proxy1Ip = $proxy1.status.loadBalancer.ingress.ip
$proxy1Url = "http://" + $proxy1Ip + ":3128"
# ----- Enroll AKS #1 with Arc
Write-Title("Enroll AKS #1 with Arc")
az extension add --name "connectedk8s"
az extension add --name "k8s-configuration"
az extension add --name "k8s-extension"
az extension add --name "customlocation"
az connectedk8s connect --name $aks1Name --resource-group $resourceGroupName --location $Location --proxy-http $proxy1Url --proxy-https $proxy1Url --proxy-skip-range 10.0.0.0/16,kubernetes.default.svc,.svc.cluster.local,.svc
az connectedk8s enable-features -n $aks1Name -g $resourceGroupName --features cluster-connect
# ----- Get Cluster Credentials
Write-Title("Get AKS #2 Credentials")
az aks get-credentials --admin --name $aks2Name --resource-group $resourceGroupName --overwrite-existing
#----- Proxy
Write-Title("Install Proxy")
helm install squid-proxy ./helm/squid-proxy `
--set-string parent.ipAddress="$proxy1Ip" `
--set-string parent.port="3128" `
--namespace edge-proxy `
--create-namespace `
--wait
#----- Dapr
Write-Title("Install Dapr")
helm repo add dapr https://dapr.github.io/helm-charts/
helm repo update
helm upgrade --install dapr dapr/dapr `
--version=1.5 `
--namespace edge-core `
--create-namespace `
--wait
#----- Redis
Write-Title("Install Redis")
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
helm install redis bitnami/redis --wait `
--namespace edge-core `
--create-namespace `
--wait
# Copy Redis secret from edge-core namesapce to edge-app1 namespace where application is deployed.
kubectl create namespace edge-app1
kubectl get secret redis --namespace=edge-core -o yaml | % {$_.replace("namespace: edge-core","namespace: edge-app1")} | kubectl apply -f -
# ----- Run Helm
Write-Title("Install Pod/Containers with Helm in Cluster")
$datagatewaymoduleimage = $acrName + ".azurecr.io/datagatewaymodule:" + $deploymentId
$simtempimage = $acrName + ".azurecr.io/simulatedtemperaturesensormodule:" + $deploymentId
$opcplcimage = "mcr.microsoft.com/iotedge/opc-plc:2.2.0"
$opcpublisherimage = $acrName + ".azurecr.io/dapr-adapter/iotedge/opc-publisher:" + $deploymentId
helm install iot-edge-accelerator ./helm/iot-edge-accelerator `
--set-string images.datagatewaymodule="$datagatewaymoduleimage" `
--set-string images.simulatedtemperaturesensormodule="$simtempimage" `
--set-string images.opcplcmodule="$opcplcimage" `
--set-string images.opcpublishermodule="$opcpublisherimage" `
--set-string dataGatewayModule.eventHubConnectionString="$eventHubConnectionString" `
--set-string dataGatewayModule.storageAccountName="$storageName" `
--set-string dataGatewayModule.storageAccountKey="$storageKey" `
--set-string dataGatewayModule.storageAccountKey="$storageKey" `
--namespace edge-app1 `
--create-namespace `
--wait
# ----- Get AKS #2 Proxy IP Address
Write-Title("Get AKS #2 Proxy IP Address")
$proxy2 = kubectl get service squid-proxy-module -n edge-proxy -o json | ConvertFrom-Json
$proxy2Ip = $proxy2.status.loadBalancer.ingress.ip
$proxy2Url = "http://" + $proxy2Ip + ":3128"
# ----- Enroll AKS #2 with Arc
Write-Title("Enroll AKS #2 with Arc")
az connectedk8s connect --name $aks2Name --resource-group $resourceGroupName --location $Location --proxy-http $proxy2Url --proxy-https $proxy2Url --proxy-skip-range 10.0.0.0/16,kubernetes.default.svc,.svc.cluster.local,.svc
az connectedk8s enable-features -n $aks2Name -g $resourceGroupName --features cluster-connect
# ----- Clean up
if($DeleteResourceGroup)
{
Write-Title("Delete Resources")
if(Remove-AzResourceGroup -Name $resourceGroupName -Force)
{
Write-Host "All resources deleted" -ForegroundColor Yellow
}
Write-Title("Delete AKS Service Principals")
az ad sp delete --id $aks1ClientId
az ad sp delete --id $aks2ClientId
}
$env:RESOURCEGROUPNAME=$resourceGroupName
$runningTime = New-TimeSpan -Start $startTime
Write-Host "Running time:" $runningTime.ToString() -ForegroundColor Yellow
| 41.313305
| 224
| 0.727613
|
4c63927cafda2e0285dc90b7cde1b7b3db8c73bd
| 390
|
lua
|
Lua
|
formatter_dartformat.lua
|
Faetu/lite-formatters
|
937ead666231013ce0fcf2de17ee5d59538e9120
|
[
"MIT"
] | 11
|
2021-04-29T05:16:10.000Z
|
2022-02-04T07:49:52.000Z
|
formatter_dartformat.lua
|
Faetu/lite-formatters
|
937ead666231013ce0fcf2de17ee5d59538e9120
|
[
"MIT"
] | 5
|
2021-05-18T18:05:42.000Z
|
2022-02-07T03:38:38.000Z
|
formatter_dartformat.lua
|
Faetu/lite-formatters
|
937ead666231013ce0fcf2de17ee5d59538e9120
|
[
"MIT"
] | 8
|
2021-05-16T18:33:36.000Z
|
2022-02-05T17:30:54.000Z
|
-- mod-version:2 lite-xl 2.00
-- for Dart formatter
local config = require "core.config"
local formatter = require "plugins.formatter"
config.dartformat_args = {} -- Like the previous case, it is better to leave it as default
formatter.add_formatter {
name = "Dart Formatter",
file_patterns = {
"%.dart$"
},
command = "dart format $ARGS $FILENAME",
args = config.dartformat_args
}
| 24.375
| 90
| 0.715385
|
034c1a75334a8d94d3417e79e1c62c31cfaba285
| 1,111
|
rb
|
Ruby
|
spec/unit/sql/processor/requalify/test_on_inner_join.rb
|
ciremoussadia/bmg
|
19971a6973a859978ffd1e82e0034c66d1ed8993
|
[
"MIT"
] | 210
|
2017-11-30T08:10:06.000Z
|
2022-02-28T13:02:36.000Z
|
spec/unit/sql/processor/requalify/test_on_inner_join.rb
|
ciremoussadia/bmg
|
19971a6973a859978ffd1e82e0034c66d1ed8993
|
[
"MIT"
] | 11
|
2018-05-08T13:06:31.000Z
|
2021-12-11T07:44:42.000Z
|
spec/unit/sql/processor/requalify/test_on_inner_join.rb
|
ciremoussadia/bmg
|
19971a6973a859978ffd1e82e0034c66d1ed8993
|
[
"MIT"
] | 6
|
2020-07-14T16:52:04.000Z
|
2021-01-11T14:06:39.000Z
|
require 'sql_helper'
module Bmg
module Sql
class Processor
describe Requalify, "on_inner_join" do
subject{ Requalify.new(Builder.new(2)).apply(expr) }
context 'with a predicate to requalify' do
let(:expr){
sexpr [ :inner_join,
[:table_as, [:table_name, :supplies], [:range_var_name, "t1"]],
[:table_as, [:table_name, :parts], [:range_var_name, "t2"]],
Predicate::Grammar.sexpr([:eq,
[:qualified_identifier, :t1, :pid],
[:qualified_identifier, :t2, :pid]
])
]
}
let(:expected){
sexpr [ :inner_join,
[:table_as, [:table_name, :supplies], [:range_var_name, "t3"]],
[:table_as, [:table_name, :parts], [:range_var_name, "t4"]],
Predicate::Grammar.sexpr([:eq,
[:qualified_identifier, :t3, :pid],
[:qualified_identifier, :t4, :pid]
])
]
}
it{ should eq(expected) }
end
end
end
end
end
| 28.487179
| 77
| 0.488749
|
2c4348d96274fe9e6302cf8b5352642bd0e0f303
| 1,429
|
py
|
Python
|
wagtail_onboarding/models.py
|
KalobTaulien/wagtail-onboarding
|
418837e28f58eaa01a0b98e209d9be3972dc5b47
|
[
"MIT"
] | 6
|
2021-02-15T04:15:20.000Z
|
2021-03-03T14:18:59.000Z
|
wagtail_onboarding/models.py
|
KalobTaulien/wagtail-onboarding
|
418837e28f58eaa01a0b98e209d9be3972dc5b47
|
[
"MIT"
] | null | null | null |
wagtail_onboarding/models.py
|
KalobTaulien/wagtail-onboarding
|
418837e28f58eaa01a0b98e209d9be3972dc5b47
|
[
"MIT"
] | null | null | null |
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
class Onboarding(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=False,
blank=False,
)
progress = models.PositiveSmallIntegerField(
default=0,
validators=[
MinValueValidator(0),
MaxValueValidator(100),
],
)
completed_admin_tour = models.BooleanField(default=False)
completed_page_edit_tour = models.BooleanField(default=False)
@property
def percent_complete(self) -> int:
progress = 0
fields = [
"completed_admin_tour",
"completed_page_edit_tour",
]
total_fields = len(fields)
for field in fields:
if getattr(self, field, False):
progress = progress + round(100 / total_fields)
# Theoretically `progress` could be over 100 due to rounding.
# Ensure it's always 100 or less.
if progress > 100:
progres = 100
return progress
def update_progress(self):
self.progress = self.percent_complete
self.save()
def __str__(self):
return self.user.username
class Meta:
verbose_name = "Onboarding status"
verbose_name_plural = "Onboarding status"
| 27.480769
| 71
| 0.627012
|
3a0cc9e2e1d92f10826c3276b365626713f97300
| 80
|
sql
|
SQL
|
presto-product-tests/src/main/resources/sql-tests/testcases/horology_functions/checkHorologyFunctionsRegistered.sql
|
photogamerun/weiwodb
|
6768496f0b6aa1e8d6f486e71e4711a1a3432c84
|
[
"Apache-2.0"
] | 1
|
2020-06-19T13:33:45.000Z
|
2020-06-19T13:33:45.000Z
|
presto-product-tests/src/main/resources/sql-tests/testcases/horology_functions/checkHorologyFunctionsRegistered.sql
|
photogamerun/weiwodb
|
6768496f0b6aa1e8d6f486e71e4711a1a3432c84
|
[
"Apache-2.0"
] | null | null | null |
presto-product-tests/src/main/resources/sql-tests/testcases/horology_functions/checkHorologyFunctionsRegistered.sql
|
photogamerun/weiwodb
|
6768496f0b6aa1e8d6f486e71e4711a1a3432c84
|
[
"Apache-2.0"
] | 2
|
2019-03-01T05:03:41.000Z
|
2019-04-16T06:13:26.000Z
|
-- database: presto; groups: qe, horology_functions, functions
show functions
| 26.666667
| 63
| 0.775
|
f095f7ffe035da2bf51e36a56a37b5bb0b056825
| 441
|
asm
|
Assembly
|
programs/oeis/106/A106040.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 22
|
2018-02-06T19:19:31.000Z
|
2022-01-17T21:53:31.000Z
|
programs/oeis/106/A106040.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 41
|
2021-02-22T19:00:34.000Z
|
2021-08-28T10:47:47.000Z
|
programs/oeis/106/A106040.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 5
|
2021-02-24T21:14:16.000Z
|
2021-08-09T19:48:05.000Z
|
; A106040: First 9-free digit in the fractional part of the decimal expansion of (1/10^n)^(1/10^n).
; 0,7,5,3,0,8,8,8,8,7,7,7,7,7,6,6,6,6,5,5,5,5,4,4,4,4,4,3,3,3,3,2,2,2,2,1,1,1,1,1,0,0,0,0,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,7
mul $0,23
lpb $0
mov $1,20
mov $2,$0
div $0,10
mul $2,9
add $1,$2
lpe
mov $3,$1
cmp $3,0
add $1,$3
mov $0,$1
sub $0,1
mod $0,10
| 24.5
| 201
| 0.55102
|
81746f21fe58dfaf27907bda8d87fcf27fc6937c
| 12,507
|
php
|
PHP
|
cache/f08d6e93c83deb629f01ad2d67c8d17685c4163e.php
|
soumyadipdas37/finescoop.github.io
|
0346d6175a2c36d4054083c144b7f8364db73f2f
|
[
"MIT"
] | null | null | null |
cache/f08d6e93c83deb629f01ad2d67c8d17685c4163e.php
|
soumyadipdas37/finescoop.github.io
|
0346d6175a2c36d4054083c144b7f8364db73f2f
|
[
"MIT"
] | null | null | null |
cache/f08d6e93c83deb629f01ad2d67c8d17685c4163e.php
|
soumyadipdas37/finescoop.github.io
|
0346d6175a2c36d4054083c144b7f8364db73f2f
|
[
"MIT"
] | 2
|
2021-09-18T12:06:26.000Z
|
2021-11-14T15:17:34.000Z
|
<?php $__env->startSection('content'); ?><p>Viewers watching BBC documentary Freddie Flintoff: Living with Bulimia, which recounts the cricketing hero's 20-year battle with an eating disorder, say they were 'left in tears' by the Top Gear presenter's 'raw' honesty. </p>
<p>Andrew 'Freddie' Flintoff, 42, talked candidly about how painful the process of making himself sick is in an eye-opening BBC documentary about the illness, which aired last night on BBC One at 9pm.</p>
<p>The unflinching account of the father-of-four's illness saw him talking to other men who suffer with disordered eating and detailing his own episodes of vomiting in graphic detail - including how the physical 'wrenching' of his body leaves him with 'bloodshot' and 'gone' eyes. </p>
<p>At one point, Freddie tells viewers he's 'done it this year' and says he 'can't say' that was the last time it'll happen. </p>
<p>Viewers took to social media to praise the cricket star's bravery in speaking out, saying it will encourage other sufferers to seek help. </p>
<p>Scroll down for video </p>
<p>'I still do it, I've done it this year': Freddie Flintoff: Living with Bulimia, which aired on BBC One on Monday at 9pm, saw the cricket star offer an unflinching account of his 20-year battle with bulimia</p>
<p>The father-of-four offered a graphic account of what his body goes through when he purges following a 'pre-planned' binge - admitting he's 'done it this year' and saying he 'can't say' it was the last time it'll happen</p>
<p>Viewers of the hard-to-watch documentary, which saw the Top Gear presenter speak to other men with the illness, praised Freddie for his bravery in speaking out about his experiences</p>
<p>After the show aired, social media was awash with comments about the programme. </p>
<p>One viewer said: 'Such an incredibly brave thing to do, the world needs more people to speak out about mental ill-health. I know this will be tough to watch, but hopefully will help so many.'</p>
<p>Another added: 'Freddie Flintoff speaking out about his bulimia is so so important. So raw. So heart wrenching. </p>
<p>'Eating disorders are the biggest killers out of all mental illnesses. They wreak havoc on your body, your mind, your person. Accepted, glorified, all consuming and deadly.'</p>
<p>A third added: 'Massive respect for Flintoff for admitting to everything he's been going through for so long.' </p>
<p>Describing how he would make himself sick in a bid to lose weight, the former England cricket captain revealed that 20 years after he first began suffering from bulimia, he still, on occasion, makes himself vomit after meals.</p>
<p>He said: 'I've had periods where I've not done it for a long time and I've had periods when I've done it. I've done it this year. It's not right, is it? I know it's not right but I can't say for certain when it's going to stop.' </p>
<p>Although he says he does not suffer with bulimia as much as before, Freddie - who trains most days at the gym - admitted he had purged the same year as the documentary was filmed and said he can never be certain if it will stop</p>
<p>In the new documentary, Freddie Flintoff: Living with Bulimia, the TV presenter (pictured) became emotional when speaking to other men suffering from the eating disorder</p>
<p>Andrew Flintoff (pictured) spoke openly about his battles with bulimia, which began around 20 years ago when he was a professional cricketer. Former England captain explained in detail what the experience of purging is like </p>
<p>In the programme, Freddie explained that the issue began around 20 years ago when he faced criticism in the press about his size. </p>
<p>Freddie became emotional when he met several other men suffering from the condition and spoke to them about their experiences - something he told the programme he had never done before.</p>
<p>In addition, the 42-year-old father was introduced to the mother and brother of one man who died from a heart attack at the age of 24 due to his life-altering eating disorder. </p>
<p>Freddie spoke about the origins of his eating disorder, starting when he received comments about being 'fat' during his cricketing career, bringing into question his fitness and capability. </p>
<p>Not realising he had put on weight, he was surprised to find out after a weigh in that he was in fact 19 stone. </p>
<p>Others said watching the programme was 'heart wrenching' and suggested the programme was an important step in encouraging people to open up about their own experiences</p>
<p>The now TV presenter soon began to develop unhealthy thoughts about his body and would make himself sick after meals. </p>
<p>He said: 'That's when I started, that's when I became aware I put this weight on. I was in decent nick and I put a little bit of size on, I just didn't see it coming.</p>
<p>'Something changed in my mind where I was acutely aware of it but worse than everyone else was aware of it. I became known as a fat cricketer really, that was horrible.' </p>
<p>The 42-year-old father (above) was also introduced to the mother and brother of a man called Laurence, who died from a heart attack at the age of 24 due to his life-altering eating disorder</p>
<p>Freddie said his problems with his weight and eating disorder began when he was 'hammered' in the press for his size after his fitness was called into question. Pictured, looking at shots of himself in the Lancashire cricket team over the years</p>
<p>The bulimia ramped up when his career began to take off and he was becoming more successful - linking his success to the eating disorder. </p>
<p>After losing three stone, he said he started to think 'I'm bossing this' and the bulimia continued. He explained one of the hardest parts was keeping it hidden from everyone around him, including his team mates. </p>
<p>Speaking candidly about how it dictated his life, he said he would pre-plan how and where he would purge to ensure he was not caught. </p>
<p>Despite telling his now wife Rachael, 42, about his condition, the father-of-four never revealed how bad his bulimia had become and would lie when she asked him how often it was happening. </p>
<p>The bulimia ramped up when his career began to take off and he lost three stone. He started linking his success to the eating disorder said he thought 'I'm bossing this'. Pictured, Freddie at Lords Cricket Ground</p>
<p>Freddie (above) explained one of the hardest parts was keeping it hidden from everyone around him, including his team mates and his wife</p>
<p>Freddie spoke in excruciating detail about how painful the process of making himself sick is: 'Your eyes are just bloodshot, your eyes have gone. If I didn’t do it, I didn’t feel any good about myself - it wasn’t about my weight it was just how it made me feel.' </p>
<p>According to the documentary, over 1.5million people in the UK suffer from eating disorders such as bulimia and experts estimate 1 in 4 sufferers are male.</p>
<p>Freddie also opened up about how he felt small as a youngster and took longer to look bigger and more muscly. </p>
<p>To this day he still suffers with body issues, stating during the documentary that he will always be overweight - much to the documentary makers shock. </p>
<p>He said: 'Shape is something I’m heavily aware off. Having been big before I never want to experience it again. I will always be overweight - it's not in my mind, I will.</p>
<p>'I am not the optimum weight for my size, that is fact. I know how I feel when I put weight on and I don’t want it, I don’t want to feel like that.'</p>
<p>Freddie (pictured above) spoke in excruciating detail about how painful the process of making himself sick is</p>
<p>To this day he still suffers with body issues, stating during the documentary that he will always be overweight, despite training in the gym for at least an hour most days</p>
<p>Instead, the former professional cricketer trains in the gym several days a week for an hour at a time. </p>
<p>During the documentary, his personal trainer explains that Freddie pushes himself extremely far in the gym and at times he has struggled to keep up with the TV presenter. </p>
<p>But, during an uncomfortable discussion with dietitian Renee McGregor, Freddie reveals that he does not see his heavy reliance on the gym as a bad thing as it does not negatively affect anyone around him. </p>
<p>He explained he has never sought out professional help or treatment for his disorder and that the only time that he considered speaking to someone about it was during a visit from a dietitian for the England cricket team. </p>
<p>But he never went through with it, after she told the room: 'I work with female Olympians and gymnasts "but there will be none of that in this room will there", so I carried on.' </p>
<p>In an emotional interview, Freddie visited Pam Nugent, and her son Chris, who told him about her son Laurence who suffered from bulimia - purging after everything he ate</p>
<p>Her son's bulimia spiralled out of control and in 2009 he had a heart attack and died as a result of the eating disorder - aged just 24 years old. Pictured, Pam and son Chris explaining they hoped they could 'fix him'</p>
<p>It was while filming another documentary about training to be a boxer in 2012 that Freddie first revealed he had bulimia.</p>
<p>BEAT eating disorders explains the condition:</p>
<p>In the documentary, he spoke to Pam Nugent, and her son Chris, about the death of her other son Laurence. </p>
<p>After his bulimia spiralled out of control, unable to eat a single meal without purging, the young man died in 2009 from a heart attack - aged just 24 years old. </p>
<p>Pam told Freddie that her son had been turned away by doctors when he finally plucked up the courage to visit and said his family always hoped they would be able to 'fix him'. </p>
<p>Freddie said hearing from the mother made him 'question how I deal with my eating disorder'. </p>
<p>He added: 'It's that thing where you think it's never going to happen to you.</p>
<p>'I don't want to be a statistic, I don't want to be something that's read about in years to come, that something's happened to me'.</p>
<p>The mother even put Freddie on the spot, asking him where he is in the battle with his own eating disorder. </p>
<p>'Every time I eat I feel some kind of guilt but I think I’m dictating the terms to the eating disorder as opposed to the other way round. I still feel the compulsion but I can control that.'</p>
<p>When asked if he thought he would have bulimia in 20 years time, he admitted he thinks he will. </p>
<p>The much-loved presenter also spoke to Simon, who visits the Oxford Annex, an NHS eating disorder service in Preston, who revealed he would eat as much as a whole loaf of bread or a jar of peanut butter before making himself sick. </p>
<p>He explained his heartbreaking backstory, where his mother had killed herself when he was just two years old and his brother also did the same years later. </p>
<p>The much-loved presenter also spoke to Simon, who visit the Oxford Annex, an NHS eating disorder service in Preston, who revealed he would eat as much as a whole loaf of bread or a jar of peanut butter before purging</p>
<p>A fellow former boxer, Aiden, also spoke about overcoming bulimia which took over his life in his 20s - driving into the countryside to avoid being caught purging</p>
<p>Simon said: 'There’s no enjoyment, I know the consequences will be negative. I think it's a way of self harming by eating that much.'</p>
<p>A fellow former boxer, Aiden, also spoke about overcoming bulimia which took over his life in his 20s. </p>
<p>He told Freddie how he would 'drive out into the sticks' before binging and purging so he did not get caught. </p>
<p>As a side effect of the bulimia, he explained to Freddie that on occasions he would pass out while purging and experience chest pains. </p>
<p>It was not until he went to see the GP that he was able to recover from the disorder and described it as feeling 'like a pressure was released'. </p>
<p>At the end of the documentary, Freddie reveals he has decided to seek help for his eating disorder and speaks about 'the shame' he feels. </p>
<p>Freddie Flintoff: Living With Bulimia is available on BBC iPlayer</p>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('_layouts.post', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
| 85.081633
| 285
| 0.762213
|
a3440cfd174d9fa985008c7a12499d1a694769a8
| 5,337
|
h
|
C
|
libtensor/linalg/lapack_essl.h
|
pjknowles/libtensor
|
f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24
|
[
"BSL-1.0"
] | 33
|
2016-02-08T06:05:17.000Z
|
2021-11-17T01:23:11.000Z
|
libtensor/linalg/lapack_essl.h
|
pjknowles/libtensor
|
f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24
|
[
"BSL-1.0"
] | 5
|
2016-06-14T15:54:11.000Z
|
2020-12-07T08:27:20.000Z
|
libtensor/linalg/lapack_essl.h
|
pjknowles/libtensor
|
f18e0e33c6c4512e4ea1dde31ed8d74fe536ed24
|
[
"BSL-1.0"
] | 12
|
2016-05-19T18:09:38.000Z
|
2021-02-24T17:35:21.000Z
|
#ifndef LIBTENSOR_LAPACK_ESSL_H
#define LIBTENSOR_LAPACK_ESSL_H
#include "essl/essl_h.h"
#include "../not_implemented.h"
namespace libtensor {
/** \brief LAPACK function dgesv (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dgesv(size_t n, size_t nrhs, double *a, size_t lda, int *ipiv,
double *b, size_t ldb) {
int info = 0;
dgesv(n, nrhs, a, lda, ipiv, b, ldb, info);
return info;
}
/** \brief LAPACK function dgesvd (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dgesvd(char jobu, char jobvt, size_t m, size_t n, double *a,
size_t lda, double *s, double *u, size_t ldu, double *vt, size_t ldvt,
double *work, size_t lwork) {
int info = 0;
//dgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, &info);
return info;
}
/** \brief LAPACK function zgesvd (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_zgesvd(char jobu, char jobvt, size_t m, size_t n,
std::complex<double> *a, size_t lda, double *s, std::complex<double> *u,
size_t ldu, std::complex<double> *vt, size_t ldvt,
std::complex<double> *work, size_t lwork, double *rwork) {
int info = 0;
//zgesvd(jobu, jobvt, m, n, a, lda, s, u, ldu, vt, ldvt, &info);
return info;
}
/** \brief LAPACK function dsyev (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dsyev(char jobz, char uplo, size_t n, double *a, size_t lda,
double *w, double *work, size_t lwork) {
int info = 0;
//dsyev(jobz, uplo, n, a, lda, w, &info);
return info;
}
/** \brief LAPACK function dgeev (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dgeev(char jobvl, char jobvr, size_t n, double *a,
size_t lda, double *wr, double *wi, double *vl, size_t ldvl, double *vr,
size_t ldvr, double *work, size_t lwork) {
int info = 0;
//dgeev(jobvl, jobvr, n, a, lda, wr, wi, vl, ldvl, vr, ldvr, &info);
return info;
}
/** \brief LAPACK function dggev (ESSL)
*
* \ingroup libtensor_linalg
* **/
inline int lapack_dggev(char jobvl, char jobvr, size_t n, double *a,
size_t lda, double * b, size_t ldb, double *alphar, double *alphai, double * beta, double *vl, size_t ldvl, double *vr,
size_t ldvr, double *work, size_t lwork) {
int info = 0;
//dggev(jobvl, jobvr, n, a, lda, b, ldb, alphar, alphai, beta, vl, ldvl, vr, ldvr, &info);
return info;
}
/** \brief LAPACK function zgeev (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_zgeev(char jobvl, char jobvr, size_t n,
std::complex<double> *a, size_t lda, std::complex<double> *w,
std::complex<double> *vl, size_t ldvl, std::complex<double> *vr,
size_t ldvr, std::complex<double> *work, size_t lwork, double *rwork) {
int info = 0;
//zgeev(jobvl, jobvr, n, a, lda, w, vl, ldvl, vr, ldvr, &info);
return info;
}
/** \brief LAPACK function dgelss (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dgelss(size_t m, size_t n, size_t nrhs, double *B, size_t lda,
double *rhs, size_t ldb, double *S, double rcond, int *rank, double *work,
size_t lwork) {
int info = 0;
//dgelss(m, n, nrhs, B, lda, rhs, ldb, S, rcond, rank, &info);
return info;
}
/** \brief LAPACK function dgelsd (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dgelsd(size_t m, size_t n, size_t nrhs, double *B, size_t lda,
double *rhs, size_t ldb, double *S, double rcond, int *rank, double *work,
size_t lwork, int *iwork) {
int info = 0;
//dgelsd(m, n, nrhs, B, lda, rhs, ldb, S, rcond, rank, &info);
return info;
}
/** \brief LAPACK function dpotrf (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dpotrf(char uplo, size_t n, double *a, size_t lda) {
int info = 0;
dpotrf(&uplo, n, a, lda, info);
return info;
}
/** \brief LAPACK function dpotri (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dpotri(char uplo, size_t n, double *a, size_t lda) {
int info = 0;
dpotri(&uplo, n, a, lda, info);
return info;
}
/** \brief LAPACK function dlarnv (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dlarnv(size_t idist, int *iseed, size_t n, double *x) {
throw not_implemented(g_ns, 0, "lapack_dlarnv", __FILE__, __LINE__);
//dlarnv(idist, iseed, n, x);
return 0;
}
/** \brief LAPACK function dpotrf (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dpstrf(char uplo, size_t n, double *a, size_t lda, int *p,
int *rank, double tol, double *work) {
int info = 0;
#ifdef HAVE_LAPACK_DPSTRF
dpstrf(uplo, n, a, lda, p, rank, tol, work, &info);
#else // HAVE_LAPACK_DPSTRF
throw not_implemented(g_ns, 0, "lapack_dpstrf", __FILE__, __LINE__);
#endif // HAVE_LAPACK_DPSTRF
return info;
}
/** \brief LAPACK function dpteqr (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dpteqr(char compz, size_t n, double *d, double *e, double *z,
size_t ldz, double *work) {
throw not_implemented(g_ns, 0, "lapack_dpteqr", __FILE__, __LINE__);
}
/** \brief LAPACK function dsteqr (ESSL)
\ingroup libtensor_linalg
**/
inline int lapack_dsteqr(char compz, size_t n, double *d, double *e, double *z,
size_t ldz, double *work) {
throw not_implemented(g_ns, 0, "lapack_dsteqr", __FILE__, __LINE__);
}
} // namespace libtensor
#endif // LIBTENSOR_LAPACK_ESSL_H
| 24.823256
| 123
| 0.653363
|
a3b09a1fdcf4c133e8454ee1744c94d06d336f13
| 2,804
|
java
|
Java
|
src/test/java/uk/gov/hmcts/reform/dg/docassembly/rest/DocumentConversionResourceTest.java
|
uk-gov-mirror/hmcts.dg-docassembly-api
|
557c2e67bb5bf8ce3c352749b5ea09ca2e59e95e
|
[
"MIT"
] | null | null | null |
src/test/java/uk/gov/hmcts/reform/dg/docassembly/rest/DocumentConversionResourceTest.java
|
uk-gov-mirror/hmcts.dg-docassembly-api
|
557c2e67bb5bf8ce3c352749b5ea09ca2e59e95e
|
[
"MIT"
] | null | null | null |
src/test/java/uk/gov/hmcts/reform/dg/docassembly/rest/DocumentConversionResourceTest.java
|
uk-gov-mirror/hmcts.dg-docassembly-api
|
557c2e67bb5bf8ce3c352749b5ea09ca2e59e95e
|
[
"MIT"
] | null | null | null |
package uk.gov.hmcts.reform.dg.docassembly.rest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import uk.gov.hmcts.reform.dg.docassembly.Application;
import uk.gov.hmcts.reform.dg.docassembly.service.FileToPDFConverterService;
import uk.gov.hmcts.reform.dg.docassembly.service.exception.DocumentProcessingException;
import uk.gov.hmcts.reform.dg.docassembly.service.exception.FileTypeException;
import java.io.File;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class, TestSecurityConfiguration.class})
@AutoConfigureMockMvc
public class DocumentConversionResourceTest {
@InjectMocks
private DocumentConversionResource documentConversionResource;
@Mock
private FileToPDFConverterService fileToPDFConverterService;
private UUID docId = null;
private static final File TEST_PDF_FILE = new File(
ClassLoader.getSystemResource("Test.pdf").getPath());
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
docId = UUID.randomUUID();
}
@Test
public void shouldConvertDocument() {
when(fileToPDFConverterService.convertFile(docId))
.thenReturn(TEST_PDF_FILE);
ResponseEntity response = documentConversionResource.convert(docId);
assertEquals(200, response.getStatusCodeValue());
verify(fileToPDFConverterService, Mockito.atMost(1))
.convertFile(docId);
}
@Test
public void shouldFailConvertDocumentToPDF() {
when(fileToPDFConverterService.convertFile(docId))
.thenThrow(DocumentProcessingException.class);
ResponseEntity response = documentConversionResource.convert(docId);
assertEquals(400, response.getStatusCodeValue());
verify(fileToPDFConverterService, Mockito.atMost(1))
.convertFile(docId);
}
@Test
public void shouldFailConvertOtherThanAcceptedFormatDocumentToPDF() {
when(fileToPDFConverterService.convertFile(docId))
.thenThrow(FileTypeException.class);
ResponseEntity response = documentConversionResource.convert(docId);
assertEquals(400, response.getStatusCodeValue());
verify(fileToPDFConverterService, Mockito.atMost(1))
.convertFile(docId);
}
}
| 31.863636
| 88
| 0.751783
|
cd45dcb439c4dd945b7fc0cfd2b77acce910d965
| 45,322
|
cs
|
C#
|
Source/Assembly-CSharp/XLua/Utils.cs
|
Shadowrabbit/BigBiaDecompilation
|
a9b1fb42f22384ceb046ed7f413c7b76ce4ae2d6
|
[
"Apache-2.0"
] | 1
|
2021-09-20T07:39:55.000Z
|
2021-09-20T07:39:55.000Z
|
Source/Assembly-CSharp/XLua/Utils.cs
|
Shadowrabbit/BigBiaDecompilation
|
a9b1fb42f22384ceb046ed7f413c7b76ce4ae2d6
|
[
"Apache-2.0"
] | null | null | null |
Source/Assembly-CSharp/XLua/Utils.cs
|
Shadowrabbit/BigBiaDecompilation
|
a9b1fb42f22384ceb046ed7f413c7b76ce4ae2d6
|
[
"Apache-2.0"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using XLua.LuaDLL;
namespace XLua
{
public static class Utils
{
public static bool LoadField(IntPtr L, int idx, string field_name)
{
idx = ((idx > 0) ? idx : (Lua.lua_gettop(L) + idx + 1));
Lua.xlua_pushasciistring(L, field_name);
Lua.lua_rawget(L, idx);
return !Lua.lua_isnil(L, -1);
}
public static IntPtr GetMainState(IntPtr L)
{
IntPtr result = 0;
Lua.xlua_pushasciistring(L, "xlua_main_thread");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
if (Lua.lua_isthread(L, -1))
{
result = Lua.lua_tothread(L, -1);
}
Lua.lua_pop(L, 1);
return result;
}
public static List<Type> GetAllTypes(bool exclude_generic_definition = true)
{
List<Type> list = new List<Type>();
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
Func<Type, bool> <>9__0;
for (int i = 0; i < assemblies.Length; i++)
{
try
{
List<Type> list2 = list;
IEnumerable<Type> types = assemblies[i].GetTypes();
Func<Type, bool> predicate;
if ((predicate = <>9__0) == null)
{
predicate = (<>9__0 = ((Type type) => !exclude_generic_definition || !type.IsGenericTypeDefinition()));
}
list2.AddRange(types.Where(predicate));
}
catch (Exception)
{
}
}
return list;
}
private static lua_CSFunction genFieldGetter(Type type, FieldInfo field)
{
if (field.IsStatic)
{
return delegate(IntPtr L)
{
ObjectTranslatorPool.Instance.Find(L).PushAny(L, field.GetValue(null));
return 1;
};
}
return delegate(IntPtr L)
{
ObjectTranslator objectTranslator = ObjectTranslatorPool.Instance.Find(L);
object obj = objectTranslator.FastGetCSObj(L, 1);
if (obj == null || !type.IsInstanceOfType(obj))
{
string[] array = new string[6];
array[0] = "Expected type ";
int num = 1;
Type type2 = type;
array[num] = ((type2 != null) ? type2.ToString() : null);
array[2] = ", but got ";
array[3] = ((obj == null) ? "null" : obj.GetType().ToString());
array[4] = ", while get field ";
int num2 = 5;
FieldInfo field2 = field;
array[num2] = ((field2 != null) ? field2.ToString() : null);
return Lua.luaL_error(L, string.Concat(array));
}
objectTranslator.PushAny(L, field.GetValue(obj));
return 1;
};
}
private static lua_CSFunction genFieldSetter(Type type, FieldInfo field)
{
if (field.IsStatic)
{
return delegate(IntPtr L)
{
object @object = ObjectTranslatorPool.Instance.Find(L).GetObject(L, 1, field.FieldType);
if (field.FieldType.IsValueType() && Nullable.GetUnderlyingType(field.FieldType) == null && @object == null)
{
string[] array = new string[5];
array[0] = type.Name;
array[1] = ".";
array[2] = field.Name;
array[3] = " Expected type ";
int num = 4;
Type fieldType = field.FieldType;
array[num] = ((fieldType != null) ? fieldType.ToString() : null);
return Lua.luaL_error(L, string.Concat(array));
}
field.SetValue(null, @object);
return 0;
};
}
return delegate(IntPtr L)
{
ObjectTranslator objectTranslator = ObjectTranslatorPool.Instance.Find(L);
object obj = objectTranslator.FastGetCSObj(L, 1);
if (obj == null || !type.IsInstanceOfType(obj))
{
string[] array = new string[6];
array[0] = "Expected type ";
int num = 1;
Type type2 = type;
array[num] = ((type2 != null) ? type2.ToString() : null);
array[2] = ", but got ";
array[3] = ((obj == null) ? "null" : obj.GetType().ToString());
array[4] = ", while set field ";
int num2 = 5;
FieldInfo field2 = field;
array[num2] = ((field2 != null) ? field2.ToString() : null);
return Lua.luaL_error(L, string.Concat(array));
}
object @object = objectTranslator.GetObject(L, 2, field.FieldType);
if (field.FieldType.IsValueType() && Nullable.GetUnderlyingType(field.FieldType) == null && @object == null)
{
string[] array2 = new string[5];
array2[0] = type.Name;
array2[1] = ".";
array2[2] = field.Name;
array2[3] = " Expected type ";
int num3 = 4;
Type fieldType = field.FieldType;
array2[num3] = ((fieldType != null) ? fieldType.ToString() : null);
return Lua.luaL_error(L, string.Concat(array2));
}
field.SetValue(obj, @object);
if (type.IsValueType())
{
objectTranslator.Update(L, 1, obj);
}
return 0;
};
}
private static lua_CSFunction genItemGetter(Type type, PropertyInfo[] props)
{
props = (from prop in props
where !prop.GetIndexParameters()[0].ParameterType.IsAssignableFrom(typeof(string))
select prop).ToArray<PropertyInfo>();
if (props.Length == 0)
{
return null;
}
Type[] params_type = new Type[props.Length];
for (int i = 0; i < props.Length; i++)
{
params_type[i] = props[i].GetIndexParameters()[0].ParameterType;
}
object[] arg = new object[1];
return delegate(IntPtr L)
{
ObjectTranslator objectTranslator = ObjectTranslatorPool.Instance.Find(L);
object obj = objectTranslator.FastGetCSObj(L, 1);
if (obj == null || !type.IsInstanceOfType(obj))
{
string[] array = new string[6];
array[0] = "Expected type ";
int num = 1;
Type type2 = type;
array[num] = ((type2 != null) ? type2.ToString() : null);
array[2] = ", but got ";
array[3] = ((obj == null) ? "null" : obj.GetType().ToString());
array[4] = ", while get prop ";
array[5] = props[0].Name;
return Lua.luaL_error(L, string.Concat(array));
}
for (int j = 0; j < props.Length; j++)
{
if (objectTranslator.Assignable(L, 2, params_type[j]))
{
PropertyInfo propertyInfo = props[j];
try
{
object @object = objectTranslator.GetObject(L, 2, params_type[j]);
arg[0] = @object;
object value = propertyInfo.GetValue(obj, arg);
Lua.lua_pushboolean(L, true);
objectTranslator.PushAny(L, value);
return 2;
}
catch (Exception ex)
{
string[] array2 = new string[8];
array2[0] = "try to get ";
int num2 = 1;
Type type3 = type;
array2[num2] = ((type3 != null) ? type3.ToString() : null);
array2[2] = ".";
array2[3] = propertyInfo.Name;
array2[4] = " throw a exception:";
int num3 = 5;
Exception ex2 = ex;
array2[num3] = ((ex2 != null) ? ex2.ToString() : null);
array2[6] = ",stack:";
array2[7] = ex.StackTrace;
return Lua.luaL_error(L, string.Concat(array2));
}
}
}
Lua.lua_pushboolean(L, false);
return 1;
};
}
private static lua_CSFunction genItemSetter(Type type, PropertyInfo[] props)
{
props = (from prop in props
where !prop.GetIndexParameters()[0].ParameterType.IsAssignableFrom(typeof(string))
select prop).ToArray<PropertyInfo>();
if (props.Length == 0)
{
return null;
}
Type[] params_type = new Type[props.Length];
for (int i = 0; i < props.Length; i++)
{
params_type[i] = props[i].GetIndexParameters()[0].ParameterType;
}
object[] arg = new object[1];
return delegate(IntPtr L)
{
ObjectTranslator objectTranslator = ObjectTranslatorPool.Instance.Find(L);
object obj = objectTranslator.FastGetCSObj(L, 1);
if (obj == null || !type.IsInstanceOfType(obj))
{
string[] array = new string[6];
array[0] = "Expected type ";
int num = 1;
Type type2 = type;
array[num] = ((type2 != null) ? type2.ToString() : null);
array[2] = ", but got ";
array[3] = ((obj == null) ? "null" : obj.GetType().ToString());
array[4] = ", while set prop ";
array[5] = props[0].Name;
return Lua.luaL_error(L, string.Concat(array));
}
for (int j = 0; j < props.Length; j++)
{
if (objectTranslator.Assignable(L, 2, params_type[j]))
{
PropertyInfo propertyInfo = props[j];
try
{
arg[0] = objectTranslator.GetObject(L, 2, params_type[j]);
object @object = objectTranslator.GetObject(L, 3, propertyInfo.PropertyType);
if (@object == null)
{
string[] array2 = new string[5];
array2[0] = type.Name;
array2[1] = ".";
array2[2] = propertyInfo.Name;
array2[3] = " Expected type ";
int num2 = 4;
Type propertyType = propertyInfo.PropertyType;
array2[num2] = ((propertyType != null) ? propertyType.ToString() : null);
return Lua.luaL_error(L, string.Concat(array2));
}
propertyInfo.SetValue(obj, @object, arg);
Lua.lua_pushboolean(L, true);
return 1;
}
catch (Exception ex)
{
string[] array3 = new string[8];
array3[0] = "try to set ";
int num3 = 1;
Type type3 = type;
array3[num3] = ((type3 != null) ? type3.ToString() : null);
array3[2] = ".";
array3[3] = propertyInfo.Name;
array3[4] = " throw a exception:";
int num4 = 5;
Exception ex2 = ex;
array3[num4] = ((ex2 != null) ? ex2.ToString() : null);
array3[6] = ",stack:";
array3[7] = ex.StackTrace;
return Lua.luaL_error(L, string.Concat(array3));
}
}
}
Lua.lua_pushboolean(L, false);
return 1;
};
}
private static lua_CSFunction genEnumCastFrom(Type type)
{
return delegate(IntPtr L)
{
int result;
try
{
result = ObjectTranslatorPool.Instance.Find(L).TranslateToEnumToTop(L, type, 1);
}
catch (Exception ex)
{
string str = "cast to ";
Type type2 = type;
string str2 = (type2 != null) ? type2.ToString() : null;
string str3 = " exception:";
Exception ex2 = ex;
result = Lua.luaL_error(L, str + str2 + str3 + ((ex2 != null) ? ex2.ToString() : null));
}
return result;
};
}
internal static IEnumerable<MethodInfo> GetExtensionMethodsOf(Type type_to_be_extend)
{
if (InternalGlobals.extensionMethodMap == null)
{
List<Type> list = new List<Type>();
IEnumerator<Type> enumerator = Utils.GetAllTypes(true).GetEnumerator();
while (enumerator.MoveNext())
{
Type type2 = enumerator.Current;
if (type2.IsDefined(typeof(ExtensionAttribute), false) && type2.IsDefined(typeof(ReflectionUseAttribute), false))
{
list.Add(type2);
}
if (type2.IsAbstract() && type2.IsSealed())
{
foreach (FieldInfo fieldInfo in type2.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
if (fieldInfo.IsDefined(typeof(ReflectionUseAttribute), false) && typeof(IEnumerable<Type>).IsAssignableFrom(fieldInfo.FieldType))
{
list.AddRange(from t in fieldInfo.GetValue(null) as IEnumerable<Type>
where t.IsDefined(typeof(ExtensionAttribute), false)
select t);
}
}
foreach (PropertyInfo propertyInfo in type2.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
if (propertyInfo.IsDefined(typeof(ReflectionUseAttribute), false) && typeof(IEnumerable<Type>).IsAssignableFrom(propertyInfo.PropertyType))
{
list.AddRange(from t in propertyInfo.GetValue(null, null) as IEnumerable<Type>
where t.IsDefined(typeof(ExtensionAttribute), false)
select t);
}
}
}
}
enumerator.Dispose();
InternalGlobals.extensionMethodMap = (from type in list
from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public)
where method.IsDefined(typeof(ExtensionAttribute), false) && Utils.IsSupportedMethod(method)
group method by Utils.getExtendedType(method)).ToDictionary((IGrouping<Type, MethodInfo> g) => g.Key, (IGrouping<Type, MethodInfo> g) => g);
}
IEnumerable<MethodInfo> result = null;
InternalGlobals.extensionMethodMap.TryGetValue(type_to_be_extend, out result);
return result;
}
private static void makeReflectionWrap(IntPtr L, Type type, int cls_field, int cls_getter, int cls_setter, int obj_field, int obj_getter, int obj_setter, int obj_meta, out lua_CSFunction item_getter, out lua_CSFunction item_setter, BindingFlags access)
{
ObjectTranslator objectTranslator = ObjectTranslatorPool.Instance.Find(L);
BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | access;
FieldInfo[] fields = type.GetFields(bindingFlags);
EventInfo[] events = type.GetEvents(bindingFlags | BindingFlags.Public | BindingFlags.NonPublic);
Lua.lua_checkstack(L, 2);
for (int i = 0; i < fields.Length; i++)
{
FieldInfo fieldInfo = fields[i];
string fieldName = fieldInfo.Name;
if (!fieldInfo.IsStatic || (!fieldInfo.Name.StartsWith("__Hotfix") && !fieldInfo.Name.StartsWith("_c__Hotfix")) || !typeof(Delegate).IsAssignableFrom(fieldInfo.FieldType))
{
if (events.Any((EventInfo e) => e.Name == fieldName))
{
fieldName = "&" + fieldName;
}
if (fieldInfo.IsStatic && (fieldInfo.IsInitOnly || fieldInfo.IsLiteral))
{
Lua.xlua_pushasciistring(L, fieldName);
objectTranslator.PushAny(L, fieldInfo.GetValue(null));
Lua.lua_rawset(L, cls_field);
}
else
{
Lua.xlua_pushasciistring(L, fieldName);
objectTranslator.PushFixCSFunction(L, Utils.genFieldGetter(type, fieldInfo));
Lua.lua_rawset(L, fieldInfo.IsStatic ? cls_getter : obj_getter);
Lua.xlua_pushasciistring(L, fieldName);
objectTranslator.PushFixCSFunction(L, Utils.genFieldSetter(type, fieldInfo));
Lua.lua_rawset(L, fieldInfo.IsStatic ? cls_setter : obj_setter);
}
}
}
foreach (EventInfo eventInfo in type.GetEvents(bindingFlags))
{
Lua.xlua_pushasciistring(L, eventInfo.Name);
objectTranslator.PushFixCSFunction(L, objectTranslator.methodWrapsCache.GetEventWrap(type, eventInfo.Name));
Lua.lua_rawset(L, ((eventInfo.GetAddMethod(true) != null) ? eventInfo.GetAddMethod(true).IsStatic : eventInfo.GetRemoveMethod(true).IsStatic) ? cls_field : obj_field);
}
List<PropertyInfo> list = new List<PropertyInfo>();
foreach (PropertyInfo propertyInfo in type.GetProperties(bindingFlags))
{
if (propertyInfo.GetIndexParameters().Length != 0)
{
list.Add(propertyInfo);
}
}
PropertyInfo[] array = list.ToArray();
item_getter = ((array.Length != 0) ? Utils.genItemGetter(type, array) : null);
item_setter = ((array.Length != 0) ? Utils.genItemSetter(type, array) : null);
MethodInfo[] array2 = type.GetMethods(bindingFlags);
if (access == BindingFlags.NonPublic)
{
array2 = (from p in type.GetMethods(bindingFlags | BindingFlags.Public)
join q in array2 on p.Name equals q.Name
select p).ToArray<MethodInfo>();
}
Dictionary<Utils.MethodKey, List<MemberInfo>> dictionary = new Dictionary<Utils.MethodKey, List<MemberInfo>>();
foreach (MethodInfo methodInfo in array2)
{
string name = methodInfo.Name;
Utils.MethodKey key = new Utils.MethodKey
{
Name = name,
IsStatic = methodInfo.IsStatic
};
List<MemberInfo> list2;
if (dictionary.TryGetValue(key, out list2))
{
list2.Add(methodInfo);
}
else if ((!methodInfo.IsSpecialName || ((!(methodInfo.Name == "get_Item") || methodInfo.GetParameters().Length != 1) && (!(methodInfo.Name == "set_Item") || methodInfo.GetParameters().Length != 2)) || methodInfo.GetParameters()[0].ParameterType.IsAssignableFrom(typeof(string))) && ((!name.StartsWith("add_") && !name.StartsWith("remove_")) || !methodInfo.IsSpecialName))
{
if (name.StartsWith("op_") && methodInfo.IsSpecialName)
{
if (InternalGlobals.supportOp.ContainsKey(name))
{
if (list2 == null)
{
list2 = new List<MemberInfo>();
dictionary.Add(key, list2);
}
list2.Add(methodInfo);
}
}
else if (name.StartsWith("get_") && methodInfo.IsSpecialName && methodInfo.GetParameters().Length != 1)
{
string text = methodInfo.Name.Substring(4);
Lua.xlua_pushasciistring(L, text);
objectTranslator.PushFixCSFunction(L, new lua_CSFunction(objectTranslator.methodWrapsCache._GenMethodWrap(methodInfo.DeclaringType, text, new MethodBase[]
{
methodInfo
}, false).Call));
Lua.lua_rawset(L, methodInfo.IsStatic ? cls_getter : obj_getter);
}
else if (name.StartsWith("set_") && methodInfo.IsSpecialName && methodInfo.GetParameters().Length != 2)
{
string text2 = methodInfo.Name.Substring(4);
Lua.xlua_pushasciistring(L, text2);
objectTranslator.PushFixCSFunction(L, new lua_CSFunction(objectTranslator.methodWrapsCache._GenMethodWrap(methodInfo.DeclaringType, text2, new MethodBase[]
{
methodInfo
}, false).Call));
Lua.lua_rawset(L, methodInfo.IsStatic ? cls_setter : obj_setter);
}
else if (!(name == ".ctor") || !methodInfo.IsConstructor)
{
if (list2 == null)
{
list2 = new List<MemberInfo>();
dictionary.Add(key, list2);
}
list2.Add(methodInfo);
}
}
}
IEnumerable<MethodInfo> extensionMethodsOf = Utils.GetExtensionMethodsOf(type);
if (extensionMethodsOf != null)
{
foreach (MethodInfo methodInfo2 in extensionMethodsOf)
{
Utils.MethodKey key2 = new Utils.MethodKey
{
Name = methodInfo2.Name,
IsStatic = false
};
List<MemberInfo> list3;
if (dictionary.TryGetValue(key2, out list3))
{
list3.Add(methodInfo2);
}
else
{
list3 = new List<MemberInfo>
{
methodInfo2
};
dictionary.Add(key2, list3);
}
}
}
foreach (KeyValuePair<Utils.MethodKey, List<MemberInfo>> keyValuePair in dictionary)
{
if (keyValuePair.Key.Name.StartsWith("op_"))
{
Lua.xlua_pushasciistring(L, InternalGlobals.supportOp[keyValuePair.Key.Name]);
objectTranslator.PushFixCSFunction(L, new lua_CSFunction(objectTranslator.methodWrapsCache._GenMethodWrap(type, keyValuePair.Key.Name, keyValuePair.Value.ToArray(), false).Call));
Lua.lua_rawset(L, obj_meta);
}
else
{
Lua.xlua_pushasciistring(L, keyValuePair.Key.Name);
objectTranslator.PushFixCSFunction(L, new lua_CSFunction(objectTranslator.methodWrapsCache._GenMethodWrap(type, keyValuePair.Key.Name, keyValuePair.Value.ToArray(), false).Call));
Lua.lua_rawset(L, keyValuePair.Key.IsStatic ? cls_field : obj_field);
}
}
}
public static void loadUpvalue(IntPtr L, Type type, string metafunc, int index)
{
ObjectTranslator objectTranslator = ObjectTranslatorPool.Instance.Find(L);
Lua.xlua_pushasciistring(L, metafunc);
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
objectTranslator.Push(L, type);
Lua.lua_rawget(L, -2);
Lua.lua_remove(L, -2);
for (int i = 1; i <= index; i++)
{
Lua.lua_getupvalue(L, -i, i);
if (Lua.lua_isnil(L, -1))
{
Lua.lua_pop(L, 1);
Lua.lua_newtable(L);
Lua.lua_pushvalue(L, -1);
Lua.lua_setupvalue(L, -i - 2, i);
}
}
for (int j = 0; j < index; j++)
{
Lua.lua_remove(L, -2);
}
}
public static void RegisterEnumType(IntPtr L, Type type)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
foreach (string text in Enum.GetNames(type))
{
Utils.RegisterObject(L, translator, -4, text, Enum.Parse(type, text));
}
}
public static void MakePrivateAccessible(IntPtr L, Type type)
{
Lua.lua_checkstack(L, 20);
int newTop = Lua.lua_gettop(L);
Lua.luaL_getmetatable(L, type.FullName);
if (Lua.lua_isnil(L, -1))
{
Lua.lua_settop(L, newTop);
throw new Exception("can not find the metatable for " + ((type != null) ? type.ToString() : null));
}
int obj_meta = Lua.lua_gettop(L);
Utils.LoadCSTable(L, type);
if (Lua.lua_isnil(L, -1))
{
Lua.lua_settop(L, newTop);
throw new Exception("can not find the class for " + ((type != null) ? type.ToString() : null));
}
int cls_field = Lua.lua_gettop(L);
Utils.loadUpvalue(L, type, "LuaIndexs", 2);
int obj_getter = Lua.lua_gettop(L);
Utils.loadUpvalue(L, type, "LuaIndexs", 1);
int obj_field = Lua.lua_gettop(L);
Utils.loadUpvalue(L, type, "LuaNewIndexs", 1);
int obj_setter = Lua.lua_gettop(L);
Utils.loadUpvalue(L, type, "LuaClassIndexs", 1);
int cls_getter = Lua.lua_gettop(L);
Utils.loadUpvalue(L, type, "LuaClassNewIndexs", 1);
int cls_setter = Lua.lua_gettop(L);
lua_CSFunction lua_CSFunction;
lua_CSFunction lua_CSFunction2;
Utils.makeReflectionWrap(L, type, cls_field, cls_getter, cls_setter, obj_field, obj_getter, obj_setter, obj_meta, out lua_CSFunction, out lua_CSFunction2, BindingFlags.NonPublic);
Lua.lua_settop(L, newTop);
foreach (Type type2 in type.GetNestedTypes(BindingFlags.NonPublic))
{
if ((type2.IsAbstract() || !typeof(Delegate).IsAssignableFrom(type2)) && !type2.IsGenericTypeDefinition())
{
ObjectTranslatorPool.Instance.Find(L).TryDelayWrapLoader(L, type2);
Utils.MakePrivateAccessible(L, type2);
}
}
}
[MonoPInvokeCallback(typeof(lua_CSFunction))]
internal static int LazyReflectionCall(IntPtr L)
{
int result;
try
{
ObjectTranslator objectTranslator = ObjectTranslatorPool.Instance.Find(L);
Type type;
objectTranslator.Get<Type>(L, Lua.xlua_upvalueindex(1), out type);
LazyMemberTypes lazyMemberTypes = (LazyMemberTypes)Lua.xlua_tointeger(L, Lua.xlua_upvalueindex(2));
string memberName = Lua.lua_tostring(L, Lua.xlua_upvalueindex(3));
bool flag = Lua.lua_toboolean(L, Lua.xlua_upvalueindex(4));
lua_CSFunction lua_CSFunction;
switch (lazyMemberTypes)
{
case LazyMemberTypes.Method:
{
MemberInfo[] member = type.GetMember(memberName);
if (member == null || member.Length == 0)
{
string str = "can not find ";
string memberName5 = memberName;
string str2 = " for ";
Type type2 = type;
return Lua.luaL_error(L, str + memberName5 + str2 + ((type2 != null) ? type2.ToString() : null));
}
IEnumerable<MemberInfo> enumerable = member;
if (!flag)
{
IEnumerable<MethodInfo> extensionMethodsOf = Utils.GetExtensionMethodsOf(type);
if (extensionMethodsOf != null)
{
enumerable = enumerable.Concat((from m in extensionMethodsOf
where m.Name == memberName
select m).Cast<MemberInfo>());
}
}
lua_CSFunction = new lua_CSFunction(objectTranslator.methodWrapsCache._GenMethodWrap(type, memberName, enumerable.ToArray<MemberInfo>(), false).Call);
if (flag)
{
Utils.LoadCSTable(L, type);
}
else
{
Utils.loadUpvalue(L, type, "LuaIndexs", 1);
}
if (Lua.lua_isnil(L, -1))
{
string str3 = "can not find the meta info for ";
Type type3 = type;
return Lua.luaL_error(L, str3 + ((type3 != null) ? type3.ToString() : null));
}
break;
}
case LazyMemberTypes.FieldGet:
case LazyMemberTypes.FieldSet:
{
FieldInfo field = type.GetField(memberName);
if (field == null)
{
string str4 = "can not find ";
string memberName2 = memberName;
string str5 = " for ";
Type type4 = type;
return Lua.luaL_error(L, str4 + memberName2 + str5 + ((type4 != null) ? type4.ToString() : null));
}
if (flag)
{
if (lazyMemberTypes == LazyMemberTypes.FieldGet)
{
Utils.loadUpvalue(L, type, "LuaClassIndexs", 1);
}
else
{
Utils.loadUpvalue(L, type, "LuaClassNewIndexs", 1);
}
}
else if (lazyMemberTypes == LazyMemberTypes.FieldGet)
{
Utils.loadUpvalue(L, type, "LuaIndexs", 2);
}
else
{
Utils.loadUpvalue(L, type, "LuaNewIndexs", 1);
}
lua_CSFunction = ((lazyMemberTypes == LazyMemberTypes.FieldGet) ? Utils.genFieldGetter(type, field) : Utils.genFieldSetter(type, field));
break;
}
case LazyMemberTypes.PropertyGet:
case LazyMemberTypes.PropertySet:
{
PropertyInfo property = type.GetProperty(memberName);
if (property == null)
{
string str6 = "can not find ";
string memberName3 = memberName;
string str7 = " for ";
Type type5 = type;
return Lua.luaL_error(L, str6 + memberName3 + str7 + ((type5 != null) ? type5.ToString() : null));
}
if (flag)
{
if (lazyMemberTypes == LazyMemberTypes.PropertyGet)
{
Utils.loadUpvalue(L, type, "LuaClassIndexs", 1);
}
else
{
Utils.loadUpvalue(L, type, "LuaClassNewIndexs", 1);
}
}
else if (lazyMemberTypes == LazyMemberTypes.PropertyGet)
{
Utils.loadUpvalue(L, type, "LuaIndexs", 2);
}
else
{
Utils.loadUpvalue(L, type, "LuaNewIndexs", 1);
}
if (Lua.lua_isnil(L, -1))
{
string str8 = "can not find the meta info for ";
Type type6 = type;
return Lua.luaL_error(L, str8 + ((type6 != null) ? type6.ToString() : null));
}
lua_CSFunction = new lua_CSFunction(objectTranslator.methodWrapsCache._GenMethodWrap(property.DeclaringType, property.Name, new MethodBase[]
{
(lazyMemberTypes == LazyMemberTypes.PropertyGet) ? property.GetGetMethod() : property.GetSetMethod()
}, false).Call);
break;
}
case LazyMemberTypes.Event:
{
EventInfo @event = type.GetEvent(memberName);
if (@event == null)
{
string str9 = "can not find ";
string memberName4 = memberName;
string str10 = " for ";
Type type7 = type;
return Lua.luaL_error(L, str9 + memberName4 + str10 + ((type7 != null) ? type7.ToString() : null));
}
if (flag)
{
Utils.LoadCSTable(L, type);
}
else
{
Utils.loadUpvalue(L, type, "LuaIndexs", 1);
}
if (Lua.lua_isnil(L, -1))
{
string str11 = "can not find the meta info for ";
Type type8 = type;
return Lua.luaL_error(L, str11 + ((type8 != null) ? type8.ToString() : null));
}
lua_CSFunction = objectTranslator.methodWrapsCache.GetEventWrap(type, @event.Name);
break;
}
default:
return Lua.luaL_error(L, "unsupport member type" + lazyMemberTypes.ToString());
}
Lua.xlua_pushasciistring(L, memberName);
objectTranslator.PushFixCSFunction(L, lua_CSFunction);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
result = lua_CSFunction(L);
}
catch (Exception ex)
{
string str12 = "c# exception in LazyReflectionCall:";
Exception ex2 = ex;
result = Lua.luaL_error(L, str12 + ((ex2 != null) ? ex2.ToString() : null));
}
return result;
}
public static void ReflectionWrap(IntPtr L, Type type, bool privateAccessible)
{
Lua.lua_checkstack(L, 20);
Lua.lua_gettop(L);
ObjectTranslator objectTranslator = ObjectTranslatorPool.Instance.Find(L);
Lua.luaL_getmetatable(L, type.FullName);
if (Lua.lua_isnil(L, -1))
{
Lua.lua_pop(L, 1);
Lua.luaL_newmetatable(L, type.FullName);
}
Lua.lua_pushlightuserdata(L, Lua.xlua_tag());
Lua.lua_pushnumber(L, 1.0);
Lua.lua_rawset(L, -3);
int num = Lua.lua_gettop(L);
Lua.lua_newtable(L);
int index = Lua.lua_gettop(L);
Lua.lua_newtable(L);
int num2 = Lua.lua_gettop(L);
Lua.lua_newtable(L);
int num3 = Lua.lua_gettop(L);
Lua.lua_newtable(L);
int num4 = Lua.lua_gettop(L);
Lua.lua_newtable(L);
int num5 = Lua.lua_gettop(L);
Utils.SetCSTable(L, type, num5);
Lua.lua_newtable(L);
int num6 = Lua.lua_gettop(L);
Lua.lua_newtable(L);
int num7 = Lua.lua_gettop(L);
lua_CSFunction func;
lua_CSFunction func2;
Utils.makeReflectionWrap(L, type, num5, num6, num7, num2, num3, num4, num, out func, out func2, privateAccessible ? (BindingFlags.Public | BindingFlags.NonPublic) : BindingFlags.Public);
Lua.xlua_pushasciistring(L, "__gc");
Lua.lua_pushstdcallcfunction(L, objectTranslator.metaFunctions.GcMeta, 0);
Lua.lua_rawset(L, num);
Lua.xlua_pushasciistring(L, "__tostring");
Lua.lua_pushstdcallcfunction(L, objectTranslator.metaFunctions.ToStringMeta, 0);
Lua.lua_rawset(L, num);
Lua.xlua_pushasciistring(L, "__index");
Lua.lua_pushvalue(L, num2);
Lua.lua_pushvalue(L, num3);
objectTranslator.PushFixCSFunction(L, func);
objectTranslator.PushAny(L, type.BaseType());
Lua.xlua_pushasciistring(L, "LuaIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
Lua.lua_pushnil(L);
Lua.gen_obj_indexer(L);
Lua.xlua_pushasciistring(L, "LuaIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
objectTranslator.Push(L, type);
Lua.lua_pushvalue(L, -3);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
Lua.lua_rawset(L, num);
Lua.xlua_pushasciistring(L, "__newindex");
Lua.lua_pushvalue(L, num4);
objectTranslator.PushFixCSFunction(L, func2);
objectTranslator.Push(L, type.BaseType());
Lua.xlua_pushasciistring(L, "LuaNewIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
Lua.lua_pushnil(L);
Lua.gen_obj_newindexer(L);
Lua.xlua_pushasciistring(L, "LuaNewIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
objectTranslator.Push(L, type);
Lua.lua_pushvalue(L, -3);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
Lua.lua_rawset(L, num);
Lua.xlua_pushasciistring(L, "UnderlyingSystemType");
objectTranslator.PushAny(L, type);
Lua.lua_rawset(L, num5);
if (type != null && type.IsEnum())
{
Lua.xlua_pushasciistring(L, "__CastFrom");
objectTranslator.PushFixCSFunction(L, Utils.genEnumCastFrom(type));
Lua.lua_rawset(L, num5);
}
Lua.xlua_pushasciistring(L, "__index");
Lua.lua_pushvalue(L, num6);
Lua.lua_pushvalue(L, num5);
objectTranslator.Push(L, type.BaseType());
Lua.xlua_pushasciistring(L, "LuaClassIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
Lua.gen_cls_indexer(L);
Lua.xlua_pushasciistring(L, "LuaClassIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
objectTranslator.Push(L, type);
Lua.lua_pushvalue(L, -3);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
Lua.lua_rawset(L, index);
Lua.xlua_pushasciistring(L, "__newindex");
Lua.lua_pushvalue(L, num7);
objectTranslator.Push(L, type.BaseType());
Lua.xlua_pushasciistring(L, "LuaClassNewIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
Lua.gen_cls_newindexer(L);
Lua.xlua_pushasciistring(L, "LuaClassNewIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
objectTranslator.Push(L, type);
Lua.lua_pushvalue(L, -3);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
Lua.lua_rawset(L, index);
lua_CSFunction lua_CSFunction = typeof(Delegate).IsAssignableFrom(type) ? objectTranslator.metaFunctions.DelegateCtor : objectTranslator.methodWrapsCache.GetConstructorWrap(type);
if (lua_CSFunction == null)
{
lua_CSFunction = delegate(IntPtr LL)
{
string str = "No constructor for ";
Type type2 = type;
return Lua.luaL_error(LL, str + ((type2 != null) ? type2.ToString() : null));
};
}
Lua.xlua_pushasciistring(L, "__call");
objectTranslator.PushFixCSFunction(L, lua_CSFunction);
Lua.lua_rawset(L, index);
Lua.lua_pushvalue(L, index);
Lua.lua_setmetatable(L, num5);
Lua.lua_pop(L, 8);
}
public static void BeginObjectRegister(Type type, IntPtr L, ObjectTranslator translator, int meta_count, int method_count, int getter_count, int setter_count, int type_id = -1)
{
if (type == null)
{
if (type_id == -1)
{
throw new Exception("Fatal: must provide a type of type_id");
}
Lua.xlua_rawgeti(L, LuaIndexes.LUA_REGISTRYINDEX, (long)type_id);
}
else
{
Lua.luaL_getmetatable(L, type.FullName);
if (Lua.lua_isnil(L, -1))
{
Lua.lua_pop(L, 1);
Lua.luaL_newmetatable(L, type.FullName);
}
}
Lua.lua_pushlightuserdata(L, Lua.xlua_tag());
Lua.lua_pushnumber(L, 1.0);
Lua.lua_rawset(L, -3);
if ((type == null || !translator.HasCustomOp(type)) && type != typeof(decimal))
{
Lua.xlua_pushasciistring(L, "__gc");
Lua.lua_pushstdcallcfunction(L, translator.metaFunctions.GcMeta, 0);
Lua.lua_rawset(L, -3);
}
Lua.xlua_pushasciistring(L, "__tostring");
Lua.lua_pushstdcallcfunction(L, translator.metaFunctions.ToStringMeta, 0);
Lua.lua_rawset(L, -3);
if (method_count == 0)
{
Lua.lua_pushnil(L);
}
else
{
Lua.lua_createtable(L, 0, method_count);
}
if (getter_count == 0)
{
Lua.lua_pushnil(L);
}
else
{
Lua.lua_createtable(L, 0, getter_count);
}
if (setter_count == 0)
{
Lua.lua_pushnil(L);
return;
}
Lua.lua_createtable(L, 0, setter_count);
}
private static int abs_idx(int top, int idx)
{
if (idx <= 0)
{
return top + idx + 1;
}
return idx;
}
public static void EndObjectRegister(Type type, IntPtr L, ObjectTranslator translator, lua_CSFunction csIndexer, lua_CSFunction csNewIndexer, Type base_type, lua_CSFunction arrayIndexer, lua_CSFunction arrayNewIndexer)
{
int top = Lua.lua_gettop(L);
int index = Utils.abs_idx(top, -4);
int index2 = Utils.abs_idx(top, -3);
int index3 = Utils.abs_idx(top, -2);
int index4 = Utils.abs_idx(top, -1);
Lua.xlua_pushasciistring(L, "__index");
Lua.lua_pushvalue(L, index2);
Lua.lua_pushvalue(L, index3);
if (csIndexer == null)
{
Lua.lua_pushnil(L);
}
else
{
Lua.lua_pushstdcallcfunction(L, csIndexer, 0);
}
translator.Push(L, (type == null) ? base_type : type.BaseType());
Lua.xlua_pushasciistring(L, "LuaIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
if (arrayIndexer == null)
{
Lua.lua_pushnil(L);
}
else
{
Lua.lua_pushstdcallcfunction(L, arrayIndexer, 0);
}
Lua.gen_obj_indexer(L);
if (type != null)
{
Lua.xlua_pushasciistring(L, "LuaIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
translator.Push(L, type);
Lua.lua_pushvalue(L, -3);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
}
Lua.lua_rawset(L, index);
Lua.xlua_pushasciistring(L, "__newindex");
Lua.lua_pushvalue(L, index4);
if (csNewIndexer == null)
{
Lua.lua_pushnil(L);
}
else
{
Lua.lua_pushstdcallcfunction(L, csNewIndexer, 0);
}
translator.Push(L, (type == null) ? base_type : type.BaseType());
Lua.xlua_pushasciistring(L, "LuaNewIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
if (arrayNewIndexer == null)
{
Lua.lua_pushnil(L);
}
else
{
Lua.lua_pushstdcallcfunction(L, arrayNewIndexer, 0);
}
Lua.gen_obj_newindexer(L);
if (type != null)
{
Lua.xlua_pushasciistring(L, "LuaNewIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
translator.Push(L, type);
Lua.lua_pushvalue(L, -3);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
}
Lua.lua_rawset(L, index);
Lua.lua_pop(L, 4);
}
public static void RegisterFunc(IntPtr L, int idx, string name, lua_CSFunction func)
{
idx = Utils.abs_idx(Lua.lua_gettop(L), idx);
Lua.xlua_pushasciistring(L, name);
Lua.lua_pushstdcallcfunction(L, func, 0);
Lua.lua_rawset(L, idx);
}
public static void RegisterLazyFunc(IntPtr L, int idx, string name, Type type, LazyMemberTypes memberType, bool isStatic)
{
idx = Utils.abs_idx(Lua.lua_gettop(L), idx);
Lua.xlua_pushasciistring(L, name);
ObjectTranslatorPool.Instance.Find(L).PushAny(L, type);
Lua.xlua_pushinteger(L, (int)memberType);
Lua.lua_pushstring(L, name);
Lua.lua_pushboolean(L, isStatic);
Lua.lua_pushstdcallcfunction(L, InternalGlobals.LazyReflectionWrap, 4);
Lua.lua_rawset(L, idx);
}
public static void RegisterObject(IntPtr L, ObjectTranslator translator, int idx, string name, object obj)
{
idx = Utils.abs_idx(Lua.lua_gettop(L), idx);
Lua.xlua_pushasciistring(L, name);
translator.PushAny(L, obj);
Lua.lua_rawset(L, idx);
}
public static void BeginClassRegister(Type type, IntPtr L, lua_CSFunction creator, int class_field_count, int static_getter_count, int static_setter_count)
{
ObjectTranslator objectTranslator = ObjectTranslatorPool.Instance.Find(L);
Lua.lua_createtable(L, 0, class_field_count);
Lua.xlua_pushasciistring(L, "UnderlyingSystemType");
objectTranslator.PushAny(L, type);
Lua.lua_rawset(L, -3);
int num = Lua.lua_gettop(L);
Utils.SetCSTable(L, type, num);
Lua.lua_createtable(L, 0, 3);
int index = Lua.lua_gettop(L);
if (creator != null)
{
Lua.xlua_pushasciistring(L, "__call");
Lua.lua_pushstdcallcfunction(L, creator, 0);
Lua.lua_rawset(L, -3);
}
if (static_getter_count == 0)
{
Lua.lua_pushnil(L);
}
else
{
Lua.lua_createtable(L, 0, static_getter_count);
}
if (static_setter_count == 0)
{
Lua.lua_pushnil(L);
}
else
{
Lua.lua_createtable(L, 0, static_setter_count);
}
Lua.lua_pushvalue(L, index);
Lua.lua_setmetatable(L, num);
}
public static void EndClassRegister(Type type, IntPtr L, ObjectTranslator translator)
{
int top = Lua.lua_gettop(L);
int index = Utils.abs_idx(top, -4);
int index2 = Utils.abs_idx(top, -2);
int index3 = Utils.abs_idx(top, -1);
int index4 = Utils.abs_idx(top, -3);
Lua.xlua_pushasciistring(L, "__index");
Lua.lua_pushvalue(L, index2);
Lua.lua_pushvalue(L, index);
translator.Push(L, type.BaseType());
Lua.xlua_pushasciistring(L, "LuaClassIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
Lua.gen_cls_indexer(L);
Lua.xlua_pushasciistring(L, "LuaClassIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
translator.Push(L, type);
Lua.lua_pushvalue(L, -3);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
Lua.lua_rawset(L, index4);
Lua.xlua_pushasciistring(L, "__newindex");
Lua.lua_pushvalue(L, index3);
translator.Push(L, type.BaseType());
Lua.xlua_pushasciistring(L, "LuaClassNewIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
Lua.gen_cls_newindexer(L);
Lua.xlua_pushasciistring(L, "LuaClassNewIndexs");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
translator.Push(L, type);
Lua.lua_pushvalue(L, -3);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
Lua.lua_rawset(L, index4);
Lua.lua_pop(L, 4);
}
private static List<string> getPathOfType(Type type)
{
List<string> list = new List<string>();
if (type.Namespace != null)
{
list.AddRange(type.Namespace.Split(new char[]
{
'.'
}));
}
string text = type.ToString().Substring((type.Namespace == null) ? 0 : (type.Namespace.Length + 1));
if (type.IsNested)
{
list.AddRange(text.Split(new char[]
{
'+'
}));
}
else
{
list.Add(text);
}
return list;
}
public static void LoadCSTable(IntPtr L, Type type)
{
int newTop = Lua.lua_gettop(L);
Lua.xlua_pushasciistring(L, "xlua_csharp_namespace");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
List<string> pathOfType = Utils.getPathOfType(type);
for (int i = 0; i < pathOfType.Count; i++)
{
Lua.xlua_pushasciistring(L, pathOfType[i]);
if (Lua.xlua_pgettable(L, -2) != 0)
{
Lua.lua_settop(L, newTop);
Lua.lua_pushnil(L);
return;
}
if (!Lua.lua_istable(L, -1) && i < pathOfType.Count - 1)
{
Lua.lua_settop(L, newTop);
Lua.lua_pushnil(L);
return;
}
Lua.lua_remove(L, -2);
}
}
public static void SetCSTable(IntPtr L, Type type, int cls_table)
{
int num = Lua.lua_gettop(L);
cls_table = Utils.abs_idx(num, cls_table);
Lua.xlua_pushasciistring(L, "xlua_csharp_namespace");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
List<string> pathOfType = Utils.getPathOfType(type);
for (int i = 0; i < pathOfType.Count - 1; i++)
{
Lua.xlua_pushasciistring(L, pathOfType[i]);
if (Lua.xlua_pgettable(L, -2) != 0)
{
string str = Lua.lua_tostring(L, -1);
Lua.lua_settop(L, num);
throw new Exception("SetCSTable for [" + ((type != null) ? type.ToString() : null) + "] error: " + str);
}
if (Lua.lua_isnil(L, -1))
{
Lua.lua_pop(L, 1);
Lua.lua_createtable(L, 0, 0);
Lua.xlua_pushasciistring(L, pathOfType[i]);
Lua.lua_pushvalue(L, -2);
Lua.lua_rawset(L, -4);
}
else if (!Lua.lua_istable(L, -1))
{
Lua.lua_settop(L, num);
throw new Exception("SetCSTable for [" + ((type != null) ? type.ToString() : null) + "] error: ancestors is not a table!");
}
Lua.lua_remove(L, -2);
}
Lua.xlua_pushasciistring(L, pathOfType[pathOfType.Count - 1]);
Lua.lua_pushvalue(L, cls_table);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
Lua.xlua_pushasciistring(L, "xlua_csharp_namespace");
Lua.lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
ObjectTranslatorPool.Instance.Find(L).PushAny(L, type);
Lua.lua_pushvalue(L, cls_table);
Lua.lua_rawset(L, -3);
Lua.lua_pop(L, 1);
}
public static bool IsParamsMatch(MethodInfo delegateMethod, MethodInfo bridgeMethod)
{
if (delegateMethod == null || bridgeMethod == null)
{
return false;
}
if (delegateMethod.ReturnType != bridgeMethod.ReturnType)
{
return false;
}
ParameterInfo[] parameters = delegateMethod.GetParameters();
ParameterInfo[] parameters2 = bridgeMethod.GetParameters();
if (parameters.Length != parameters2.Length)
{
return false;
}
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i].ParameterType != parameters2[i].ParameterType || parameters[i].IsOut != parameters2[i].IsOut)
{
return false;
}
}
int num = parameters.Length - 1;
return num < 0 || parameters[num].IsDefined(typeof(ParamArrayAttribute), false) == parameters2[num].IsDefined(typeof(ParamArrayAttribute), false);
}
public static bool IsSupportedMethod(MethodInfo method)
{
if (!method.ContainsGenericParameters)
{
return true;
}
ParameterInfo[] parameters = method.GetParameters();
Type returnType = method.ReturnType;
bool flag = false;
bool flag2 = !returnType.IsGenericParameter;
for (int i = 0; i < parameters.Length; i++)
{
Type parameterType = parameters[i].ParameterType;
if (parameterType.IsGenericParameter)
{
Type[] genericParameterConstraints = parameterType.GetGenericParameterConstraints();
if (genericParameterConstraints.Length == 0)
{
return false;
}
foreach (Type type in genericParameterConstraints)
{
if (!type.IsClass() || type == typeof(ValueType))
{
return false;
}
}
flag = true;
if (!flag2 && parameterType == returnType)
{
flag2 = true;
}
}
}
return flag && flag2;
}
public static MethodInfo MakeGenericMethodWithConstraints(MethodInfo method)
{
MethodInfo result;
try
{
Type[] genericArguments = method.GetGenericArguments();
Type[] array = new Type[genericArguments.Length];
for (int i = 0; i < genericArguments.Length; i++)
{
Type[] genericParameterConstraints = genericArguments[i].GetGenericParameterConstraints();
array[i] = genericParameterConstraints[0];
}
result = method.MakeGenericMethod(array);
}
catch (Exception)
{
result = null;
}
return result;
}
private static Type getExtendedType(MethodInfo method)
{
Type parameterType = method.GetParameters()[0].ParameterType;
if (!parameterType.IsGenericParameter)
{
return parameterType;
}
Type[] genericParameterConstraints = parameterType.GetGenericParameterConstraints();
if (genericParameterConstraints.Length == 0)
{
throw new InvalidOperationException();
}
Type type = genericParameterConstraints[0];
if (!type.IsClass())
{
throw new InvalidOperationException();
}
return type;
}
public static bool IsStaticPInvokeCSFunction(lua_CSFunction csFunction)
{
return csFunction.Method.IsStatic && Attribute.IsDefined(csFunction.Method, typeof(MonoPInvokeCallbackAttribute));
}
public static bool IsPublic(Type type)
{
if (type.IsNested)
{
return type.IsNestedPublic() && Utils.IsPublic(type.DeclaringType);
}
if (type.IsGenericType())
{
Type[] genericArguments = type.GetGenericArguments();
for (int i = 0; i < genericArguments.Length; i++)
{
if (!Utils.IsPublic(genericArguments[i]))
{
return false;
}
}
}
return type.IsPublic();
}
public const int OBJ_META_IDX = -4;
public const int METHOD_IDX = -3;
public const int GETTER_IDX = -2;
public const int SETTER_IDX = -1;
public const int CLS_IDX = -4;
public const int CLS_META_IDX = -3;
public const int CLS_GETTER_IDX = -2;
public const int CLS_SETTER_IDX = -1;
public const string LuaIndexsFieldName = "LuaIndexs";
public const string LuaNewIndexsFieldName = "LuaNewIndexs";
public const string LuaClassIndexsFieldName = "LuaClassIndexs";
public const string LuaClassNewIndexsFieldName = "LuaClassNewIndexs";
private struct MethodKey
{
public string Name;
public bool IsStatic;
}
}
}
| 32.211798
| 375
| 0.651648
|
43a79293d2d22257ce51beb6e3a09e204fb175fb
| 1,197
|
tsx
|
TypeScript
|
packages/paste-core/utilities/media-object/src/index.tsx
|
sakshamtaneja21/paste
|
8c3623f474832f33080a7e10ac3e173e53fa2e82
|
[
"MIT"
] | null | null | null |
packages/paste-core/utilities/media-object/src/index.tsx
|
sakshamtaneja21/paste
|
8c3623f474832f33080a7e10ac3e173e53fa2e82
|
[
"MIT"
] | null | null | null |
packages/paste-core/utilities/media-object/src/index.tsx
|
sakshamtaneja21/paste
|
8c3623f474832f33080a7e10ac3e173e53fa2e82
|
[
"MIT"
] | null | null | null |
import styled from '@emotion/styled';
import {space, Theme, themeGet} from 'styled-system';
import {MarginProps, PaddingProps} from '@twilio-paste/types';
export interface MediaObjectProps extends Theme {
isCentered?: boolean;
}
const MediaObject = styled.div<MediaObjectProps>`
align-items: ${(props: MediaObjectProps) => (props.isCentered ? 'center' : 'flex-start')};
display: flex;
`;
export interface MediaFigureProps extends Theme {
align?: 'start' | 'end';
spacing?: 'space20' | 'space30';
}
const getMargin = (props: MediaFigureProps): string => {
const direction = props.align === 'end' ? 'left' : 'right';
const spacing = themeGet(`space.${props.spacing}`)(props);
return `margin-${direction}: ${spacing}`;
};
const MediaFigure = styled.div<MediaFigureProps>`
flex-shrink: 0;
${getMargin};
`;
MediaFigure.defaultProps = {
align: 'start',
spacing: 'space20',
};
export interface MediaBodyProps extends Theme, MarginProps, PaddingProps {}
const MediaBody = styled.div<MediaBodyProps>`
flex: 1;
min-width: ${themeGet('minWidths.size0')};
${space};
`;
const Media = {
Object: MediaObject,
Figure: MediaFigure,
Body: MediaBody,
};
export {Media};
| 23.94
| 92
| 0.695071
|
4ceba7ef32d29987f218aafadb72621903be14be
| 8,367
|
py
|
Python
|
ladim2/tracker.py
|
bjornaa/ladim2
|
f6c1be9028ca54370ce33dde25b005d5b0bb4677
|
[
"MIT"
] | null | null | null |
ladim2/tracker.py
|
bjornaa/ladim2
|
f6c1be9028ca54370ce33dde25b005d5b0bb4677
|
[
"MIT"
] | null | null | null |
ladim2/tracker.py
|
bjornaa/ladim2
|
f6c1be9028ca54370ce33dde25b005d5b0bb4677
|
[
"MIT"
] | null | null | null |
"""Tracker – physical particle tracker"""
# ------------------------------------
# tracker.py
# Part of the LADiM Model
#
# Bjørn Ådlandsvik, <bjorn@imr.no>
# Institute of Marine Research
#
# Licensed under the MIT license
# ------------------------------------
import logging
from typing import Any
import numpy as np
import numba # type: ignore
from ladim2.forcing import BaseForce
ParticleArray = np.ndarray # 1D array, one element per particle
Velocity = tuple[ParticleArray, ParticleArray]
PARALLEL = False
DEBUG = False
logger = logging.getLogger(__name__)
if DEBUG:
logger.setLevel(logging.DEBUG)
class Tracker:
"""The physical particle tracking kernel"""
def __init__(
self,
advection: str, # EF, RK2, or RK4
diffusion: float = 0.0,
vertdiff: float = 0.0,
vertical_advection: bool = False,
*,
modules: dict[str, Any]
# modules: Optional[dict[str, Any]] = None,
) -> None:
logger.info("Initiating the particle tracker")
self.modules = modules
self.dt = modules["time"].dt / np.timedelta64(1, "s")
self.advection = advection # Name of advection method
logger.info(" Advection method: %s", advection)
# advect <- requested advection method
# advection = string "EF", "RK2", "RK4"
# advect = the actual method
if self.advection:
self.advect = getattr(self, self.advection)
self.vertical_advection = vertical_advection
if vertical_advection:
logger.info(" Vertical advection activated")
self.diffusion = bool(diffusion)
self.D = diffusion
if self.diffusion:
logger.info(" Horizontal diffusion: %s m²/s", diffusion)
self.vertdiff = bool(vertdiff)
self.Dz = vertdiff
if self.vertdiff:
logger.info(" Vertical diffusion: %s m²/s", vertdiff)
def update(self) -> None:
"""Move the particles one time step"""
state = self.modules["state"]
grid = self.modules["grid"]
force = self.modules["forcing"]
X, Y, Z = state.X, state.Y, state.Z
self.dx, self.dy = grid.metric(X, Y)
self.xmin = grid.xmin + 0.01
self.xmax = grid.xmax - 0.01
self.ymin = grid.ymin + 0.01
self.ymax = grid.ymax - 0.01
U = np.zeros_like(X)
V = np.zeros_like(Y)
# --- Advection ---
if self.advection:
Uadv, Vadv = self.advect(X, Y, Z, force)
U += Uadv
V += Vadv
# --- Diffusion ---
if self.diffusion:
Udiff, Vdiff = self.diffuse(num_particles=len(X))
U += Udiff
V += Vdiff
# --- Move the particles
# New position, if OK
X1 = X + U * self.dt / self.dx
Y1 = Y + V * self.dt / self.dy
# Kill particles trying to move out of the grid
out_of_grid = ~grid.ingrid(X1, Y1)
state.alive[out_of_grid] = False
state.active[out_of_grid] = False # Not necessary if they are removed
# Do not move inactive particles
inactive = ~state.active
X1[inactive] = X[inactive]
Y1[inactive] = Y[inactive]
# Land, boundary treatment. Do not move the particles onto land
# Consider a sequence of different actions
onland = ~grid.atsea(X1, Y1)
X1[onland] = X[onland]
Y1[onland] = Y[onland]
# Update the particle positions
state["X"] = X1
state["Y"] = Y1
# --- Vertical movement ---
# Sample the depth level
h = None
if self.vertdiff or self.vertical_advection:
# if hasattr(grid, "sample_depth") and callable(grid.sample_depth):
# h = grid.sample_depth(X, Y)
# elif hasattr(grid, "depth") and callable(grid.depth):
# h = grid.depth(X, Y)
h = grid.depth(X, Y)
# Diffusion
if self.vertdiff:
W = self.diffuse_vert(num_particles=len(X))
Z += W * self.dt
# Advection
if self.vertical_advection:
W = force.variables["w"]
Z += W * self.dt
# Reflexive boundary conditions at surface
Z[Z < 0] *= -1
# Reflexive boundary conditions at bottom
if h is not None:
below_seabed = Z > h
Z[below_seabed] = 2 * h[below_seabed] - Z[below_seabed]
# Update particle positions
state["Z"] = Z
def EF(
self, X: ParticleArray, Y: ParticleArray, Z: ParticleArray, force: BaseForce
) -> Velocity:
"""Euler-Forward advective velocity"""
U, V = force.velocity(X, Y, Z)
return U, V
def RK2(
self, X: ParticleArray, Y: ParticleArray, Z: ParticleArray, force: BaseForce
) -> Velocity:
"""Runge-Kutta second order = Heun scheme
This version does not sample velocities outside the grid
"""
dt = self.dt
dtdx = dt / self.dx
dtdy = dt / self.dy
U, V = force.velocity(X, Y, Z)
X1, Y1 = RKstep(X, Y, U, V, 0.5, dtdx, dtdy)
clip(X, Y, self.xmin, self.xmax, self.ymin, self.ymax)
return force.velocity(X1, Y1, Z, fractional_step=0.5)
def RK4(
self, X: ParticleArray, Y: ParticleArray, Z: ParticleArray, force: BaseForce
) -> Velocity:
"""Runge-Kutta fourth order advection
This version does not sample velocities outside the grid
"""
dt = self.dt
dtdx = dt / self.dx
dtdy = dt / self.dy
xmin, xmax, ymin, ymax = self.xmin, self.xmax, self.ymin, self.ymax
U1, V1 = force.velocity(X, Y, Z, fractional_step=0.0)
X1, Y1 = RKstep(X, Y, U1, V1, 0.5, dtdx, dtdy)
clip(X1, Y1, xmin, xmax, ymin, ymax)
U2, V2 = force.velocity(X1, Y1, Z, fractional_step=0.5)
X2, Y2 = RKstep(X, Y, U2, V2, 0.5, dtdx, dtdy)
clip(X2, Y2, xmin, xmax, ymin, ymax)
U3, V3 = force.velocity(X2, Y2, Z, fractional_step=0.5)
X3, Y3 = RKstep(X, Y, U3, V3, 1.0, dtdx, dtdy)
clip(X3, Y3, xmin, xmax, ymin, ymax)
U4, V4 = force.velocity(X3, Y3, Z, fractional_step=1.0)
return RK4avg(U1, U2, U3, U4), RK4avg(V1, V2, V3, V4)
def diffuse(self, num_particles: int) -> Velocity:
"""Random walk diffusion"""
# Diffusive velocity
stddev = (2 * self.D / self.dt) ** 0.5
U = stddev * np.random.normal(size=num_particles)
V = stddev * np.random.normal(size=num_particles)
return U, V
def diffuse_vert(self, num_particles: int) -> ParticleArray:
"""Random walk diffusion"""
# Diffusive velocity
stddev = (2 * self.Dz / self.dt) ** 0.5
W: ParticleArray = stddev * np.random.normal(size=num_particles)
return W
@numba.njit(parallel=PARALLEL)
def RKstep0(
X: ParticleArray,
Y: ParticleArray,
U: ParticleArray,
V: ParticleArray,
frac: float,
dtdx: ParticleArray,
dtdy: ParticleArray,
) -> tuple[ParticleArray, ParticleArray]:
Xp = X + frac * U * dtdx
Yp = Y + frac * V * dtdy
return Xp, Yp
@numba.njit(parallel=False)
def RKstep1(
X: ParticleArray,
Y: ParticleArray,
U: ParticleArray,
V: ParticleArray,
frac: float,
dtdx: ParticleArray,
dtdy: ParticleArray,
) -> Velocity:
"""Do a forward Runge-Kutta (partial) step"""
N = len(X)
Xp = np.empty(N)
Yp = np.empty(N)
for i in numba.prange(N):
Xp[i] = X[i] + frac * U[i] * dtdx[i]
Yp[i] = Y[i] + frac * V[i] * dtdy[i]
return X, Y
RKstep = RKstep1
@numba.njit(parallel=PARALLEL)
def clip(
X: ParticleArray,
Y: ParticleArray,
xmin: float,
xmax: float,
ymin: float,
ymax: float,
) -> None:
"""Clip particle positions in place towards forcing domain boundary"""
for p in numba.prange(len(X)):
X[p] = max(min(X[p], xmax), xmin)
Y[p] = max(min(Y[p], ymax), ymin)
@numba.njit(parallel=PARALLEL)
def RK4avg(
U1: ParticleArray, U2: ParticleArray, U3: ParticleArray, U4: ParticleArray
) -> ParticleArray:
"""Average velocity component for Runge-Kutta 4-th order"""
return (U1 + 2 * U2 + 2 * U3 + U4) / 6.0
| 27.983278
| 84
| 0.565077
|
b4e62088b2e86af4c22405a29f661d8526f432d8
| 1,342
|
rb
|
Ruby
|
app/models/member.rb
|
mrfarmer777/byteclub
|
8ac0ca9935d458f832e29c609fd10b1bd3a1da8e
|
[
"MIT"
] | null | null | null |
app/models/member.rb
|
mrfarmer777/byteclub
|
8ac0ca9935d458f832e29c609fd10b1bd3a1da8e
|
[
"MIT"
] | null | null | null |
app/models/member.rb
|
mrfarmer777/byteclub
|
8ac0ca9935d458f832e29c609fd10b1bd3a1da8e
|
[
"MIT"
] | 1
|
2021-02-28T20:34:56.000Z
|
2021-02-28T20:34:56.000Z
|
class Member < ApplicationRecord
has_secure_password
validates :email, uniqueness: true
validates :uid, uniqueness: true
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create
has_many :member_meetings
has_many :meetings, through: :member_meetings
has_many :projects
has_many :announcements
def update_status
new_stat=""
if self.meetings.count>=(Meeting.past.count/2)
new_stat="active"
else
new_stat="potatoe"
end
self.update(status: new_stat)
end
def year_from_email
#updates the user's year as a function of their email, not yet implemented
grad_year=(self.email.split("@").first/10000).to_i
end
def self.from_omniauth(auth)
# Creates a new user only if it doesn't exist
where(provider: auth.provider, uid: auth.uid).first_or_create do |member|
member.provider=auth.provider
member.uid = auth.uid
member.email=auth.info.email
member.username = auth.info.name
member.name=auth.info.name
member.google_token= auth.credentials.token
member.password=SecureRandom.hex
member.save
end
end
end
| 27.958333
| 100
| 0.597615
|
753fc38e791677bdb4bbec5be84b0a241536b2f1
| 1,614
|
asm
|
Assembly
|
programs/oeis/168/A168668.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | 1
|
2021-03-15T11:38:20.000Z
|
2021-03-15T11:38:20.000Z
|
programs/oeis/168/A168668.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | null | null | null |
programs/oeis/168/A168668.asm
|
karttu/loda
|
9c3b0fc57b810302220c044a9d17db733c76a598
|
[
"Apache-2.0"
] | null | null | null |
; A168668: a(n) = n*(2 + 5*n).
; 0,7,24,51,88,135,192,259,336,423,520,627,744,871,1008,1155,1312,1479,1656,1843,2040,2247,2464,2691,2928,3175,3432,3699,3976,4263,4560,4867,5184,5511,5848,6195,6552,6919,7296,7683,8080,8487,8904,9331,9768,10215,10672,11139,11616,12103,12600,13107,13624,14151,14688,15235,15792,16359,16936,17523,18120,18727,19344,19971,20608,21255,21912,22579,23256,23943,24640,25347,26064,26791,27528,28275,29032,29799,30576,31363,32160,32967,33784,34611,35448,36295,37152,38019,38896,39783,40680,41587,42504,43431,44368,45315,46272,47239,48216,49203,50200,51207,52224,53251,54288,55335,56392,57459,58536,59623,60720,61827,62944,64071,65208,66355,67512,68679,69856,71043,72240,73447,74664,75891,77128,78375,79632,80899,82176,83463,84760,86067,87384,88711,90048,91395,92752,94119,95496,96883,98280,99687,101104,102531,103968,105415,106872,108339,109816,111303,112800,114307,115824,117351,118888,120435,121992,123559,125136,126723,128320,129927,131544,133171,134808,136455,138112,139779,141456,143143,144840,146547,148264,149991,151728,153475,155232,156999,158776,160563,162360,164167,165984,167811,169648,171495,173352,175219,177096,178983,180880,182787,184704,186631,188568,190515,192472,194439,196416,198403,200400,202407,204424,206451,208488,210535,212592,214659,216736,218823,220920,223027,225144,227271,229408,231555,233712,235879,238056,240243,242440,244647,246864,249091,251328,253575,255832,258099,260376,262663,264960,267267,269584,271911,274248,276595,278952,281319,283696,286083,288480,290887,293304,295731,298168,300615,303072,305539,308016,310503
mov $1,5
mul $1,$0
add $1,2
mul $1,$0
| 201.75
| 1,543
| 0.820942
|
4f76cf0881bfc7f42eb3200741dedbd192a96511
| 533
|
lua
|
Lua
|
ProgrammingInLua/ch04/stringplus.lua
|
you-know-who-2017/RockInLua
|
ef21756d2e5fcc09309bca5af1e10b6341a36a1a
|
[
"MIT"
] | null | null | null |
ProgrammingInLua/ch04/stringplus.lua
|
you-know-who-2017/RockInLua
|
ef21756d2e5fcc09309bca5af1e10b6341a36a1a
|
[
"MIT"
] | null | null | null |
ProgrammingInLua/ch04/stringplus.lua
|
you-know-who-2017/RockInLua
|
ef21756d2e5fcc09309bca5af1e10b6341a36a1a
|
[
"MIT"
] | null | null | null |
string.format("x = %d y = %d", 10, 20)
string.format("x = %x", 200)
string.format("x = 0x%X", 200)
string.format("x = %f", 200)
tag, title = "h1", "a title"
string.format("<%s>%s</%s>", tag, title, tag)
print(string.format("pi = %.4f", math.pi))
d = 5; m = 11; y = 1990
print(string.format("%02d/%02d/%04d", d, m, y)) --> 05/11/1990
string.find("hello world", "wor")
string.find("hello world", "war")
string.gsub("hello world", "l", ".")
string.gsub("hello world", "ll", "..")
string.gsub("hello world", "a", ".")
| 25.380952
| 62
| 0.560976
|
9ff048d58ca2f656063ac9f73dccb6d22e8f63ac
| 2,258
|
py
|
Python
|
fluid/parameter.py
|
PaulDodd/signac-flow-project-helpers
|
208c7c8da52c4b0108c3989c77423cc5ff86ba59
|
[
"MIT"
] | 1
|
2017-05-30T14:22:59.000Z
|
2017-05-30T14:22:59.000Z
|
fluid/parameter.py
|
PaulDodd/signac-flow-project-helpers
|
208c7c8da52c4b0108c3989c77423cc5ff86ba59
|
[
"MIT"
] | null | null | null |
fluid/parameter.py
|
PaulDodd/signac-flow-project-helpers
|
208c7c8da52c4b0108c3989c77423cc5ff86ba59
|
[
"MIT"
] | null | null | null |
# TODO: Remove from project
_params_warned_once = False
class FluidParams(dict):
defaults = dict() # the default values of the parameters
def __init__(self, job, readonly=None):
dict.__init__(self)
try:
# TODO: this may not really be the right case.
from mpi4py import MPI
self._comm = MPI.COMM_WORLD
rank = comm.Get_rank()
except ImportError as err:
#TODO:handle error.
if not _params_warned_once:
logger.warning("Could not import mpi4py. parameters will default to read only.")
_params_warned_once = True
if readonly is None:
readonly = True
if readonly is None or type(readonly) is not bool:
readonly = (rank != 0)
self.__dict__.update(dict(_job=job, defaults=self.defaults, _readonly=readonly))
self.load()
def load(self):
for key in self.defaults:
self[key] = self._job.document.get(key, self.defaults[key])
def save(self):
if _comm: _comm.Barrier() # ensure all ranks are not accessing the data.
ret = False
if not self._readonly:
for key in self.keys():
self._job.document[key] = self[key]
ret = True
if _comm: _comm.Barrier() # ensure all ranks are not accessing the data.
return True
def __getitem__(self, key):
return super(FlowParams, self).__getitem__(key)
def __setattr__(self, name, value):
if not hasattr(self.defaults, name):
raise AttributeError('{} instance has no attribute {!r}'.format(type(self).__name__, name))
super(FlowParams, self).__setattr__(name, value)
@classmethod
def get_value(cls, job, name):
return job.document.get(name, cls.defaults[name])
def update(self, src):
extra, override = self.extract(src)
super(FlowParams, self).update(override)
@classmethod
def extract(cls, src):
unused = dict()
params = dict()
for key in src:
if key in cls.defaults.keys():
params[key] = src[key]
else:
unused[key] = src[key]
return params, unused
| 34.738462
| 103
| 0.590345
|
82b222c88a8f0c24b94c0065fe76ba394aa62133
| 2,569
|
rs
|
Rust
|
tests/build.rs
|
chrissie-c/rust-corosync
|
765327f308e78db2a028a330e88b010195594f01
|
[
"MIT"
] | 3
|
2021-01-20T14:33:05.000Z
|
2021-02-16T18:47:39.000Z
|
tests/build.rs
|
chrissie-c/rust-corosync
|
765327f308e78db2a028a330e88b010195594f01
|
[
"MIT"
] | null | null | null |
tests/build.rs
|
chrissie-c/rust-corosync
|
765327f308e78db2a028a330e88b010195594f01
|
[
"MIT"
] | null | null | null |
extern crate pkg_config;
fn main() {
if let Err(e) = pkg_config::probe_library("libcpg") {
match e {
pkg_config::Error::Failure { .. } => panic! (
"Pkg-config failed - usually this is because corosync development headers are not installed.\n\n\
For Fedora users:\n# dnf install corosynclib-devel\n\n\
For Debian/Ubuntu users:\n# apt-get install libcpg-dev\n\n\
pkg_config details:\n{}",
e
),
_ => panic!("{}", e)
}
}
if let Err(e) = pkg_config::probe_library("libquorum") {
match e {
pkg_config::Error::Failure { .. } => panic! (
"Pkg-config failed - usually this is because corosync development headers are not installed.\n\n\
For Fedora users:\n# dnf install corosynclib-devel\n\n\
For Debian/Ubuntu users:\n# apt-get install libquorum-dev\n\n\
pkg_config details:\n{}",
e
),
_ => panic!("{}", e)
}
}
if let Err(e) = pkg_config::probe_library("libvotequorum") {
match e {
pkg_config::Error::Failure { .. } => panic! (
"Pkg-config failed - usually this is because corosync development headers are not installed.\n\n\
For Fedora users:\n# dnf install corosynclib-devel\n\n\
For Debian/Ubuntu users:\n# apt-get install libvotequorum-dev\n\n\
pkg_config details:\n{}",
e
),
_ => panic!("{}", e)
}
}
if let Err(e) = pkg_config::probe_library("libcfg") {
match e {
pkg_config::Error::Failure { .. } => panic! (
"Pkg-config failed - usually this is because corosync development headers are not installed.\n\n\
For Fedora users:\n# dnf install corosynclib-devel\n\n\
For Debian/Ubuntu users:\n# apt-get install libcfg-dev\n\n\
pkg_config details:\n{}",
e
),
_ => panic!("{}", e)
}
}
if let Err(e) = pkg_config::probe_library("libcmap") {
match e {
pkg_config::Error::Failure { .. } => panic! (
"Pkg-config failed - usually this is because corosync development headers are not installed.\n\n\
For Fedora users:\n# dnf install corosynclib-devel\n\n\
For Debian/Ubuntu users:\n# apt-get install libcmap-dev\n\n\
pkg_config details:\n{}",
e
),
_ => panic!("{}", e)
}
}
println!("cargo:rustc-link-lib=cpg");
println!("cargo:rustc-link-lib=cfg");
println!("cargo:rustc-link-lib=cmap");
println!("cargo:rustc-link-lib=quorum");
println!("cargo:rustc-link-lib=votequorum");
}
| 36.183099
| 99
| 0.587777
|
1d7237303f2c58b0923fa5a106118975b40366c6
| 230
|
swift
|
Swift
|
MyiOSApp/Networking/Result.swift
|
soufianesalouf/MyiOSApp
|
6997d81c8f1955eeccf96a81b375ba676d2e2e3b
|
[
"MIT"
] | null | null | null |
MyiOSApp/Networking/Result.swift
|
soufianesalouf/MyiOSApp
|
6997d81c8f1955eeccf96a81b375ba676d2e2e3b
|
[
"MIT"
] | null | null | null |
MyiOSApp/Networking/Result.swift
|
soufianesalouf/MyiOSApp
|
6997d81c8f1955eeccf96a81b375ba676d2e2e3b
|
[
"MIT"
] | null | null | null |
//
// Result.swift
// MyiOSApp
//
// Created by Soufiane SALOUF on 06/08/20.
// Copyright © 2020 Soufiane SALOUF. All rights reserved.
//
import Foundation
enum Result<T> {
case success(T)
case failure(Error)
}
| 14.375
| 58
| 0.647826
|
aaa6da761fb8521da4794beec319adf23e6d2621
| 119,073
|
lua
|
Lua
|
src/leda/controller/http_flot.lua
|
LuaDist-testing/leda
|
42a84e5c1527c315b02b0d2d99e8e21585d5860d
|
[
"MIT",
"Unlicense"
] | 7
|
2015-11-05T17:44:16.000Z
|
2019-06-04T01:35:46.000Z
|
src/leda/controller/http_flot.lua
|
Salmito/leda
|
7980e8c82722bd06788136e28312af3b02999bf1
|
[
"Unlicense",
"MIT"
] | null | null | null |
src/leda/controller/http_flot.lua
|
Salmito/leda
|
7980e8c82722bd06788136e28312af3b02999bf1
|
[
"Unlicense",
"MIT"
] | null | null | null |
return [===[
/* Javascript plotting library for jQuery, version 0.8.1.
Copyright (c) 2007-2013 IOLA and Ole Laursen.
Licensed under the MIT license.
*/
// first an inline dependency, jquery.colorhelpers.js, we inline it here
// for convenience
/* Plugin for jQuery for working with colors.
*
* Version 1.1.
*
* Inspiration from jQuery color animation plugin by John Resig.
*
* Released under the MIT license by Ole Laursen, October 2009.
*
* Examples:
*
* $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
* var c = $.color.extract($("#mydiv"), 'background-color');
* console.log(c.r, c.g, c.b, c.a);
* $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
*
* Note that .scale() and .add() return the same modified object
* instead of making a new one.
*
* V. 1.1: Fix error handling so e.g. parsing an empty string does
* produce a color rather than just crashing.
*/
(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]+=I}return G.normalize()};G.scale=function(J,I){for(var H=0;H<J.length;++H){G[J.charAt(H)]*=I}return G.normalize()};G.toString=function(){if(G.a>=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return K<J?J:(K>I?I:K)}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
// the actual Flot code
(function($) {
// Cache the prototype hasOwnProperty for faster access
var hasOwnProperty = Object.prototype.hasOwnProperty;
///////////////////////////////////////////////////////////////////////////
// The Canvas object is a wrapper around an HTML5 <canvas> tag.
//
// @constructor
// @param {string} cls List of classes to apply to the canvas.
// @param {element} container Element onto which to append the canvas.
//
// Requiring a container is a little iffy, but unfortunately canvas
// operations don't work unless the canvas is attached to the DOM.
function Canvas(cls, container) {
var element = container.children("." + cls)[0];
if (element == null) {
element = document.createElement("canvas");
element.className = cls;
$(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 })
.appendTo(container);
// If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas
if (!element.getContext) {
if (window.G_vmlCanvasManager) {
element = window.G_vmlCanvasManager.initElement(element);
} else {
throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");
}
}
}
this.element = element;
var context = this.context = element.getContext("2d");
// Determine the screen's ratio of physical to device-independent
// pixels. This is the ratio between the canvas width that the browser
// advertises and the number of pixels actually present in that space.
// The iPhone 4, for example, has a device-independent width of 320px,
// but its screen is actually 640px wide. It therefore has a pixel
// ratio of 2, while most normal devices have a ratio of 1.
var devicePixelRatio = window.devicePixelRatio || 1,
backingStoreRatio =
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
this.pixelRatio = devicePixelRatio / backingStoreRatio;
// Size the canvas to match the internal dimensions of its container
this.resize(container.width(), container.height());
// Collection of HTML div layers for text overlaid onto the canvas
this.textContainer = null;
this.text = {};
// Cache of text fragments and metrics, so we can avoid expensively
// re-calculating them when the plot is re-rendered in a loop.
this._textCache = {};
}
// Resizes the canvas to the given dimensions.
//
// @param {number} width New width of the canvas, in pixels.
// @param {number} width New height of the canvas, in pixels.
Canvas.prototype.resize = function(width, height) {
if (width <= 0 || height <= 0) {
throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height);
}
var element = this.element,
context = this.context,
pixelRatio = this.pixelRatio;
// Resize the canvas, increasing its density based on the display's
// pixel ratio; basically giving it more pixels without increasing the
// size of its element, to take advantage of the fact that retina
// displays have that many more pixels in the same advertised space.
// Resizing should reset the state (excanvas seems to be buggy though)
if (this.width != width) {
element.width = width * pixelRatio;
element.style.width = width + "px";
this.width = width;
}
if (this.height != height) {
element.height = height * pixelRatio;
element.style.height = height + "px";
this.height = height;
}
// Save the context, so we can reset in case we get replotted. The
// restore ensure that we're really back at the initial state, and
// should be safe even if we haven't saved the initial state yet.
context.restore();
context.save();
// Scale the coordinate space to match the display density; so even though we
// may have twice as many pixels, we still want lines and other drawing to
// appear at the same size; the extra pixels will just make them crisper.
context.scale(pixelRatio, pixelRatio);
};
// Clears the entire canvas area, not including any overlaid HTML text
Canvas.prototype.clear = function() {
this.context.clearRect(0, 0, this.width, this.height);
};
// Finishes rendering the canvas, including managing the text overlay.
Canvas.prototype.render = function() {
var cache = this._textCache;
// For each text layer, add elements marked as active that haven't
// already been rendered, and remove those that are no longer active.
for (var layerKey in cache) {
if (hasOwnProperty.call(cache, layerKey)) {
var layer = this.getTextLayer(layerKey),
layerCache = cache[layerKey];
layer.hide();
for (var styleKey in layerCache) {
if (hasOwnProperty.call(layerCache, styleKey)) {
var styleCache = layerCache[styleKey];
for (var key in styleCache) {
if (hasOwnProperty.call(styleCache, key)) {
var positions = styleCache[key].positions;
for (var i = 0, position; position = positions[i]; i++) {
if (position.active) {
if (!position.rendered) {
layer.append(position.element);
position.rendered = true;
}
} else {
positions.splice(i--, 1);
if (position.rendered) {
position.element.detach();
}
}
}
if (positions.length == 0) {
delete styleCache[key];
}
}
}
}
}
layer.show();
}
}
};
// Creates (if necessary) and returns the text overlay container.
//
// @param {string} classes String of space-separated CSS classes used to
// uniquely identify the text layer.
// @return {object} The jQuery-wrapped text-layer div.
Canvas.prototype.getTextLayer = function(classes) {
var layer = this.text[classes];
// Create the text layer if it doesn't exist
if (layer == null) {
// Create the text layer container, if it doesn't exist
if (this.textContainer == null) {
this.textContainer = $("<div class='flot-text'></div>")
.css({
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0,
'font-size': "smaller",
color: "#545454"
})
.insertAfter(this.element);
}
layer = this.text[classes] = $("<div></div>")
.addClass(classes)
.css({
position: "absolute",
top: 0,
left: 0,
bottom: 0,
right: 0
})
.appendTo(this.textContainer);
}
return layer;
};
// Creates (if necessary) and returns a text info object.
//
// The object looks like this:
//
// {
// width: Width of the text's wrapper div.
// height: Height of the text's wrapper div.
// element: The jQuery-wrapped HTML div containing the text.
// positions: Array of positions at which this text is drawn.
// }
//
// The positions array contains objects that look like this:
//
// {
// active: Flag indicating whether the text should be visible.
// rendered: Flag indicating whether the text is currently visible.
// element: The jQuery-wrapped HTML div containing the text.
// x: X coordinate at which to draw the text.
// y: Y coordinate at which to draw the text.
// }
//
// Each position after the first receives a clone of the original element.
//
// The idea is that that the width, height, and general 'identity' of the
// text is constant no matter where it is placed; the placements are a
// secondary property.
//
// Canvas maintains a cache of recently-used text info objects; getTextInfo
// either returns the cached element or creates a new entry.
//
// @param {string} layer A string of space-separated CSS classes uniquely
// identifying the layer containing this text.
// @param {string} text Text string to retrieve info for.
// @param {(string|object)=} font Either a string of space-separated CSS
// classes or a font-spec object, defining the text's font and style.
// @param {number=} angle Angle at which to rotate the text, in degrees.
// Angle is currently unused, it will be implemented in the future.
// @param {number=} width Maximum width of the text before it wraps.
// @return {object} a text info object.
Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
var textStyle, layerCache, styleCache, info;
// Cast the value to a string, in case we were given a number or such
text = "" + text;
// If the font is a font-spec object, generate a CSS font definition
if (typeof font === "object") {
textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family;
} else {
textStyle = font;
}
// Retrieve (or create) the cache for the text's layer and styles
layerCache = this._textCache[layer];
if (layerCache == null) {
layerCache = this._textCache[layer] = {};
}
styleCache = layerCache[textStyle];
if (styleCache == null) {
styleCache = layerCache[textStyle] = {};
}
info = styleCache[text];
// If we can't find a matching element in our cache, create a new one
if (info == null) {
var element = $("<div></div>").html(text)
.css({
position: "absolute",
'max-width': width,
top: -9999
})
.appendTo(this.getTextLayer(layer));
if (typeof font === "object") {
element.css({
font: textStyle,
color: font.color
});
} else if (typeof font === "string") {
element.addClass(font);
}
info = styleCache[text] = {
width: element.outerWidth(true),
height: element.outerHeight(true),
element: element,
positions: []
};
element.detach();
}
return info;
};
// Adds a text string to the canvas text overlay.
//
// The text isn't drawn immediately; it is marked as rendering, which will
// result in its addition to the canvas on the next render pass.
//
// @param {string} layer A string of space-separated CSS classes uniquely
// identifying the layer containing this text.
// @param {number} x X coordinate at which to draw the text.
// @param {number} y Y coordinate at which to draw the text.
// @param {string} text Text string to draw.
// @param {(string|object)=} font Either a string of space-separated CSS
// classes or a font-spec object, defining the text's font and style.
// @param {number=} angle Angle at which to rotate the text, in degrees.
// Angle is currently unused, it will be implemented in the future.
// @param {number=} width Maximum width of the text before it wraps.
// @param {string=} halign Horizontal alignment of the text; either "left",
// "center" or "right".
// @param {string=} valign Vertical alignment of the text; either "top",
// "middle" or "bottom".
Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {
var info = this.getTextInfo(layer, text, font, angle, width),
positions = info.positions;
// Tweak the div's position to match the text's alignment
if (halign == "center") {
x -= info.width / 2;
} else if (halign == "right") {
x -= info.width;
}
if (valign == "middle") {
y -= info.height / 2;
} else if (valign == "bottom") {
y -= info.height;
}
// Determine whether this text already exists at this position.
// If so, mark it for inclusion in the next render pass.
for (var i = 0, position; position = positions[i]; i++) {
if (position.x == x && position.y == y) {
position.active = true;
return;
}
}
// If the text doesn't exist at this position, create a new entry
// For the very first position we'll re-use the original element,
// while for subsequent ones we'll clone it.
position = {
active: true,
rendered: false,
element: positions.length ? info.element.clone() : info.element,
x: x,
y: y
}
positions.push(position);
// Move the element to its final position within the container
position.element.css({
top: Math.round(y),
left: Math.round(x),
'text-align': halign // In case the text wraps
});
};
// Removes one or more text strings from the canvas text overlay.
//
// If no parameters are given, all text within the layer is removed.
//
// Note that the text is not immediately removed; it is simply marked as
// inactive, which will result in its removal on the next render pass.
// This avoids the performance penalty for 'clear and redraw' behavior,
// where we potentially get rid of all text on a layer, but will likely
// add back most or all of it later, as when redrawing axes, for example.
//
// @param {string} layer A string of space-separated CSS classes uniquely
// identifying the layer containing this text.
// @param {number=} x X coordinate of the text.
// @param {number=} y Y coordinate of the text.
// @param {string=} text Text string to remove.
// @param {(string|object)=} font Either a string of space-separated CSS
// classes or a font-spec object, defining the text's font and style.
// @param {number=} angle Angle at which the text is rotated, in degrees.
// Angle is currently unused, it will be implemented in the future.
Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
if (text == null) {
var layerCache = this._textCache[layer];
if (layerCache != null) {
for (var styleKey in layerCache) {
if (hasOwnProperty.call(layerCache, styleKey)) {
var styleCache = layerCache[styleKey];
for (var key in styleCache) {
if (hasOwnProperty.call(styleCache, key)) {
var positions = styleCache[key].positions;
for (var i = 0, position; position = positions[i]; i++) {
position.active = false;
}
}
}
}
}
}
} else {
var positions = this.getTextInfo(layer, text, font, angle).positions;
for (var i = 0, position; position = positions[i]; i++) {
if (position.x == x && position.y == y) {
position.active = false;
}
}
}
};
///////////////////////////////////////////////////////////////////////////
// The top-level container for the entire plot.
function Plot(placeholder, data_, options_, plugins) {
// data is on the form:
// [ series1, series2 ... ]
// where series is either just the data as [ [x1, y1], [x2, y2], ... ]
// or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
var series = [],
options = {
// the color theme used for graphs
colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
legend: {
show: true,
noColumns: 1, // number of colums in legend table
labelFormatter: null, // fn: string -> string
labelBoxBorderColor: "#ccc", // border color for the little label boxes
container: null, // container (as jQuery object) to put legend in, null means default on top of graph
position: "ne", // position of default legend container within plot
margin: 5, // distance from grid edge to default legend container within plot
backgroundColor: null, // null means auto-detect
backgroundOpacity: 0.85, // set to 0 to avoid background
sorted: null // default to no legend sorting
},
xaxis: {
show: null, // null = auto-detect, true = always, false = never
position: "bottom", // or "top"
mode: null, // null or "time"
font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" }
color: null, // base color, labels, ticks
tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
transform: null, // null or f: number -> number to transform axis
inverseTransform: null, // if transform is set, this should be the inverse function
min: null, // min. value to show, null means set automatically
max: null, // max. value to show, null means set automatically
autoscaleMargin: null, // margin in % to add if auto-setting min/max
ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
tickFormatter: null, // fn: number -> string
labelWidth: null, // size of tick labels in pixels
labelHeight: null,
reserveSpace: null, // whether to reserve space even if axis isn't shown
tickLength: null, // size in pixels of ticks, or "full" for whole line
alignTicksWithAxis: null, // axis number or null for no sync
tickDecimals: null, // no. of decimals, null means auto
tickSize: null, // number or [number, "unit"]
minTickSize: null // number or [number, "unit"]
},
yaxis: {
autoscaleMargin: 0.02,
position: "left" // or "right"
},
xaxes: [],
yaxes: [],
series: {
points: {
show: false,
radius: 3,
lineWidth: 2, // in pixels
fill: true,
fillColor: "#ffffff",
symbol: "circle" // or callback
},
lines: {
// we don't put in show: false so we can see
// whether lines were actively disabled
lineWidth: 2, // in pixels
fill: false,
fillColor: null,
steps: false
// Omit 'zero', so we can later default its value to
// match that of the 'fill' option.
},
bars: {
show: false,
lineWidth: 2, // in pixels
barWidth: 1, // in units of the x axis
fill: true,
fillColor: null,
align: "left", // "left", "right", or "center"
horizontal: false,
zero: true
},
shadowSize: 3,
highlightColor: null
},
grid: {
show: true,
aboveData: false,
color: "#545454", // primary color used for outline and labels
backgroundColor: null, // null for transparent, else color
borderColor: null, // set if different from the grid color
tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
margin: 0, // distance from the canvas edge to the grid
labelMargin: 5, // in pixels
axisMargin: 8, // in pixels
borderWidth: 2, // in pixels
minBorderMargin: null, // in pixels, null means taken from points radius
markings: null, // array of ranges or fn: axes -> array of ranges
markingsColor: "#f4f4f4",
markingsLineWidth: 2,
// interactive stuff
clickable: false,
hoverable: false,
autoHighlight: true, // highlight in case mouse is near
mouseActiveRadius: 10 // how far the mouse can be away to activate an item
},
interaction: {
redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow
},
hooks: {}
},
surface = null, // the canvas for the plot itself
overlay = null, // canvas for interactive stuff on top of plot
eventHolder = null, // jQuery object that events should be bound to
ctx = null, octx = null,
xaxes = [], yaxes = [],
plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
plotWidth = 0, plotHeight = 0,
hooks = {
processOptions: [],
processRawData: [],
processDatapoints: [],
processOffset: [],
drawBackground: [],
drawSeries: [],
draw: [],
bindEvents: [],
drawOverlay: [],
shutdown: []
},
plot = this;
// public functions
plot.setData = setData;
plot.setupGrid = setupGrid;
plot.draw = draw;
plot.getPlaceholder = function() { return placeholder; };
plot.getCanvas = function() { return surface.element; };
plot.getPlotOffset = function() { return plotOffset; };
plot.width = function () { return plotWidth; };
plot.height = function () { return plotHeight; };
plot.offset = function () {
var o = eventHolder.offset();
o.left += plotOffset.left;
o.top += plotOffset.top;
return o;
};
plot.getData = function () { return series; };
plot.getAxes = function () {
var res = {}, i;
$.each(xaxes.concat(yaxes), function (_, axis) {
if (axis)
res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
});
return res;
};
plot.getXAxes = function () { return xaxes; };
plot.getYAxes = function () { return yaxes; };
plot.c2p = canvasToAxisCoords;
plot.p2c = axisToCanvasCoords;
plot.getOptions = function () { return options; };
plot.highlight = highlight;
plot.unhighlight = unhighlight;
plot.triggerRedrawOverlay = triggerRedrawOverlay;
plot.pointOffset = function(point) {
return {
left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
};
};
plot.shutdown = shutdown;
plot.resize = function () {
var width = placeholder.width(),
height = placeholder.height();
surface.resize(width, height);
overlay.resize(width, height);
};
// public attributes
plot.hooks = hooks;
// initialize
initPlugins(plot);
parseOptions(options_);
setupCanvases();
setData(data_);
setupGrid();
draw();
bindEvents();
function executeHooks(hook, args) {
args = [plot].concat(args);
for (var i = 0; i < hook.length; ++i)
hook[i].apply(this, args);
}
function initPlugins() {
// References to key classes, allowing plugins to modify them
var classes = {
Canvas: Canvas
};
for (var i = 0; i < plugins.length; ++i) {
var p = plugins[i];
p.init(plot, classes);
if (p.options)
$.extend(true, options, p.options);
}
}
function parseOptions(opts) {
$.extend(true, options, opts);
// $.extend merges arrays, rather than replacing them. When less
// colors are provided than the size of the default palette, we
// end up with those colors plus the remaining defaults, which is
// not expected behavior; avoid it by replacing them here.
if (opts && opts.colors) {
options.colors = opts.colors;
}
if (options.xaxis.color == null)
options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
if (options.yaxis.color == null)
options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility
options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility
options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;
if (options.grid.borderColor == null)
options.grid.borderColor = options.grid.color;
if (options.grid.tickColor == null)
options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
// Fill in defaults for axis options, including any unspecified
// font-spec fields, if a font-spec was provided.
// If no x/y axis options were provided, create one of each anyway,
// since the rest of the code assumes that they exist.
var i, axisOptions, axisCount,
fontDefaults = {
style: placeholder.css("font-style"),
size: Math.round(0.8 * (+placeholder.css("font-size").replace("px", "") || 13)),
variant: placeholder.css("font-variant"),
weight: placeholder.css("font-weight"),
family: placeholder.css("font-family")
};
fontDefaults.lineHeight = fontDefaults.size * 1.15;
axisCount = options.xaxes.length || 1;
for (i = 0; i < axisCount; ++i) {
axisOptions = options.xaxes[i];
if (axisOptions && !axisOptions.tickColor) {
axisOptions.tickColor = axisOptions.color;
}
axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
options.xaxes[i] = axisOptions;
if (axisOptions.font) {
axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
if (!axisOptions.font.color) {
axisOptions.font.color = axisOptions.color;
}
}
}
axisCount = options.yaxes.length || 1;
for (i = 0; i < axisCount; ++i) {
axisOptions = options.yaxes[i];
if (axisOptions && !axisOptions.tickColor) {
axisOptions.tickColor = axisOptions.color;
}
axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
options.yaxes[i] = axisOptions;
if (axisOptions.font) {
axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
if (!axisOptions.font.color) {
axisOptions.font.color = axisOptions.color;
}
}
}
// backwards compatibility, to be removed in future
if (options.xaxis.noTicks && options.xaxis.ticks == null)
options.xaxis.ticks = options.xaxis.noTicks;
if (options.yaxis.noTicks && options.yaxis.ticks == null)
options.yaxis.ticks = options.yaxis.noTicks;
if (options.x2axis) {
options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
options.xaxes[1].position = "top";
}
if (options.y2axis) {
options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
options.yaxes[1].position = "right";
}
if (options.grid.coloredAreas)
options.grid.markings = options.grid.coloredAreas;
if (options.grid.coloredAreasColor)
options.grid.markingsColor = options.grid.coloredAreasColor;
if (options.lines)
$.extend(true, options.series.lines, options.lines);
if (options.points)
$.extend(true, options.series.points, options.points);
if (options.bars)
$.extend(true, options.series.bars, options.bars);
if (options.shadowSize != null)
options.series.shadowSize = options.shadowSize;
if (options.highlightColor != null)
options.series.highlightColor = options.highlightColor;
// save options on axes for future reference
for (i = 0; i < options.xaxes.length; ++i)
getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
for (i = 0; i < options.yaxes.length; ++i)
getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
// add hooks from options
for (var n in hooks)
if (options.hooks[n] && options.hooks[n].length)
hooks[n] = hooks[n].concat(options.hooks[n]);
executeHooks(hooks.processOptions, [options]);
}
function setData(d) {
series = parseData(d);
fillInSeriesOptions();
processData();
}
function parseData(d) {
var res = [];
for (var i = 0; i < d.length; ++i) {
var s = $.extend(true, {}, options.series);
if (d[i].data != null) {
s.data = d[i].data; // move the data instead of deep-copy
delete d[i].data;
$.extend(true, s, d[i]);
d[i].data = s.data;
}
else
s.data = d[i];
res.push(s);
}
return res;
}
function axisNumber(obj, coord) {
var a = obj[coord + "axis"];
if (typeof a == "object") // if we got a real axis, extract number
a = a.n;
if (typeof a != "number")
a = 1; // default to first axis
return a;
}
function allAxes() {
// return flat array without annoying null entries
return $.grep(xaxes.concat(yaxes), function (a) { return a; });
}
function canvasToAxisCoords(pos) {
// return an object with x/y corresponding to all used axes
var res = {}, i, axis;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used)
res["x" + axis.n] = axis.c2p(pos.left);
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used)
res["y" + axis.n] = axis.c2p(pos.top);
}
if (res.x1 !== undefined)
res.x = res.x1;
if (res.y1 !== undefined)
res.y = res.y1;
return res;
}
function axisToCanvasCoords(pos) {
// get canvas coords from the first pair of x/y found in pos
var res = {}, i, axis, key;
for (i = 0; i < xaxes.length; ++i) {
axis = xaxes[i];
if (axis && axis.used) {
key = "x" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "x";
if (pos[key] != null) {
res.left = axis.p2c(pos[key]);
break;
}
}
}
for (i = 0; i < yaxes.length; ++i) {
axis = yaxes[i];
if (axis && axis.used) {
key = "y" + axis.n;
if (pos[key] == null && axis.n == 1)
key = "y";
if (pos[key] != null) {
res.top = axis.p2c(pos[key]);
break;
}
}
}
return res;
}
function getOrCreateAxis(axes, number) {
if (!axes[number - 1])
axes[number - 1] = {
n: number, // save the number for future reference
direction: axes == xaxes ? "x" : "y",
options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
};
return axes[number - 1];
}
function fillInSeriesOptions() {
var neededColors = series.length, maxIndex = -1, i;
// Subtract the number of series that already have fixed colors or
// color indexes from the number that we still need to generate.
for (i = 0; i < series.length; ++i) {
var sc = series[i].color;
if (sc != null) {
neededColors--;
if (typeof sc == "number" && sc > maxIndex) {
maxIndex = sc;
}
}
}
// If any of the series have fixed color indexes, then we need to
// generate at least as many colors as the highest index.
if (neededColors <= maxIndex) {
neededColors = maxIndex + 1;
}
// Generate all the colors, using first the option colors and then
// variations on those colors once they're exhausted.
var c, colors = [], colorPool = options.colors,
colorPoolSize = colorPool.length, variation = 0;
for (i = 0; i < neededColors; i++) {
c = $.color.parse(colorPool[i % colorPoolSize] || "#666");
// Each time we exhaust the colors in the pool we adjust
// a scaling factor used to produce more variations on
// those colors. The factor alternates negative/positive
// to produce lighter/darker colors.
// Reset the variation after every few cycles, or else
// it will end up producing only white or black colors.
if (i % colorPoolSize == 0 && i) {
if (variation >= 0) {
if (variation < 0.5) {
variation = -variation - 0.2;
} else variation = 0;
} else variation = -variation;
}
colors[i] = c.scale('rgb', 1 + variation);
}
// Finalize the series options, filling in their colors
var colori = 0, s;
for (i = 0; i < series.length; ++i) {
s = series[i];
// assign colors
if (s.color == null) {
s.color = colors[colori].toString();
++colori;
}
else if (typeof s.color == "number")
s.color = colors[s.color].toString();
// turn on lines automatically in case nothing is set
if (s.lines.show == null) {
var v, show = true;
for (v in s)
if (s[v] && s[v].show) {
show = false;
break;
}
if (show)
s.lines.show = true;
}
// If nothing was provided for lines.zero, default it to match
// lines.fill, since areas by default should extend to zero.
if (s.lines.zero == null) {
s.lines.zero = !!s.lines.fill;
}
// setup axes
s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
}
}
function processData() {
var topSentry = Number.POSITIVE_INFINITY,
bottomSentry = Number.NEGATIVE_INFINITY,
fakeInfinity = Number.MAX_VALUE,
i, j, k, m, length,
s, points, ps, x, y, axis, val, f, p,
data, format;
function updateAxis(axis, min, max) {
if (min < axis.datamin && min != -fakeInfinity)
axis.datamin = min;
if (max > axis.datamax && max != fakeInfinity)
axis.datamax = max;
}
$.each(allAxes(), function (_, axis) {
// init axis
axis.datamin = topSentry;
axis.datamax = bottomSentry;
axis.used = false;
});
for (i = 0; i < series.length; ++i) {
s = series[i];
s.datapoints = { points: [] };
executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
}
// first pass: clean and copy data
for (i = 0; i < series.length; ++i) {
s = series[i];
data = s.data;
format = s.datapoints.format;
if (!format) {
format = [];
// find out how to copy
format.push({ x: true, number: true, required: true });
format.push({ y: true, number: true, required: true });
if (s.bars.show || (s.lines.show && s.lines.fill)) {
var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
if (s.bars.horizontal) {
delete format[format.length - 1].y;
format[format.length - 1].x = true;
}
}
s.datapoints.format = format;
}
if (s.datapoints.pointsize != null)
continue; // already filled in
s.datapoints.pointsize = format.length;
ps = s.datapoints.pointsize;
points = s.datapoints.points;
var insertSteps = s.lines.show && s.lines.steps;
s.xaxis.used = s.yaxis.used = true;
for (j = k = 0; j < data.length; ++j, k += ps) {
p = data[j];
var nullify = p == null;
if (!nullify) {
for (m = 0; m < ps; ++m) {
val = p[m];
f = format[m];
if (f) {
if (f.number && val != null) {
val = +val; // convert to number
if (isNaN(val))
val = null;
else if (val == Infinity)
val = fakeInfinity;
else if (val == -Infinity)
val = -fakeInfinity;
}
if (val == null) {
if (f.required)
nullify = true;
if (f.defaultValue != null)
val = f.defaultValue;
}
}
points[k + m] = val;
}
}
if (nullify) {
for (m = 0; m < ps; ++m) {
val = points[k + m];
if (val != null) {
f = format[m];
// extract min/max info
if (f.autoscale) {
if (f.x) {
updateAxis(s.xaxis, val, val);
}
if (f.y) {
updateAxis(s.yaxis, val, val);
}
}
}
points[k + m] = null;
}
}
else {
// a little bit of line specific stuff that
// perhaps shouldn't be here, but lacking
// better means...
if (insertSteps && k > 0
&& points[k - ps] != null
&& points[k - ps] != points[k]
&& points[k - ps + 1] != points[k + 1]) {
// copy the point to make room for a middle point
for (m = 0; m < ps; ++m)
points[k + ps + m] = points[k + m];
// middle point has same y
points[k + 1] = points[k - ps + 1];
// we've added a point, better reflect that
k += ps;
}
}
}
}
// give the hooks a chance to run
for (i = 0; i < series.length; ++i) {
s = series[i];
executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
}
// second pass: find datamax/datamin for auto-scaling
for (i = 0; i < series.length; ++i) {
s = series[i];
points = s.datapoints.points;
ps = s.datapoints.pointsize;
format = s.datapoints.format;
var xmin = topSentry, ymin = topSentry,
xmax = bottomSentry, ymax = bottomSentry;
for (j = 0; j < points.length; j += ps) {
if (points[j] == null)
continue;
for (m = 0; m < ps; ++m) {
val = points[j + m];
f = format[m];
if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity)
continue;
if (f.x) {
if (val < xmin)
xmin = val;
if (val > xmax)
xmax = val;
}
if (f.y) {
if (val < ymin)
ymin = val;
if (val > ymax)
ymax = val;
}
}
}
if (s.bars.show) {
// make sure we got room for the bar on the dancing floor
var delta;
switch (s.bars.align) {
case "left":
delta = 0;
break;
case "right":
delta = -s.bars.barWidth;
break;
case "center":
delta = -s.bars.barWidth / 2;
break;
default:
throw new Error("Invalid bar alignment: " + s.bars.align);
}
if (s.bars.horizontal) {
ymin += delta;
ymax += delta + s.bars.barWidth;
}
else {
xmin += delta;
xmax += delta + s.bars.barWidth;
}
}
updateAxis(s.xaxis, xmin, xmax);
updateAxis(s.yaxis, ymin, ymax);
}
$.each(allAxes(), function (_, axis) {
if (axis.datamin == topSentry)
axis.datamin = null;
if (axis.datamax == bottomSentry)
axis.datamax = null;
});
}
function setupCanvases() {
// Make sure the placeholder is clear of everything except canvases
// from a previous plot in this container that we'll try to re-use.
placeholder.css("padding", 0) // padding messes up the positioning
.children(":not(.flot-base,.flot-overlay)").remove();
if (placeholder.css("position") == 'static')
placeholder.css("position", "relative"); // for positioning labels and overlay
surface = new Canvas("flot-base", placeholder);
overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features
ctx = surface.context;
octx = overlay.context;
// define which element we're listening for events on
eventHolder = $(overlay.element).unbind();
// If we're re-using a plot object, shut down the old one
var existing = placeholder.data("plot");
if (existing) {
existing.shutdown();
overlay.clear();
}
// save in case we get replotted
placeholder.data("plot", plot);
}
function bindEvents() {
// bind events
if (options.grid.hoverable) {
eventHolder.mousemove(onMouseMove);
// Use bind, rather than .mouseleave, because we officially
// still support jQuery 1.2.6, which doesn't define a shortcut
// for mouseenter or mouseleave. This was a bug/oversight that
// was fixed somewhere around 1.3.x. We can return to using
// .mouseleave when we drop support for 1.2.6.
eventHolder.bind("mouseleave", onMouseLeave);
}
if (options.grid.clickable)
eventHolder.click(onClick);
executeHooks(hooks.bindEvents, [eventHolder]);
}
function shutdown() {
if (redrawTimeout)
clearTimeout(redrawTimeout);
eventHolder.unbind("mousemove", onMouseMove);
eventHolder.unbind("mouseleave", onMouseLeave);
eventHolder.unbind("click", onClick);
executeHooks(hooks.shutdown, [eventHolder]);
}
function setTransformationHelpers(axis) {
// set helper functions on the axis, assumes plot area
// has been computed already
function identity(x) { return x; }
var s, m, t = axis.options.transform || identity,
it = axis.options.inverseTransform;
// precompute how much the axis is scaling a point
// in canvas space
if (axis.direction == "x") {
s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
m = Math.min(t(axis.max), t(axis.min));
}
else {
s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
s = -s;
m = Math.max(t(axis.max), t(axis.min));
}
// data point to canvas coordinate
if (t == identity) // slight optimization
axis.p2c = function (p) { return (p - m) * s; };
else
axis.p2c = function (p) { return (t(p) - m) * s; };
// canvas coordinate to data point
if (!it)
axis.c2p = function (c) { return m + c / s; };
else
axis.c2p = function (c) { return it(m + c / s); };
}
function measureTickLabels(axis) {
var opts = axis.options,
ticks = axis.ticks || [],
labelWidth = opts.labelWidth || 0,
labelHeight = opts.labelHeight || 0,
maxWidth = labelWidth || axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null;
legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
font = opts.font || "flot-tick-label tickLabel";
for (var i = 0; i < ticks.length; ++i) {
var t = ticks[i];
if (!t.label)
continue;
var info = surface.getTextInfo(layer, t.label, font, null, maxWidth);
labelWidth = Math.max(labelWidth, info.width);
labelHeight = Math.max(labelHeight, info.height);
}
axis.labelWidth = opts.labelWidth || labelWidth;
axis.labelHeight = opts.labelHeight || labelHeight;
}
function allocateAxisBoxFirstPhase(axis) {
// find the bounding box of the axis by looking at label
// widths/heights and ticks, make room by diminishing the
// plotOffset; this first phase only looks at one
// dimension per axis, the other dimension depends on the
// other axes so will have to wait
var lw = axis.labelWidth,
lh = axis.labelHeight,
pos = axis.options.position,
tickLength = axis.options.tickLength,
axisMargin = options.grid.axisMargin,
padding = options.grid.labelMargin,
all = axis.direction == "x" ? xaxes : yaxes,
index, innermost;
// determine axis margin
var samePosition = $.grep(all, function (a) {
return a && a.options.position == pos && a.reserveSpace;
});
if ($.inArray(axis, samePosition) == samePosition.length - 1)
axisMargin = 0; // outermost
// determine tick length - if we're innermost, we can use "full"
if (tickLength == null) {
var sameDirection = $.grep(all, function (a) {
return a && a.reserveSpace;
});
innermost = $.inArray(axis, sameDirection) == 0;
if (innermost)
tickLength = "full";
else
tickLength = 5;
}
if (!isNaN(+tickLength))
padding += +tickLength;
// compute box
if (axis.direction == "x") {
lh += padding;
if (pos == "bottom") {
plotOffset.bottom += lh + axisMargin;
axis.box = { top: surface.height - plotOffset.bottom, height: lh };
}
else {
axis.box = { top: plotOffset.top + axisMargin, height: lh };
plotOffset.top += lh + axisMargin;
}
}
else {
lw += padding;
if (pos == "left") {
axis.box = { left: plotOffset.left + axisMargin, width: lw };
plotOffset.left += lw + axisMargin;
}
else {
plotOffset.right += lw + axisMargin;
axis.box = { left: surface.width - plotOffset.right, width: lw };
}
}
// save for future reference
axis.position = pos;
axis.tickLength = tickLength;
axis.box.padding = padding;
axis.innermost = innermost;
}
function allocateAxisBoxSecondPhase(axis) {
// now that all axis boxes have been placed in one
// dimension, we can set the remaining dimension coordinates
if (axis.direction == "x") {
axis.box.left = plotOffset.left - axis.labelWidth / 2;
axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth;
}
else {
axis.box.top = plotOffset.top - axis.labelHeight / 2;
axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight;
}
}
function adjustLayoutForThingsStickingOut() {
// possibly adjust plot offset to ensure everything stays
// inside the canvas and isn't clipped off
var minMargin = options.grid.minBorderMargin,
margins = { x: 0, y: 0 }, i, axis;
// check stuff from the plot (FIXME: this should just read
// a value from the series, otherwise it's impossible to
// customize)
if (minMargin == null) {
minMargin = 0;
for (i = 0; i < series.length; ++i)
minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2));
}
margins.x = margins.y = Math.ceil(minMargin);
// check axis labels, note we don't check the actual
// labels but instead use the overall width/height to not
// jump as much around with replots
$.each(allAxes(), function (_, axis) {
var dir = axis.direction;
if (axis.reserveSpace)
margins[dir] = Math.ceil(Math.max(margins[dir], (dir == "x" ? axis.labelWidth : axis.labelHeight) / 2));
});
plotOffset.left = Math.max(margins.x, plotOffset.left);
plotOffset.right = Math.max(margins.x, plotOffset.right);
plotOffset.top = Math.max(margins.y, plotOffset.top);
plotOffset.bottom = Math.max(margins.y, plotOffset.bottom);
}
function setupGrid() {
var i, axes = allAxes(), showGrid = options.grid.show;
// Initialize the plot's offset from the edge of the canvas
for (var a in plotOffset) {
var margin = options.grid.margin || 0;
plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0;
}
executeHooks(hooks.processOffset, [plotOffset]);
// If the grid is visible, add its border width to the offset
for (var a in plotOffset) {
if(typeof(options.grid.borderWidth) == "object") {
plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0;
}
else {
plotOffset[a] += showGrid ? options.grid.borderWidth : 0;
}
}
// init axes
$.each(axes, function (_, axis) {
axis.show = axis.options.show;
if (axis.show == null)
axis.show = axis.used; // by default an axis is visible if it's got data
axis.reserveSpace = axis.show || axis.options.reserveSpace;
setRange(axis);
});
if (showGrid) {
var allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; });
$.each(allocatedAxes, function (_, axis) {
// make the ticks
setupTickGeneration(axis);
setTicks(axis);
snapRangeToTicks(axis, axis.ticks);
// find labelWidth/Height for axis
measureTickLabels(axis);
});
// with all dimensions calculated, we can compute the
// axis bounding boxes, start from the outside
// (reverse order)
for (i = allocatedAxes.length - 1; i >= 0; --i)
allocateAxisBoxFirstPhase(allocatedAxes[i]);
// make sure we've got enough space for things that
// might stick out
adjustLayoutForThingsStickingOut();
$.each(allocatedAxes, function (_, axis) {
allocateAxisBoxSecondPhase(axis);
});
}
plotWidth = surface.width - plotOffset.left - plotOffset.right;
plotHeight = surface.height - plotOffset.bottom - plotOffset.top;
// now we got the proper plot dimensions, we can compute the scaling
$.each(axes, function (_, axis) {
setTransformationHelpers(axis);
});
if (showGrid) {
drawAxisLabels();
}
insertLegend();
}
function setRange(axis) {
var opts = axis.options,
min = +(opts.min != null ? opts.min : axis.datamin),
max = +(opts.max != null ? opts.max : axis.datamax),
delta = max - min;
if (delta == 0.0) {
// degenerate case
var widen = max == 0 ? 1 : 0.01;
if (opts.min == null)
min -= widen;
// always widen max if we couldn't widen min to ensure we
// don't fall into min == max which doesn't work
if (opts.max == null || opts.min != null)
max += widen;
}
else {
// consider autoscaling
var margin = opts.autoscaleMargin;
if (margin != null) {
if (opts.min == null) {
min -= delta * margin;
// make sure we don't go below zero if all values
// are positive
if (min < 0 && axis.datamin != null && axis.datamin >= 0)
min = 0;
}
if (opts.max == null) {
max += delta * margin;
if (max > 0 && axis.datamax != null && axis.datamax <= 0)
max = 0;
}
}
}
axis.min = min;
axis.max = max;
}
function setupTickGeneration(axis) {
var opts = axis.options;
// estimate number of ticks
var noTicks;
if (typeof opts.ticks == "number" && opts.ticks > 0)
noTicks = opts.ticks;
else
// heuristic based on the model a*sqrt(x) fitted to
// some data points that seemed reasonable
noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height);
var delta = (axis.max - axis.min) / noTicks,
dec = -Math.floor(Math.log(delta) / Math.LN10),
maxDec = opts.tickDecimals;
if (maxDec != null && dec > maxDec) {
dec = maxDec;
}
var magn = Math.pow(10, -dec),
norm = delta / magn, // norm is between 1.0 and 10.0
size;
if (norm < 1.5) {
size = 1;
} else if (norm < 3) {
size = 2;
// special case for 2.5, requires an extra decimal
if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
size = 2.5;
++dec;
}
} else if (norm < 7.5) {
size = 5;
} else {
size = 10;
}
size *= magn;
if (opts.minTickSize != null && size < opts.minTickSize) {
size = opts.minTickSize;
}
axis.delta = delta;
axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
axis.tickSize = opts.tickSize || size;
// Time mode was moved to a plug-in in 0.8, but since so many people use this
// we'll add an especially friendly make sure they remembered to include it.
if (opts.mode == "time" && !axis.tickGenerator) {
throw new Error("Time mode requires the flot.time plugin.");
}
// Flot supports base-10 axes; any other mode else is handled by a plug-in,
// like flot.time.js.
if (!axis.tickGenerator) {
axis.tickGenerator = function (axis) {
var ticks = [],
start = floorInBase(axis.min, axis.tickSize),
i = 0,
v = Number.NaN,
prev;
do {
prev = v;
v = start + i * axis.tickSize;
ticks.push(v);
++i;
} while (v < axis.max && v != prev);
return ticks;
};
axis.tickFormatter = function (value, axis) {
var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1;
var formatted = "" + Math.round(value * factor) / factor;
// If tickDecimals was specified, ensure that we have exactly that
// much precision; otherwise default to the value's own precision.
if (axis.tickDecimals != null) {
var decimal = formatted.indexOf(".");
var precision = decimal == -1 ? 0 : formatted.length - decimal - 1;
if (precision < axis.tickDecimals) {
return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision);
}
}
return formatted;
};
}
if ($.isFunction(opts.tickFormatter))
axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
if (opts.alignTicksWithAxis != null) {
var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
if (otherAxis && otherAxis.used && otherAxis != axis) {
// consider snapping min/max to outermost nice ticks
var niceTicks = axis.tickGenerator(axis);
if (niceTicks.length > 0) {
if (opts.min == null)
axis.min = Math.min(axis.min, niceTicks[0]);
if (opts.max == null && niceTicks.length > 1)
axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
}
axis.tickGenerator = function (axis) {
// copy ticks, scaled to this axis
var ticks = [], v, i;
for (i = 0; i < otherAxis.ticks.length; ++i) {
v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
v = axis.min + v * (axis.max - axis.min);
ticks.push(v);
}
return ticks;
};
// we might need an extra decimal since forced
// ticks don't necessarily fit naturally
if (!axis.mode && opts.tickDecimals == null) {
var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1),
ts = axis.tickGenerator(axis);
// only proceed if the tick interval rounded
// with an extra decimal doesn't give us a
// zero at end
if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
axis.tickDecimals = extraDec;
}
}
}
}
function setTicks(axis) {
var oticks = axis.options.ticks, ticks = [];
if (oticks == null || (typeof oticks == "number" && oticks > 0))
ticks = axis.tickGenerator(axis);
else if (oticks) {
if ($.isFunction(oticks))
// generate the ticks
ticks = oticks(axis);
else
ticks = oticks;
}
// clean up/labelify the supplied ticks, copy them over
var i, v;
axis.ticks = [];
for (i = 0; i < ticks.length; ++i) {
var label = null;
var t = ticks[i];
if (typeof t == "object") {
v = +t[0];
if (t.length > 1)
label = t[1];
}
else
v = +t;
if (label == null)
label = axis.tickFormatter(v, axis);
if (!isNaN(v))
axis.ticks.push({ v: v, label: label });
}
}
function snapRangeToTicks(axis, ticks) {
if (axis.options.autoscaleMargin && ticks.length > 0) {
// snap to ticks
if (axis.options.min == null)
axis.min = Math.min(axis.min, ticks[0].v);
if (axis.options.max == null && ticks.length > 1)
axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
}
}
function draw() {
surface.clear();
executeHooks(hooks.drawBackground, [ctx]);
var grid = options.grid;
// draw background, if any
if (grid.show && grid.backgroundColor)
drawBackground();
if (grid.show && !grid.aboveData) {
drawGrid();
}
for (var i = 0; i < series.length; ++i) {
executeHooks(hooks.drawSeries, [ctx, series[i] ]);
drawSeries(series[i]);
}
executeHooks(hooks.draw, [ctx]);
if (grid.show && grid.aboveData) {
drawGrid();
}
surface.render();
// A draw implies that either the axes or data have changed, so we
// should probably update the overlay highlights as well.
triggerRedrawOverlay();
}
function extractRange(ranges, coord) {
var axis, from, to, key, axes = allAxes();
for (var i = 0; i < axes.length; ++i) {
axis = axes[i];
if (axis.direction == coord) {
key = coord + axis.n + "axis";
if (!ranges[key] && axis.n == 1)
key = coord + "axis"; // support x1axis as xaxis
if (ranges[key]) {
from = ranges[key].from;
to = ranges[key].to;
break;
}
}
}
// backwards-compat stuff - to be removed in future
if (!ranges[key]) {
axis = coord == "x" ? xaxes[0] : yaxes[0];
from = ranges[coord + "1"];
to = ranges[coord + "2"];
}
// auto-reverse as an added bonus
if (from != null && to != null && from > to) {
var tmp = from;
from = to;
to = tmp;
}
return { from: from, to: to, axis: axis };
}
function drawBackground() {
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
ctx.fillRect(0, 0, plotWidth, plotHeight);
ctx.restore();
}
function drawGrid() {
var i, axes, bw, bc;
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// draw markings
var markings = options.grid.markings;
if (markings) {
if ($.isFunction(markings)) {
axes = plot.getAxes();
// xmin etc. is backwards compatibility, to be
// removed in the future
axes.xmin = axes.xaxis.min;
axes.xmax = axes.xaxis.max;
axes.ymin = axes.yaxis.min;
axes.ymax = axes.yaxis.max;
markings = markings(axes);
}
for (i = 0; i < markings.length; ++i) {
var m = markings[i],
xrange = extractRange(m, "x"),
yrange = extractRange(m, "y");
// fill in missing
if (xrange.from == null)
xrange.from = xrange.axis.min;
if (xrange.to == null)
xrange.to = xrange.axis.max;
if (yrange.from == null)
yrange.from = yrange.axis.min;
if (yrange.to == null)
yrange.to = yrange.axis.max;
// clip
if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
continue;
xrange.from = Math.max(xrange.from, xrange.axis.min);
xrange.to = Math.min(xrange.to, xrange.axis.max);
yrange.from = Math.max(yrange.from, yrange.axis.min);
yrange.to = Math.min(yrange.to, yrange.axis.max);
if (xrange.from == xrange.to && yrange.from == yrange.to)
continue;
// then draw
xrange.from = xrange.axis.p2c(xrange.from);
xrange.to = xrange.axis.p2c(xrange.to);
yrange.from = yrange.axis.p2c(yrange.from);
yrange.to = yrange.axis.p2c(yrange.to);
if (xrange.from == xrange.to || yrange.from == yrange.to) {
// draw line
ctx.beginPath();
ctx.strokeStyle = m.color || options.grid.markingsColor;
ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth;
ctx.moveTo(xrange.from, yrange.from);
ctx.lineTo(xrange.to, yrange.to);
ctx.stroke();
}
else {
// fill area
ctx.fillStyle = m.color || options.grid.markingsColor;
ctx.fillRect(xrange.from, yrange.to,
xrange.to - xrange.from,
yrange.from - yrange.to);
}
}
}
// draw the ticks
axes = allAxes();
bw = options.grid.borderWidth;
for (var j = 0; j < axes.length; ++j) {
var axis = axes[j], box = axis.box,
t = axis.tickLength, x, y, xoff, yoff;
if (!axis.show || axis.ticks.length == 0)
continue;
ctx.lineWidth = 1;
// find the edges
if (axis.direction == "x") {
x = 0;
if (t == "full")
y = (axis.position == "top" ? 0 : plotHeight);
else
y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
}
else {
y = 0;
if (t == "full")
x = (axis.position == "left" ? 0 : plotWidth);
else
x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
}
// draw tick bar
if (!axis.innermost) {
ctx.strokeStyle = axis.options.color;
ctx.beginPath();
xoff = yoff = 0;
if (axis.direction == "x")
xoff = plotWidth + 1;
else
yoff = plotHeight + 1;
if (ctx.lineWidth == 1) {
if (axis.direction == "x") {
y = Math.floor(y) + 0.5;
} else {
x = Math.floor(x) + 0.5;
}
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
ctx.stroke();
}
// draw ticks
ctx.strokeStyle = axis.options.tickColor;
ctx.beginPath();
for (i = 0; i < axis.ticks.length; ++i) {
var v = axis.ticks[i].v;
xoff = yoff = 0;
if (isNaN(v) || v < axis.min || v > axis.max
// skip those lying on the axes if we got a border
|| (t == "full"
&& ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0)
&& (v == axis.min || v == axis.max)))
continue;
if (axis.direction == "x") {
x = axis.p2c(v);
yoff = t == "full" ? -plotHeight : t;
if (axis.position == "top")
yoff = -yoff;
}
else {
y = axis.p2c(v);
xoff = t == "full" ? -plotWidth : t;
if (axis.position == "left")
xoff = -xoff;
}
if (ctx.lineWidth == 1) {
if (axis.direction == "x")
x = Math.floor(x) + 0.5;
else
y = Math.floor(y) + 0.5;
}
ctx.moveTo(x, y);
ctx.lineTo(x + xoff, y + yoff);
}
ctx.stroke();
}
// draw border
if (bw) {
// If either borderWidth or borderColor is an object, then draw the border
// line by line instead of as one rectangle
bc = options.grid.borderColor;
if(typeof bw == "object" || typeof bc == "object") {
if (typeof bw !== "object") {
bw = {top: bw, right: bw, bottom: bw, left: bw};
}
if (typeof bc !== "object") {
bc = {top: bc, right: bc, bottom: bc, left: bc};
}
if (bw.top > 0) {
ctx.strokeStyle = bc.top;
ctx.lineWidth = bw.top;
ctx.beginPath();
ctx.moveTo(0 - bw.left, 0 - bw.top/2);
ctx.lineTo(plotWidth, 0 - bw.top/2);
ctx.stroke();
}
if (bw.right > 0) {
ctx.strokeStyle = bc.right;
ctx.lineWidth = bw.right;
ctx.beginPath();
ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top);
ctx.lineTo(plotWidth + bw.right / 2, plotHeight);
ctx.stroke();
}
if (bw.bottom > 0) {
ctx.strokeStyle = bc.bottom;
ctx.lineWidth = bw.bottom;
ctx.beginPath();
ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2);
ctx.lineTo(0, plotHeight + bw.bottom / 2);
ctx.stroke();
}
if (bw.left > 0) {
ctx.strokeStyle = bc.left;
ctx.lineWidth = bw.left;
ctx.beginPath();
ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom);
ctx.lineTo(0- bw.left/2, 0);
ctx.stroke();
}
}
else {
ctx.lineWidth = bw;
ctx.strokeStyle = options.grid.borderColor;
ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
}
}
ctx.restore();
}
function drawAxisLabels() {
$.each(allAxes(), function (_, axis) {
if (!axis.show || axis.ticks.length == 0)
return;
var box = axis.box,
legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
font = axis.options.font || "flot-tick-label tickLabel",
tick, x, y, halign, valign;
surface.removeText(layer);
for (var i = 0; i < axis.ticks.length; ++i) {
tick = axis.ticks[i];
if (!tick.label || tick.v < axis.min || tick.v > axis.max)
continue;
if (axis.direction == "x") {
halign = "center";
x = plotOffset.left + axis.p2c(tick.v);
if (axis.position == "bottom") {
y = box.top + box.padding;
} else {
y = box.top + box.height - box.padding;
valign = "bottom";
}
} else {
valign = "middle";
y = plotOffset.top + axis.p2c(tick.v);
if (axis.position == "left") {
x = box.left + box.width - box.padding;
halign = "right";
} else {
x = box.left + box.padding;
}
}
surface.addText(layer, x, y, tick.label, font, null, null, halign, valign);
}
});
}
function drawSeries(series) {
if (series.lines.show)
drawSeriesLines(series);
if (series.bars.show)
drawSeriesBars(series);
if (series.points.show)
drawSeriesPoints(series);
}
function drawSeriesLines(series) {
function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
prevx = null, prevy = null;
ctx.beginPath();
for (var i = ps; i < points.length; i += ps) {
var x1 = points[i - ps], y1 = points[i - ps + 1],
x2 = points[i], y2 = points[i + 1];
if (x1 == null || x2 == null)
continue;
// clip with ymin
if (y1 <= y2 && y1 < axisy.min) {
if (y2 < axisy.min)
continue; // line segment is outside
// compute new intersection point
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min) {
if (y1 < axisy.min)
continue;
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max) {
if (y2 > axisy.max)
continue;
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max) {
if (y1 > axisy.max)
continue;
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (x1 != prevx || y1 != prevy)
ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
prevx = x2;
prevy = y2;
ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
}
ctx.stroke();
}
function plotLineArea(datapoints, axisx, axisy) {
var points = datapoints.points,
ps = datapoints.pointsize,
bottom = Math.min(Math.max(0, axisy.min), axisy.max),
i = 0, top, areaOpen = false,
ypos = 1, segmentStart = 0, segmentEnd = 0;
// we process each segment in two turns, first forward
// direction to sketch out top, then once we hit the
// end we go backwards to sketch the bottom
while (true) {
if (ps > 0 && i > points.length + ps)
break;
i += ps; // ps is negative if going backwards
var x1 = points[i - ps],
y1 = points[i - ps + ypos],
x2 = points[i], y2 = points[i + ypos];
if (areaOpen) {
if (ps > 0 && x1 != null && x2 == null) {
// at turning point
segmentEnd = i;
ps = -ps;
ypos = 2;
continue;
}
if (ps < 0 && i == segmentStart + ps) {
// done with the reverse sweep
ctx.fill();
areaOpen = false;
ps = -ps;
ypos = 1;
i = segmentStart = segmentEnd + ps;
continue;
}
}
if (x1 == null || x2 == null)
continue;
// clip x values
// clip with xmin
if (x1 <= x2 && x1 < axisx.min) {
if (x2 < axisx.min)
continue;
y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.min;
}
else if (x2 <= x1 && x2 < axisx.min) {
if (x1 < axisx.min)
continue;
y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.min;
}
// clip with xmax
if (x1 >= x2 && x1 > axisx.max) {
if (x2 > axisx.max)
continue;
y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x1 = axisx.max;
}
else if (x2 >= x1 && x2 > axisx.max) {
if (x1 > axisx.max)
continue;
y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
x2 = axisx.max;
}
if (!areaOpen) {
// open area
ctx.beginPath();
ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
areaOpen = true;
}
// now first check the case where both is outside
if (y1 >= axisy.max && y2 >= axisy.max) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
continue;
}
else if (y1 <= axisy.min && y2 <= axisy.min) {
ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
continue;
}
// else it's a bit more complicated, there might
// be a flat maxed out rectangle first, then a
// triangular cutout or reverse; to find these
// keep track of the current x values
var x1old = x1, x2old = x2;
// clip the y values, without shortcutting, we
// go through all cases in turn
// clip with ymin
if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.min;
}
else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.min;
}
// clip with ymax
if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y1 = axisy.max;
}
else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
y2 = axisy.max;
}
// if the x value was changed we got a rectangle
// to fill
if (x1 != x1old) {
ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
// it goes to (x1, y1), but we fill that below
}
// fill triangular section, this sometimes result
// in redundant points if (x1, y1) hasn't changed
// from previous line to, but we just ignore that
ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
// fill the other rectangle if it's there
if (x2 != x2old) {
ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
}
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
ctx.lineJoin = "round";
var lw = series.lines.lineWidth,
sw = series.shadowSize;
// FIXME: consider another form of shadow when filling is turned on
if (lw > 0 && sw > 0) {
// draw shadow as a thick and thin line with transparency
ctx.lineWidth = sw;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
// position shadow at angle from the mid of line
var angle = Math.PI/18;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
ctx.lineWidth = sw/2;
plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
if (fillStyle) {
ctx.fillStyle = fillStyle;
plotLineArea(series.datapoints, series.xaxis, series.yaxis);
}
if (lw > 0)
plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
ctx.restore();
}
function drawSeriesPoints(series) {
function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
var x = points[i], y = points[i + 1];
if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
continue;
ctx.beginPath();
x = axisx.p2c(x);
y = axisy.p2c(y) + offset;
if (symbol == "circle")
ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
else
symbol(ctx, x, y, radius, shadow);
ctx.closePath();
if (fillStyle) {
ctx.fillStyle = fillStyle;
ctx.fill();
}
ctx.stroke();
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
var lw = series.points.lineWidth,
sw = series.shadowSize,
radius = series.points.radius,
symbol = series.points.symbol;
// If the user sets the line width to 0, we change it to a very
// small value. A line width of 0 seems to force the default of 1.
// Doing the conditional here allows the shadow setting to still be
// optional even with a lineWidth of 0.
if( lw == 0 )
lw = 0.0001;
if (lw > 0 && sw > 0) {
// draw shadow in two steps
var w = sw / 2;
ctx.lineWidth = w;
ctx.strokeStyle = "rgba(0,0,0,0.1)";
plotPoints(series.datapoints, radius, null, w + w/2, true,
series.xaxis, series.yaxis, symbol);
ctx.strokeStyle = "rgba(0,0,0,0.2)";
plotPoints(series.datapoints, radius, null, w/2, true,
series.xaxis, series.yaxis, symbol);
}
ctx.lineWidth = lw;
ctx.strokeStyle = series.color;
plotPoints(series.datapoints, radius,
getFillStyle(series.points, series.color), 0, false,
series.xaxis, series.yaxis, symbol);
ctx.restore();
}
function drawBar(x, y, b, barLeft, barRight, offset, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
var left, right, bottom, top,
drawLeft, drawRight, drawTop, drawBottom,
tmp;
// in horizontal mode, we start the bar from the left
// instead of from the bottom so it appears to be
// horizontal rather than vertical
if (horizontal) {
drawBottom = drawRight = drawTop = true;
drawLeft = false;
left = b;
right = x;
top = y + barLeft;
bottom = y + barRight;
// account for negative bars
if (right < left) {
tmp = right;
right = left;
left = tmp;
drawLeft = true;
drawRight = false;
}
}
else {
drawLeft = drawRight = drawTop = true;
drawBottom = false;
left = x + barLeft;
right = x + barRight;
bottom = b;
top = y;
// account for negative bars
if (top < bottom) {
tmp = top;
top = bottom;
bottom = tmp;
drawBottom = true;
drawTop = false;
}
}
// clip
if (right < axisx.min || left > axisx.max ||
top < axisy.min || bottom > axisy.max)
return;
if (left < axisx.min) {
left = axisx.min;
drawLeft = false;
}
if (right > axisx.max) {
right = axisx.max;
drawRight = false;
}
if (bottom < axisy.min) {
bottom = axisy.min;
drawBottom = false;
}
if (top > axisy.max) {
top = axisy.max;
drawTop = false;
}
left = axisx.p2c(left);
bottom = axisy.p2c(bottom);
right = axisx.p2c(right);
top = axisy.p2c(top);
// fill the bar
if (fillStyleCallback) {
c.beginPath();
c.moveTo(left, bottom);
c.lineTo(left, top);
c.lineTo(right, top);
c.lineTo(right, bottom);
c.fillStyle = fillStyleCallback(bottom, top);
c.fill();
}
// draw outline
if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
c.beginPath();
// FIXME: inline moveTo is buggy with excanvas
c.moveTo(left, bottom + offset);
if (drawLeft)
c.lineTo(left, top + offset);
else
c.moveTo(left, top + offset);
if (drawTop)
c.lineTo(right, top + offset);
else
c.moveTo(right, top + offset);
if (drawRight)
c.lineTo(right, bottom + offset);
else
c.moveTo(right, bottom + offset);
if (drawBottom)
c.lineTo(left, bottom + offset);
else
c.moveTo(left, bottom + offset);
c.stroke();
}
}
function drawSeriesBars(series) {
function plotBars(datapoints, barLeft, barRight, offset, fillStyleCallback, axisx, axisy) {
var points = datapoints.points, ps = datapoints.pointsize;
for (var i = 0; i < points.length; i += ps) {
if (points[i] == null)
continue;
drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, offset, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
}
}
ctx.save();
ctx.translate(plotOffset.left, plotOffset.top);
// FIXME: figure out a way to add shadows (for instance along the right edge)
ctx.lineWidth = series.bars.lineWidth;
ctx.strokeStyle = series.color;
var barLeft;
switch (series.bars.align) {
case "left":
barLeft = 0;
break;
case "right":
barLeft = -series.bars.barWidth;
break;
case "center":
barLeft = -series.bars.barWidth / 2;
break;
default:
throw new Error("Invalid bar alignment: " + series.bars.align);
}
var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, 0, fillStyleCallback, series.xaxis, series.yaxis);
ctx.restore();
}
function getFillStyle(filloptions, seriesColor, bottom, top) {
var fill = filloptions.fill;
if (!fill)
return null;
if (filloptions.fillColor)
return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
var c = $.color.parse(seriesColor);
c.a = typeof fill == "number" ? fill : 0.4;
c.normalize();
return c.toString();
}
function insertLegend() {
placeholder.find(".legend").remove();
if (!options.legend.show)
return;
var fragments = [], entries = [], rowStarted = false,
lf = options.legend.labelFormatter, s, label;
// Build a list of legend entries, with each having a label and a color
for (var i = 0; i < series.length; ++i) {
s = series[i];
if (s.label) {
label = lf ? lf(s.label, s) : s.label;
if (label) {
entries.push({
label: label,
color: s.color
});
}
}
}
// Sort the legend using either the default or a custom comparator
if (options.legend.sorted) {
if ($.isFunction(options.legend.sorted)) {
entries.sort(options.legend.sorted);
} else if (options.legend.sorted == "reverse") {
entries.reverse();
} else {
var ascending = options.legend.sorted != "descending";
entries.sort(function(a, b) {
return a.label == b.label ? 0 : (
(a.label < b.label) != ascending ? 1 : -1 // Logical XOR
);
});
}
}
// Generate markup for the list of entries, in their final order
for (var i = 0; i < entries.length; ++i) {
var entry = entries[i];
if (i % options.legend.noColumns == 0) {
if (rowStarted)
fragments.push('</tr>');
fragments.push('<tr>');
rowStarted = true;
}
fragments.push(
'<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' +
'<td class="legendLabel">' + entry.label + '</td>'
);
}
if (rowStarted)
fragments.push('</tr>');
if (fragments.length == 0)
return;
var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
if (options.legend.container != null)
$(options.legend.container).html(table);
else {
var pos = "",
p = options.legend.position,
m = options.legend.margin;
if (m[0] == null)
m = [m, m];
if (p.charAt(0) == "n")
pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
else if (p.charAt(0) == "s")
pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
if (p.charAt(1) == "e")
pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
else if (p.charAt(1) == "w")
pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
if (options.legend.backgroundOpacity != 0.0) {
// put in the transparent background
// separately to avoid blended labels and
// label boxes
var c = options.legend.backgroundColor;
if (c == null) {
c = options.grid.backgroundColor;
if (c && typeof c == "string")
c = $.color.parse(c);
else
c = $.color.extract(legend, 'background-color');
c.a = 1;
c = c.toString();
}
var div = legend.children();
$('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
}
}
}
// interactive features
var highlights = [],
redrawTimeout = null;
// returns the data item the mouse is over, or null if none is found
function findNearbyItem(mouseX, mouseY, seriesFilter) {
var maxDistance = options.grid.mouseActiveRadius,
smallestDistance = maxDistance * maxDistance + 1,
item = null, foundPoint = false, i, j, ps;
for (i = series.length - 1; i >= 0; --i) {
if (!seriesFilter(series[i]))
continue;
var s = series[i],
axisx = s.xaxis,
axisy = s.yaxis,
points = s.datapoints.points,
mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
my = axisy.c2p(mouseY),
maxx = maxDistance / axisx.scale,
maxy = maxDistance / axisy.scale;
ps = s.datapoints.pointsize;
// with inverse transforms, we can't use the maxx/maxy
// optimization, sadly
if (axisx.options.inverseTransform)
maxx = Number.MAX_VALUE;
if (axisy.options.inverseTransform)
maxy = Number.MAX_VALUE;
if (s.lines.show || s.points.show) {
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1];
if (x == null)
continue;
// For points and lines, the cursor must be within a
// certain distance to the data point
if (x - mx > maxx || x - mx < -maxx ||
y - my > maxy || y - my < -maxy)
continue;
// We have to calculate distances in pixels, not in
// data units, because the scales of the axes may be different
var dx = Math.abs(axisx.p2c(x) - mouseX),
dy = Math.abs(axisy.p2c(y) - mouseY),
dist = dx * dx + dy * dy; // we save the sqrt
// use <= to ensure last point takes precedence
// (last generally means on top of)
if (dist < smallestDistance) {
smallestDistance = dist;
item = [i, j / ps];
}
}
}
if (s.bars.show && !item) { // no other point can be nearby
var barLeft = s.bars.align == "left" ? 0 : -s.bars.barWidth/2,
barRight = barLeft + s.bars.barWidth;
for (j = 0; j < points.length; j += ps) {
var x = points[j], y = points[j + 1], b = points[j + 2];
if (x == null)
continue;
// for a bar graph, the cursor must be inside the bar
if (series[i].bars.horizontal ?
(mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
my >= y + barLeft && my <= y + barRight) :
(mx >= x + barLeft && mx <= x + barRight &&
my >= Math.min(b, y) && my <= Math.max(b, y)))
item = [i, j / ps];
}
}
}
if (item) {
i = item[0];
j = item[1];
ps = series[i].datapoints.pointsize;
return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
dataIndex: j,
series: series[i],
seriesIndex: i };
}
return null;
}
function onMouseMove(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return s["hoverable"] != false; });
}
function onMouseLeave(e) {
if (options.grid.hoverable)
triggerClickHoverEvent("plothover", e,
function (s) { return false; });
}
function onClick(e) {
triggerClickHoverEvent("plotclick", e,
function (s) { return s["clickable"] != false; });
}
// trigger click or hover event (they send the same parameters
// so we share their code)
function triggerClickHoverEvent(eventname, event, seriesFilter) {
var offset = eventHolder.offset(),
canvasX = event.pageX - offset.left - plotOffset.left,
canvasY = event.pageY - offset.top - plotOffset.top,
pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
pos.pageX = event.pageX;
pos.pageY = event.pageY;
var item = findNearbyItem(canvasX, canvasY, seriesFilter);
if (item) {
// fill in mouse pos for any listeners out there
item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10);
item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10);
}
if (options.grid.autoHighlight) {
// clear auto-highlights
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.auto == eventname &&
!(item && h.series == item.series &&
h.point[0] == item.datapoint[0] &&
h.point[1] == item.datapoint[1]))
unhighlight(h.series, h.point);
}
if (item)
highlight(item.series, item.datapoint, eventname);
}
placeholder.trigger(eventname, [ pos, item ]);
}
function triggerRedrawOverlay() {
var t = options.interaction.redrawOverlayInterval;
if (t == -1) { // skip event queue
drawOverlay();
return;
}
if (!redrawTimeout)
redrawTimeout = setTimeout(drawOverlay, t);
}
function drawOverlay() {
redrawTimeout = null;
// draw highlights
octx.save();
overlay.clear();
octx.translate(plotOffset.left, plotOffset.top);
var i, hi;
for (i = 0; i < highlights.length; ++i) {
hi = highlights[i];
if (hi.series.bars.show)
drawBarHighlight(hi.series, hi.point);
else
drawPointHighlight(hi.series, hi.point);
}
octx.restore();
executeHooks(hooks.drawOverlay, [octx]);
}
function highlight(s, point, auto) {
if (typeof s == "number")
s = series[s];
if (typeof point == "number") {
var ps = s.datapoints.pointsize;
point = s.datapoints.points.slice(ps * point, ps * (point + 1));
}
var i = indexOfHighlight(s, point);
if (i == -1) {
highlights.push({ series: s, point: point, auto: auto });
triggerRedrawOverlay();
}
else if (!auto)
highlights[i].auto = false;
}
function unhighlight(s, point) {
if (s == null && point == null) {
highlights = [];
triggerRedrawOverlay();
return;
}
if (typeof s == "number")
s = series[s];
if (typeof point == "number") {
var ps = s.datapoints.pointsize;
point = s.datapoints.points.slice(ps * point, ps * (point + 1));
}
var i = indexOfHighlight(s, point);
if (i != -1) {
highlights.splice(i, 1);
triggerRedrawOverlay();
}
}
function indexOfHighlight(s, p) {
for (var i = 0; i < highlights.length; ++i) {
var h = highlights[i];
if (h.series == s && h.point[0] == p[0]
&& h.point[1] == p[1])
return i;
}
return -1;
}
function drawPointHighlight(series, point) {
var x = point[0], y = point[1],
axisx = series.xaxis, axisy = series.yaxis,
highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString();
if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
return;
var pointRadius = series.points.radius + series.points.lineWidth / 2;
octx.lineWidth = pointRadius;
octx.strokeStyle = highlightColor;
var radius = 1.5 * pointRadius;
x = axisx.p2c(x);
y = axisy.p2c(y);
octx.beginPath();
if (series.points.symbol == "circle")
octx.arc(x, y, radius, 0, 2 * Math.PI, false);
else
series.points.symbol(octx, x, y, radius, false);
octx.closePath();
octx.stroke();
}
function drawBarHighlight(series, point) {
var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(),
fillStyle = highlightColor,
barLeft = series.bars.align == "left" ? 0 : -series.bars.barWidth/2;
octx.lineWidth = series.bars.lineWidth;
octx.strokeStyle = highlightColor;
drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
0, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
}
function getColorOrGradient(spec, bottom, top, defaultColor) {
if (typeof spec == "string")
return spec;
else {
// assume this is a gradient spec; IE currently only
// supports a simple vertical gradient properly, so that's
// what we support too
var gradient = ctx.createLinearGradient(0, top, 0, bottom);
for (var i = 0, l = spec.colors.length; i < l; ++i) {
var c = spec.colors[i];
if (typeof c != "string") {
var co = $.color.parse(defaultColor);
if (c.brightness != null)
co = co.scale('rgb', c.brightness);
if (c.opacity != null)
co.a *= c.opacity;
c = co.toString();
}
gradient.addColorStop(i / (l - 1), c);
}
return gradient;
}
}
}
// Add the plot function to the top level of the jQuery object
$.plot = function(placeholder, data, options) {
//var t0 = new Date();
var plot = new Plot($(placeholder), data, options, $.plot.plugins);
//(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
return plot;
};
$.plot.version = "0.8.1";
$.plot.plugins = [];
// Also add the plot function as a chainable property
$.fn.plot = function(data, options) {
return this.each(function() {
$.plot(this, data, options);
});
};
// round to nearby lower multiple of base
function floorInBase(n, base) {
return base * Math.floor(n / base);
}
})(jQuery);
]===]
| 38.861945
| 2,952
| 0.458064
|
97cb8143ec8e806bc11d9568d6ee6b5e4fbc3d5f
| 7,465
|
sql
|
SQL
|
src/server/db/02seed_events.sql
|
alnye655321/gEvents
|
fb177f1390f9c2f3fbd03971a9e3d9b033f18bd4
|
[
"MIT"
] | null | null | null |
src/server/db/02seed_events.sql
|
alnye655321/gEvents
|
fb177f1390f9c2f3fbd03971a9e3d9b033f18bd4
|
[
"MIT"
] | null | null | null |
src/server/db/02seed_events.sql
|
alnye655321/gEvents
|
fb177f1390f9c2f3fbd03971a9e3d9b033f18bd4
|
[
"MIT"
] | null | null | null |
\c gevents;
delete from events where id > 0;
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Persistent asymmetric moderator', 'Sed ante. Vivamus tortor.', true, 11, '2016/03/11', '0:19', '19:07');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Team-oriented regional model', 'Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris. Morbi non lectus.', true, 11, '2015/12/08', '8:35', '22:02');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Object-based foreground challenge', 'Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo. Pellentesque viverra pede ac diam. Cras pellentesque volutpat dui. Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam. Suspendisse potenti. Nullam porttitor lacus at turpis.', false, 13, '2016/01/15', '18:48', '21:49');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Team-oriented zero tolerance internet solution', 'Fusce congue, diam id ornare imperdiet, sapien urna pretium nisl, ut volutpat sapien arcu sed augue. Aliquam erat volutpat. In congue.', false, 3, '2016/08/10', '7:39', '22:55');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Upgradable client-server capacity', 'Donec posuere metus vitae ipsum. Aliquam non mauris. Morbi non lectus.', false, 8, '2016/03/01', '7:29', '19:49');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Enterprise-wide bifurcated ability', 'Donec dapibus. Duis at velit eu est congue elementum.', true, 18, '2016/10/02', '14:15', '19:37');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Customizable dedicated hardware', 'Vestibulum ac est lacinia nisi venenatis tristique. Fusce congue, diam id ornare imperdiet, sapien urna pretium nisl, ut volutpat sapien arcu sed augue. Aliquam erat volutpat. In congue. Etiam justo. Etiam pretium iaculis justo. In hac habitasse platea dictumst. Etiam faucibus cursus urna. Ut tellus. Nulla ut erat id mauris vulputate elementum.', true, 6, '2016/09/01', '12:30', '20:44');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Programmable local knowledge base', 'Nunc rhoncus dui vel sem. Sed sagittis. Nam congue, risus semper porta volutpat, quam pede lobortis ligula, sit amet eleifend pede libero quis orci.', false, 8, '2016/05/11', '8:35', '21:45');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Synchronised real-time moderator', 'Morbi vestibulum, velit id pretium iaculis, diam erat fermentum justo, nec condimentum neque sapien placerat ante.', false, 1, '2016/04/23', '8:22', '19:52');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Integrated upward-trending contingency', 'Donec diam neque, vestibulum eget, vulputate ut, ultrices vel, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pharetra, magna vestibulum aliquet ultrices, erat tortor sollicitudin mi, sit amet lobortis sapien sapien non mi. Integer ac neque. Duis bibendum.', false, 13, '2016/05/09', '2:53', '21:44');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Object-based systematic toolset', 'Aliquam quis turpis eget elit sodales scelerisque. Mauris sit amet eros. Suspendisse accumsan tortor quis turpis.', true, 15, '2016/05/12', '2:24', '20:33');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Quality-focused intermediate capacity', 'Integer tincidunt ante vel ipsum. Praesent blandit lacinia erat. Vestibulum sed magna at nunc commodo placerat. Praesent blandit. Nam nulla. Integer pede justo, lacinia eget, tincidunt eget, tempus vel, pede. Morbi porttitor lorem id ligula. Suspendisse ornare consequat lectus.', true, 15, '2015/09/10', '5:04', '19:55');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Visionary mobile data-warehouse', 'Nulla ac enim. In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem. Duis aliquam convallis nunc.', false, 1, '2015/11/07', '11:29', '19:06');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Extended analyzing circuit', 'Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa. Donec dapibus. Duis at velit eu est congue elementum.', true, 4, '2015/11/14', '11:39', '23:00');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('User-friendly high-level open architecture', 'Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam. Suspendisse potenti. Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum. Aliquam non mauris.', true, 11, '2016/01/20', '4:05', '22:06');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Reverse-engineered radical access', 'Integer aliquet, massa id lobortis convallis, tortor risus dapibus augue, vel accumsan tellus nisi eu orci. Mauris lacinia sapien quis libero. Nullam sit amet turpis elementum ligula vehicula consequat. Morbi a ipsum. Integer a nibh.', true, 19, '2016/01/27', '14:34', '21:24');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Diverse discrete leverage', 'Nullam porttitor lacus at turpis. Donec posuere metus vitae ipsum.', false, 1, '2016/05/03', '7:41', '23:11');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Self-enabling upward-trending access', 'Fusce lacus purus, aliquet at, feugiat non, pretium quis, lectus. Suspendisse potenti. In eleifend quam a odio.', true, 15, '2016/05/20', '11:57', '23:54');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Down-sized system-worthy leverage', 'Duis aliquam convallis nunc. Proin at turpis a pede posuere nonummy. Integer non velit. Donec diam neque, vestibulum eget, vulputate ut, ultrices vel, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pharetra, magna vestibulum aliquet ultrices, erat tortor sollicitudin mi, sit amet lobortis sapien sapien non mi. Integer ac neque. Duis bibendum. Morbi non quam nec dui luctus rutrum.', true, 1, '2016/05/27', '17:18', '22:18');
insert into events (title, description, over_21, venue_ID, start_date, start_time, end_time) values ('Reduced 3rd generation firmware', 'Aliquam sit amet diam in magna bibendum imperdiet. Nullam orci pede, venenatis non, sodales sed, tincidunt eu, felis.', false, 16, '2015/09/21', '10:31', '19:59');
| 324.565217
| 619
| 0.766912
|
8e50f65c520aa87b3e348e565dd395205d94fa7b
| 326
|
rb
|
Ruby
|
lib/fake_series/generators.rb
|
kbennoune/fake_series
|
57048a431f4aec448d26fc7eeecd8dbe5c776377
|
[
"MIT"
] | null | null | null |
lib/fake_series/generators.rb
|
kbennoune/fake_series
|
57048a431f4aec448d26fc7eeecd8dbe5c776377
|
[
"MIT"
] | null | null | null |
lib/fake_series/generators.rb
|
kbennoune/fake_series
|
57048a431f4aec448d26fc7eeecd8dbe5c776377
|
[
"MIT"
] | null | null | null |
require "fake_series/generators/composable"
require "fake_series/generators/random_cyclic"
require "fake_series/generators/simple_random_walk"
require "fake_series/generators/gaussian_random_walk"
require "fake_series/generators/pink_noise"
require "fake_series/generators/cyclic"
require "fake_series/generators/expression"
| 36.222222
| 53
| 0.868098
|
bb2d70f80ef39002ed1402cfe5d0fc7c330bf71f
| 5,751
|
cs
|
C#
|
eBay.Service.Standard/Call/AddSellingManagerProductCall.cs
|
mccj/eBay.Service.Standard
|
70510de58c2da6a8c7d1f363ddcba138c07c21c5
|
[
"MIT"
] | 1
|
2018-12-15T05:58:09.000Z
|
2018-12-15T05:58:09.000Z
|
eBay.Service.Standard/Call/AddSellingManagerProductCall.cs
|
mccj/eBay.Service.Standard
|
70510de58c2da6a8c7d1f363ddcba138c07c21c5
|
[
"MIT"
] | null | null | null |
eBay.Service.Standard/Call/AddSellingManagerProductCall.cs
|
mccj/eBay.Service.Standard
|
70510de58c2da6a8c7d1f363ddcba138c07c21c5
|
[
"MIT"
] | null | null | null |
#region Copyright
// Copyright (c) 2013 eBay, Inc.
//
// This program is licensed under the terms of the eBay Common Development and
// Distribution License (CDDL) Version 1.0 (the "License") and any subsequent
// version thereof released by eBay. The then-current version of the License can be
// found at http://www.opensource.org/licenses/cddl1.php and in the eBaySDKLicense
// file that is under the eBay SDK ../docs directory
#endregion
#region Namespaces
using System;
using System.Runtime.InteropServices;
using eBay.Service.Core.Sdk;
using eBay.Service.Core.Soap;
using eBay.Service.EPS;
using eBay.Service.Util;
#endregion
namespace eBay.Service.Call
{
/// <summary>
///
/// </summary>
[ClassInterface(ClassInterfaceType.AutoDispatch)]
public class AddSellingManagerProductCall : ApiCall
{
#region Constructors
/// <summary>
///
/// </summary>
public AddSellingManagerProductCall()
{
ApiRequest = new AddSellingManagerProductRequestType();
}
/// <summary>
///
/// </summary>
/// <param name="ApiContext">The <see cref="ApiCall.ApiContext"/> for this API Call of type <see cref="ApiContext"/>.</param>
public AddSellingManagerProductCall(ApiContext ApiContext)
{
ApiRequest = new AddSellingManagerProductRequestType();
this.ApiContext = ApiContext;
}
#endregion
#region Public Methods
/// <summary>
/// The base request type of the <b>AddSellingManagerProduct</b> call, which is used to create a product or a group of product variations within the Selling Manager Pro system. Once a Selling Manager Pro product or production variation group is created, the product settings and product specifics can be transferred over into a Selling Manager Pro listing template with the <b>AddSellingManagerTemplate</b> call.
/// </summary>
///
/// <param name="SellingManagerProductDetails">
/// This container is used to provide details about the Selling Manager product, such as product name, quantity available, and unit price.
/// </param>
///
/// <param name="FolderID">
/// This is the unique identifier of the folder in which the new product will be placed. This folder can be a new folder or a folder that already exists for the seller in Selling Manager Pro. If no folder is specified through this field, the new product is place into the <em>My Products</em> folder by default.
/// </param>
///
/// <param name="SellingManagerProductSpecifics">
/// This container allows the seller to specify item specifics for a product, to create a product variation group and variation specifics, and/or to specify a listing category for the product or product variation group. A product variation group can be transferred into a listing template that can create a multiple-variation listing. The listing category can either be provided through the <b>PrimaryCategoryID</b> value of this call, or through the <b>Item.PrimaryCategory.CategoryID</b> field of the subsequent <b>AddSellingManagerTemplate</b> call.
/// </param>
///
public SellingManagerProductDetailsType AddSellingManagerProduct(SellingManagerProductDetailsType SellingManagerProductDetails, long FolderID, SellingManagerProductSpecificsType SellingManagerProductSpecifics)
{
this.SellingManagerProductDetails = SellingManagerProductDetails;
this.FolderID = FolderID;
this.SellingManagerProductSpecifics = SellingManagerProductSpecifics;
Execute();
return ApiResponse.SellingManagerProductDetails;
}
#endregion
#region Properties
/// <summary>
/// The base interface object.
/// </summary>
/// <remarks>This property is reserved for users who have difficulty querying multiple interfaces.</remarks>
public ApiCall ApiCallBase
{
get { return this; }
}
/// <summary>
/// Gets or sets the <see cref="AddSellingManagerProductRequestType"/> for this API call.
/// </summary>
public AddSellingManagerProductRequestType ApiRequest
{
get { return (AddSellingManagerProductRequestType) AbstractRequest; }
set { AbstractRequest = value; }
}
/// <summary>
/// Gets the <see cref="AddSellingManagerProductResponseType"/> for this API call.
/// </summary>
public AddSellingManagerProductResponseType ApiResponse
{
get { return (AddSellingManagerProductResponseType) AbstractResponse; }
}
/// <summary>
/// Gets or sets the <see cref="AddSellingManagerProductRequestType.SellingManagerProductDetails"/> of type <see cref="SellingManagerProductDetailsType"/>.
/// </summary>
public SellingManagerProductDetailsType SellingManagerProductDetails
{
get { return ApiRequest.SellingManagerProductDetails; }
set { ApiRequest.SellingManagerProductDetails = value; }
}
/// <summary>
/// Gets or sets the <see cref="AddSellingManagerProductRequestType.FolderID"/> of type <see cref="long"/>.
/// </summary>
public long FolderID
{
get { return ApiRequest.FolderID.Value; }
set { ApiRequest.FolderID = value; }
}
/// <summary>
/// Gets or sets the <see cref="AddSellingManagerProductRequestType.SellingManagerProductSpecifics"/> of type <see cref="SellingManagerProductSpecificsType"/>.
/// </summary>
public SellingManagerProductSpecificsType SellingManagerProductSpecifics
{
get { return ApiRequest.SellingManagerProductSpecifics; }
set { ApiRequest.SellingManagerProductSpecifics = value; }
}
/// <summary>
/// Gets the returned <see cref="AddSellingManagerProductResponseType.SellingManagerProductDetails"/> of type <see cref="SellingManagerProductDetailsType"/>.
/// </summary>
public SellingManagerProductDetailsType SellingManagerProductDetailsReturn
{
get { return ApiResponse.SellingManagerProductDetails; }
}
#endregion
}
}
| 37.103226
| 554
| 0.746305
|
6b5e49567c820d090396c767e4dadbc3621adf7c
| 130
|
js
|
JavaScript
|
unpackage/dist/build/app-plus/pages/trade/kline/main.js
|
wenjiping/exchange-app
|
25efa573299aae1af90537b55e72fa548bc9ac2a
|
[
"Apache-2.0"
] | null | null | null |
unpackage/dist/build/app-plus/pages/trade/kline/main.js
|
wenjiping/exchange-app
|
25efa573299aae1af90537b55e72fa548bc9ac2a
|
[
"Apache-2.0"
] | null | null | null |
unpackage/dist/build/app-plus/pages/trade/kline/main.js
|
wenjiping/exchange-app
|
25efa573299aae1af90537b55e72fa548bc9ac2a
|
[
"Apache-2.0"
] | null | null | null |
document.dispatchEvent(new CustomEvent("generateFuncReady", { detail: { generateFunc: $gwx('./pages/trade/kline/main.wxml') } }));
| 130
| 130
| 0.738462
|
e3df1f95be4f3bca10a0292aeff191e63119e6b3
| 118
|
rb
|
Ruby
|
test/support/test.rb
|
fixrb/defi
|
305b2e50ee03172e0f4cff8998b37c2a5bbf0ea0
|
[
"MIT"
] | null | null | null |
test/support/test.rb
|
fixrb/defi
|
305b2e50ee03172e0f4cff8998b37c2a5bbf0ea0
|
[
"MIT"
] | null | null | null |
test/support/test.rb
|
fixrb/defi
|
305b2e50ee03172e0f4cff8998b37c2a5bbf0ea0
|
[
"MIT"
] | 1
|
2016-10-17T20:16:31.000Z
|
2016-10-17T20:16:31.000Z
|
# frozen_string_literal: true
class Test
attr_reader :challenge
def initialize
@challenge = yield
end
end
| 11.8
| 29
| 0.737288
|
79b6ac7bc5ba57a1ba604348023d3440cb5ed0b1
| 5,468
|
php
|
PHP
|
social/module/custom/include/service/group/process.class.php
|
bansalhimanshu0296/jyc.club
|
a3a4c5deaadde82ea895ae8e6b2fe42bd906b652
|
[
"Apache-2.0"
] | null | null | null |
social/module/custom/include/service/group/process.class.php
|
bansalhimanshu0296/jyc.club
|
a3a4c5deaadde82ea895ae8e6b2fe42bd906b652
|
[
"Apache-2.0"
] | null | null | null |
social/module/custom/include/service/group/process.class.php
|
bansalhimanshu0296/jyc.club
|
a3a4c5deaadde82ea895ae8e6b2fe42bd906b652
|
[
"Apache-2.0"
] | null | null | null |
<?php
/**
* [NULLED BY DARKGOTH 2014]
*/
defined('PHPFOX') or exit('NO DICE!');
/**
*
*
* @copyright [PHPFOX_COPYRIGHT]
* @author Raymond Benc
* @package Phpfox_Service
* @version $Id: process.class.php 3533 2011-11-21 14:07:21Z Raymond_Benc $
*/
class Custom_Service_Group_Process extends Phpfox_Service
{
/**
* Class constructor
*/
public function __construct()
{
$this->_sTable = Phpfox::getT('custom_group');
}
public function add($aVals)
{
Phpfox::getUserParam('custom.can_add_custom_fields_group', true);
if (!isset($aVals['module_id']))
{
return Phpfox_Error::set(Phpfox::getPhrase('custom.provide_a_module_for_this_group_to_belong_to'));
}
foreach ($aVals['group'] as $sPhrase)
{
if (empty($sPhrase))
{
continue;
}
$sVarName = Phpfox::getService('language.phrase.process')->prepare($sPhrase);
break;
}
if (empty($sVarName))
{
return Phpfox_Error::set(Phpfox::getPhrase('custom.provide_a_name_for_this_group'));
}
$sVarName = 'custom_group_' . $sVarName;
if ($this->database()->select('COUNT(*)')->from($this->_sTable)->where('phrase_var_name = \'' . $this->database()->escape($aVals['module_id'] . '.' . $sVarName) . '\'')->execute('getField'))
{
return Phpfox_Error::set(Phpfox::getPhrase('custom.there_is_already_a_group_with_the_same_name'));
}
$iId = $this->database()->insert($this->_sTable, array(
'module_id' => $aVals['module_id'],
'product_id' => $aVals['product_id'],
'user_group_id' => (int) (isset($aVals['user_group_id']) ? $aVals['user_group_id'] : 0),
'type_id' => $aVals['type_id'],
'phrase_var_name' => $aVals['module_id'] . '.' . $sVarName,
'ordering' => 0
)
);
// Add the new phrase
Phpfox::getService('language.phrase.process')->add(array(
'var_name' => $sVarName,
'module' => $aVals['module_id'] . '|' . $aVals['module_id'],
'product_id' => $aVals['product_id'],
'text' => $aVals['group']
), true
);
return $iId;
}
public function update($iId, $aVals)
{
Phpfox::getUserParam('custom.can_manage_custom_fields', true);
foreach ($aVals['group'] as $sKey => $aPhrases)
{
foreach ($aPhrases as $sLang => $sValue)
{
if (Phpfox::getService('language.phrase')->isValid($sKey, $sLang))
{
Phpfox::getService('language.phrase.process')->updateVarName($sLang, $sKey, $sValue);
}
else
{
list($sModule, $sVarName) = explode('.', $sKey);
// Add the new phrase
Phpfox::getService('language.phrase.process')->add(array(
'var_name' => $sVarName,
'module' => $sModule . '|' . $sModule,
'product_id' => $aVals['product_id'],
'text' => array($sLang => $sValue)
), true
);
}
}
}
return true;
}
public function toggleActivity($iId)
{
Phpfox::getUserParam('custom.can_manage_custom_fields', true);
$aField = $this->database()->select('group_id, is_active')
->from($this->_sTable)
->where('group_id = ' . (int) $iId)
->execute('getSlaveRow');
if (!isset($aField['group_id']))
{
return Phpfox_Error::set(Phpfox::getPhrase('custom.unable_to_find_the_custom_group'));
}
$this->database()->update($this->_sTable, array('is_active' => ($aField['is_active'] ? 0 : 1)), 'group_id = ' . $aField['group_id']);
$this->cache()->remove('custom_field', 'substr');
$this->cache()->remove('custom_public_', 'substr');
return true;
}
public function updateOrder($aVals)
{
Phpfox::getUserParam('custom.can_manage_custom_fields', true);
foreach ($aVals as $iId => $iOrder)
{
$this->database()->update($this->_sTable, array('ordering' => (int) $iOrder), 'group_id = ' . (int) $iId);
}
$this->cache()->remove('custom_field', 'substr');
return true;
}
public function delete($iId)
{
Phpfox::getUserParam('custom.can_manage_custom_fields', true);
$aGroup = $this->database()->select('*')
->from($this->_sTable)
->where('group_id = ' . (int) $iId)
->execute('getRow');
if (!isset($aGroup['group_id']))
{
return Phpfox_Error::set(Phpfox::getPhrase('custom.unable_to_find_the_group_you_plan_on_deleting'));
}
list($sModule, $sPhrase) = explode('.', $aGroup['phrase_var_name']);
$this->database()->delete(Phpfox::getT('language_phrase'), 'module_id = \'' . $sModule . '\' AND var_name = \'' . $sPhrase . '\'');
$this->database()->update(Phpfox::getT('custom_field'), array('group_id' => 0), 'group_id = ' . $aGroup['group_id']);
$this->database()->delete($this->_sTable, 'group_id = ' . $aGroup['group_id']);
$this->cache()->remove('custom_field', 'substr');
return true;
}
/**
* If a call is made to an unknown method attempt to connect
* it to a specific plug-in with the same name thus allowing
* plug-in developers the ability to extend classes.
*
* @param string $sMethod is the name of the method
* @param array $aArguments is the array of arguments of being passed
*/
public function __call($sMethod, $aArguments)
{
/**
* Check if such a plug-in exists and if it does call it.
*/
if ($sPlugin = Phpfox_Plugin::get('custom.service_group_process__call'))
{
return eval($sPlugin);
}
/**
* No method or plug-in found we must throw a error.
*/
Phpfox_Error::trigger('Call to undefined method ' . __CLASS__ . '::' . $sMethod . '()', E_USER_ERROR);
}
}
?>
| 27.34
| 192
| 0.619971
|
a1fd196bdde3d9147b4849b1ffc2e6c6d5f3762b
| 1,722
|
dart
|
Dart
|
lib/src/slices/user_referral/ui/user_referral_view_code.dart
|
bhaskarvilles/app
|
dee089328837dd041dd0649899639e1f5c26b02d
|
[
"MIT"
] | null | null | null |
lib/src/slices/user_referral/ui/user_referral_view_code.dart
|
bhaskarvilles/app
|
dee089328837dd041dd0649899639e1f5c26b02d
|
[
"MIT"
] | null | null | null |
lib/src/slices/user_referral/ui/user_referral_view_code.dart
|
bhaskarvilles/app
|
dee089328837dd041dd0649899639e1f5c26b02d
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) TIKI Inc.
* MIT license. See LICENSE file in root directory.
*/
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sizer/sizer.dart';
import '../../../config/config_color.dart';
import '../../../utils/helper_image.dart';
import '../user_referral_service.dart';
class UserReferralViewCode extends StatelessWidget {
static const String _text = "YOUR CODE:";
static const num _fontSize = 12;
@override
Widget build(BuildContext context) {
var service = Provider.of<UserReferralService>(context);
return OutlinedButton(
onPressed: () async => service.controller.copyLink(context),
style: OutlinedButton.styleFrom(
side: BorderSide(color: ConfigColor.greyFour),
primary: ConfigColor.greyFive,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(1.h)))),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Row(mainAxisSize: MainAxisSize.min, children: [
Text(_text,
style: TextStyle(
fontSize: _fontSize.sp,
fontWeight: FontWeight.bold,
color: ConfigColor.greyFive)),
Container(
margin: EdgeInsets.only(
left: 2.w, top: 1.5.h, right: 1.h, bottom: 1.5.h),
child: Text(service.model.code,
style: TextStyle(
fontSize: _fontSize.sp,
fontWeight: FontWeight.bold,
color: ConfigColor.tikiBlue)))
]),
HelperImage("icon-copy", height: _fontSize.sp),
]));
}
}
| 35.875
| 71
| 0.591173
|
5df53d6d97c8bc4307d93f202acfe67b94973e08
| 238
|
cpp
|
C++
|
src/PL_CSC.cpp
|
ddsmarques/pairtree
|
b04e590acf769269ebc38b76ba1f19d6344fef80
|
[
"BSD-3-Clause"
] | null | null | null |
src/PL_CSC.cpp
|
ddsmarques/pairtree
|
b04e590acf769269ebc38b76ba1f19d6344fef80
|
[
"BSD-3-Clause"
] | null | null | null |
src/PL_CSC.cpp
|
ddsmarques/pairtree
|
b04e590acf769269ebc38b76ba1f19d6344fef80
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright (c) 2018 Daniel dos Santos Marques <danielsmarques7@gmail.com>
// License: BSD 3 clause
#include <iostream>
#include "Trainer.h"
int main(int argc, char** argv) {
Trainer trainer;
trainer.train(argv[1]);
return 0;
}
| 18.307692
| 75
| 0.697479
|
1c9b3d18534f94d2aee63a83a879d956562c1f46
| 234
|
dart
|
Dart
|
lib/flutter_ssi_wallet.dart
|
b2cm/dart_ssi
|
ffc7b9a322a52fa087facb8093f523bd0e4ef1fb
|
[
"BSD-3-Clause"
] | null | null | null |
lib/flutter_ssi_wallet.dart
|
b2cm/dart_ssi
|
ffc7b9a322a52fa087facb8093f523bd0e4ef1fb
|
[
"BSD-3-Clause"
] | null | null | null |
lib/flutter_ssi_wallet.dart
|
b2cm/dart_ssi
|
ffc7b9a322a52fa087facb8093f523bd0e4ef1fb
|
[
"BSD-3-Clause"
] | null | null | null |
library flutter_ssi_wallet;
export 'src/credential_exchange.dart';
export 'src/credential_operations.dart';
export 'src/ethereum_connector.dart';
export 'src/hive_model.dart';
export 'src/utils.dart';
export 'src/wallet_store.dart';
| 26
| 40
| 0.803419
|
7a9f7ca61dfdf4775c44270b01b57f36faf7b82a
| 1,613
|
cs
|
C#
|
Assets/Scripts/Objects/Telephone/UIPhonebookEntry.cs
|
polylith/PlumploriGame
|
c3970504a780bd13c81be725d66c60ca87feb8ed
|
[
"MIT"
] | null | null | null |
Assets/Scripts/Objects/Telephone/UIPhonebookEntry.cs
|
polylith/PlumploriGame
|
c3970504a780bd13c81be725d66c60ca87feb8ed
|
[
"MIT"
] | null | null | null |
Assets/Scripts/Objects/Telephone/UIPhonebookEntry.cs
|
polylith/PlumploriGame
|
c3970504a780bd13c81be725d66c60ca87feb8ed
|
[
"MIT"
] | null | null | null |
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.EventSystems;
public class UIPhonebookEntry : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler, IPointerClickHandler
{
public Image back;
public TextMeshProUGUI entryNameDisplay;
public TextMeshProUGUI entryNumberDisplay;
private PhoneBookEntry pbEntry;
private TelephoneUI telephoneUI;
public UIPhonebookEntry Instantiate(PhoneBookEntry entry, TelephoneUI telephoneUI, int i)
{
UIPhonebookEntry uiEntry = Instantiate(this);
uiEntry.telephoneUI = telephoneUI;
uiEntry.name = "Entry " + i;
uiEntry.SetEntry(entry);
return uiEntry;
}
public void SetEntry(PhoneBookEntry entry)
{
pbEntry = entry;
UpdateDisplays();
}
private void UpdateDisplays()
{
entryNameDisplay.SetText(pbEntry.Name);
entryNumberDisplay.SetText(pbEntry.Number);
}
public void OnPointerClick(PointerEventData eventData)
{
if (telephoneUI.InUse)
return;
telephoneUI.InputNumber(pbEntry.Number);
}
public void OnPointerEnter(PointerEventData eventData)
{
if (telephoneUI.InUse)
return;
UIGame.GetInstance().SetCursorEnabled(true, false);
back.color = Color.yellow;
}
public void OnPointerExit(PointerEventData eventData)
{
if (telephoneUI.InUse)
return;
UIGame uiGame = UIGame.GetInstance();
uiGame.SetCursorEnabled(false, !uiGame.IsUIExclusive);
back.color = Color.white;
}
}
| 26.016129
| 110
| 0.67142
|
78b0b545a5cbb1af21b8ff4d2d130f0c039a70c1
| 1,866
|
sql
|
SQL
|
db_archive/sql_archive/1183__drop_create_table_sa_suorat_rekrytointihaut.sql
|
CSCfi/antero
|
e762c09e395cb01e334f2a04753ba983107ac7d7
|
[
"MIT"
] | 6
|
2017-08-03T08:49:17.000Z
|
2021-11-14T17:09:27.000Z
|
db_archive/sql_archive/1183__drop_create_table_sa_suorat_rekrytointihaut.sql
|
CSC-IT-Center-for-Science/antero
|
2835d7fd07cd7399a348033a6230d1b16634fb3b
|
[
"MIT"
] | 3
|
2017-05-03T08:45:42.000Z
|
2020-10-27T06:30:40.000Z
|
db_archive/sql_archive/1183__drop_create_table_sa_suorat_rekrytointihaut.sql
|
CSC-IT-Center-for-Science/antero
|
2835d7fd07cd7399a348033a6230d1b16634fb3b
|
[
"MIT"
] | 4
|
2017-10-19T11:31:43.000Z
|
2022-01-05T14:53:57.000Z
|
USE ANTERO
IF EXISTS
(select * from INFORMATION_SCHEMA.TABLES
where TABLE_SCHEMA='sa' and TABLE_NAME='sa_suorat_amk7a_rekrytointihaut')
BEGIN
drop table [sa].[sa_suorat_amk7a_rekrytointihaut]
END
IF NOT EXISTS
(select * from INFORMATION_SCHEMA.TABLES
where TABLE_SCHEMA='sa' and TABLE_NAME='sa_suorat_amk7a_rekrytointihaut')
BEGIN
CREATE TABLE [sa].[sa_suorat_amk7a_rekrytointihaut](
[Korkeakoulu] [nvarchar](5) NULL,
[Tilastovuosi] [nvarchar](4) NULL,
[Hakunumero] [nvarchar](100) NULL,
[Haun kansainvälisyys] [nvarchar](5) NULL,
[Sukupuoli] [nvarchar](5) NULL,
[Kansalaisuus] [nvarchar](5) NULL,
[Ei-suomalaisen hakijan maanosa] [nvarchar](5) NULL,
[Hakijoiden määrä] [nvarchar](100) NULL,
[Hakijoiden määrä yhteensä haussa] [nvarchar](100) NULL,
[IMP_CREATED_DATE] [datetime] NULL,
[IMP_UPDATED_DATE] [datetime] NULL,
[IMP_CREATED_BY] [nvarchar](100) NULL
) ON [PRIMARY]
END
IF EXISTS
(select * from INFORMATION_SCHEMA.TABLES
where TABLE_SCHEMA='sa' and TABLE_NAME='sa_suorat_yo8a_rekrytointihaut')
BEGIN
drop table [sa].[sa_suorat_yo8a_rekrytointihaut]
END
IF NOT EXISTS
(select * from INFORMATION_SCHEMA.TABLES
where TABLE_SCHEMA='sa' and TABLE_NAME='sa_suorat_yo8a_rekrytointihaut')
BEGIN
CREATE TABLE [sa].[sa_suorat_yo8a_rekrytointihaut](
[Korkeakoulu] [nvarchar](5) NULL,
[Tilastovuosi] [nvarchar](4) NULL,
[Hakunumero] [nvarchar](100) NULL,
[Kutsuhaku] [nvarchar](5) NULL,
[Yhteisprofessuuri] [nvarchar](5) NULL,
[Haun kansainvälisyys] [nvarchar](5) NULL,
[Sukupuoli] [nvarchar](5) NULL,
[Kansalaisuus] [nvarchar](5) NULL,
[Ei-suomalaisen hakijan maanosa] [nvarchar](5) NULL,
[Hakijoiden määrä] [nvarchar](100) NULL,
[Hakijoiden määrä yhteensä haussa] [nvarchar](100) NULL,
[IMP_CREATED_DATE] [datetime] NULL,
[IMP_UPDATED_DATE] [datetime] NULL,
[IMP_CREATED_BY] [nvarchar](100) NULL
) ON [PRIMARY]
END
| 31.627119
| 76
| 0.755091
|
e7250a3f03dfb8ff6b1f9afc817d8bd1f1ccf6dc
| 3,567
|
php
|
PHP
|
routes/web.php
|
kunkun1231998/ttcs1
|
cee30ed268543a8190264b1f11c9d9cec532dc88
|
[
"MIT"
] | null | null | null |
routes/web.php
|
kunkun1231998/ttcs1
|
cee30ed268543a8190264b1f11c9d9cec532dc88
|
[
"MIT"
] | 1
|
2021-01-06T06:02:26.000Z
|
2021-01-06T06:02:26.000Z
|
routes/web.php
|
kunkun1231998/ttcs1
|
cee30ed268543a8190264b1f11c9d9cec532dc88
|
[
"MIT"
] | null | null | null |
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
/* Route for user */
Route::get('', 'PagesController@getindex');
/* Display front */
Route::get('category/{slug}','PagesController@getCategory');
Route::get('post/{slug}.html','PagesController@getPost');
Route::get('tag/{tag}','PagesController@getTag');
Route::get('author/{name}','PagesController@getAuthor');
Route::get('search','PagesController@getSearch')->name('search');
Route::get('contact.html','PagesController@getContact');
Route::get('login', 'LoginController@getLogin');
Route::post('login', 'LoginController@postLogin')->name('login');
Route::get('logout', 'LoginController@getLogout');
/*Group router for author and admin */
Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function(){
Route::get('/', 'HomeController@getdashbroad')->name('dashbroad');
/* Group for profile */
Route::get('profile', 'ProfileController@getProfile');
Route::post('profile/update', 'ProfileController@profileUpdate');
/*Web structure*/
Route::prefix('structure')->name('structure')->group(function(){
Route::get('/', 'WebStructureController@index')->name('.index');
Route::post('/update-post-length', 'WebStructureController@updatePostPagePostLength')->name('.update_post_length');
});
/* Group post*/
Route::prefix('post')->group(function () {
Route::get('/', 'PostController@getList')->name('list-post');
Route::get('add', 'PostController@getAdd');
Route::put('updateStatus', 'PostController@updateStatus');
Route::put('updateHot', 'PostController@updateHot');
Route::post('add', 'PostController@postAdd');
Route::get('update/{id}', 'PostController@getUpdate');
Route::post('update/{id}', 'PostController@postUpdate');
Route::get('delete/{id}', 'PostController@getDelete');
});
/* Group for admin */
Route::middleware(['role'])->group(function () {
/* Group category */
Route::prefix('category')->group(function () {
Route::get('/', 'CategoryController@getList');
Route::get('add', 'CategoryController@getAdd');
Route::post('add', 'CategoryController@postAdd');
Route::get('data', 'CategoryController@dataTable')->name('data');
Route::post('update', 'CategoryController@postUpdate');
Route::delete('delete', 'CategoryController@delete');
});
/* Group file */
Route::prefix('tag')->group(function () {
Route::get('/', 'TagController@getList')->name('list-tag');
Route::get('data', 'TagController@dataTable')->name('data-tag');
Route::post('add', 'TagController@postAdd');
Route::put('update', 'TagController@putUpdate');
Route::delete('delete', 'TagController@delete');
});
/* Group author */
Route::prefix('author')->group(function () {
Route::get('/', 'AdminController@getList')->name('list-author');
Route::get('data', 'AdminController@dataTable')->name('data-author');
Route::post('add', 'AdminController@postAdd');
Route::delete('delete', 'AdminController@delete');
});
});
});
| 44.5875
| 123
| 0.599103
|
a3d378c7dc7c58f68b22a21bc2f50bef7e3b623b
| 3,176
|
java
|
Java
|
src/main/java/seedu/budgetbaby/logic/parser/BudgetBabyParser.java
|
natosy/tp
|
fe47e54a60f057af3e37f90de9ae99b069069094
|
[
"MIT"
] | null | null | null |
src/main/java/seedu/budgetbaby/logic/parser/BudgetBabyParser.java
|
natosy/tp
|
fe47e54a60f057af3e37f90de9ae99b069069094
|
[
"MIT"
] | 184
|
2021-02-25T02:16:59.000Z
|
2021-04-12T15:54:54.000Z
|
src/main/java/seedu/budgetbaby/logic/parser/BudgetBabyParser.java
|
natosy/tp
|
fe47e54a60f057af3e37f90de9ae99b069069094
|
[
"MIT"
] | 5
|
2021-02-15T14:12:49.000Z
|
2021-02-15T14:13:40.000Z
|
package seedu.budgetbaby.logic.parser;
import static seedu.budgetbaby.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.budgetbaby.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import seedu.budgetbaby.logic.commands.AddFrCommand;
import seedu.budgetbaby.logic.commands.BudgetBabyCommand;
import seedu.budgetbaby.logic.commands.DeleteFrCommand;
import seedu.budgetbaby.logic.commands.EditFrCommand;
import seedu.budgetbaby.logic.commands.ExitCommand;
import seedu.budgetbaby.logic.commands.FindFrCommand;
import seedu.budgetbaby.logic.commands.HelpCommand;
import seedu.budgetbaby.logic.commands.RedoCommand;
import seedu.budgetbaby.logic.commands.ResetFilterCommand;
import seedu.budgetbaby.logic.commands.SetBudgetCommand;
import seedu.budgetbaby.logic.commands.UndoCommand;
import seedu.budgetbaby.logic.commands.ViewMonthCommand;
import seedu.budgetbaby.logic.parser.exceptions.ParseException;
/**
* Parses user input.
*/
public class BudgetBabyParser {
/**
* Used for initial separation of command word and args.
*/
private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)");
/**
* Parses user input into command for execution.
*
* @param userInput full user input string
* @return the command based on the user input
* @throws ParseException if the user input does not conform the expected format
*/
public BudgetBabyCommand parseCommand(String userInput) throws ParseException {
final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim());
if (!matcher.matches()) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE));
}
final String commandWord = matcher.group("commandWord");
final String arguments = matcher.group("arguments");
switch (commandWord) {
case AddFrCommand.COMMAND_WORD:
return new AddFrCommandParser().parse(arguments);
case DeleteFrCommand.COMMAND_WORD:
return new DeleteFrCommandParser().parse(arguments);
case EditFrCommand.COMMAND_WORD:
return new EditFrCommandParser().parse(arguments);
case SetBudgetCommand.COMMAND_WORD:
return new SetBudgetCommandParser().parse(arguments);
case FindFrCommand.COMMAND_WORD:
return new FindFrCommandParser().parse(arguments);
case ResetFilterCommand.COMMAND_WORD:
return new ResetFilterCommand();
case ViewMonthCommand.COMMAND_WORD:
return new ViewMonthCommandParser().parse(arguments);
case UndoCommand.COMMAND_WORD:
return new UndoCommandParser().parse(arguments);
case RedoCommand.COMMAND_WORD:
return new RedoCommandParser().parse(arguments);
case ExitCommand.COMMAND_WORD:
return new ExitCommand();
case HelpCommand.COMMAND_WORD:
return new HelpCommand();
default:
throw new ParseException(MESSAGE_UNKNOWN_COMMAND);
}
}
}
| 35.288889
| 112
| 0.72796
|
be03384fea664b4f534f7695cbdfd613fdb99dcc
| 272
|
ts
|
TypeScript
|
libs/data/src/lib/DisplayedTip.ts
|
mJehanno/cr-tips
|
fdca264325c20684b878ae4d280621abd64aca77
|
[
"MIT"
] | 1
|
2019-11-11T08:56:30.000Z
|
2019-11-11T08:56:30.000Z
|
libs/data/src/lib/DisplayedTip.ts
|
mJehanno/cr-tips
|
fdca264325c20684b878ae4d280621abd64aca77
|
[
"MIT"
] | 22
|
2019-09-04T14:50:32.000Z
|
2022-02-26T15:38:43.000Z
|
libs/data/src/lib/DisplayedTip.ts
|
mJehanno/cr-tips
|
fdca264325c20684b878ae4d280621abd64aca77
|
[
"MIT"
] | 1
|
2021-08-22T17:08:12.000Z
|
2021-08-22T17:08:12.000Z
|
import { User, Commentary } from '..';
export interface DisplayedTip {
idTips?: string;
authorUser: User;
date: Date;
title: string;
content: string;
commentaries?: Commentary[];
score: number;
game_mode?: string;
category?: string;
}
| 19.428571
| 38
| 0.628676
|
455a299b2c1c67daac2d82fda35406e23bdeee5c
| 651
|
py
|
Python
|
Algorithms/Medium/200. Number of Islands/answer.py
|
KenWoo/Algorithm
|
4012a2f0a099a502df1e5df2e39faa75fe6463e8
|
[
"Apache-2.0"
] | null | null | null |
Algorithms/Medium/200. Number of Islands/answer.py
|
KenWoo/Algorithm
|
4012a2f0a099a502df1e5df2e39faa75fe6463e8
|
[
"Apache-2.0"
] | null | null | null |
Algorithms/Medium/200. Number of Islands/answer.py
|
KenWoo/Algorithm
|
4012a2f0a099a502df1e5df2e39faa75fe6463e8
|
[
"Apache-2.0"
] | null | null | null |
from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
if not grid:
return 0
M, N = len(grid), len(grid[0])
def dfs(x, y):
if x < 0 or x >= M or y < 0 or y >= N or grid[x][y] == '0':
return
grid[x][y] = '0'
dfs(x+1, y)
dfs(x-1, y)
dfs(x, y+1)
dfs(x, y-1)
res = 0
for i in range(M):
for j in range(N):
if grid[i][j] == '1':
res += 1
dfs(i, j)
return res
if __name__ == "__main__":
pass
| 22.448276
| 71
| 0.380952
|
51cef877308979347e8d2794f96747e41ef78f86
| 20,830
|
lua
|
Lua
|
durden/tiler_mh.lua
|
diegogangl/durden
|
0a9abe18d38c4a1d55a20b10ae0cab3eb712416c
|
[
"BSD-3-Clause"
] | null | null | null |
durden/tiler_mh.lua
|
diegogangl/durden
|
0a9abe18d38c4a1d55a20b10ae0cab3eb712416c
|
[
"BSD-3-Clause"
] | null | null | null |
durden/tiler_mh.lua
|
diegogangl/durden
|
0a9abe18d38c4a1d55a20b10ae0cab3eb712416c
|
[
"BSD-3-Clause"
] | null | null | null |
--
-- This translation unit returns factory functions for the possible decoration
-- mouse handlers, as well as the default implementation for mouse events that
-- are attached to a window on creation.
--
-- Much of this could/should be reworked to use builtin/decorator.lua instead.
--
local tiler_logfun = suppl_add_logfn("wm");
local function tiler_debug(wm, msg)
msg = msg and msg or "bad message";
tiler_logfun(wm.name .. ":" .. msg);
end
local function dist(x, y)
return math.sqrt(x * x + y * y);
end
-- map rectangle edge to mouse-cursor direction and name
local dir_lut = {
ul = {"rz_diag_r", {-1, -1, 1, 1}},
u = {"rz_up", {0, -1, 0, 1}},
ur = {"rz_diag_l", {1, -1, 0, 1}},
r = {"rz_right", {1, 0, 0, 0}},
lr = {"rz_diag_r", {1, 1, 0, 0}},
d = {"rz_down", {0, 1, 0, 0}},
ll = {"rz_diag_l", {-1, 1, 1, 0}},
l = {"rz_left", {-1, 0, 1, 0}}
};
-- display- local coordinate to window border conversion
-- returns a matching string/key from dir_lut
local function mouse_to_border(wnd)
local x, y = mouse_xy();
local props = image_surface_resolve(wnd.anchor);
-- hi-clamp radius, select corner by distance (priority)
local cd_ul = dist(x-props.x, y-props.y);
local cd_ur = dist(props.x + props.width - x, y - props.y);
local cd_ll = dist(x-props.x, props.y + props.height - y);
local cd_lr = dist(props.x + props.width - x, props.y + props.height - y);
local lim = 32;
if (cd_ur < lim) then
return "ur";
elseif (cd_lr < lim) then
return "lr";
elseif (cd_ll < lim) then
return "ll";
elseif (cd_ul < lim) then
return "ul";
end
local dle = x-props.x;
local dre = props.x+props.width-x;
local due = y-props.y;
local dde = props.y+props.height-y;
local dx = dle < dre and dle or dre;
local dy = due < dde and due or dde;
-- for aspect ratio scaling, we practically only have the diagonals
if (wnd.scalemode == "aspect") then
if (dx < dy) then
if (dle < dre) then
return due < 0.5 * props.height and "ul" or "ll";
else
return due < 0.5 * props.height and "ur" or "lr";
end
else
if (dle < dre) then
return due < 0.5 * props.height and "ul" or "ll";
else
return due < 0.5 * props.height and "ur" or "lr";
end
end
end
if (dx < dy) then
return dle < dre and "l" or "r";
else
return due < dde and "u" or "d";
end
end
local old_btn
local function wnd_drag_preview_synch(wnd)
if wnd.in_drag_ts < wnd.space.last_action then
wnd.in_drag_move = wnd:linearize(wnd.space);
end
-- more options here is with tab (swap order) and if rcpt is the titlebar
-- (merge/hide into window then add as button)
local x, y = mouse_xy();
-- statusbar buttons are the exception, we need to go in / out
if old_btn and valid_vid(old_btn.bg) then
if image_hit(old_btn.bg, x, y) then
old_btn:switch_state("active")
return
end
old_btn:switch_state("inactive")
end
for btn in wnd.wm.statusbar:all_buttons() do
if image_hit(btn.bg, x, y) then
old_btn = btn
btn:switch_state("active")
if valid_vid(wnd.drag_move_preview) then
delete_image(wnd.drag_move_preview)
wnd.drag_move_preview = nil
wnd.in_drag_last = nil
wnd.drag_move_pos = nil
end
return
end
end
old_btn = nil
-- the action depends on if we are in tiling or not
if wnd.space.mode ~= "tile" then
return
end
-- cache to not iterate on every step, account for lw being removed during drag
local lw = wnd.in_drag_last;
if lw then
if lw.x and
x >= lw.x and x <= lw.width + lw.x and
y >= lw.y and y <= lw.height + lw.y then
else
lw = nil;
end
end
-- otherwise we have to searh
if not lw then
for _,v in ipairs(wnd.in_drag_move) do
if v ~= wnd and x >= v.x and x <= v.width + v.x and
y >= v.y and y <= v.height + v.y then
lw = v;
break;
end
end
end
wnd.in_drag_last = lw;
if not lw then
-- top, bottom or statusbar
return
end
-- figure out effective region (and action), since it attaches to the current
-- 'over' window it could die while we are moving
local dmp;
local dpos = wnd.drag_move_pos;
if not valid_vid(wnd.drag_move_preview) then
wnd.drag_move_preview = color_surface(64, 64, unpack(gconfig_get("titlebar_color")));
image_inherit_order(wnd.drag_move_preview, true);
order_image(wnd.drag_move_preview, 1);
dmp = wnd.drag_move_preview;
else
dmp = wnd.drag_move_preview;
end
local set_preview =
function(anchor, anchor_dir, w, h, dw, dh, tag)
if dpos == tag then
return;
end
local at = gconfig_get("animation");
hide_image(dmp);
resize_image(dmp, 1, 1);
move_image(dmp, 0, 0);
link_image(dmp, anchor, anchor_dir);
resize_image(dmp, w, h, at);
move_image(dmp, w * dw, h * dh, at);
blend_image(dmp, 0.5, at);
image_mask_set(dmp, MASK_UNPICKABLE);
wnd.drag_move_pos = tag;
end
if y < lw.y + lw.effective_h * 0.2 then
set_preview(lw.canvas, ANCHOR_UL,
lw.effective_w, lw.effective_h * 0.2, 0, 0, "t");
elseif y > lw.y + lw.effective_h * 0.8 then
local bh = math.ceil(lw.effective_h * 0.2);
set_preview(lw.canvas, ANCHOR_LL, lw.effective_w, bh, 0, -1, "d");
elseif x < lw.x + lw.effective_w * 0.2 then
set_preview(lw.canvas, ANCHOR_UL,
lw.effective_w * 0.2, lw.effective_h, 0, 0, "l");
elseif x > lw.x + lw.effective_w * 0.8 then
local bw = math.ceil(lw.effective_w * 0.2);
set_preview(lw.canvas, ANCHOR_UR, bw, lw.effective_h, -1, 0, "r");
else
local bw = math.ceil(lw.effective_w * 0.4);
local bh = math.ceil(lw.effective_h * 0.4);
set_preview(lw.canvas, ANCHOR_C, bw, bh, -0.5, -0.5, "c");
end
end
-- evaluate position and update cursor etc. based on where we are, this is
-- made more complicated about a client actually telling us which border it
-- thinks that we are on.
local function set_borderstate(ctx)
local p = mouse_to_border(ctx.tag);
local ent = dir_lut[p];
ctx.mask = ent[2];
mouse_switch_cursor(ent[1]);
end
local function step_drag_resize(wnd, mctx, vid, dx, dy)
-- absurd warp->drag without over first
if (not mctx.mask) then
return;
end
local dt = wnd.drag_sz_ack
-- for client- driven resizing, we can only send our suggestion ('configure')
-- and then wait in the client event handler on a time where that makes sense
if (wnd.scalemode == "client" and
valid_vid(wnd.external, TYPE_FRAMESERVER)) then
-- remember the accumulated delta (as the client ack will be dragging behind)
-- then we flush in the extevh- resized handler
dt.acc_x = dt.acc_x + dx
dt.acc_y = dt.acc_y + dy
wnd:displayhint(
dt.w + dt.acc_x * dt.size_x,
dt.h + dt.acc_y * dt.size_y, wnd.dispmask
);
else
wnd.x = wnd.x + dx * mctx.mask[3];
wnd.y = wnd.y + dy * mctx.mask[4];
wnd:resize(
wnd.width + dx * mctx.mask[1],
wnd.height + dy * mctx.mask[2],
true, false
);
move_image(wnd.anchor, wnd.x, wnd.y);
end
end
-- special sematics for dragging a window and dropping it on top of another
local function try_swap(wnd, tgt, tgt_dir)
if tgt_dir == "c" then
wnd:swap(tgt, false, false);
elseif tgt_dir == "t" then
local top = wnd
while top.parent ~= nil do
top = top.parent
end
wnd:collapse();
wnd:reparent(tgt);
wnd:swap(wnd.parent);
wnd.space:resize();
elseif tgt_dir == "l" then
wnd:collapse();
wnd:reparent(tgt, true);
-- re-order so it lands at the index to the left
table.remove_match(tgt.parent.children, wnd);
local i = table.find_i(tgt.parent.children, tgt);
table.insert(tgt.parent.children, i, wnd);
wnd.space:resize();
elseif tgt_dir == "r" then
wnd:collapse();
wnd:reparent(tgt, true);
table.remove_match(tgt.parent.children, wnd);
local i = table.find_i(tgt.parent.children, tgt);
table.insert(tgt.parent.children, i + 1, wnd);
wnd.space:resize();
-- re-order so it lands at the index to the right
elseif tgt_dir == "d" then
wnd:collapse();
wnd:reparent(tgt);
wnd.space:resize();
end
end
local function drop_swap(wnd, mode, tgt, tgt_dir)
-- first clean up
wnd.drag_move_pos = nil;
if valid_vid(wnd.drag_move_preview) then
delete_image(wnd.drag_move_preview);
wnd.drag_move_preview = nil;
end
-- if we have an explicit target, just go with that
if tgt then
if mode == "tile" then
try_swap(wnd, tgt, tgt_dir);
wnd.space:resize();
end
return;
end
-- otherwise we still need to check for drag over statusbar buttons
local x, y = mouse_xy();
wnd.in_drag_move = false;
if valid_vid(wnd.drag_move_preview) then
delete_image(wnd.drag_move_preview);
wnd.drag_move_preview = nil;
end
-- gather / repack the suspects
local items = pick_items(x, y, 8, true, active_display(true));
if not items or #items == 0 then
return;
end
local set = {};
for i,v in ipairs(items) do
set[v] = true;
end
-- this could also be used for individual window titlebar buttons or
-- the bar itself, e.g. drag to dock into titlebar for pseudo- tabbed
for btn in wnd.wm.statusbar:all_buttons() do
if set[btn.bg] then
if (btn.drag_command) then
dispatch_symbol_wnd(wnd, btn.drag_command);
end
break;
end
end
wnd.space:resize();
end
local function build_border(wnd)
local table =
{
-- required 'metadata'
name = wnd.name .. "_mh_border",
own =
function(ctx, vid)
return vid == wnd.border;
end,
tag = wnd,
-- actual event handlers:
motion =
function(ctx)
if (wnd.space.mode == "float") then
set_borderstate(ctx);
end
end,
over = function(ctx)
return ctx.motion;
end,
out =
function(ctx)
mouse_switch_cursor("default");
wnd.in_drag_rz = false;
wnd.in_drag_move = false;
end,
-- The worst of the bunch: border-drag-resize, this is made worse by the
-- wayland case where clients may have border contents we don't know about
-- and may need the client canvas to act as 'border'.
--
-- To deal with that, part of the drag_rz behavior is split into the handler
-- here and the in_drag_rz / drag_rz_enter states of the wnd table.
drag =
function(ctx, vid, dx, dy)
if (not ctx.mask) then
set_borderstate(ctx);
end
-- protect against ugly "window destroyed just as we got drag"
if (not wnd.drag_resize or wnd.space.mode ~= "float") then
return;
end
if (not wnd.in_drag_rz and wnd.drag_rz_enter) then
wnd:drag_rz_enter(ctx.mask);
end
-- some (wayland) clients need entirely different behaviors here,
-- so we add an override that can be hooked and fall back to our own
-- if needed
if (wnd.in_drag_rz) then
if (type(wnd.in_drag_rz) == "function") then
wnd:in_drag_rz(ctx, vid, dx, dy, false);
else
step_drag_resize(wnd, ctx, vid, dx, dy);
end
return;
end
-- distinguish between on_begin_drag_resize and update_drag_resize
wnd:drag_resize(ctx, true);
step_drag_resize(wnd, ctx, vid, dx, dy);
end,
drop = function(ctx)
tiler_debug(wnd.wm, "begin_drop");
if (wnd.space.mode ~= "float") then
return;
end
-- should have separate rules for tiling here that shows a drag 'anchor'
-- which we use to calculate splitting point
if (type(wnd.in_drag_rz) == "function") then
-- wnd:in_drag_rz(vid, 0, 0, true);
end
-- normal might also care
if (wnd.drag_resize) then
wnd:drag_resize(ctx, false);
end
end
};
mouse_addlistener(table, {"motion", "out", "over", "drag", "drop"});
return table;
end
local function build_canvas(wnd)
local table =
{
name = wnd.name .. "_mh_canvas",
own =
function(ctx, vid)
return vid == wnd.canvas;
end,
motion =
function(ctx, vid, x, y, rx, ry)
local ct = mouse_state().cursortag;
if (ct) then
-- update accept state, for external clients we need to do a lot more
-- via the clipboard - i.e. ask if the type is currently accepted and
-- so on. the distributed mouse.lua is flawed here so temporarily set
-- overrides on vid and state here
if (ct.handler and ct.handler(ct.ref, nil, wnd)) then
mouse_cursortag_state(true);
if (valid_vid(ct.vid)) then
blend_image(ct.vid, 1.0);
end
ct.accept = true;
else
mouse_cursortag_state(false);
if (valid_vid(ct.vid)) then
blend_image(ct.vid, 0.5);
end
ct.accept = false;
end
end
wnd:run_event("mouse_motion", x, y);
wnd:mousemotion(x, y, rx, ry);
end,
-- We support two modes of 'drag and drop' where one comes from press/
-- release and the other, more disability friendly, is a full click.
release = function(ctx, vid, ...)
local ct = mouse_state().cursortag;
if (not ct) then
return;
end
ct.handler(ct.ref, true, wnd);
wnd.wm:cancellation();
end,
drag = function(ctx, vid, dx, dy, ...)
-- handle drag as well since it will mask 'motion' events as soon as we
-- are out of the drag threshold (if the event is handled)
if (wnd.space.mode ~= "float" and wnd.space.mode ~= "tile") then
local x, y = mouse_xy();
wnd:mousemotion(x, y, dx, dy);
return;
end
-- it has been an established custom elsewhere to always allow 'canvas+meta'
-- drag as an interpretation of starting a move, so go with that
if (not wnd.in_drag_move) then
local m1, m2 = dispatch_meta();
if (m1 or m2) then
wnd.x = wnd.x + wnd.ofs_x;
wnd.y = wnd.y + wnd.ofs_y;
wnd.in_drag_move = wnd.space:linearize();
wnd.in_drag_ts = CLOCK;
mouse_switch_cursor("drag");
end
end
-- with no decoration and a client that has requested that we are in resize
-- mode, we need to repeat the same dance we do in the border handler
if (wnd.in_drag_rz) then
if (type(wnd.in_drag_rz) == "function") then
wnd:in_drag_rz(ctx, vid, dx, dy);
else
step_drag_resize(wnd, ctx, vid, dx, dy);
end
-- move is easier, but options that are specific for mouse here:
-- a. don't align
-- b. interpret coordinates relative
-- c. perform instantaneous (no animation)
elseif (wnd.in_drag_move) then
wnd:move(dx, dy, false, false, true);
wnd_drag_preview_synch(wnd);
for k,v in ipairs(wnd.space.wm.on_wnd_drag) do
v(wnd.space.wm, wnd, dx, dy);
end
return true;
-- otherwise let the normal window mouse motion handler take care of
-- forwarding, updating state and translate to client coordinates
else
local x, y = mouse_xy();
wnd:mousemotion(x, y, dx, dy);
end
end,
drop = function(ctx, vid)
if (wnd.in_drag_move) then
drop_swap(wnd, wnd.space.mode, wnd.in_drag_last, wnd.drag_move_pos);
-- wm global drag handlers
for k,v in ipairs(wnd.space.wm.on_wnd_drag) do
v(wnd.space.wm, wnd, 0, 0, true);
end
wnd:recovertag();
end
wnd.in_drag_rz = false;
wnd:mouseactivate();
end,
press = function(ctx, vid, ...)
if (wnd.mousepress and not wnd.in_drag_rz and not wnd.in_drag_move) then
wnd:mousepress(...);
end
end,
over = function(ctx)
if (wnd.wm.selected ~= wnd and
gconfig_get("mouse_focus_event") == "motion") then
wnd:select();
else
wnd:mouseactivate();
end
end,
-- make sure that the cursor is always visible (if it is supposed to be)
-- when we leave the surface, chances are it might get re-hidden when it
-- enters something else though.
out = function(ctx)
mouse_hidemask(true);
mouse_show();
mouse_switch_cursor();
mouse_hidemask(false);
-- also reset border drag-state
wnd.in_drag_rz = false;
wnd.in_drag_move = false;
end,
button = function(ctx, vid, ...)
if wnd.mousebutton then
wnd:mousebutton(...);
end
end,
dblclick = function(ctx)
if wnd.mousedblclick then
wnd:mousedblclick();
end
end
};
mouse_addlistener(table, {
"motion", "out", "over", "drag", "drop",
"button", "dblclick", "press", "release"
});
return table;
end
local function build_titlebar(wnd)
local table = {
tag = wnd,
name = wnd.name .. "_tbar_mh",
over =
function(ctx)
if (wnd.space.mode == "float" or wnd.space.mode == "tile") then
mouse_switch_cursor("grabhint");
end
end,
out =
function(ctx)
mouse_switch_cursor("default");
end,
press =
function(ctx)
wnd:select();
local mode = wnd.space.mode;
if (mode == "float" or mode == "tile") then
mouse_switch_cursor("drag");
end
end,
release =
function(ctx)
if (wnd.space.mode == "tile") then
mouse_switch_cursor("grabhint");
end
end,
drop =
function(ctx)
local mode = wnd.space.mode;
drop_swap(wnd, wnd.space.mode, wnd.in_drag_last, wnd.drag_move_pos);
if old_btn and valid_vid(old_btn.bg) then
old_btn:switch_state("inactive")
old_btn = nil
end
if (mode == "float" or mode == "tile") then
mouse_switch_cursor("grabhint");
for k,v in ipairs(wnd.wm.on_wnd_drag) do
v(wnd.wm, wnd, 0, 0, true);
end
-- make sure new position gets saved
wnd:recovertag();
end
end,
drag =
function(ctx, vid, dx, dy)
local mode = wnd.space.mode;
-- no constraint or collision solver here, might be needed?
if (mode == "float" or mode == "tile") then
-- disable the VIDs from the 'drag' so that on-over/on-out tracking
-- register for windows that we are passing
if not wnd.in_drag_move then
wnd:set_drag_move();
end
wnd:move(dx, dy, false, false, true);
wnd_drag_preview_synch(wnd);
-- some event handlers to allow determining if it is 'droppable' or not
for k,v in ipairs(wnd.wm.on_wnd_drag) do
v(wnd.wm, wnd, dx, dy);
end
end
end,
click =
function(ctx)
end,
rclick =
function(ctx)
wnd:select();
dispatch_symbol(gconfig_get("tbar_rclick"));
end,
dblclick =
function(ctx)
if (wnd.space.mode == "float") then
wnd:toggle_maximize();
end
end
};
return table;
end
local function build_statusbar_icon(wm, cmd, alt_cmd)
tiler_debug(wm, "sbar_icon:" ..
"cmd=" .. (cmd and cmd or "none"),
"alt_cmd=" .. (alt_cmd and alt_cmd or "none"));
local table = {
click =
function(btn)
local m1, m2 = dispatch_meta();
if (m1 and alt_cmd) then
dispatch_symbol(alt_cmd);
elseif (cmd) then
dispatch_symbol(cmd);
end
end,
over =
function(btn)
btn:switch_state("active");
end,
out =
function(btn)
btn:switch_state("inactive");
end,
rclick =
function(btn)
dispatch_symbol(alt_cmd and alt_cmd or cmd);
end
};
return table;
end
local function build_statusbar_addicon(wm)
return {
click =
function(btn)
dispatch_symbol("/global/workspace/switch/new");
end,
over =
function(btn)
btn:switch_state("active");
end,
out =
function(btn)
btn:switch_state("inactive")
end
};
end
local function build_statusbar_wsicon(wm, i)
local table = {
click =
function(btn)
wm:switch_ws(i);
end,
rclick =
function(btn)
local ment = gconfig_get("ws_popup");
local menu = menu_lookup_custom(ment);
if not menu then
tiler_debug(wm, "wsbtn:kind=error:status=einval:message=redirect_click:name=" .. ment);
return btn:click();
end
menu = table.copy(menu);
menu.preset = i;
local x, y = mouse_xy();
uimap_popup(menu, x, y, btn.bg);
end,
over =
function(btn)
btn:switch_state(wm.space_ind == i and "alert" or "active");
end,
out =
function(btn)
btn:switch_state(wm.space_ind == i and "active" or "inactive")
end
}
return table;
end
local function fallthrough(wm)
local m1, m2 = dispatch_meta();
return (wm.fallthrough_ioh and not m1 and not m2);
end
local function symaction(wm, sym)
local action = gconfig_get(sym);
tiler_logfun(string.format("action: %s, fallthrough: %s", action, tostring(fallthrough(wm))));
if not action or #action == 0 or fallthrough(wm) then
return;
end
dispatch_symbol(action);
end
local function build_background(wm)
local table = {
name = "workspace_background",
motion = function(ctx, vid, x, y, rx, ry)
if not fallthrough(wm) then
return;
end
-- re-use the window coordinate bits so that we get the storage-
-- relative coordinate scaling etc.
local fakewnd = {
last_ms = wm.last_ms,
external = wm:active_space().background_src,
canvas = vid
};
local mv = wm.convert_mouse_xy(fakewnd, x, y, rx, ry);
wm:fallthrough_ioh({
kind = "analog",
mouse = true,
devid = 0,
subid = 0,
samples = {mv[1], mv[2]}
});
wm:fallthrough_ioh({
kind = "analog",
mouse = true,
devid = 0,
subid = 1,
samples = {mv[3], mv[4]}
});
end,
button = function(ctx, vid, ind, pressed, x, y)
if (wm.selected) then
wm.selected:deselect();
end
-- only forward if meta is not being held
if fallthrough(wm) then
wm:fallthrough_ioh(
{
kind = "digital", mouse = true, devid = 0,
active = pressed, subid = ind
});
end
end,
click = function(ctx, vid, ...)
symaction(wm, "float_bg_click");
end,
rclick = function(ctx, vid, ...)
symaction(wm, "float_bg_rclick");
end,
dblclick = function(ctx, vid, ...)
symaction(wm, "float_bg_dblclick");
end,
own = function(ctx, vid, ...)
local sp = wm:active_space();
return sp and sp.background == vid and sp.mode == "float";
end
};
return table;
end
return {
background = build_background,
border = build_border,
canvas = build_canvas,
titlebar = build_titlebar,
statusbar_icon = build_statusbar_icon,
statusbar_wsicon = build_statusbar_wsicon,
statusbar_addicon = build_statusbar_addicon
};
| 24.025375
| 95
| 0.67398
|
3123705475c680b86411810361457b0fa611148f
| 3,001
|
sql
|
SQL
|
EMPRESA.sql
|
dario-gms/Modelagem-de-Dados
|
8f999fa615791f04847fcf45771b4f831396c126
|
[
"MIT"
] | null | null | null |
EMPRESA.sql
|
dario-gms/Modelagem-de-Dados
|
8f999fa615791f04847fcf45771b4f831396c126
|
[
"MIT"
] | null | null | null |
EMPRESA.sql
|
dario-gms/Modelagem-de-Dados
|
8f999fa615791f04847fcf45771b4f831396c126
|
[
"MIT"
] | null | null | null |
CREATE TABLE TB_FUNCIONARIO (
CPF VARCHAR(11) NOT NULL,
DATA_NASCIMENTO DATE NOT NULL,
PRIMEIRO_NOME VARCHAR(100) NOT NULL,
NOME_MEIO VARCHAR(100) NOT NULL,
ULTIMO_NOME VARCHAR(100) NOT NULL,
ENDERECO VARCHAR(250) NOT NULL,
SALARIO DOUBLE PRECISION NOT NULL,
SEXO VARCHAR(1) NOT NULL,
CPF_SUPERVISOR VARCHAR(11) NOT NULL,
NUMERO_DEPARTAMENTO INT NOT NULL,
PRIMARY KEY (CPF)
);
CREATE TABLE TB_DEPARTAMENTO (
NUMERO_DEPARTAMENTO INT NOT NULL,
DATA_INICIO_GERENTE DATE NOT NULL,
NOME_DEPARTAMENTO VARCHAR(50) NOT NULL,
CPF_GERENTE VARCHAR(11) NOT NULL,
PRIMARY KEY (NUMERO_DEPARTAMENTO)
);
CREATE TABLE TB_LOCALIZACOES_DEPARTAMENTOS (
LOCAL VARCHAR(50) NOT NULL,
NUMERO_DEPARTAMENTO INT NOT NULL,
PRIMARY KEY (LOCAL, NUMERO_DEPARTAMENTO)
);
CREATE TABLE TB_PROJETO (
NUMERO_PROJETO INT NOT NULL,
NOME_PROJETO VARCHAR(50) NOT NULL,
LOCAL_PROJETO VARCHAR(50) NOT NULL,
NUMERO_DEPARTAMENTO INT NOT NULL,
PRIMARY KEY (NUMERO_PROJETO)
);
CREATE TABLE TB_TRABALHA_EM (
CPF_FUNCIONARIO VARCHAR(11) NOT NULL,
NUMERO_PROJETO INT NOT NULL,
HORAS INT NOT NULL,
PRIMARY KEY (CPF_FUNCIONARIO, NUMERO_PROJETO)
);
CREATE TABLE TB_DEPENDENTE (
CPF_FUNCIONARIO VARCHAR(11) NOT NULL,
NOME_DEPENDENTE VARCHAR(100) NOT NULL,
SEXO VARCHAR(1) NOT NULL,
DATA_NASCIMENTO DATE NOT NULL,
PARENTESCO VARCHAR(50) NOT NULL,
PRIMARY KEY (CPF_FUNCIONARIO, NOME_DEPENDENTE)
);
ALTER TABLE TB_FUNCIONARIO ADD CONSTRAINT tb_funcionario_tb_funcionario_fk
FOREIGN KEY (CPF_SUPERVISOR)
REFERENCES TB_FUNCIONARIO (CPF)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE TB_DEPENDENTE ADD CONSTRAINT tb_funcionario_tb_dependente_fk
FOREIGN KEY (CPF_FUNCIONARIO)
REFERENCES TB_FUNCIONARIO (CPF)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE TB_TRABALHA_EM ADD CONSTRAINT tb_funcionario_tb_trabalha_em_fk
FOREIGN KEY (CPF_FUNCIONARIO)
REFERENCES TB_FUNCIONARIO (CPF)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE TB_DEPARTAMENTO ADD CONSTRAINT tb_funcionario_tb_departamento_fk
FOREIGN KEY (CPF_GERENTE)
REFERENCES TB_FUNCIONARIO (CPF)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE TB_FUNCIONARIO ADD CONSTRAINT tb_departamento_tb_funcionario_fk
FOREIGN KEY (NUMERO_DEPARTAMENTO)
REFERENCES TB_DEPARTAMENTO (NUMERO_DEPARTAMENTO)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE TB_PROJETO ADD CONSTRAINT tb_departamento_tb_projeto_fk
FOREIGN KEY (NUMERO_DEPARTAMENTO)
REFERENCES TB_DEPARTAMENTO (NUMERO_DEPARTAMENTO)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE TB_LOCALIZACOES_DEPARTAMENTOS ADD CONSTRAINT tb_departamento_tb_localizacoes_departamentos_fk
FOREIGN KEY (NUMERO_DEPARTAMENTO)
REFERENCES TB_DEPARTAMENTO (NUMERO_DEPARTAMENTO)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
ALTER TABLE TB_TRABALHA_EM ADD CONSTRAINT tb_projeto_tb_trabalha_em_fk
FOREIGN KEY (NUMERO_PROJETO)
REFERENCES TB_PROJETO (NUMERO_PROJETO)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
| 30.01
| 105
| 0.797401
|
c977677d8c7e8c8af06f6813406567d9ec7e8116
| 4,199
|
ts
|
TypeScript
|
node_modules/react-use-gesture/dist/Controller.d.ts
|
ajchdev/outside-event
|
edaa958d74d5a1431f617bcbcef0d2e838103bd2
|
[
"MIT"
] | null | null | null |
node_modules/react-use-gesture/dist/Controller.d.ts
|
ajchdev/outside-event
|
edaa958d74d5a1431f617bcbcef0d2e838103bd2
|
[
"MIT"
] | null | null | null |
node_modules/react-use-gesture/dist/Controller.d.ts
|
ajchdev/outside-event
|
edaa958d74d5a1431f617bcbcef0d2e838103bd2
|
[
"MIT"
] | null | null | null |
import { StateKey, State, Fn, ReactEventHandlers, InternalConfig, InternalHandlers } from './types';
declare type GestureTimeouts = Partial<{
[stateKey in StateKey]: number;
}>;
/**
* The controller will keep track of the state for all gestures and also keep
* track of timeouts, and window listeners.
*
* @template BinderType the type the bind function should return
*/
export default class Controller {
config: InternalConfig;
handlers: Partial<InternalHandlers>;
state: State;
timeouts: GestureTimeouts;
private domListeners;
private windowListeners;
private bindings;
/**
* Function ran on component unmount: cleans timeouts and removes dom listeners set by the bind function.
*/
clean: () => void;
/**
* Function run every time the bind function is run (ie on every render).
* Resets the binding object and remove dom listeners attached to config.domTarget
*/
resetBindings: () => void;
/**
* Returns the domTarget element and parses a ref if needed.
*/
private getDomTarget;
/**
* Commodity function to let recognizers simply add listeners to config.window.
*/
addWindowListeners: (stateKey: "move" | "drag" | "wheel" | "scroll" | "pinch", listeners: [string, Fn][]) => void;
/**
* Commodity function to let recognizers simply remove listeners to config.window.
*/
removeWindowListeners: (stateKey: "move" | "drag" | "wheel" | "scroll" | "pinch") => void;
/**
* When config.domTarget is set, this function will add dom listeners to it
*/
addDomTargetListeners: (target: EventTarget) => void;
/**
* this.bindings is an object which keys match ReactEventHandlerKeys.
* Since a recognizer might want to bind a handler function to an event key already used by a previously
* added recognizer, we need to make sure that each event key is an array of all the functions mapped for
* that key.
*/
addBindings: (eventNames: "onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onGestureStart" | "onGestureChange" | "onGestureEnd" | ("onMouseDown" | "onMouseDownCapture" | "onMouseEnter" | "onMouseLeave" | "onMouseMove" | "onMouseMoveCapture" | "onMouseOut" | "onMouseOutCapture" | "onMouseOver" | "onMouseOverCapture" | "onMouseUp" | "onMouseUpCapture" | "onTouchCancel" | "onTouchCancelCapture" | "onTouchEnd" | "onTouchEndCapture" | "onTouchMove" | "onTouchMoveCapture" | "onTouchStart" | "onTouchStartCapture" | "onPointerDown" | "onPointerDownCapture" | "onPointerMove" | "onPointerMoveCapture" | "onPointerUp" | "onPointerUpCapture" | "onPointerCancel" | "onPointerCancelCapture" | "onPointerEnter" | "onPointerEnterCapture" | "onPointerLeave" | "onPointerLeaveCapture" | "onPointerOver" | "onPointerOverCapture" | "onPointerOut" | "onPointerOutCapture" | "onGotPointerCapture" | "onGotPointerCaptureCapture" | "onLostPointerCapture" | "onLostPointerCaptureCapture" | "onScroll" | "onScrollCapture" | "onWheel" | "onWheelCapture" | "onGestureStart" | "onGestureChange" | "onGestureEnd")[], fn: Fn) => void;
/**
* getBindings will return an object that will be bound by users
* to the react component they want to interact with.
*/
getBindings: () => ReactEventHandlers;
getBind: () => ReactEventHandlers | (() => void);
}
export {};
| 71.169492
| 1,971
| 0.708978
|
adea18ccad109854088a02db74d8b50bcb9b4f02
| 21,109
|
lua
|
Lua
|
awesome/lib/gears/shape.lua
|
pixelsyntax/dotfiles
|
15f0efd7b0bba8801f77bab46182dd44bc8ac1cb
|
[
"Unlicense"
] | null | null | null |
awesome/lib/gears/shape.lua
|
pixelsyntax/dotfiles
|
15f0efd7b0bba8801f77bab46182dd44bc8ac1cb
|
[
"Unlicense"
] | null | null | null |
awesome/lib/gears/shape.lua
|
pixelsyntax/dotfiles
|
15f0efd7b0bba8801f77bab46182dd44bc8ac1cb
|
[
"Unlicense"
] | null | null | null |
---------------------------------------------------------------------------
--- Module dedicated to gather common shape painters.
--
-- It add the concept of "shape" to Awesome. A shape can be applied to a
-- background, a margin, a mask or a drawable shape bounding.
--
-- The functions exposed by this module always take a context as first
-- parameter followed by the widget and height and additional parameters.
--
-- The functions provided by this module only create a path in the content.
-- to actually draw the content, use `cr:fill()`, `cr:mask()`, `cr:clip()` or
-- `cr:stroke()`
--
-- In many case, it is necessary to apply the shape using a transformation
-- such as a rotation. The preferred way to do this is to wrap the function
-- in another function calling `cr:rotate()` (or any other transformation
-- matrix).
--
-- To specialize a shape where the API doesn't allows extra arguments to be
-- passed, it is possible to wrap the shape function like:
--
-- local new_shape = function(cr, width, height)
-- gears.shape.rounded_rect(cr, width, height, 2)
-- end
--
-- Many elements can be shaped. This include:
--
-- * `client`s (see `gears.surface.apply_shape_bounding`)
-- * `wibox`es (see `wibox.shape`)
-- * All widgets (see `wibox.container.background`)
-- * The progressbar (see `wibox.widget.progressbar.bar_shape`)
-- * The graph (see `wibox.widget.graph.step_shape`)
-- * The checkboxes (see `wibox.widget.checkbox.check_shape`)
-- * Images (see `wibox.widget.imagebox.clip_shape`)
-- * The taglist tags (see `awful.widget.taglist`)
-- * The tasklist clients (see `awful.widget.tasklist`)
-- * The tooltips (see `awful.tooltip`)
--
-- @author Emmanuel Lepage Vallee
-- @copyright 2011-2016 Emmanuel Lepage Vallee
-- @module gears.shape
---------------------------------------------------------------------------
local g_matrix = require( "gears.matrix" )
local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1)
local atan2 = math.atan2 or math.atan -- lua 5.3 compat
local module = {}
--- Add a rounded rectangle to the current path.
-- Note: If the radius is bigger than either half side, it will be reduced.
--
--
--
-- @param cr A cairo content
-- @tparam number width The rectangle width
-- @tparam number height The rectangle height
-- @tparam number radius the corner radius
function module.rounded_rect(cr, width, height, radius)
radius = radius or 10
if width / 2 < radius then
radius = width / 2
end
if height / 2 < radius then
radius = height / 2
end
cr:move_to(0, radius)
cr:arc( radius , radius , radius, math.pi , 3*(math.pi/2) )
cr:arc( width-radius, radius , radius, 3*(math.pi/2), math.pi*2 )
cr:arc( width-radius, height-radius, radius, math.pi*2 , math.pi/2 )
cr:arc( radius , height-radius, radius, math.pi/2 , math.pi )
cr:close_path()
end
--- Add a rectangle delimited by 2 180 degree arcs to the path.
--
--
--
-- @param cr A cairo content
-- @param width The rectangle width
-- @param height The rectangle height
function module.rounded_bar(cr, width, height)
module.rounded_rect(cr, width, height, height / 2)
end
--- A rounded rect with only some of the corners rounded.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam boolean tl If the top left corner is rounded
-- @tparam boolean tr If the top right corner is rounded
-- @tparam boolean br If the bottom right corner is rounded
-- @tparam boolean bl If the bottom left corner is rounded
-- @tparam number rad The corner radius
function module.partially_rounded_rect(cr, width, height, tl, tr, br, bl, rad)
rad = rad or 10
if width / 2 < rad then
rad = width / 2
end
if height / 2 < rad then
rad = height / 2
end
-- Top left
if tl then
cr:arc( rad, rad, rad, math.pi, 3*(math.pi/2))
else
cr:move_to(0,0)
end
-- Top right
if tr then
cr:arc( width-rad, rad, rad, 3*(math.pi/2), math.pi*2)
else
cr:line_to(width, 0)
end
-- Bottom right
if br then
cr:arc( width-rad, height-rad, rad, math.pi*2 , math.pi/2)
else
cr:line_to(width, height)
end
-- Bottom left
if bl then
cr:arc( rad, height-rad, rad, math.pi/2, math.pi)
else
cr:line_to(0, height)
end
cr:close_path()
end
--- A rounded rectangle with a triangle at the top.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam[opt=5] number corner_radius The corner radius
-- @tparam[opt=10] number arrow_size The width and height of the arrow
-- @tparam[opt=width/2 - arrow_size/2] number arrow_position The position of the arrow
function module.infobubble(cr, width, height, corner_radius, arrow_size, arrow_position)
arrow_size = arrow_size or 10
corner_radius = math.min((height-arrow_size)/2, corner_radius or 5)
arrow_position = arrow_position or width/2 - arrow_size/2
cr:move_to(0 ,corner_radius+arrow_size)
-- Top left corner
cr:arc(corner_radius, corner_radius+arrow_size, (corner_radius), math.pi, 3*(math.pi/2))
-- The arrow triangle (still at the top)
cr:line_to(arrow_position , arrow_size )
cr:line_to(arrow_position + arrow_size , 0 )
cr:line_to(arrow_position + 2*arrow_size , arrow_size )
-- Complete the rounded rounded rectangle
cr:arc(width-corner_radius, corner_radius+arrow_size , (corner_radius) , 3*(math.pi/2) , math.pi*2 )
cr:arc(width-corner_radius, height-(corner_radius) , (corner_radius) , math.pi*2 , math.pi/2 )
cr:arc(corner_radius , height-(corner_radius) , (corner_radius) , math.pi/2 , math.pi )
-- Close path
cr:close_path()
end
--- A rectangle terminated by an arrow.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam[opt=height/2] number arrow_length The length of the arrow part
function module.rectangular_tag(cr, width, height, arrow_length)
arrow_length = arrow_length or height/2
if arrow_length > 0 then
cr:move_to(0 , height/2 )
cr:line_to(arrow_length , 0 )
cr:line_to(width , 0 )
cr:line_to(width , height )
cr:line_to(arrow_length , height )
else
cr:move_to(0 , 0 )
cr:line_to(-arrow_length, height/2 )
cr:line_to(0 , height )
cr:line_to(width , height )
cr:line_to(width , 0 )
end
cr:close_path()
end
--- A simple arrow shape.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam[opt=head_width] number head_width The width of the head (/\) of the arrow
-- @tparam[opt=width /2] number shaft_width The width of the shaft of the arrow
-- @tparam[opt=height/2] number shaft_length The head_length of the shaft (the rest is the head)
function module.arrow(cr, width, height, head_width, shaft_width, shaft_length)
shaft_length = shaft_length or height / 2
shaft_width = shaft_width or width / 2
head_width = head_width or width
local head_length = height - shaft_length
cr:move_to ( width/2 , 0 )
cr:rel_line_to( head_width/2 , head_length )
cr:rel_line_to( -(head_width-shaft_width)/2 , 0 )
cr:rel_line_to( 0 , shaft_length )
cr:rel_line_to( -shaft_width , 0 )
cr:rel_line_to( 0 , -shaft_length )
cr:rel_line_to( -(head_width-shaft_width)/2 , 0 )
cr:close_path()
end
--- A squeezed hexagon filling the rectangle.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
function module.hexagon(cr, width, height)
cr:move_to(height/2,0)
cr:line_to(width-height/2,0)
cr:line_to(width,height/2)
cr:line_to(width-height/2,height)
cr:line_to(height/2,height)
cr:line_to(0,height/2)
cr:line_to(height/2,0)
cr:close_path()
end
--- Double arrow popularized by the vim-powerline module.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam[opt=height/2] number arrow_depth The width of the arrow part of the shape
function module.powerline(cr, width, height, arrow_depth)
arrow_depth = arrow_depth or height/2
local offset = 0
-- Avoid going out of the (potential) clip area
if arrow_depth < 0 then
width = width + 2*arrow_depth
offset = -arrow_depth
end
cr:move_to(offset , 0 )
cr:line_to(offset + width - arrow_depth , 0 )
cr:line_to(offset + width , height/2 )
cr:line_to(offset + width - arrow_depth , height )
cr:line_to(offset , height )
cr:line_to(offset + arrow_depth , height/2 )
cr:close_path()
end
--- An isosceles triangle.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
function module.isosceles_triangle(cr, width, height)
cr:move_to( width/2, 0 )
cr:line_to( width , height )
cr:line_to( 0 , height )
cr:close_path()
end
--- A cross (**+**) symbol.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam[opt=width/3] number thickness The cross section thickness
function module.cross(cr, width, height, thickness)
thickness = thickness or width/3
local xpadding = (width - thickness) / 2
local ypadding = (height - thickness) / 2
cr:move_to(xpadding, 0)
cr:line_to(width - xpadding, 0)
cr:line_to(width - xpadding, ypadding)
cr:line_to(width , ypadding)
cr:line_to(width , height-ypadding)
cr:line_to(width - xpadding, height-ypadding)
cr:line_to(width - xpadding, height )
cr:line_to(xpadding , height )
cr:line_to(xpadding , height-ypadding)
cr:line_to(0 , height-ypadding)
cr:line_to(0 , ypadding )
cr:line_to(xpadding , ypadding )
cr:close_path()
end
--- A similar shape to the `rounded_rect`, but with sharp corners.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam number corner_radius
function module.octogon(cr, width, height, corner_radius)
corner_radius = corner_radius or math.min(10, math.min(width, height)/4)
local offset = math.sqrt( (corner_radius*corner_radius) / 2 )
cr:move_to(offset, 0)
cr:line_to(width-offset, 0)
cr:line_to(width, offset)
cr:line_to(width, height-offset)
cr:line_to(width-offset, height)
cr:line_to(offset, height)
cr:line_to(0, height-offset)
cr:line_to(0, offset)
cr:close_path()
end
--- A circle shape.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam[opt=math.min(width height) / 2)] number radius The radius
function module.circle(cr, width, height, radius)
radius = radius or math.min(width, height) / 2
cr:move_to(width/2+radius, height/2)
cr:arc(width / 2, height / 2, radius, 0, 2*math.pi)
cr:close_path()
end
--- A simple rectangle.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
function module.rectangle(cr, width, height)
cr:rectangle(0, 0, width, height)
end
--- A diagonal parallelogram with the bottom left corner at x=0 and top right
-- at x=width.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam[opt=width/3] number base_width The parallelogram base width
function module.parallelogram(cr, width, height, base_width)
base_width = base_width or width/3
cr:move_to(width-base_width, 0 )
cr:line_to(width , 0 )
cr:line_to(base_width , height )
cr:line_to(0 , height )
cr:close_path()
end
--- A losange.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
function module.losange(cr, width, height)
cr:move_to(width/2 , 0 )
cr:line_to(width , height/2 )
cr:line_to(width/2 , height )
cr:line_to(0 , height/2 )
cr:close_path()
end
--- A pie.
--
-- The pie center is the center of the area.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam[opt=0] number start_angle The start angle (in radian)
-- @tparam[opt=math.pi/2] number end_angle The end angle (in radian)
-- @tparam[opt=math.min(width height)/2] number radius The shape height
function module.pie(cr, width, height, start_angle, end_angle, radius)
radius = radius or math.floor(math.min(width, height)/2)
start_angle, end_angle = start_angle or 0, end_angle or math.pi/2
-- If the shape is a circle, then avoid the lines
if math.abs(start_angle + end_angle - 2*math.pi) <= 0.01 then
cr:arc(width/2, height/2, radius, 0, 2*math.pi)
else
cr:move_to(width/2, height/2)
cr:line_to(
width/2 + math.cos(start_angle)*radius,
height/2 + math.sin(start_angle)*radius
)
cr:arc(width/2, height/2, radius, start_angle, end_angle)
end
cr:close_path()
end
--- A rounded arc.
--
-- The pie center is the center of the area.
--
--
--
-- @param cr A cairo context
-- @tparam number width The shape width
-- @tparam number height The shape height
-- @tparam[opt=math.min(width height)/2] number thickness The arc thickness
-- @tparam[opt=0] number start_angle The start angle (in radian)
-- @tparam[opt=math.pi/2] number end_angle The end angle (in radian)
-- @tparam[opt=false] boolean start_rounded if the arc start rounded
-- @tparam[opt=false] boolean end_rounded if the arc end rounded
function module.arc(cr, width, height, thickness, start_angle, end_angle, start_rounded, end_rounded)
start_angle = start_angle or 0
end_angle = end_angle or math.pi/2
-- This shape is a partial circle
local radius = math.min(width, height)/2
thickness = thickness or radius/2
local inner_radius = radius - thickness
-- As the edge of the small arc need to touch the [start_p1, start_p2]
-- line, a small subset of the arc circumference has to be substracted
-- that's (less or more) equal to the thickness/2 (a little longer given
-- it is an arc and not a line, but it wont show)
local arc_percent = math.abs(end_angle-start_angle)/(2*math.pi)
local arc_length = ((radius-thickness/2)*2*math.pi)*arc_percent
if start_rounded then
arc_length = arc_length - thickness/2
-- And back to angles
start_angle = end_angle - (arc_length/(radius - thickness/2))
end
if end_rounded then
arc_length = arc_length - thickness/2
-- And back to angles. Also make sure to avoid underflowing when the
-- rounded edge radius is greater than the angle delta.
end_angle = start_angle + math.max(
0, arc_length/(radius - thickness/2)
)
end
-- The path is a curcular arc joining 4 points
-- Outer first corner
local start_p1 = {
width /2 + math.cos(start_angle)*radius,
height/2 + math.sin(start_angle)*radius
}
if start_rounded then
-- Inner first corner
local start_p2 = {
width /2 + math.cos(start_angle)*inner_radius,
height/2 + math.sin(start_angle)*inner_radius
}
local median_angle = atan2(
start_p2[1] - start_p1[1],
-(start_p2[2] - start_p1[2])
)
local arc_center = {
(start_p1[1] + start_p2[1])/2,
(start_p1[2] + start_p2[2])/2,
}
cr:arc(arc_center[1], arc_center[2], thickness/2,
median_angle-math.pi/2, median_angle+math.pi/2
)
else
cr:move_to(unpack(start_p1))
end
cr:arc(width/2, height/2, radius, start_angle, end_angle)
if end_rounded then
-- Outer second corner
local end_p1 = {
width /2 + math.cos(end_angle)*radius,
height/2 + math.sin(end_angle)*radius
}
-- Inner first corner
local end_p2 = {
width /2 + math.cos(end_angle)*inner_radius,
height/2 + math.sin(end_angle)*inner_radius
}
local median_angle = atan2(
end_p2[1] - end_p1[1],
-(end_p2[2] - end_p1[2])
) - math.pi
local arc_center = {
(end_p1[1] + end_p2[1])/2,
(end_p1[2] + end_p2[2])/2,
}
cr:arc(arc_center[1], arc_center[2], thickness/2,
median_angle-math.pi/2, median_angle+math.pi/2
)
end
cr:arc_negative(width/2, height/2, inner_radius, end_angle, start_angle)
cr:close_path()
end
--- A partial rounded bar. How much of the rounded bar is visible depends on
-- the given percentage value.
--
-- Note that this shape is not closed and thus filling it doesn't make much
-- sense.
--
--
--
-- @param cr A cairo context
-- @tparam number w The shape width
-- @tparam number h The shape height
-- @tparam number percent The progressbar percent
-- @tparam boolean hide_left Do not draw the left side of the shape
function module.radial_progress(cr, w, h, percent, hide_left)
percent = percent or 1
local total_length = (2*(w-h))+2*((h/2)*math.pi)
local bar_percent = (w-h)/total_length
local arc_percent = ((h/2)*math.pi)/total_length
-- Bottom line
if percent > bar_percent then
cr:move_to(h/2,h)
cr:line_to((h/2) + (w-h),h)
cr:stroke()
elseif percent < bar_percent then
cr:move_to(h/2,h)
cr:line_to(h/2+(total_length*percent),h)
cr:stroke()
end
-- Right arc
if percent >= bar_percent+arc_percent then
cr:arc(w-h/2 , h/2, h/2,3*(math.pi/2),math.pi/2)
cr:stroke()
elseif percent > bar_percent and percent < bar_percent+(arc_percent/2) then
cr:arc(w-h/2 , h/2, h/2,(math.pi/2)-((math.pi/2)*((percent-bar_percent)/(arc_percent/2))),math.pi/2)
cr:stroke()
elseif percent >= bar_percent+arc_percent/2 and percent < bar_percent+arc_percent then
cr:arc(w-h/2 , h/2, h/2,0,math.pi/2)
cr:stroke()
local add = (math.pi/2)*((percent-bar_percent-arc_percent/2)/(arc_percent/2))
cr:arc(w-h/2 , h/2, h/2,2*math.pi-add,0)
cr:stroke()
end
-- Top line
if percent > 2*bar_percent+arc_percent then
cr:move_to((h/2) + (w-h),0)
cr:line_to(h/2,0)
cr:stroke()
elseif percent > bar_percent+arc_percent and percent < 2*bar_percent+arc_percent then
cr:move_to((h/2) + (w-h),0)
cr:line_to(((h/2) + (w-h))-total_length*(percent-bar_percent-arc_percent),0)
cr:stroke()
end
-- Left arc
if not hide_left then
if percent > 0.985 then
cr:arc(h/2, h/2, h/2,math.pi/2,3*(math.pi/2))
cr:stroke()
elseif percent > 2*bar_percent+arc_percent then
local relpercent = (percent - 2*bar_percent - arc_percent)/arc_percent
cr:arc(h/2, h/2, h/2,3*(math.pi/2)-(math.pi)*relpercent,3*(math.pi/2))
cr:stroke()
end
end
end
--- Adjust the shape using a transformation object
--
-- Apply various transformations to the shape
--
-- @usage gears.shape.transform(gears.shape.rounded_bar)
-- : rotate(math.pi/2)
-- : translate(10, 10)
--
-- @param shape A shape function
-- @return A transformation handle, also act as a shape function
function module.transform(shape)
-- Apply the transformation matrix and apply the shape, then restore
local function apply(self, cr, width, height, ...)
cr:save()
cr:transform(self.matrix:to_cairo_matrix())
shape(cr, width, height, ...)
cr:restore()
end
-- Redirect function calls like :rotate() to the underlying matrix
local function index(_, key)
return function(self, ...)
self.matrix = self.matrix[key](self.matrix, ...)
return self
end
end
local result = setmetatable({
matrix = g_matrix.identity
}, {
__call = apply,
__index = index
})
return result
end
return module
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| 31.934947
| 108
| 0.632195
|
fa1fddb081239efffa3294942da958b06f2e49de
| 5,102
|
cpp
|
C++
|
src/test/lemoncoin_tests.cpp
|
fflo/lemoncoin
|
1d45a3821afacf24d07827b64712d31f28b75730
|
[
"MIT"
] | null | null | null |
src/test/lemoncoin_tests.cpp
|
fflo/lemoncoin
|
1d45a3821afacf24d07827b64712d31f28b75730
|
[
"MIT"
] | null | null | null |
src/test/lemoncoin_tests.cpp
|
fflo/lemoncoin
|
1d45a3821afacf24d07827b64712d31f28b75730
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2015 The Dogecoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "arith_uint256.h"
#include "chainparams.h"
#include "lemoncoin.h"
#include "main.h"
#include "test/test_bitcoin.h"
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(lemoncoin_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(get_next_work_difficulty_limit)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus(0);
CBlockIndex pindexLast;
int64_t nLastRetargetTime = 1455393600; // Block # 1
/*
pindexLast.nHeight = 239;
pindexLast.nTime = 1386475638; // Block #239
pindexLast.nBits = 0x1e0ffff0;
BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1e00ffff);*/
}
BOOST_AUTO_TEST_CASE(get_next_work_digishield)
{
/*SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus(145000);
CBlockIndex pindexLast;
int64_t nLastRetargetTime = 1395094427;
// First hard-fork at 145,000, which applies to block 145,001 onwards
pindexLast.nHeight = 145000;
pindexLast.nTime = 1395094679;
pindexLast.nBits = 0x1b499dfd;
BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1b671062);*/
}
BOOST_AUTO_TEST_CASE(get_next_work_digishield_modulated_upper)
{
/*SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus(145000);
CBlockIndex pindexLast;
int64_t nLastRetargetTime = 1395100835;
// Test the upper bound on modulated time using mainnet block #145,107
pindexLast.nHeight = 145107;
pindexLast.nTime = 1395101360;
pindexLast.nBits = 0x1b3439cd;
BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1b4e56b3);*/
}
BOOST_AUTO_TEST_CASE(get_next_work_digishield_modulated_lower)
{
/*SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus(145000);
CBlockIndex pindexLast;
int64_t nLastRetargetTime = 1395380517;
// Test the lower bound on modulated time using mainnet block #149,423
pindexLast.nHeight = 149423;
pindexLast.nTime = 1395380447;
pindexLast.nBits = 0x1b446f21;
BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1b335358);*/
}
BOOST_AUTO_TEST_CASE(get_next_work_digishield_rounding)
{
/*SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& params = Params().GetConsensus(145000);
CBlockIndex pindexLast;
int64_t nLastRetargetTime = 1395094679;
// Test case for correct rounding of modulated time - this depends on
// handling of integer division, and is not obvious from the code
pindexLast.nHeight = 145001;
pindexLast.nTime = 1395094727;
pindexLast.nBits = 0x1b671062;
BOOST_CHECK_EQUAL(CalculateLemonCoinNextWorkRequired(&pindexLast, nLastRetargetTime, params), 0x1b6558a4);*/
}
BOOST_AUTO_TEST_CASE(hardfork_parameters)
{
SelectParams(CBaseChainParams::MAIN);
const Consensus::Params& initialParams = Params().GetConsensus(0);
BOOST_CHECK_EQUAL(initialParams.nPowTargetTimespan, 60);
BOOST_CHECK_EQUAL(initialParams.fAllowLegacyBlocks, true);
BOOST_CHECK_EQUAL(initialParams.fDigishieldDifficultyCalculation, true);
/*
const Consensus::Params& initialParamsEnd = Params().GetConsensus(144999);
BOOST_CHECK_EQUAL(initialParamsEnd.nPowTargetTimespan, 14400);
BOOST_CHECK_EQUAL(initialParamsEnd.fAllowLegacyBlocks, true);
BOOST_CHECK_EQUAL(initialParamsEnd.fDigishieldDifficultyCalculation, false);
const Consensus::Params& digishieldParams = Params().GetConsensus(145000);
BOOST_CHECK_EQUAL(digishieldParams.nPowTargetTimespan, 60);
BOOST_CHECK_EQUAL(digishieldParams.fAllowLegacyBlocks, true);
BOOST_CHECK_EQUAL(digishieldParams.fDigishieldDifficultyCalculation, true);
const Consensus::Params& digishieldParamsEnd = Params().GetConsensus(371336);
BOOST_CHECK_EQUAL(digishieldParamsEnd.nPowTargetTimespan, 60);
BOOST_CHECK_EQUAL(digishieldParamsEnd.fAllowLegacyBlocks, true);
BOOST_CHECK_EQUAL(digishieldParamsEnd.fDigishieldDifficultyCalculation, true);
const Consensus::Params& auxpowParams = Params().GetConsensus(371337);
BOOST_CHECK_EQUAL(auxpowParams.nHeightEffective, 371337);
BOOST_CHECK_EQUAL(auxpowParams.nPowTargetTimespan, 60);
BOOST_CHECK_EQUAL(auxpowParams.fAllowLegacyBlocks, false);
BOOST_CHECK_EQUAL(auxpowParams.fDigishieldDifficultyCalculation, true);
const Consensus::Params& auxpowHighParams = Params().GetConsensus(700000); // Arbitrary point after last hard-fork
BOOST_CHECK_EQUAL(auxpowHighParams.nPowTargetTimespan, 60);
BOOST_CHECK_EQUAL(auxpowHighParams.fAllowLegacyBlocks, false);
BOOST_CHECK_EQUAL(auxpowHighParams.fDigishieldDifficultyCalculation, true);
*/
}
BOOST_AUTO_TEST_SUITE_END()
| 39.246154
| 118
| 0.777342
|
dee6d955b26ccbcf636ae279bf9326bdb0a556e2
| 7,227
|
swift
|
Swift
|
Classes/Core/Message/MTMessage.swift
|
ShuNegus/mobile-messaging-sdk-ios
|
529260234c18f8ffba794585b481b13d98c686a7
|
[
"Apache-2.0"
] | null | null | null |
Classes/Core/Message/MTMessage.swift
|
ShuNegus/mobile-messaging-sdk-ios
|
529260234c18f8ffba794585b481b13d98c686a7
|
[
"Apache-2.0"
] | null | null | null |
Classes/Core/Message/MTMessage.swift
|
ShuNegus/mobile-messaging-sdk-ios
|
529260234c18f8ffba794585b481b13d98c686a7
|
[
"Apache-2.0"
] | null | null | null |
//
// MTMessage.swift
// MobileMessaging
//
// Created by Andrey Kadochnikov on 18/10/2017.
//
import Foundation
public protocol MTMessageProtocol {
/// Contains info about the action was applied to the message
var appliedAction: NotificationAction? {get set}
/// Structure representing APS payload attributes
var aps: PushPayloadAPS {get}
/// Defines if a message is silent. Silent messages have neither text nor sound attributes.
var isSilent: Bool {get}
/// Title of the message. If message title may be localized ("alert.title-loc-key" attribute is present and refers to an existing localized string), the localized string is returned, otherwise the value of "alert.title" attribute is returned if present.
var title: String? {get}
/// Localization key of the message title.
var title_loc_key: String? {get}
/// Localization args of the message title.
var title_loc_args: [String]? {get}
/// Localization key of the message text.
var loc_key: String? {get}
/// Localization args of the message.
var loc_args: [String]? {get}
/// Sound of the message.
var sound: String? {get}
/// Interactive category Id
var category: String? {get}
/// Badge counter
var badge: Int? {get}
/// URL representing rich notification content
var contentUrl: String? {get}
/// Servers datetime
var sendDateTime: TimeInterval {get} // seconds
/// Messages seen status
var seenStatus: MMSeenStatus {get}
/// Datetime that message was seen
var seenDate: Date? {get}
/// Flag indicates whether the message was reported on delivery
var isDeliveryReportSent: Bool {get}
/// Datetime that message was reported on delivery
var deliveryReportedDate: Date? {get}
/// Internal data for internal use
var internalData: StringKeyPayload? {get}
/// APNS payload (`aps` object) sent with the silent push notifications
var silentData: StringKeyPayload? {get}
/// Indicates whether the message represents a geo campaign subscription
var isGeoSignalingMessage: Bool {get}
}
@objcMembers
public class MTMessage: BaseMessage, MTMessageProtocol {
public var appliedAction: NotificationAction?
public var aps: PushPayloadAPS
public var sendDateTime: TimeInterval
public var seenStatus: MMSeenStatus
public var seenDate: Date?
public var isDeliveryReportSent: Bool
public var deliveryReportedDate: Date?
public var title: String? { return String.localizedUserNotificationStringOrFallback(key: title_loc_key, args: title_loc_args, fallback: aps.title) }
public var title_loc_key: String? { return aps.title_loc_key }
public var title_loc_args: [String]? { return aps.title_loc_args }
public var loc_key: String? { return aps.loc_key }
public var loc_args: [String]? { return aps.loc_args }
public var sound: String? { return aps.sound }
public var badge: Int? { return aps.badge }
public var category: String? { return aps.category }
public var isSilent: Bool { return isSilentInternalData(internalData) }
public var contentUrl: String? {
if let atts = internalData?[Consts.InternalDataKeys.attachments] as? [StringKeyPayload], let firstOne = atts.first {
return firstOne[Consts.Attachments.Keys.url] as? String
} else {
return nil
}
}
// var downloadedPictureUrl: URL? //NOTE: this field may be used to keep url of downloaded content/cache
public var showInApp: Bool {
return internalData?[Consts.InternalDataKeys.showInApp] as? Bool ?? false
}
public var inAppStyle: InAppNotificationStyle? {
let defaultStyle = showInApp ? InAppNotificationStyle.Modal : nil
let resolvedStyle: InAppNotificationStyle?
if #available(iOS 10.0, *) { // means foreground banner is supported
if let rawValue = internalData?[Consts.InternalDataKeys.inAppStyle] as? Int16 {
resolvedStyle = InAppNotificationStyle(rawValue: rawValue) ?? defaultStyle
} else {
resolvedStyle = defaultStyle
}
} else {
resolvedStyle = defaultStyle
}
return resolvedStyle
}
public var isGeoSignalingMessage: Bool {
return internalData?[Consts.InternalDataKeys.geo] != nil && isSilent
}
public var silentData: StringKeyPayload? {
return internalData?[Consts.InternalDataKeys.silent] as? StringKeyPayload
}
public var internalData: StringKeyPayload? {
return originalPayload[Consts.APNSPayloadKeys.internalData] as? StringKeyPayload
}
public override var customPayload: StringKeyPayload? {
get {
return originalPayload[Consts.APNSPayloadKeys.customPayload] as? StringKeyPayload
}
set {}
}
public override var text: String? {
get {
return String.localizedUserNotificationStringOrFallback(key: loc_key, args: loc_args, fallback: aps.text)
}
set {}
}
convenience init?(messageSyncResponseJson json: JSON) {
if let payload = json.dictionaryObject {
self.init(payload: payload,
deliveryMethod: .pull,
seenDate: nil,
deliveryReportDate: nil,
seenStatus: .NotSeen,
isDeliveryReportSent: false)
} else {
return nil
}
self.deliveryMethod = .pull
}
/// Initializes the MTMessage from Message storage's message
convenience init?(messageStorageMessageManagedObject m: Message) {
guard let deliveryMethod = MessageDeliveryMethod(rawValue: m.deliveryMethod) else {
return nil
}
self.init(payload: m.payload,
deliveryMethod: deliveryMethod,
seenDate: m.seenDate,
deliveryReportDate: m.deliveryReportedDate,
seenStatus: MMSeenStatus(rawValue: m.seenStatusValue) ?? .NotSeen,
isDeliveryReportSent: m.isDeliveryReportSent)
}
/// Designated init
public init?(payload: APNSPayload, deliveryMethod: MessageDeliveryMethod, seenDate: Date?, deliveryReportDate: Date?, seenStatus: MMSeenStatus, isDeliveryReportSent: Bool) {
guard let payload = payload as? StringKeyPayload,
let messageId = payload[Consts.APNSPayloadKeys.messageId] as? String else
{
return nil
}
//workaround for cordova
let internData = payload[Consts.APNSPayloadKeys.internalData] as? StringKeyPayload
let nativeAPS = payload[Consts.APNSPayloadKeys.aps] as? StringKeyPayload
if isSilentInternalData(internData) {
if let silentAPS = (payload[Consts.APNSPayloadKeys.internalData] as? StringKeyPayload)?[Consts.InternalDataKeys.silent] as? StringKeyPayload {
self.aps = PushPayloadAPS.SilentAPS(apsByMerging(nativeAPS: nativeAPS ?? [:], withSilentAPS: silentAPS))
} else {
return nil
}
} else if let nativeAPS = nativeAPS {
self.aps = PushPayloadAPS.NativeAPS(nativeAPS)
} else {
return nil
}
if let sendDateTimeMillis = (payload[Consts.APNSPayloadKeys.internalData] as? StringKeyPayload)?[Consts.InternalDataKeys.sendDateTime] as? Double {
self.sendDateTime = sendDateTimeMillis/1000
} else {
self.sendDateTime = MobileMessaging.date.now.timeIntervalSince1970
}
self.seenStatus = seenStatus
self.isDeliveryReportSent = isDeliveryReportSent
self.seenDate = seenDate
self.deliveryReportedDate = deliveryReportDate
super.init(messageId: messageId, direction: .MT, originalPayload: payload, deliveryMethod: deliveryMethod)
}
}
func isSilentInternalData(_ internalData: StringKeyPayload?) -> Bool {
return internalData?[Consts.InternalDataKeys.silent] != nil
}
| 31.558952
| 254
| 0.746091
|
a307d97769c7fe2329c51ddb30ae62bfe0ff151f
| 1,940
|
c
|
C
|
nm/src/extract_symbols.c
|
nsarno/nm-objdump
|
3a98316f29265e2f8b1275f0df2e0f74a066226a
|
[
"MIT"
] | 14
|
2016-11-11T20:45:34.000Z
|
2021-11-29T13:59:50.000Z
|
nm/src/extract_symbols.c
|
Venatoral/nm-objdump
|
3a98316f29265e2f8b1275f0df2e0f74a066226a
|
[
"MIT"
] | null | null | null |
nm/src/extract_symbols.c
|
Venatoral/nm-objdump
|
3a98316f29265e2f8b1275f0df2e0f74a066226a
|
[
"MIT"
] | 14
|
2015-07-24T08:31:08.000Z
|
2021-06-30T09:02:04.000Z
|
/*
** extract_symbols.c for extract symbols in /home/mesure_a/workspace/c/nm-objdump
**
** Made by arnaud mesureur
** Login <mesure_a@epitech.net>
**
** Started on Sat Mar 12 10:42:22 2011 arnaud mesureur
** Last update Sun Mar 13 21:19:45 2011 arnaud mesureur
*/
#include <stdlib.h>
#include <stddef.h>
#include <elf.h>
#include <string.h>
#include <stdio.h>
#include "list.h"
#include "nm.h"
static void fit_symbol(Elf64_Sym *st, Elf32_Sym *addr)
{
st->st_name = addr->st_name;
st->st_value = addr->st_value;
st->st_size = addr->st_size;
st->st_info = addr->st_info;
st->st_other = addr->st_other;
st->st_shndx = addr->st_shndx;
}
static Elf64_Sym *fit_symbol_table(void *addr, Elf64_Shdr *shdr,
t_elf *elf)
{
Elf64_Sym *st;
Elf32_Sym *data;
size_t nmemb;
size_t i;
if (elf->ehdr->e_ident[EI_CLASS] == ELFCLASS64)
st = (Elf64_Sym*)addr;
else
{
i = 0;
data = addr;
nmemb = shdr->sh_size / shdr->sh_entsize;
st = malloc(sizeof(*st) * nmemb);
if (NULL == st)
return (perror("malloc"), NULL);
while (i < nmemb)
{
fit_symbol(&(st[i]), &(data[i]));
++i;
}
}
return (st);
}
static Elf64_Sym *get_next_symtab(Elf64_Shdr **shdr,
t_elf *elf)
{
static size_t i = 0;
Elf64_Ehdr *ehdr;
Elf64_Shdr *shtab;
ehdr = elf->ehdr;
shtab = elf->shtab;
while (i < ehdr->e_shnum)
{
if (shtab[i].sh_type == SHT_SYMTAB)
{
*shdr = &shtab[i++];
return (fit_symbol_table(elf->addr + (*shdr)->sh_offset,
*shdr, elf));
}
++i;
}
i = 0;
return (NULL);
}
t_sym_list *extract_symbols(t_elf *elf)
{
t_sym_list *list;
Elf64_Shdr *symhdr;
Elf64_Sym *symtab;
list = new_list_by_default();
while ((symtab = get_next_symtab(&symhdr, elf)))
{
list = symbols_table_to_list(list, symhdr, symtab, elf);
if (elf->ehdr->e_ident[EI_CLASS] == ELFCLASS32)
free(symtab);
}
return (list);
}
| 20.421053
| 81
| 0.619588
|
a362a0f825a9be05c256915ef41877cc338dfd61
| 4,918
|
java
|
Java
|
modules/benchmarks/src/main/java/org/apache/ignite/internal/benchmarks/jmh/cache/JmhCacheBenchmark.java
|
FedorUporov/gridgain
|
883125f943743fa8198d88be98dfe61bde86ad96
|
[
"CC0-1.0"
] | 218
|
2015-01-04T13:20:55.000Z
|
2022-03-28T05:28:55.000Z
|
modules/benchmarks/src/main/java/org/apache/ignite/internal/benchmarks/jmh/cache/JmhCacheBenchmark.java
|
FedorUporov/gridgain
|
883125f943743fa8198d88be98dfe61bde86ad96
|
[
"CC0-1.0"
] | 175
|
2015-02-04T23:16:56.000Z
|
2022-03-28T18:34:24.000Z
|
modules/benchmarks/src/main/java/org/apache/ignite/internal/benchmarks/jmh/cache/JmhCacheBenchmark.java
|
FedorUporov/gridgain
|
883125f943743fa8198d88be98dfe61bde86ad96
|
[
"CC0-1.0"
] | 93
|
2015-01-06T20:54:23.000Z
|
2022-03-31T08:09:00.000Z
|
/*
* Copyright 2019 GridGain Systems, Inc. and Contributors.
*
* Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license
*
* 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.ignite.internal.benchmarks.jmh.cache;
import org.apache.ignite.IgniteDataStreamer;
import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheWriteSynchronizationMode;
import org.apache.ignite.internal.benchmarks.jmh.runner.JmhIdeBenchmarkRunner;
import org.apache.ignite.internal.benchmarks.model.IntValue;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.profile.GCProfiler;
import java.util.concurrent.ThreadLocalRandom;
/**
* Put benchmark.
*/
@SuppressWarnings("unchecked")
public class JmhCacheBenchmark extends JmhCacheAbstractBenchmark {
/** {@inheritDoc} */
@Override public void setup() throws Exception {
super.setup();
IgniteDataStreamer<Integer, IntValue> dataLdr = node.dataStreamer(cache.getName());
for (int i = 0; i < CNT; i++)
dataLdr.addData(i, new IntValue(i));
dataLdr.close();
System.out.println("Cache populated.");
}
/**
* Test PUT operation.
*
* @throws Exception If failed.
*/
@Benchmark
public void put() throws Exception {
int key = ThreadLocalRandom.current().nextInt(CNT);
cache.put(key, new IntValue(key));
}
/**
* Test PUT operation.
*
* @throws Exception If failed.
*/
@Benchmark
public Object get() throws Exception {
int key = ThreadLocalRandom.current().nextInt(CNT);
return cache.get(key);
}
/**
* Run benchmarks.
*
* @param args Arguments.
* @throws Exception If failed.
*/
public static void main(String[] args) throws Exception {
run("put", CacheAtomicityMode.ATOMIC);
run("get", CacheAtomicityMode.ATOMIC);
run("put", CacheAtomicityMode.TRANSACTIONAL);
run("get", CacheAtomicityMode.TRANSACTIONAL);
}
/**
* Run benchmarks for atomic cache.
*
* @param benchmark Benchmark name.
* @param atomicityMode Atomicity mode.
* @throws Exception If failed.
*/
private static void run(String benchmark, CacheAtomicityMode atomicityMode) throws Exception {
run(benchmark, 4, true, atomicityMode, CacheWriteSynchronizationMode.PRIMARY_SYNC);
run(benchmark, 4, true, atomicityMode, CacheWriteSynchronizationMode.FULL_SYNC);
run(benchmark, 4, false, atomicityMode, CacheWriteSynchronizationMode.PRIMARY_SYNC);
run(benchmark, 4, false, atomicityMode, CacheWriteSynchronizationMode.FULL_SYNC);
}
/**
* Run benchmark.
*
* @param benchmark Benchmark to run.
* @param threads Amount of threads.
* @param client Client mode flag.
* @param atomicityMode Atomicity mode.
* @param writeSyncMode Write synchronization mode.
* @throws Exception If failed.
*/
private static void run(String benchmark, int threads, boolean client, CacheAtomicityMode atomicityMode,
CacheWriteSynchronizationMode writeSyncMode) throws Exception {
String simpleClsName = JmhCacheBenchmark.class.getSimpleName();
String output = simpleClsName + "-" + benchmark +
"-" + threads + "-threads" +
"-" + (client ? "client" : "data") +
"-" + atomicityMode +
"-" + writeSyncMode;
JmhIdeBenchmarkRunner.create()
.forks(1)
.threads(threads)
.warmupIterations(10)
.measurementIterations(60)
.benchmarks(simpleClsName + "." + benchmark)
.output(output + ".jmh.log")
.profilers(GCProfiler.class)
.jvmArguments(
"-Xms4g",
"-Xmx4g",
"-XX:+UnlockCommercialFeatures",
"-XX:+FlightRecorder",
"-XX:StartFlightRecording=delay=30s,dumponexit=true,settings=alloc,filename=" + output + ".jfr",
JmhIdeBenchmarkRunner.createProperty(PROP_ATOMICITY_MODE, atomicityMode),
JmhIdeBenchmarkRunner.createProperty(PROP_WRITE_SYNC_MODE, writeSyncMode),
JmhIdeBenchmarkRunner.createProperty(PROP_DATA_NODES, 2),
JmhIdeBenchmarkRunner.createProperty(PROP_CLIENT_MODE, client))
.run();
}
}
| 35.128571
| 112
| 0.660838
|
57f45bcf272ddd87951879a7e1f8eb384153e7b8
| 1,860
|
php
|
PHP
|
models/TipoEncargo.php
|
themarcosramos/proger
|
0acc2d440326a129bdae4e8e19615fd027744cb2
|
[
"BSD-3-Clause"
] | 1
|
2019-09-30T23:05:57.000Z
|
2019-09-30T23:05:57.000Z
|
models/TipoEncargo.php
|
themarcosramos/Proger
|
0acc2d440326a129bdae4e8e19615fd027744cb2
|
[
"BSD-3-Clause"
] | null | null | null |
models/TipoEncargo.php
|
themarcosramos/Proger
|
0acc2d440326a129bdae4e8e19615fd027744cb2
|
[
"BSD-3-Clause"
] | null | null | null |
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "tipoEncargo".
*
* @property integer $id
* @property string $nome
*
* @property CursoProger[] $cursoProgers
* @property EventoProger[] $eventoProgers
* @property ProgramaProger[] $programas
* @property ProjetoProger[] $projetoProgers
*/
class TipoEncargo extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'tipoEncargo';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['nome'], 'required'],
[['nome'], 'string'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'nome' => 'Nome',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCursoProgers()
{
return $this->hasMany(CursoProger::className(), ['idTipoEncargo' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getEventoProgers()
{
return $this->hasMany(EventoProger::className(), ['idTipoEncargo' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getProgramaProgers()
{
return $this->hasMany(ProgramaProger::className(), ['idTipoEncargo' => 'id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getProjetoProgers()
{
return $this->hasMany(ProjetoProger::className(), ['idTipoEncargo' => 'id']);
}
public static function dropdown() {
$models = static::find()->orderBy('nome')->all();
$dropdown = null;
foreach ($models as $model) {
$dropdown[$model->id] = $model->nome;
}
return $dropdown;
}
}
| 19.578947
| 86
| 0.533333
|
a0119ed67d635be381e74b2ecf8ca5906cc76c45
| 6,620
|
ts
|
TypeScript
|
src/index.ts
|
yeonjuan/mode-image
|
3223fb01b3adc3158a1c827404814c69449595d9
|
[
"MIT"
] | 3
|
2021-08-14T10:40:36.000Z
|
2021-08-14T18:05:03.000Z
|
src/index.ts
|
yeonjuan/mode-image
|
3223fb01b3adc3158a1c827404814c69449595d9
|
[
"MIT"
] | null | null | null |
src/index.ts
|
yeonjuan/mode-image
|
3223fb01b3adc3158a1c827404814c69449595d9
|
[
"MIT"
] | null | null | null |
import type {
CreateCanvas,
CloneCanvas,
ImageSource,
Options,
PartialSize,
RectArea,
NumberPair,
Size,
CreateImage,
CanvasContext,
Task,
CanvasCreator,
ImageCreator,
Drawable,
DataURLOptions,
} from "./types";
const DEFAULT_OPTIONS = {
createCanvas: () => window.document.createElement("canvas"),
createImage: () => new window.Image(),
};
const withDefault = <Value>(
defaultValue: NonNullable<Value>,
value?: Value
) => {
return value ? value : defaultValue;
};
const sin = Math.sin;
const cos = Math.cos;
const max = Math.max;
const getSize = (drawable: { width: number; height: number }): Size => [
drawable.width,
drawable.height,
];
const mapSize = (
size: Size,
mapFn: (num: number, index: number) => number
): Size => size.map(mapFn) as Size;
const diffSize = (sizeA: Size, sizeB: Size): Size => [
sizeA[0] - sizeB[0],
sizeA[1] - sizeB[1],
];
const half = (n: number) => n / 2;
const neg = (n: number) => -n;
const drawRotatedImage = (
ctx: CanvasContext,
drawable: Drawable,
radian: number
) => {
const cSize = mapSize(getSize(ctx.canvas), half);
const dSize = getSize(drawable);
ctx.translate(...cSize);
ctx.rotate(radian);
ctx.translate(...mapSize(cSize, neg));
ctx.drawImage(drawable, ...diffSize(cSize, mapSize(dSize, half)), ...dSize);
};
const drawPattern = (ctx: CanvasContext, pattern: CanvasPattern) => {
ctx.save();
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, ...getSize(ctx.canvas));
ctx.restore();
};
const calcRotatedSize = (ctx: CanvasContext, radian: number): Size => {
const [width, height] = getSize(ctx.canvas);
const cosVal = cos(radian);
const sinVal = sin(radian);
return [sinVal * height + cosVal * width, sinVal * width + cosVal * height];
};
const mergeSize = (sizeA: Size, sizeB: Size): Size => {
return mapSize(sizeA, (size, index) => max(size, sizeB[index]));
};
class ModeImage {
private readonly canvas: HTMLCanvasElement;
private readonly ctx: CanvasContext;
private readonly tasks: Task[] = [];
private readonly canvasCreator: CanvasCreator;
private readonly imageCreator: ImageCreator;
public static create(src: ImageSource, options?: Options) {
return new ModeImage(src, options);
}
private constructor(src: ImageSource, options: Options = {}) {
this.canvasCreator = withDefault(
DEFAULT_OPTIONS.createCanvas,
options.createCanvas
);
this.imageCreator = withDefault(
DEFAULT_OPTIONS.createImage,
options.createImage
);
this.canvas = this.createCanvas();
this.ctx = this.canvas.getContext("2d")!;
const loadingImage = this.loadImage(src);
this.schedule(async () => {
const image = await loadingImage;
this.canvas.width = image.width;
this.canvas.height = image.height;
this.ctx.drawImage(image, 0, 0);
});
}
private loadImage(src: ImageSource): Promise<HTMLImageElement> {
if (typeof src === "object")
return Promise.resolve(src as HTMLImageElement);
const image = this.imageCreator() as HTMLImageElement;
return new Promise((resolve, reject) => {
image.onload = () => resolve(image);
image.onerror = () => reject(new Error("Load failed"));
(image as any).crossOrigin = "Anonymous";
image.src = src;
});
}
private schedule(task: Task) {
this.tasks.push(task);
}
private createCanvas(size?: Size) {
const canvas = this.canvasCreator();
size && ([canvas.width, canvas.height] = size);
return canvas;
}
private setCanvasSize(size: Size) {
[this.canvas.width, this.canvas.height] = size;
}
private copyCanvas() {
const size = this.getSize();
const copied = this.createCanvas(size);
copied.getContext("2d")!.drawImage(this.canvas, 0, 0, ...size);
return copied;
}
private clearCanvas() {
this.ctx.clearRect(0, 0, ...this.getSize());
}
private getSize() {
return getSize(this.canvas);
}
private async runSchedules() {
for (const task of this.tasks) {
await task();
}
}
public rotate(radian: number): this {
this.schedule(() => {
const copied = this.copyCanvas();
this.setCanvasSize(calcRotatedSize(this.ctx, radian));
this.clearCanvas();
drawRotatedImage(this.ctx, copied, radian);
});
return this;
}
public resize(resize: PartialSize): this {
this.schedule(() => {
const copied = this.copyCanvas();
const curSize = this.getSize();
this.clearCanvas();
const size: Size = [
resize.width || curSize[0],
resize.height || curSize[1],
];
this.setCanvasSize(size);
this.ctx.drawImage(copied, 0, 0, ...size);
});
return this;
}
public crop(area: RectArea): this {
this.schedule(() => {
const copied = this.copyCanvas();
this.clearCanvas();
const size = getSize(area);
this.setCanvasSize(size);
this.ctx.drawImage(
copied,
area.x,
area.y,
area.width,
area.height,
0,
0,
...size
);
});
return this;
}
public repeatX(repeat: number): this {
this.schedule(() => {
const copied = this.copyCanvas();
this.clearCanvas();
const [width, height] = getSize(this.canvas);
this.setCanvasSize([width * repeat, height]);
drawPattern(this.ctx, this.ctx.createPattern(copied, "repeat-x")!);
});
return this;
}
public repeatY(repeat: number): this {
this.schedule(() => {
const copied = this.copyCanvas();
this.clearCanvas();
const [width, height] = getSize(this.canvas);
this.setCanvasSize([width, repeat * height]);
drawPattern(this.ctx, this.ctx.createPattern(copied, "repeat-y")!);
});
return this;
}
public merge(source: ImageSource) {
const loadingImage = this.loadImage(source);
this.schedule(async () => {
const image = await loadingImage;
const copied = this.copyCanvas();
this.clearCanvas();
const mergedSize = mergeSize(this.getSize(), getSize(image));
this.setCanvasSize(mergedSize);
this.ctx.drawImage(copied, 0, 0, copied.width, copied.height);
this.ctx.drawImage(image, 0, 0, image.width, image.height);
});
return this;
}
public async toDataURL(options?: DataURLOptions): Promise<string> {
await this.runSchedules();
return this.canvas.toDataURL(
withDefault("image/png", options?.type),
withDefault(1, options?.quality)
);
}
}
export default (src: ImageSource, options?: Options) =>
ModeImage.create(src, options);
| 25.658915
| 78
| 0.632628
|
97d8e4056b562a7143bb34d134753dab36520cb6
| 648
|
rb
|
Ruby
|
lib/search.rb
|
RoUchiha/CLI-Ruby-project
|
aef08b633f9ffb0a0381f68ea43d37842b88bf0b
|
[
"MIT"
] | null | null | null |
lib/search.rb
|
RoUchiha/CLI-Ruby-project
|
aef08b633f9ffb0a0381f68ea43d37842b88bf0b
|
[
"MIT"
] | null | null | null |
lib/search.rb
|
RoUchiha/CLI-Ruby-project
|
aef08b633f9ffb0a0381f68ea43d37842b88bf0b
|
[
"MIT"
] | null | null | null |
require 'open-uri'
require 'nokogiri'
require 'addressable/uri'
class Search
attr_accessor :location, :zip_url
def initialize(location)
if location < 501 || location > 99950
raise ArgumentError
else
searcher(location)
end
end
def searcher(zip)
fixed_zip = zip_convert(zip)
uri = Addressable::URI.parse('https://weather.com/weather/today/l/' + fixed_zip)
@zip_url = uri.to_s
end
def zip_convert(code)
zcode = code.to_s
while zcode.length < 5 do
zcode = "0" + zcode
end
return zcode
end
end
| 20.25
| 96
| 0.57716
|
e280062527f4e06d70eca117906deb782a37cb9d
| 868
|
js
|
JavaScript
|
reason/my-first-app/src/demo.bs.js
|
agarrharr/learning
|
2c6a74459d437aab3de68b46b4cc5d6095956901
|
[
"CC0-1.0"
] | 3
|
2020-01-23T15:36:21.000Z
|
2021-12-05T17:59:47.000Z
|
reason/my-first-app/src/demo.bs.js
|
agarrharr/learning
|
2c6a74459d437aab3de68b46b4cc5d6095956901
|
[
"CC0-1.0"
] | 10
|
2020-02-25T09:59:56.000Z
|
2022-03-30T22:33:25.000Z
|
reason/my-first-app/src/demo.bs.js
|
agarrharr/learning
|
2c6a74459d437aab3de68b46b4cc5d6095956901
|
[
"CC0-1.0"
] | 3
|
2020-04-20T17:03:53.000Z
|
2022-01-16T23:55:58.000Z
|
// Generated by BUCKLESCRIPT VERSION 2.1.0, PLEASE EDIT WITH CARE
'use strict';
console.log("Hello, BuckleScript and Reason!");
var foo = "Hello";
console.log(foo);
function add(x, y) {
return x + y | 0;
}
function add2(param) {
return 2 + param | 0;
}
console.log(add2(10));
console.log(3);
var my_coin = /* Quarter */[4];
var message;
if (typeof my_coin === "number") {
switch (my_coin) {
case 0 :
message = 0.1;
break;
case 1 :
message = 0.5;
break;
case 2 :
message = 0.01;
break;
}
} else {
message = 4 * 0.25;
}
console.log(message);
var me = /* record */[
/* age */5,
/* name */"Big Reason"
];
exports.foo = foo;
exports.add = add;
exports.add2 = add2;
exports.my_coin = my_coin;
exports.message = message;
exports.me = me;
/* Not a pure module */
| 14.965517
| 65
| 0.56106
|
ae9b9f2fcd19ba59c9ae3404ff48234106af0b02
| 7,441
|
cs
|
C#
|
src/World.cs
|
alexcu/super-ie
|
fe4bbe36875abf0d7a412cac9e6ad85b196c23be
|
[
"MIT"
] | null | null | null |
src/World.cs
|
alexcu/super-ie
|
fe4bbe36875abf0d7a412cac9e6ad85b196c23be
|
[
"MIT"
] | null | null | null |
src/World.cs
|
alexcu/super-ie
|
fe4bbe36875abf0d7a412cac9e6ad85b196c23be
|
[
"MIT"
] | null | null | null |
using SplashKitSDK;
using System.Collections.Generic;
///
/// The world encapsulates all data that exists for interaction between
/// different sprites.
///
class World : IRenderable
{
// Declare the player and target. Target is set to null until such conditions
// are satisified such that it should be created.
private Player player;
private Target target;
// Positions is a 2D array representing our grid of where sprites can be.
// This constant TILE_PIXELS declares how big each tile is in our "grid" in
// pixels, while width and height represent how big the grid actually is.
private Position[,] positions;
private int width, height;
public const int TILE_PIXELS = 32;
// This list encapsulates all sprites given on the screen.
private List<Sprite> sprites;
// The SplashKit rendering window.
private Window window;
public World(int width, int height)
{
this.width = width;
this.height = height;
this.window = new Window("Super Internet Explorer",
width * TILE_PIXELS, height * TILE_PIXELS);
SetupWorld();
}
// This method randomly places sprites (coins, enemies blocks) around
// on the grid.
private void PlaceRandomSpriteAt(Position pos)
{
float rnd = SplashKit.Rnd();
if (rnd > 0.75f && rnd <= 0.8f)
{
sprites.Add(new Coin(pos));
}
else if (rnd > 0.8f && rnd <= 0.85)
{
sprites.Add(new Enemy(pos));
}
else if (rnd > 0.85)
{
sprites.Add(new Block(pos));
}
}
// This function re-initialises the entire world by scrapping all previous
// data and re-creating the grid and all sprites.
private void SetupWorld()
{
this.positions = new Position[width, height];
this.sprites = new List<Sprite>();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
Position pos = new Position(x, y);
this.positions[x,y] = pos;
// ALWAYS place the player in the top left.
if (x == 0 && y == 0)
{
this.player = new Player(pos);
sprites.Add(this.player);
}
else
{
PlaceRandomSpriteAt(pos);
}
}
}
}
// Alias method for SplashKit's CloseRequested property.
public bool IsWindowCloseRequested()
{
return this.window.CloseRequested;
}
// Returns the position of the grid at the given grid's x and y coordinate.
public Position GetPositionAt(int x, int y)
{
if (x >= this.width || y >= this.height || x < 0 || y < 0)
{
return null;
}
return this.positions[x,y];
}
// Returns the position with respective cardinality direction of the given
// position. E.g., give me the position north of positionX.
public Position GetPositionAt(Position position, Cardinality direction)
{
switch (direction)
{
case Cardinality.North:
return GetPositionAt(position.CoordinateX, position.CoordinateY - 1);
case Cardinality.South:
return GetPositionAt(position.CoordinateX, position.CoordinateY + 1);
case Cardinality.East:
return GetPositionAt(position.CoordinateX + 1, position.CoordinateY);
case Cardinality.West:
return GetPositionAt(position.CoordinateX - 1, position.CoordinateY);
default:
return null;
}
}
// Returns a list of all sprites at a given position. This method needs
// to be re-written as it is very slow.
public List<Sprite> GetSpritesAt(Position position)
{
// Result sprites.
List<Sprite> resultSprites = new List<Sprite>();
foreach (Sprite spr in this.sprites)
{
// Get only those sprites who are at this position AND where spr's
// type matches that of the subtype parameter
if (spr.IsAt(position))
{
resultSprites.Add(spr);
}
}
return resultSprites;
}
// Removes a sprite from existence.
public void RemoveSprite(Sprite sprite)
{
this.sprites.Remove(sprite);
}
// Renders the world.
public void Render()
{
// Gives the background the classic Win95 feel.
this.window.Clear(SplashKit.ColorTeal());
foreach (Sprite spr in this.sprites)
{
spr.Render();
}
// Must call refresh to actually render our canvas to screen.
this.window.Refresh();
}
// Updates the entire world on each loop within the main loop in Program.cs
public void Update()
{
// Reset World requested?
if (SplashKit.KeyTyped(KeyCode.RKey))
{
SetupWorld();
}
// Undo requested?
if (SplashKit.KeyTyped(KeyCode.ZKey))
{
MoveLedger.UndoLastMoves();
}
// When we modify each sprite, we may remove them from the list (i.e.,
// by calling Remove(Sprite sprite). If we do that, we modify the foreach
// list during enumerating through the list. Therefore we must use a
// C-style for loop.
for (int i = 0; i < this.sprites.Count; i++)
{
Sprite spr = this.sprites[i];
// If this sprite is collidable and it collides with the player...
if (spr is ICollidable)
{
if (spr.IsAt(this.player))
{
// Downcast sprite 's' into collidable object and this.player into
// a collide object
ICollidable collidableSpr = ((ICollidable)spr);
collidableSpr.CollidesWith(this.player);
}
}
// Try move the player first
if (spr.Equals(this.player))
{
// Key typed events
if (SplashKit.KeyTyped(KeyCode.UpKey))
{
this.player.Direction = Cardinality.North;
this.player.Move();
}
if (SplashKit.KeyTyped(KeyCode.DownKey))
{
this.player.Direction = Cardinality.South;
this.player.Move();
}
if (SplashKit.KeyTyped(KeyCode.LeftKey))
{
this.player.Direction = Cardinality.West;
this.player.Move();
}
if (SplashKit.KeyTyped(KeyCode.RightKey))
{
this.player.Direction = Cardinality.East;
this.player.Move();
}
}
// Check if this sprite is another Movable kind of sprite.
else if (spr is IMovable)
{
// Downcast sprite 's' into movable object
IMovable movableSpr = ((IMovable)spr);
if (movableSpr.ShouldMove)
{
movableSpr.Move();
}
}
// Check if all coins have been `eaten' up. If so, create the target
// somewhere randomly on our screen.
if (this.AllCoinsEaten() && this.target == null)
{
// Until the target has been set...
while (this.target == null)
{
int rndX = SplashKit.Rnd(width);
int rndY = SplashKit.Rnd(height);
Position rndPos = this.GetPositionAt(rndX, rndY);
// Find a random position that has no sprites and place
// the target there :)
if (!rndPos.HasSprite())
{
this.target = new Target(rndPos);
this.sprites.Add(this.target);
}
}
}
}
}
// Returns truee if there are no more coins in the world.
private bool AllCoinsEaten()
{
foreach (Sprite s in this.sprites)
{
if (s is Coin)
{
return false;
}
}
return true;
}
// Returns trus if the given sprite is at the given coordinate.
public bool IsAt(Sprite sprite)
{
return this.IsAt(sprite);
}
}
| 28.400763
| 79
| 0.610133
|
bf481a25ec87d97136710bd8c5196efaa09c88d0
| 1,281
|
kt
|
Kotlin
|
schedule/src/main/kotlin/ru/shika/app/common/adapter/SimpleListAdapter.kt
|
ShikaSD/schedule-android
|
9716dc495bda772da46147662aa856fd4920c997
|
[
"MIT"
] | 1
|
2016-09-17T17:51:10.000Z
|
2016-09-17T17:51:10.000Z
|
schedule/src/main/kotlin/ru/shika/app/common/adapter/SimpleListAdapter.kt
|
ShikaSD/schedule-android
|
9716dc495bda772da46147662aa856fd4920c997
|
[
"MIT"
] | null | null | null |
schedule/src/main/kotlin/ru/shika/app/common/adapter/SimpleListAdapter.kt
|
ShikaSD/schedule-android
|
9716dc495bda772da46147662aa856fd4920c997
|
[
"MIT"
] | null | null | null |
package ru.shika.app.common.adapter
import android.app.Activity
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.pawegio.kandroid.find
import com.pawegio.kandroid.inflateLayout
import ru.shika.app.common.model.BaseListModel
import ru.shika.mamkschedule.R
/**
* Adapter for group list
*
* Created by ashikov on 27/09/2016.
*/
class SimpleListAdapter<in T : BaseListModel> (
private val activity: Activity
) : RecyclerView.Adapter<ItemViewHolder>() {
private var items = emptyList<T>()
fun setItems(items: List<T>) {
this.items = items
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val item = items[position]
holder.label.text = item.getLabel()
holder.info.text = item.getInfo()
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int) =
ItemViewHolder(activity.inflateLayout(R.layout.fragment_list_item))
override fun getItemCount() = items.size
}
class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val info = view.find<TextView>(R.id.item_list_info)
val label = view.find<TextView>(R.id.item_list_label)
}
| 27.847826
| 75
| 0.728337
|
4bb62e5afe0f2d799629b9d02cd25eff5d5707f7
| 5,755
|
cpp
|
C++
|
game.cpp
|
sam-slate/day-in-the-life
|
76174246d763645522dbd50b18aaf1f254e5ec1e
|
[
"MIT"
] | null | null | null |
game.cpp
|
sam-slate/day-in-the-life
|
76174246d763645522dbd50b18aaf1f254e5ec1e
|
[
"MIT"
] | null | null | null |
game.cpp
|
sam-slate/day-in-the-life
|
76174246d763645522dbd50b18aaf1f254e5ec1e
|
[
"MIT"
] | null | null | null |
#include <string>
#include <iostream>
#include <fstream>
#include <time.h>
#include <unistd.h>
#include "game.h"
using namespace std;
Game :: Game(){
scores.initialize_scores(START_PAIN, START_SPOONS, START_MONEY, false);
}
void Game :: run_game(){
read_in();
print_initial_message();
start();
}
void Game :: read_in(){
string filename = "";
for (int i = 0; i < NUM_CLUSTERS; i++){
filename = CLUSTERS[i] + ".txt";
ifstream infile;
infile.open(filename.c_str());
clusters[i].read_in(infile);
}
}
void Game :: print_initial_message(){
cout << "Hello! Welcome to this little text-based, choose-your-own-adventure game! Playing this game will hopefully give you a sense of what it is like to live a day in the life of someone with an invisible physical disability at Tufts University, based on my (Sam Slate’s) own experiences.";
cout << endl << endl;
if (SLEEP){sleep(8);}
cout << "The goal is easy: make it through the day. You will be given a series of events and options as to how to proceed. Each decision influences your next option, so choose wisely!";
cout << endl << endl;
if (SLEEP){sleep(8);}
cout << "Here’s the tricky part. At the start of the day, you are given points in three areas: pain tolerance, spoons, and money (explained below). Each decision you make will either add or detract from any of these three areas. If you get to 0 or below on any of the areas, you lose!";
cout << endl << endl;
if (SLEEP){sleep(8);}
cout << "Pain tolerance: " << scores.get_pain() << endl;
cout << " This is the measure of your ability to tolerate pain. The more pain you experience, the lower your pain tolerance.";
cout << endl;
if (SLEEP){sleep(8);}
cout << "Spoons: " << scores.get_spoons() << endl;
cout << " This is the measure of your energy and motivation. You only have so much in a day!";
cout << endl;
if (SLEEP){sleep(8);}
cout << "Money: " << scores.get_money() << endl;
cout << " This is how much money you have for the day. Spend it wisely :)";
cout << endl << endl;
if (SLEEP){sleep(8);}
cout << "Ready to begin? (y/n)" << endl;
char response = ' ';
cin >> response;
if (response == 'y' or response == 'Y'){
cout << "Let's go!!" << endl;
} else {
cout << "Then why are you here . . ." << endl;
}
}
void Game :: start(){
int order[11] = {0, 4, 1, 3, 2, 5, 7, 4, 3, 4, 6};
for (int i = 0; i < 11; i++){
if (!clusters[order[i]].run_events(scores)){
lost();
return;
}
}
won();
return;
}
void Game :: won(){
cout << "Congratulations, you made it through the day! I bet it wasn't easy!" << endl;
learn_more();
}
void Game :: learn_more(){
char response = ' ';
if (SLEEP){sleep(2);}
cout << "Thank you so very much for playing. I hope you have learned something!\n\n";
if (SLEEP){sleep(2);}
cout << "Would you like to play the game again? (g) Or, would you like to learn more about the inspiration for this game? (y/n)" << endl;
cout << "Input: ";
cin >> response;
if (response == 'y' or response == 'Y'){
cout << "Great!" << endl;
if (SLEEP){sleep(2);}
cout << "As mentioned earlier, this game simulates what it is like to live a day in the life of someone with an invisible physical disability at Tufts University. All of the situations presented are pulled from my lived experiences as a disabled student, and the tradeoffs and decisions and balancing acts you had to deal with are the same that I deal with every moment of every day.\n\n";
if (SLEEP){sleep(12);}
cout << "Some days are easier and some days are harder. Some days I make it through, some days I don’t. Most day I have moments of giving up and moments of strength and nearly every day I am thankful to be living and breathing at the very least.\n\n";
if (SLEEP){sleep(12);}
cout << "The tricky part is that disability does not exist in a vacuum. Other things go wrong, there are other pains in your life, you get sick, tired, upset, angry, and everything in between. Disability is just there making all the little things harder.\n\n";
if (SLEEP){sleep(12);}
cout << "If you feel like all these little decision I showed you are hard, in reality there are five times as many that I wasn’t able to put down. When my pain is bad, which is most days, I can never not think about the things I can and cannot do. I am my pain. I am these decisions.\n\n";
if (SLEEP){sleep(12);}
cout << "And I know, in the back of my mind, that all those folks I see around me who get through the day with ease, who never have to think about the things that I think about, I know that someday something will give.\n\n";
if (SLEEP){sleep(10);}
cout << "We are all temporarily able.\n\n";
if (SLEEP){sleep(5);}
cout << "You will have to fight this fight.\n\n";
if (SLEEP){sleep(5);}
cout << "You will have to live my life.\n\n";
if (SLEEP){sleep(5);}
cout << "And you will know, then, the strength it takes to carry on.\n";
if (SLEEP){sleep(5);}
} else if (response == 'g' or response == 'G'){
cout << "Alright, have fun!";
scores.initialize_scores(START_PAIN, START_SPOONS, START_MONEY, false);
run_game();
}
}
void Game :: lost(){
//check what made you lose
if (scores.get_pain() <= 0){
cout << "Looks like you felt too much pain :( You'll need to space out how you use your body next time around. The key is to save pain tolerance for the more demanding actions later in the day.\n\n";
} else if (scores.get_money() <= 0){
cout << "Uh-oh, you ran out of money! You can't spend like crazy to protect your body, even if you'd like to.\n\n";
} else {
cout << "Your spoons seem to be compeletely gone :( You've exhausted yourself trying to compensate for your body through taking on mental and emotional labor.\n\n";
}
learn_more();
}
| 42.007299
| 391
| 0.674196
|
e4030b8db1607620cd9c3a5335d75c27c1773203
| 1,557
|
cs
|
C#
|
2.ProgrammingFundamentals/04_Lists/Exercise_03_SearchForANumber/searchForANumber.cs
|
Brankovanov/SoftUniCourses
|
39648a863c29e00057a6969c63b19cfc7cfb8f07
|
[
"MIT"
] | 1
|
2018-07-17T07:43:49.000Z
|
2018-07-17T07:43:49.000Z
|
2.ProgrammingFundamentals/04_Lists/Exercise_03_SearchForANumber/searchForANumber.cs
|
Brankovanov/SoftUniCourses
|
39648a863c29e00057a6969c63b19cfc7cfb8f07
|
[
"MIT"
] | null | null | null |
2.ProgrammingFundamentals/04_Lists/Exercise_03_SearchForANumber/searchForANumber.cs
|
Brankovanov/SoftUniCourses
|
39648a863c29e00057a6969c63b19cfc7cfb8f07
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Exercise_03_SearchForANumber
{
public class searchForANumber
{
public static void Main(string[] args)
{
Input();
}
static void Input()
{
var numbers = Console.ReadLine();
var commands = Console.ReadLine();
CreateLists(numbers, commands);
}
static void CreateLists(string numbers, string commands)
{
List<int> numbersList = new List<int>();
List<int> commandList = new List<int>();
numbersList = numbers.Split(' ').Select(x => int.Parse(x)).ToList();
commandList = commands.Split(' ').Select(y => int.Parse(y)).ToList();
SearchList(numbersList, commandList);
}
static void SearchList(List<int> numbersList, List<int> commandList)
{
var index = commandList[0];
var count = Math.Abs((commandList[0]) - numbersList.Count);
numbersList.RemoveRange(index, count);
index = 0;
count = 0;
numbersList.RemoveRange(0, commandList[1]);
Print(numbersList, commandList);
}
static void Print(List<int> numbersList, List<int> commandList)
{
if (numbersList.Contains(commandList[2]))
{
Console.WriteLine("YES!");
}
else
{
Console.WriteLine("NO!");
}
}
}
}
| 25.52459
| 81
| 0.528581
|
394e41774fd5326f80478a1aa00fec575db55d64
| 1,603
|
py
|
Python
|
TicketView.py
|
ritvikbhawnani/Zendesk_Ticket_Viewer
|
6323f3743c12c31b30e40158f3251a83e742edab
|
[
"MIT"
] | null | null | null |
TicketView.py
|
ritvikbhawnani/Zendesk_Ticket_Viewer
|
6323f3743c12c31b30e40158f3251a83e742edab
|
[
"MIT"
] | null | null | null |
TicketView.py
|
ritvikbhawnani/Zendesk_Ticket_Viewer
|
6323f3743c12c31b30e40158f3251a83e742edab
|
[
"MIT"
] | null | null | null |
from datetime import datetime
class TicketView:
"""
The TicketView presents the data to the user
"""
def display_menu(self):
"""
Displays the menu of available options
"""
print("Menu Options:")
print(" ENTER 1 to display all tickets")
print(" ENTER 2 to display a single ticket by ID")
print(" ENTER q to quit the program")
print(" ENTER m to display the menu")
print()
def display_ticket_helper(self, id, status, priority, created_at):
print("{:<15} {:<15} {:<15} {:<25}".format(
str(id), str(status), str(priority), str(created_at)))
def display_goodbye_message(self):
"""
Displays a thank you message
"""
print("Goodbye")
def display_all_tickets(self, tickets):
"""
Displays all the tickets
"""
print("all tickets")
def display_ticket_detail(self, ticket):
"""
Displays the details of a single ticket
"""
print("{:<15} {:<15} {:<15} {:<25}".format(
'Ticket ID', 'Status', 'Priority', 'Created At'))
created_at = ticket["created_at"]
created_at = datetime.fromisoformat(created_at[:-1])
created_at = created_at.strftime('%Y-%m-%d')
self.display_ticket_helper(ticket["id"], ticket["status"],
ticket["priority"], created_at)
print()
def display_error_message(self, error_message):
"""
Displays error messages
"""
print(error_message)
| 23.925373
| 70
| 0.553961
|
eb3e5b66d5cde8a53ada62e9b8a619399f43ecd8
| 22,579
|
css
|
CSS
|
css/styleX.css
|
jaerso/PAR5
|
47a4414b50f5dbfdab5d10b6d73cb499320b9850
|
[
"CC-BY-3.0"
] | null | null | null |
css/styleX.css
|
jaerso/PAR5
|
47a4414b50f5dbfdab5d10b6d73cb499320b9850
|
[
"CC-BY-3.0"
] | null | null | null |
css/styleX.css
|
jaerso/PAR5
|
47a4414b50f5dbfdab5d10b6d73cb499320b9850
|
[
"CC-BY-3.0"
] | null | null | null |
@charset "UTF-8";
@import url(font-awesome.min.css);
@import url(http://fonts.googleapis.com/css?family=Raleway:700,400);
/* Basic */
body {
background: #fff;
}
body.is-loading *, body.is-loading *:before, body.is-loading *:after {
-moz-animation: none !important;
-webkit-animation: none !important;
-o-animation: none !important;
-ms-animation: none !important;
animation: none !important;
-moz-transition: none !important;
-webkit-transition: none !important;
-o-transition: none !important;
-ms-transition: none !important;
transition: none !important;
}
body, input, select, textarea {
color: #444;
font-family: "Raleway", Helvetica, sans-serif;
font-size: 13pt;
font-weight: 400;
line-height: 1.65em;
}
a {
color: #383b43;
text-decoration: none;
}
a:active, a:hover {
text-decoration: underline;
}
strong, b {
color: #474747;
font-weight: 700;
}
em, i {
font-style: italic;
}
p {
margin: 0 0 2em 0;
}
h1, h2, h3, h4, h5, h6 {
color: #474747;
font-weight: 700;
line-height: 1em;
margin: 0 0 1em 0;
}
h1 a, h2 a, h3 a, h4 a, h5 a, h6 a {
color: inherit;
text-decoration: none;
}
h2 {
font-size: 1.75em;
line-height: 1.5em;
}
h3 {
font-size: 1.35em;
line-height: 1.5em;
}
h4 {
font-size: 1.1em;
line-height: 1.5em;
}
h5 {
font-size: 0.9em;
line-height: 1.5em;
}
h6 {
font-size: 0.7em;
line-height: 1.5em;
}
sub {
font-size: 0.8em;
position: relative;
top: 0.5em;
}
sup {
font-size: 0.8em;
position: relative;
top: -0.5em;
}
hr {
border: 0;
border-bottom: solid 1px rgba(144, 144, 144, 0.25);
margin: 2em 0;
}
hr.major {
margin: 3em 0;
}
blockquote {
border-left: solid 4px rgba(144, 144, 144, 0.25);
font-style: italic;
margin: 0 0 2em 0;
padding: 0.5em 0 0.5em 2em;
}
code {
background: rgba(144, 144, 144, 0.075);
border-radius: 4px;
border: solid 1px rgba(144, 144, 144, 0.25);
font-family: "Courier New", monospace;
font-size: 0.9em;
margin: 0 0.25em;
padding: 0.25em 0.65em;
}
pre {
-webkit-overflow-scrolling: touch;
font-family: "Courier New", monospace;
font-size: 0.9em;
margin: 0 0 2em 0;
}
pre code {
display: block;
line-height: 1.75em;
padding: 1em 1.5em;
overflow-x: auto;
}
.align-left {
text-align: left;
}
.align-center {
text-align: center;
}
.align-right {
text-align: right;
}
/* Section/Article */
section.special, article.special {
text-align: center;
}
header p {
color: #858585;
position: relative;
margin: 0 0 1.5em 0;
}
header h2 + p {
font-size: 1.25em;
margin-top: -1em;
line-height: 1.5em;
}
header h3 + p {
font-size: 1.1em;
margin-top: -0.8em;
line-height: 1.5em;
}
header h4 + p,
header h5 + p,
header h6 + p {
font-size: 0.9em;
margin-top: -0.6em;
line-height: 1.5em;
}
header.major {
text-align: center;
margin-bottom: 4em;
}
header.major h2 {
font-size: 3em;
margin-bottom: 0.5em;
}
header.major p {
font-size: 1.5em;
}
/* Form */
form {
margin: 0 0 6em 0;
}
label {
color: #474747;
display: block;
font-size: 0.9em;
font-weight: 700;
margin: 0 0 1em 0;
}
input[type="text"],
input[type="password"],
input[type="email"],
select,
textarea {
-moz-appearance: none;
-webkit-appearance: none;
-o-appearance: none;
-ms-appearance: none;
appearance: none;
background: rgba(144, 144, 144, 0.075);
border-radius: 4px;
border: none;
color: inherit;
display: block;
outline: 0;
padding: 0 1em;
text-decoration: none;
width: 100%;
}
input[type="text"]:invalid,
input[type="password"]:invalid,
input[type="email"]:invalid,
select:invalid,
textarea:invalid {
box-shadow: none;
}
input[type="text"]:focus,
input[type="password"]:focus,
input[type="email"]:focus,
select:focus,
textarea:focus {
border-color: #383b43;
box-shadow: 0 0 0 1px #383b43;
}
.select-wrapper {
text-decoration: none;
display: block;
position: relative;
}
.select-wrapper:before {
content: "";
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
text-transform: none !important;
}
.select-wrapper:before {
color: rgba(144, 144, 144, 0.25);
display: block;
height: 2.75em;
line-height: 2.75em;
pointer-events: none;
position: absolute;
right: 0;
text-align: center;
top: 0;
width: 2.75em;
}
.select-wrapper select::-ms-expand {
display: none;
}
input[type="text"],
input[type="password"],
input[type="email"],
select {
height: 2.75em;
}
textarea {
padding: 0.75em 1em;
margin-top:1.8em;
}
input[type="checkbox"],
input[type="radio"] {
-moz-appearance: none;
-webkit-appearance: none;
-o-appearance: none;
-ms-appearance: none;
appearance: none;
display: block;
float: left;
margin-right: -2em;
opacity: 0;
width: 1em;
z-index: -1;
}
input[type="checkbox"] + label,
input[type="radio"] + label {
text-decoration: none;
color: #444;
cursor: pointer;
display: inline-block;
font-size: 1em;
font-weight: 400;
padding-left: 2.4em;
padding-right: 0.75em;
position: relative;
}
input[type="checkbox"] + label:before,
input[type="radio"] + label:before {
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
text-transform: none !important;
}
input[type="checkbox"] + label:before,
input[type="radio"] + label:before {
background: rgba(144, 144, 144, 0.075);
border-radius: 4px;
border: solid 1px rgba(144, 144, 144, 0.25);
content: '';
display: inline-block;
height: 1.65em;
left: 0;
line-height: 1.58125em;
position: absolute;
text-align: center;
top: 0;
width: 1.65em;
}
input[type="checkbox"]:checked + label:before,
input[type="radio"]:checked + label:before {
background: #3cadd4;
border-color: #3cadd4;
color: #ffffff;
content: '\f00c';
}
input[type="checkbox"]:focus + label:before,
input[type="radio"]:focus + label:before {
border-color: #383b43;
box-shadow: 0 0 0 1px #383b43;
}
input[type="checkbox"] + label:before {
border-radius: 4px;
}
input[type="radio"] + label:before {
border-radius: 100%;
}
::-webkit-input-placeholder {
color: #858585 !important;
opacity: 1.0;
}
:-moz-placeholder {
color: #858585 !important;
opacity: 1.0;
}
::-moz-placeholder {
color: #858585 !important;
opacity: 1.0;
}
:-ms-input-placeholder {
color: #858585 !important;
opacity: 1.0;
}
.formerize-placeholder {
color: #858585 !important;
opacity: 1.0;
}
/* Box */
.box {
border-radius: 4px;
border: solid 1px rgba(144, 144, 144, 0.25);
margin-bottom: 2em;
padding: 1.5em;
}
.box > :last-child,
.box > :last-child > :last-child,
.box > :last-child > :last-child > :last-child {
margin-bottom: 0;
}
.box.alt {
border: 0;
border-radius: 0;
padding: 0;
}
/* Icon */
.icon {
text-decoration: none;
border-bottom: none;
position: relative;
}
.icon:before {
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-family: FontAwesome;
font-style: normal;
font-weight: normal;
text-transform: none !important;
}
.icon:active, .icon:hover {
text-decoration: none;
}
.icon > .label {
display: none;
}
.icon.rounded {
background-color: #383b43;
border-radius: 100%;
color: #ffffff;
display: inline-block;
height: 3.25em;
line-height: 3.25em;
text-align: center;
width: 3.25em;
}
.icon.rounded.big {
font-size: 2.5em;
margin-bottom: 0.5em;
}
.icon.rounded.color1 {
background-color: #3cadd4;
}
.icon.rounded.color2 {
background-color: #3c61d4;
}
.icon.rounded.color3 {
background-color: #633cd4;
}
.icon.rounded.color4 {
background-color: #af3cd4;
}
.icon.rounded.color5 {
background-color: #d43cad;
}
.icon.rounded.color6 {
background-color: #d43c61;
}
.icon.rounded.color7 {
background-color: #d4633c;
}
.icon.rounded.color8 {
background-color: #d4af3c;
}
.icon.rounded.color9 {
background-color: #3AAA35;
}
.icon.rounded.color10 {
background-color: #61d43c;
}
.icon.rounded.fa-twitter {
background-color: #2daae4;
}
.icon.rounded.fa-facebook {
background-color: #39599f;
}
.icon.rounded.fa-google-plus {
background-color: #c91e1f;
}
.icon.rounded.fa-dribbble {
background-color: #c4376b;
}
.icon.rounded.fa-tumblr, .icon.rounded.fa-linkedin {
background-color: #31516a;
}
.icon.rounded.fa-rss {
background-color: #f2600b;
}
/* List */
ul {
list-style: disc;
margin: 0 0 2em 0;
padding-left: 1em;
}
ul li {
padding-left: 0.5em;
}
ul.alt {
list-style: none;
padding-left: 0;
}
ul.alt li {
border-top: solid 1px rgba(144, 144, 144, 0.25);
padding: 0.5em 0;
}
ul.alt li:first-child {
border-top: 0;
padding-top: 0;
}
ul.unstyled {
list-style: none;
padding-left: 0;
}
ul.unstyled li {
padding: 0.4em 0;
}
ul.icons {
cursor: default;
list-style: none;
padding-left: 0;
}
ul.icons li {
display: inline-block;
padding: 0 1em 0 0;
}
ul.icons li:last-child {
padding-right: 0;
}
ul.icons li .icon:before {
font-size: 2em;
}
ul.actions {
cursor: default;
list-style: none;
padding-left: 0;
}
ul.actions li {
display: inline-block;
padding: 0 1em 0 0;
vertical-align: middle;
}
ul.actions li:last-child {
padding-right: 0;
}
ul.actions.small li {
padding: 0 0.5em 0 0;
}
ul.actions.vertical li {
display: block;
padding: 1em 0 0 0;
}
ul.actions.vertical li:first-child {
padding-top: 0;
}
ul.actions.vertical li > * {
margin-bottom: 0;
}
ul.actions.vertical.small li {
padding: 0.5em 0 0 0;
}
ul.actions.vertical.small li:first-child {
padding-top: 0;
}
ul.actions.fit {
display: table;
margin-left: -1em;
padding: 0;
table-layout: fixed;
width: calc(100% + 1em);
}
ul.actions.fit li {
display: table-cell;
padding: 0 0 0 1em;
}
ul.actions.fit li > * {
margin-bottom: 0;
}
ul.actions.fit.small {
margin-left: -0.5em;
width: calc(100% + 0.5em);
}
ul.actions.fit.small li {
padding: 0 0 0 0.5em;
}
dl {
margin: 0 0 2em 0;
}
/* Button */
input[type="submit"],
input[type="reset"],
input[type="button"],
.button {
-moz-appearance: none;
-webkit-appearance: none;
-o-appearance: none;
-ms-appearance: none;
appearance: none;
-moz-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
-webkit-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
-o-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
-ms-transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
background: linear-gradient(to top right, #798c96, #9da4c9);
border-radius: 30px;
border: 0;
color: #ffffff !important;
cursor: pointer;
display: inline-block;
font-weight: 400;
height: 2.85em;
line-height: 2.95em;
padding: 0 2em;
text-align: center;
text-decoration: none;
white-space: nowrap;
}
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="button"]:hover,
.button:hover {
background-color: #51b6d9;
text-decoration: none;
}
input[type="submit"]:active,
input[type="reset"]:active,
input[type="button"]:active,
.button:active {
background-color: #2da2ca;
text-decoration: none;
}
input[type="submit"].icon,
input[type="reset"].icon,
input[type="button"].icon,
.button.icon {
padding-left: 1.35em;
}
input[type="submit"].icon:before,
input[type="reset"].icon:before,
input[type="button"].icon:before,
.button.icon:before {
margin-right: 0.5em;
}
input[type="submit"].fit,
input[type="reset"].fit,
input[type="button"].fit,
.button.fit {
display: block;
margin: 0 0 1em 0;
width: 100%;
}
input[type="submit"].small,
input[type="reset"].small,
input[type="button"].small,
.button.small {
font-size: 0.8em;
}
input[type="submit"].big,
input[type="reset"].big,
input[type="button"].big,
.button.big {
font-size: 1.35em;
}
input[type="submit"].alt,
input[type="reset"].alt,
input[type="button"].alt,
.button.alt {
background-color: transparent;
box-shadow: inset 0 0 0 2px rgba(144, 144, 144, 0.25);
color: #474747 !important;
}
input[type="submit"].alt:hover,
input[type="reset"].alt:hover,
input[type="button"].alt:hover,
.button.alt:hover {
background-color: rgba(144, 144, 144, 0.075);
}
input[type="submit"].alt:active,
input[type="reset"].alt:active,
input[type="button"].alt:active,
.button.alt:active {
background-color: rgba(144, 144, 144, 0.2);
}
input[type="submit"].alt.icon:before,
input[type="reset"].alt.icon:before,
input[type="button"].alt.icon:before,
.button.alt.icon:before {
color: #858585;
}
input[type="submit"].special,
input[type="reset"].special,
input[type="button"].special,
.button.special {
background-color: #383b43;
color: #ffffff !important;
margin-top:1em;
}
input[type="submit"].special:hover,
input[type="reset"].special:hover,
input[type="button"].special:hover,
.button.special:hover {
background-color: #444751;
}
input[type="submit"].special:active,
input[type="reset"].special:active,
input[type="button"].special:active,
.button.special:active {
background-color: #2c2f35;
}
input[type="submit"].disabled, input[type="submit"]:disabled,
input[type="reset"].disabled,
input[type="reset"]:disabled,
input[type="button"].disabled,
input[type="button"]:disabled,
.button.disabled,
.button:disabled {
background-color: #444 !important;
box-shadow: inset 0 -0.15em 0 0 rgba(0, 0, 0, 0.15);
color: #fff !important;
cursor: default;
opacity: 0.25;
}
/* Header */
body.landing #header {
left: 0;
top: 0;
}
body.landing #header nav a {
-moz-transition: 0.3s ease-in-out;
-webkit-transition: 0.3s ease-in-out;
-o-transition: 0.3s ease-in-out;
-ms-transition: 0.3s ease-in-out;
transition: 0.3s ease-in-out;
color:#3AAA35;
font-family: "Raleway";
font-weight:bold;
font-size: 1em;
}
#header {
cursor: default;
font-size: 1.1em;
height: 5.3em;
line-height: 6em;
width: 100%;
z-index: 10000;
}
.header-background {
background-image: url("../images/pic09.jpg");
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
#header h1 {
color: #ffffff;
height: inherit;
left: 3em;
line-height: inherit;
margin: 0;
padding: 0;
position: absolute;
}
#header h1 a {
font-size: 1.25em;
}
#editor {
margin: 20px 0;
}
/* Header Login*/
header .nav-login {
float: right;
}
header .nav-login form {
float: left;
padding-top: 15px;
}
header .nav-login form input {
float: left;
width: 140px;
height: 30px;
padding: 0px 10px;
margin-right: 10px;
border: none;
background-color: #ccc;
font-family: arial;
font-size: 14px;
color: #111;
line-height: 30px;
}
header .nav-login form button {
float: left;
width: 90px;
height: 30px;
margin-right: 10px;
border: none;
background-color: #f3f3f3;
font-family: arial;
font-size: 14px;
color: #111;
cursor: pointer;
}
header .nav-login form button:hover {
background-color: #ccc;
}
header .nav-login a {
display: block;
width: 60px;
height: 60px;
border: none;
float: left;
background-color: #fff;
font-family: arial;
font-size: 16px;
color: #111;
line-height: 63px;
cursor: pointer;
}
/*signup.php*/
.signup-form {
width: 400px;
margin: 0 auto;
padding-top: 30px;
}
.signup-form input {
width: 90%;
height: 40px;
padding: 0px 5%;
margin-bottom: 4px;
background-color: lightgrey;
font-family: arial;
font-size: 16px;
color: green;
line-height: 40px;
}
.signup-form button {
display: block;
width: 30%;
height: 40px;
border: none;
background-color: #222;
font-family: arial;
font-size: 16px;
color: #fff;
cursor: pointer;
}
.signup-form button:hover {
background-color: #111;
}
/*navi orginal*/
#header nav {
height: 3em;
line-height: 3em;
position: absolute;
right: 3em;
vertical-align: middle;
}
#header nav > ul {
list-style: none;
margin: 0;
padding-left: 0;
margin-top: 0.6em;
}
#header nav > ul > li {
border-radius: 1em;
display: inline-block;
margin-left: 0.5em;
padding-left: 0;
}
#header nav > ul > li a {
display: inline-block;
text-decoration: none;
}
#header nav > ul > li a:active, #header nav > ul > li a:hover {
-moz-transition: 0.6s ease-in-out;
-webkit-transition: 0.6s ease-in-out;
-o-transition: 0.6s ease-in-out;
-ms-transition: 0.6s ease-in-out;
transition: 0.6s ease-in-out;
color: white;
background-color: black;
}
#header nav > ul > li:first-child {
margin-left: 0;
}
#header nav > ul > li .button {
height: 2.25em;
line-height: 2.25em;
margin-bottom: 0;
padding: 0 1em;
position: relative;
top: -0.075em;
vertical-align: middle;
}
/*navi orginal ende*/
#header .container {
position: relative;
}
#header .container h1 {
left: 0;
}
#header .container nav {
right: 0;
}
/* Banner */
#banner {
background-image: url(../images/dark_tint.png), url(../images/bokeh_car_lights_bg.jpg);
opacity:0.9;
background-position: center center;
background-size: cover;
color: #ffffff;
padding: 14em 0em 14em;
text-align: center;
}
#banner :last-child {
margin-bottom: 0;
}
#banner h2 {
color: #ffffff;
font-size: 4em;
line-height: 1.25em;
margin: 0 0 0.5em 0;
padding: 0;
}
#banner p {
font-size: 1.5em;
margin-bottom: 1.75em;
}
/* Wrapper */
.wrapper {
padding: 1em 0em 0em;
/* Style 1 Wrapper */
/* Style 2 Wrapper */
/* Style 3 Wrapper */
}
.wrapper.style1 {
background-color: #F5F5F5;
border-bottom: 1px solid rgba(144, 144, 144, 0.25);
border-top: 1px solid rgba(144, 144, 144, 0.25);
}
.wrapper.style1 .box {
background-color: #fff;
padding: 3em 2.5em;
}
.wrapper.style1 .box h2, .wrapper.style1 .box h3, .wrapper.style1 .box h4, .wrapper.style1 .box h5, .wrapper.style1 .box h6 {
color: #858585;
}
.wrapper.style2 .profiles {
border-bottom: 1px solid rgba(144, 144, 144, 0.25);
border-top: 1px solid rgba(144, 144, 144, 0.25);
margin-bottom: 4em;
padding-top: 4em;
}
.wrapper.style2 .profile {
margin-bottom: 2em;
text-align: left;
}
.wrapper.style2 .profile img {
border-radius: 50%;
float: left;
margin-bottom: 1em;
margin-right: 1em;
}
.wrapper.style2 .profile h4 {
margin-bottom: 0;
margin-top: 1em;
}
.wrapper.style2 footer {
margin-left: auto;
margin-right: auto;
width: 70%;
}
.wrapper.style2 footer p {
margin-bottom: 3em;
}
.wrapper.style3 {
background-color: #ffe082;
color: #ffffff;
}
.wrapper.style3 h2, .wrapper.style3 h3, .wrapper.style3 p {
color: #ffffff;
}
.wrapper.style3 input[type="text"],
.wrapper.style3 input[type="password"],
.wrapper.style3 input[type="email"],
.wrapper.style3 select,
.wrapper.style3 textarea {
background-color: #fff;
color: #444;
}
.container{
margin-bottom: 4em;
}
/* Footer */
#footer {
background: #383b43;
/*background-image: url("../images/pic07.jpg");*/
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
padding: 6em 0em 4em;
}
#footer h2, #footer h3, #footer h4 {
color: #ffffff;
}
#footer p, #footer a, #footer li {
color: #cdced0;
}
#footer .links {
border-bottom: 1px solid rgba(144, 144, 144, 0.25);
margin-bottom: 4em;
padding-bottom: 1em;
}
#footer .copyright {
margin-top: 0.65em;
padding: 0;
}
#footer .copyright li {
color: #e9e9e9;
display: inline-block;
list-style: none;
margin-left: 0.5em;
padding-left: 0.5em;
}
#footer .copyright li:first-child {
margin-left: 0;
padding-left: 0;
}
#footer .copyright a {
color: #858585;
}
#footer .icons {
text-align: right;
}
#footer a.icon {
color: #ffffff;
font-size: 0.65em;
height: 4em;
line-height: 4em;
width: 4em;
cursor: pointer;
}
/* Bahn-Editor */
#canvas{
border: 1px solid;
width: 1100px;
height: 450px;
margin: 0 20px;
display: block;
}
#clearCanvas,
#export{
margin: 10px;
font-size: 18px;
}
#clearCanvas{
background-color: #EF5350;
}
#clearCanvas:focus{
background-color: #EF5350;
color: white;
}
#clearCanvas:hover{
-moz-transition: 0.2s ease-in-out;
-webkit-transition: 0.2s ease-in-out;
-o-transition: 0.2s ease-in-out;
-ms-transition: 0.2s ease-in-out;
transition: 0.2s ease-in-out;
background-color: #E53935;
}
.dropdown,
#bahn-title{
margin: 20px;
}
#bahn-title {
background-color: #474747;
color: white;
text-align: center;
font-size: 22px;
padding: 6px 12px;
}
.dropdown ul>a>li,
.dropdown button{
font-size: 22px;
}
.btn-default{
background-color: #4CAF50;
color: white;
border: none;
border-radius: 0;
}
.btn-default:hover{
-moz-transition: 0.2s ease-in-out;
-webkit-transition: 0.2s ease-in-out;
-o-transition: 0.2s ease-in-out;
-ms-transition: 0.2s ease-in-out;
transition: 0.2s ease-in-out;
background-color: #3e8e41;
color: white;
border: none;
border-radius: 0;
}
.dropdown-menu{
border-radius: 0;
border: none;
background-color: #eee;
}
.dropdown-menu > a:hover,
.dropdown-menu > a > li:hover {
text-decoration: none;
color: whitesmoke;
background-color: #4CAF50;
}
| 17.77874
| 129
| 0.615395
|
8dec499dccbbcf18d0038fcec209a8c9b941b352
| 846
|
js
|
JavaScript
|
background.js
|
Sukhrobjon/single-tab
|
e6957c3b358534cce5bcaa1ce7fe1b7893afb54a
|
[
"MIT"
] | null | null | null |
background.js
|
Sukhrobjon/single-tab
|
e6957c3b358534cce5bcaa1ce7fe1b7893afb54a
|
[
"MIT"
] | null | null | null |
background.js
|
Sukhrobjon/single-tab
|
e6957c3b358534cce5bcaa1ce7fe1b7893afb54a
|
[
"MIT"
] | null | null | null |
// chrome.browserAction.setIcon({
// path: "stack - icon.png"
// });
const numberOftabs = chrome.tabs.query({ currentWindow: true}, function (tabs) {
console.log('found number of tabs', tabs.length)
chrome.browserAction.setBadgeText({
text: `${tabs.length}`
});
})
chrome.browserAction.setBadgeBackgroundColor({
color: [10, 20, 0, 10]
});
// this is comment
console.log('numberOftabs -- ')
console.log(numberOftabs)
// chrome.storage.onChanged.addListener
chrome.storage.onChanged.addListener(function (changes, namespace) {
console.log('on change setting badge')
const numberOftabs = chrome.tabs.query({ currentWindow: true}, function (tabs) {
console.log('found number of tabs', tabs.length)
chrome.browserAction.setBadgeText({
text: `${tabs.length}`
});
})
});
| 30.214286
| 84
| 0.660757
|
43e55c1a912729e74a490db9587a04b2d5bb47ba
| 598
|
ts
|
TypeScript
|
app/src/app/app-routing.module.ts
|
plamena-petkova/SoftUni-Forum-Angular-
|
53b4c0f3a7f563b2b5e24f06847e70726a6fade6
|
[
"MIT"
] | null | null | null |
app/src/app/app-routing.module.ts
|
plamena-petkova/SoftUni-Forum-Angular-
|
53b4c0f3a7f563b2b5e24f06847e70726a6fade6
|
[
"MIT"
] | null | null | null |
app/src/app/app-routing.module.ts
|
plamena-petkova/SoftUni-Forum-Angular-
|
53b4c0f3a7f563b2b5e24f06847e70726a6fade6
|
[
"MIT"
] | null | null | null |
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './feature/home/home.component';
import { LoginComponent } from './user/login/login.component';
import { RegisterComponent } from './user/register/register.component';
const routes: Routes = [
{
path: '',
pathMatch:'full',
redirectTo: 'home'
},
{
path: 'home',
component: HomeComponent
},
{
path: 'login',
component: LoginComponent
},
{
path: 'register',
component: RegisterComponent
},
];
export const AppRoutingModule = RouterModule.forRoot(routes);
| 18.121212
| 71
| 0.653846
|
65b67be8653a6d1d7fed11acacbd7ad7401efe2e
| 376
|
asm
|
Assembly
|
programs/oeis/094/A094918.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 22
|
2018-02-06T19:19:31.000Z
|
2022-01-17T21:53:31.000Z
|
programs/oeis/094/A094918.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 41
|
2021-02-22T19:00:34.000Z
|
2021-08-28T10:47:47.000Z
|
programs/oeis/094/A094918.asm
|
neoneye/loda
|
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
|
[
"Apache-2.0"
] | 5
|
2021-02-24T21:14:16.000Z
|
2021-08-09T19:48:05.000Z
|
; A094918: a(n) = (3^n-1)/2 mod n.
; 0,0,1,0,1,4,1,0,4,4,1,4,1,4,13,0,1,4,1,0,13,4,1,16,21,4,13,12,1,4,1,0,13,4,23,4,1,4,13,0,1,28,1,40,31,4,1,16,15,24,13,40,1,40,33,32,13,4,1,40,1,4,13,0,56,34,1,40,13,54,1,40,1,4,28,40,37,52,1,0,40,4,1,28,36,4,13,24,1,4,1,40,13,4,83,64,1,88,40,0
add $0,1
mov $2,$0
lpb $0
sub $0,1
add $1,1
mod $1,$2
mul $1,3
lpe
div $1,3
mov $0,$1
| 26.857143
| 245
| 0.553191
|
b6830f0a4ae439bc8719ae400bf00954bb7fff15
| 1,851
|
rs
|
Rust
|
src/k8-types/src/lib.rs
|
simlay/k8-api
|
3a69671c469c46757e489f4ab6919f6601e0e514
|
[
"Apache-2.0"
] | 18
|
2020-05-26T09:19:04.000Z
|
2021-12-20T04:16:07.000Z
|
src/k8-types/src/lib.rs
|
simlay/k8-api
|
3a69671c469c46757e489f4ab6919f6601e0e514
|
[
"Apache-2.0"
] | 101
|
2020-06-05T21:12:15.000Z
|
2022-03-12T05:43:27.000Z
|
src/k8-types/src/lib.rs
|
simlay/k8-api
|
3a69671c469c46757e489f4ab6919f6601e0e514
|
[
"Apache-2.0"
] | 10
|
2020-06-09T03:42:43.000Z
|
2022-02-20T01:46:44.000Z
|
mod crd;
mod metadata;
pub mod options;
pub mod store;
#[cfg(feature = "core")]
pub mod core;
#[cfg(feature = "app")]
pub mod app;
#[cfg(feature = "storage")]
pub mod storage;
#[cfg(feature = "batch")]
pub mod batch;
pub use self::crd::*;
pub use self::metadata::*;
pub use self::spec_def::*;
mod spec_def {
use std::fmt::Debug;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde::Serialize;
use super::Crd;
pub trait Status:
Sized + Debug + Clone + Default + Serialize + DeserializeOwned + Send + Sync
{
}
pub trait Header:
Sized + Debug + Clone + Default + Serialize + DeserializeOwned + Send + Sync
{
}
/// Kubernetes Spec
pub trait Spec:
Sized + Debug + Clone + Default + Serialize + DeserializeOwned + Send + Sync
{
type Status: Status;
type Header: Header;
/// if true, spec is namespaced
const NAME_SPACED: bool = true;
/// return uri for single instance
fn metadata() -> &'static Crd;
fn label() -> &'static str {
Self::metadata().names.kind
}
fn api_version() -> String {
let metadata = Self::metadata();
if metadata.group == "core" {
return metadata.version.to_owned();
}
format!("{}/{}", metadata.group, metadata.version)
}
fn kind() -> String {
Self::metadata().names.kind.to_owned()
}
/// in case of applying, we have some fields that are generated
/// or override. So need to special logic to reset them so we can do proper comparison
fn make_same(&mut self, _other: &Self) {}
}
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
pub struct DefaultHeader {}
impl Header for DefaultHeader {}
}
| 23.730769
| 95
| 0.576445
|
8e9b1030382233f136bcc85857ce4496c0408e42
| 6,425
|
dart
|
Dart
|
lib/ui/cookie/cookie_page.dart
|
MShaffar19/restler
|
20692d0cfd010c59d690c26c3d51912ddfadc33f
|
[
"MIT"
] | 1
|
2020-09-26T15:28:21.000Z
|
2020-09-26T15:28:21.000Z
|
lib/ui/cookie/cookie_page.dart
|
TKPoseidon/restler
|
14e11a1f3d999bd7eb68c343390f73f9c8a45722
|
[
"MIT"
] | null | null | null |
lib/ui/cookie/cookie_page.dart
|
TKPoseidon/restler
|
14e11a1f3d999bd7eb68c343390f73f9c8a45722
|
[
"MIT"
] | 2
|
2020-10-23T15:45:05.000Z
|
2020-10-23T15:45:13.000Z
|
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:restler/blocs/cookie/bloc.dart';
import 'package:restler/data/entities/cookie_entity.dart';
import 'package:restler/inject.dart';
import 'package:restler/mdi.dart';
import 'package:restler/messager.dart';
import 'package:restler/ui/cookie/cookie_card.dart';
import 'package:restler/ui/cookie/create_edit_cookie_dialog.dart';
import 'package:restler/ui/widgets/default_app_bar.dart';
import 'package:restler/ui/widgets/state_mixin.dart';
import 'package:restler/ui/widgets/list_page.dart';
import 'package:restler/ui/widgets/move_to_workspace_dialog.dart';
import 'package:restler/ui/widgets/powerful_text_field.dart';
enum CookiePageAction { search, clear }
class CookiePage extends StatefulWidget {
const CookiePage({
Key key,
}) : super(key: key);
@override
_CookiePageState createState() => _CookiePageState();
}
class _CookiePageState extends State<CookiePage> with StateMixin<CookiePage> {
final Messager _messager = kiwi();
final _bloc = CookieBloc();
final _searchTextController = TextEditingController();
@override
void initState() {
_messager.registerOnState(this);
_bloc.add(CookieFetched());
super.initState();
}
@override
void dispose() {
_messager.unregisterOnState(this);
_searchTextController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: DefaultAppBar(
onBack: () => true,
// Title.
title: BlocBuilder<CookieBloc, CookieState>(
cubit: _bloc,
buildWhen: (a, b) => a.search != b.search,
builder: (context, state) {
// Search.
if (state.search) {
return PowerfulTextField(
controller: _searchTextController,
onChanged: (text) {
_bloc.add(SearchTextChanged(text));
},
hintText: i18n.search,
);
}
// Title.
else {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Title.
Text(i18n.cookie),
// Counter.
BlocBuilder<CookieBloc, CookieState>(
cubit: _bloc,
buildWhen: (a, b) => a.data.length != b.data.length,
builder: (context, state) {
return Text(
i18n.itemCount(state.data.length),
style: const TextStyle(
fontSize: 11,
),
);
},
),
],
);
}
},
),
items: CookiePageAction.values,
itemBuilder: (context, action) {
if (action == CookiePageAction.search) {
return const Icon(Icons.search);
} else {
return const Icon(Icons.clear_all);
}
},
onItemSelected: (item) async {
// Search.
if (item == CookiePageAction.search) {
_bloc.add(SearchToggled());
}
// Clear.
else {
_messager.show(
(i18n) => i18n.clearCookieConfirmationMessage,
actionText: i18n.yes,
onYes: () => _bloc.add(CookieCleared()),
);
}
},
),
// List.
body: BlocBuilder<CookieBloc, CookieState>(
cubit: _bloc,
buildWhen: (a, b) => a.data != b.data,
builder: (context, state) {
return ListPage<CookieEntity>(
emptyIcon: Mdi.cookie,
items: state.data,
itemBuilder: (context, i, item) {
// Card.
return CookieCard(
cookie: item,
key: Key(item.uid),
// Enabled.
onEnabled: (enabled) {
_bloc.add(CookieEdited(item.copyWith(enabled: enabled)));
},
onActionSelected: (action) async {
// Edit.
if (action == CookieCardAction.edit) {
final res =
await CreateEditCookieDialog.show(context, item);
if (!res.cancelled && res.data != null) {
_bloc.add(CookieEdited(res.data));
}
}
// Duplicated.
else if (action == CookieCardAction.duplicate) {
_bloc.add(CookieDuplicated(item));
}
// Move.
else if (action == CookieCardAction.move) {
final res = await MoveToWorkspaceDialog.show(
context,
item.workspace,
i18n.moveCookie,
);
if (!res.cancelled && res.data != null) {
_bloc.add(CookieMoved(item, res.data));
}
}
// Copy.
else if (action == CookieCardAction.copy) {
final res = await MoveToWorkspaceDialog.show(
context,
item.workspace,
i18n.copyCookie,
);
if (!res.cancelled && res.data != null) {
_bloc.add(CookieCopied(item, res.data));
}
}
// Delete.
else if (action == CookieCardAction.delete) {
_messager.show(
(i18n) => i18n.deleteCookieConfirmationMessage,
actionText: i18n.yes,
onYes: () => _bloc.add(CookieDeleted(item)),
);
}
},
);
},
// Add.
onAdded: () async {
final res = await CreateEditCookieDialog.show(context, null);
if (!res.cancelled && res.data != null) {
_bloc.add(CookieCreated(res.data));
}
},
);
},
),
);
}
}
| 32.948718
| 78
| 0.48358
|
cf1481afc11e57ea50f306d8b0a32a3a61546aef
| 5,166
|
php
|
PHP
|
lib/W3/Plugin/NewRelicAdmin.php
|
finaldream/w3-total-cache
|
0836d8151a9d421ce1cc91ef1f01c3903f1d2930
|
[
"MIT"
] | 2
|
2016-06-29T14:25:17.000Z
|
2018-05-08T07:43:37.000Z
|
lib/W3/Plugin/NewRelicAdmin.php
|
finaldream/w3-total-cache
|
0836d8151a9d421ce1cc91ef1f01c3903f1d2930
|
[
"MIT"
] | 2
|
2016-10-19T18:54:25.000Z
|
2017-01-23T20:52:56.000Z
|
lib/W3/Plugin/NewRelicAdmin.php
|
finaldream/w3-total-cache
|
0836d8151a9d421ce1cc91ef1f01c3903f1d2930
|
[
"MIT"
] | 11
|
2016-02-04T14:09:07.000Z
|
2019-01-08T11:10:04.000Z
|
<?php
/**
* W3 NewRelicAdmin plugin
*/
if (!defined('W3TC')) {
die();
}
w3_require_once(W3TC_LIB_W3_DIR . '/Plugin.php');
w3_require_once(W3TC_INC_DIR . '/functions/rule.php');
/**
* Class W3_Plugin_NewRelicAdmin
*/
class W3_Plugin_NewRelicAdmin extends W3_Plugin {
/**
* Called on plugin instantiation
*/
function run() {
add_filter('w3tc_compatibility_test', array($this, 'verify_compatibility'));
if (is_admin()) {
add_action('wp_ajax_admin_w3tc_verify_newrelic_api_key', array($this, 'verify_newrelic_api_key'));
add_action('wp_ajax_w3tc_verify_newrelic_api_key', array($this, 'verify_newrelic_api_key'));
add_action('wp_ajax_admin_w3tc_get_newrelic_applications', array($this, 'get_newrelic_applications'));
add_action('wp_ajax_w3tc_get_newrelic_applications', array($this, 'get_newrelic_applications'));
$new_relic_enabled = $this->_config->get_boolean('newrelic.enabled');
if ($new_relic_enabled) {
global $pagenow;
w3_require_once( W3TC_LIB_W3_DIR . '/Request.php');
$page = W3_Request::get_string('page');
if ($pagenow == 'plugins.php' || strpos($page, 'w3tc_') !== false) {
if ((!w3_is_multisite()) || (w3_is_multisite() && !$this->_config->get_boolean('common.force_master'))) {
add_action('admin_notices', array($this, 'admin_notices'));
} else {
add_action('network_admin_notices', array($this, 'admin_notices'));
}
}
}
}
}
function admin_notices() {
/**
* @var $nerser W3_NewRelicService
*/
$nerser = w3_instance('W3_NewRelicService');
$new_relic_configured = $this->_config->get_string('newrelic.account_id') && $this->_config->get_string('newrelic.api_key');
if (w3_get_blog_id() == 0 || !$this->_config->get_boolean('common.force_master')) {
$new_relic_configured = $new_relic_configured && $this->_config->get_string('newrelic.application_id');
}
$verify_running_result = $nerser->verify_running();
$not_running = is_array($verify_running_result);
if ($not_running) {
$message = '<p>' . __('New Relic is not running correctly. The plugin has detected the following issues:', 'w3-total-cache') . "</p>\n";
$message .= "<ul class=\"w3-bullet-list\">\n";
foreach($verify_running_result as $cause) {
$message .= "<li>$cause</li>";
}
$message .= "</ul>\n";
$message .= "<p>" . sprintf(__('Please review the <a href="%s">settings</a>.', 'w3-total-cache'), network_admin_url('admin.php?page=w3tc_general#monitoring')) . "</p>";
w3_require_once(W3TC_INC_FUNCTIONS_DIR . '/ui.php');
w3_e_error_box($message);
}
}
/**
* Returns a list of the verification status of the the new relic requirements. To be used on the compatibility page
* @param $verified_list
* @return array
*/
function verify_compatibility($verified_list) {
$nerser = w3_instance('W3_NewRelicService');
$nr_verified = $nerser->verify_compatibility();
$verified_list[] = '<strong>New Relic</strong>';
foreach($nr_verified as $criteria => $result)
$verified_list[] = sprintf("$criteria: %s", $result);
return $verified_list;
}
/**
* Retrieve the new relic account id. Used in AJAX requests.
* Requires request param api_key with the API key
*/
function verify_newrelic_api_key() {
$api_key = W3_Request::get_string('api_key');
/**
* @var $nerser W3_NewRelicService
*/
$nerser = w3_instance('W3_NewRelicService');
try {
$account_id = $nerser->get_account_id($api_key);
if ($account_id) {
$this->_config->set('newrelic.account_id', $account_id);
$this->_config->save();
echo $account_id;
}
}catch (Exception $ex) {}
die();
}
/**
* Retrieves applications. Used in AJAX requests.
* Requires request param api_key with the API key and account_id with the Account id.
*/
function get_newrelic_applications() {
w3_require_once(W3TC_LIB_W3_DIR . '/NewRelicService.php');
$api_key = W3_Request::get_string('api_key');
$account_id = W3_Request::get_string('account_id');
if ($api_key == '0') {
$config_master = new W3_Config(true);
$api_key = $config_master->get_string('newrelic.api_key');
}
$nerser = new W3_NewRelicService($api_key);
$newrelic_applications = array();
try {
if(empty($account_id) || $account_id == '')
$account_id = $nerser->get_account_id();
$newrelic_applications = $nerser->get_applications($account_id);
} catch (Exception $ex) {}
echo json_encode($newrelic_applications);
die();
}
}
| 41
| 180
| 0.591173
|
95a02a99a6998a1d6f4aaba8a0727ef308e2f479
| 1,370
|
swift
|
Swift
|
CustomLoader/CustomLoader/CustomLoader.swift
|
pkc456/CustomLoader
|
50280bd2402bf8b28965fbb2ef5f781d00150eca
|
[
"MIT"
] | null | null | null |
CustomLoader/CustomLoader/CustomLoader.swift
|
pkc456/CustomLoader
|
50280bd2402bf8b28965fbb2ef5f781d00150eca
|
[
"MIT"
] | null | null | null |
CustomLoader/CustomLoader/CustomLoader.swift
|
pkc456/CustomLoader
|
50280bd2402bf8b28965fbb2ef5f781d00150eca
|
[
"MIT"
] | null | null | null |
//
// CustomLoader.swift
// CustomLoader
//
// Created by pradeep.chaudhary on 8/17/17.
// Copyright © 2017 pradeep.chaudhary. All rights reserved.
//
import UIKit
class CustomLoader: UIView {
@IBOutlet weak var animatedImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
animatedImageView.animationImages = [
// UIImage(named:"7")!,
UIImage(named:"1")!,
UIImage(named:"2")!,
UIImage(named:"3")!,
UIImage(named:"4")!,
UIImage(named:"5")!,
UIImage(named:"6")!,
UIImage(named:"7")!,
UIImage(named:"8")!,
UIImage(named:"9")!,
UIImage(named:"10")!,
UIImage(named:"11")!,
UIImage(named:"12")!,
UIImage(named:"13")!,
UIImage(named:"14")!,
UIImage(named:"15")!,
UIImage(named:"16")!,
UIImage(named:"17")!,
UIImage(named:"18")!,
]
animatedImageView.animationDuration = 1.0
animatedImageView.startAnimating()
}
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
}
| 25.849057
| 78
| 0.527007
|
abfd965eb29ef5931e3adeb23f0bf304478bedb1
| 44
|
asm
|
Assembly
|
Tests/yasm-regression/bittest.asm
|
13xforever/x86-assembly-textmate-bundle
|
f1bb62f77b776d87d0fd85b0276d4237ff72c43c
|
[
"MIT"
] | 69
|
2015-04-16T18:01:22.000Z
|
2022-02-15T07:54:26.000Z
|
Tests/yasm-regression/bittest.asm
|
javiercbk/x86-assembly-textmate-bundle
|
62d700e0196f62ef4353a9b95c2e64beb0a6afda
|
[
"MIT"
] | 17
|
2016-09-20T08:49:09.000Z
|
2021-02-19T15:01:04.000Z
|
Tests/yasm-regression/bittest.asm
|
javiercbk/x86-assembly-textmate-bundle
|
62d700e0196f62ef4353a9b95c2e64beb0a6afda
|
[
"MIT"
] | 19
|
2016-05-31T07:11:14.000Z
|
2021-07-19T10:17:12.000Z
|
[bits 16]
btr eax, 4 ; out: 66 0f ba f0 04
| 11
| 32
| 0.590909
|
dd7865ac5490fbd7ead878aa6160a486dedaa311
| 4,503
|
java
|
Java
|
services/service-app/src/test/java/com/thinkbiganalytics/integration/feed/FeedLoadTest.java
|
peter-ls/kylo
|
02d2a753aadb15234209e3ceacbd2a3720cb9914
|
[
"Apache-2.0"
] | 1,016
|
2017-03-03T12:05:19.000Z
|
2022-03-26T20:47:38.000Z
|
services/service-app/src/test/java/com/thinkbiganalytics/integration/feed/FeedLoadTest.java
|
Mpopoma/kylo
|
02d2a753aadb15234209e3ceacbd2a3720cb9914
|
[
"Apache-2.0"
] | 86
|
2017-03-03T23:22:32.000Z
|
2022-03-17T22:24:39.000Z
|
services/service-app/src/test/java/com/thinkbiganalytics/integration/feed/FeedLoadTest.java
|
Mpopoma/kylo
|
02d2a753aadb15234209e3ceacbd2a3720cb9914
|
[
"Apache-2.0"
] | 632
|
2017-03-02T04:37:05.000Z
|
2022-03-22T03:23:39.000Z
|
package com.thinkbiganalytics.integration.feed;
/*-
* #%L
* kylo-feed-manager-controller
* %%
* Copyright (C) 2017 ThinkBig Analytics
* %%
* 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.
* #L%
*/
import com.thinkbiganalytics.feedmgr.rest.model.FeedCategory;
import com.thinkbiganalytics.feedmgr.rest.model.FeedMetadata;
import com.thinkbiganalytics.feedmgr.service.template.importing.model.ImportTemplate;
import org.junit.Ignore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Test to load multiple feeds in a loop
*/
@Ignore
public abstract class FeedLoadTest extends FeedITBase {
private static final Logger LOG = LoggerFactory.getLogger(FeedLoadTest.class);
/**
* Load the Data Ingest template
* @throws Exception
*/
//@Test
//@Ignore
public void loadTestDataIngest() throws Exception {
// the num of categories to use
int categories = 1;
//the num of feeds to create in each category
int maxFeedsInCategory = 20;
//the category id to start. categories are created as cat_#
int startingCategoryId = 62;
prepare();
String templatePath = sampleTemplatesPath + DATA_INGEST_ZIP;
loadTest(templatePath, "feed", categories, maxFeedsInCategory, startingCategoryId);
}
/**
* Load the simple template with just 3 processors
* @throws Exception
*/
// @Test
// @Ignore
public void loadSimpleFeed() throws Exception {
// the num of categories to use
int categories = 50;
//the num of feeds to create in each category. feeds are labled cat_#_feed_#. it start creating feeds after the last feed in the category
int maxFeedsInCategory = 20;
//the category id to start. categories are created as cat_#
int startingCategoryId = 3;
prepare();
String templatePath = getClass().getClassLoader().getResource("com/thinkbiganalytics/integration/simple_template.template.zip").toURI().getPath();
loadTest(templatePath, "simple_feed", categories, maxFeedsInCategory, startingCategoryId);
}
/**
* Bulk load a template into NiFi and Kylo
* categories are named 'category_#
* feeds are named cat_#_feedName_#
*
* @param templatePath the template to use
* @param feedName the name of the feed
* @param categories the number of categories to use/create
* @param feedsInCategory the number of feeds to create in each category
* @param startingCategoryId the category number to use for the first category
* @throws Exception
*/
private void loadTest(String templatePath, String feedName, int categories, int feedsInCategory, int startingCategoryId) throws Exception {
ImportTemplate ingestTemplate = importTemplate(templatePath);
for (int i = startingCategoryId; i < (startingCategoryId + categories); i++) {
//create new category
String categoryName = "category_" + i;
FeedCategory category = getorCreateCategoryByName(categoryName);
Integer maxFeedId = category.getRelatedFeeds();
maxFeedId += 1;
for (int j = maxFeedId; j < (feedsInCategory + maxFeedId); j++) {
try {
String updateFeedName = "cat_" + i + "_" + feedName + "_" + j;
FeedMetadata feed = getCreateFeedRequest(category, ingestTemplate, updateFeedName);
long start = System.currentTimeMillis();
FeedMetadata response = createFeed(feed).getFeedMetadata();
LOG.info("Time to save: {} was: {} ms ", updateFeedName, (System.currentTimeMillis() - start));
} catch (Exception e) {
}
}
}
}
@Override
public void startClean() {
int i = 0;
// super.startClean();
}
@Override
public void cleanup() {
//noop
int i = 0;
}
}
| 34.906977
| 154
| 0.655785
|
25005b0300aa1109c68f128bc6d5c3979e8577e7
| 1,074
|
dart
|
Dart
|
example/lib/main.dart
|
liubaishui/FlutterBleLib
|
b8e5afaae3b79893584896cb03f88174905c2b7d
|
[
"Apache-2.0"
] | 448
|
2018-02-15T12:11:29.000Z
|
2021-06-17T21:06:45.000Z
|
example/lib/main.dart
|
liubaishui/FlutterBleLib
|
b8e5afaae3b79893584896cb03f88174905c2b7d
|
[
"Apache-2.0"
] | 403
|
2018-03-15T15:02:59.000Z
|
2021-06-16T13:16:11.000Z
|
example/lib/main.dart
|
liubaishui/FlutterBleLib
|
b8e5afaae3b79893584896cb03f88174905c2b7d
|
[
"Apache-2.0"
] | 143
|
2018-03-21T06:57:31.000Z
|
2021-06-15T10:29:35.000Z
|
import 'package:fimber/fimber.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ble_lib_example/devices_list/devices_bloc_provider.dart';
import 'package:flutter_ble_lib_example/devices_list/devices_list_view.dart';
import 'device_details/device_detail_view.dart';
import 'device_details/devices_details_bloc_provider.dart';
void main() {
Fimber.plantTree(DebugTree());
runApp(MyApp());
}
final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'FlutterBleLib example',
theme: new ThemeData(
primaryColor: new Color(0xFF0A3D91),
accentColor: new Color(0xFFCC0000),
),
initialRoute: "/",
routes: <String, WidgetBuilder>{
"/": (context) => DevicesBlocProvider(child: DevicesListScreen()),
"/details": (context) =>
DeviceDetailsBlocProvider(child: DeviceDetailsView()),
},
navigatorObservers: [routeObserver],
);
}
}
| 30.685714
| 81
| 0.715084
|
58cfc28453a12b2368cb658cceb41cffe166b449
| 1,709
|
php
|
PHP
|
src/KvkClientFactory.php
|
app-vise/kvk-api
|
837b2a95a180370c26bc6a6637e087119cff617e
|
[
"MIT"
] | 1
|
2022-03-24T13:04:29.000Z
|
2022-03-24T13:04:29.000Z
|
src/KvkClientFactory.php
|
app-vise/kvk-api
|
837b2a95a180370c26bc6a6637e087119cff617e
|
[
"MIT"
] | null | null | null |
src/KvkClientFactory.php
|
app-vise/kvk-api
|
837b2a95a180370c26bc6a6637e087119cff617e
|
[
"MIT"
] | null | null | null |
<?php
declare(strict_types=1);
namespace Appvise\KvkApi;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Middleware;
use GuzzleHttp\HandlerStack;
use Psr\Http\Message\RequestInterface;
use Appvise\KvkApi\Http\ClientInterface;
use Appvise\KvkApi\Http\GuzzleClient;
class KvkClientFactory
{
private const PRODUCTION_URL = 'https://api.kvk.nl/';
private const DEVELOPMENT_URL = 'https://developers.kvk.nl/test/';
public static function create(string $userKey, string $stage = 'test', string $rootCertificate = null): KvkClientInterface
{
if ($rootCertificate === null) {
trigger_error('Root certificate is required. Please configure your system or supply one here.', E_USER_DEPRECATED);
}
switch ($stage) {
case 'production':
return new KvkClient(self::createHttpClient($userKey, $rootCertificate), self::PRODUCTION_URL);
break;
case 'test':
default:
return new KvkClient(self::createHttpClient($userKey), self::DEVELOPMENT_URL);
break;
}
}
private static function createHttpClient(string $userKey, ?string $rootCertificate = null): ClientInterface
{
$stack = HandlerStack::create();
$stack->unshift(Middleware::mapRequest(function (RequestInterface $request) use ($userKey) {
return $request->withUri(Uri::withQueryValue($request->getUri(), 'user_key', $userKey));
}));
$client = new Client([
'debug' => false,
'verify' => $rootCertificate ?? false,
'handler' => $stack,
]);
return new GuzzleClient($client);
}
}
| 31.072727
| 127
| 0.637215
|
cd8b3330b8f37de336bcfd65c6e727ccd8fd87fe
| 2,383
|
cs
|
C#
|
Assets/Scripts/PhysicsObject.cs
|
IGME-202-17S2/lecture-code-leader
|
4592dcd1cea587e33fa139d68a61cba102d24e22
|
[
"MIT"
] | null | null | null |
Assets/Scripts/PhysicsObject.cs
|
IGME-202-17S2/lecture-code-leader
|
4592dcd1cea587e33fa139d68a61cba102d24e22
|
[
"MIT"
] | null | null | null |
Assets/Scripts/PhysicsObject.cs
|
IGME-202-17S2/lecture-code-leader
|
4592dcd1cea587e33fa139d68a61cba102d24e22
|
[
"MIT"
] | null | null | null |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* PhsyicsObject
* This component tracks position and movement information for a GameObject
* It knows how to ApplyForce (but some other script will call that)
* It runs its own BounceCheck method (to keep the object in-bounds)
* Movement happens in LateUpdate, so that some other script can call
* ApplyForce in its Update, and we can be sure all Forces have been
* applied before moving the PhysicsObject.
*/
public class PhysicsObject : MonoBehaviour {
Vector3 velocity;
Vector3 lastGoodVelocity;
public Vector3 followPos;
public Vector3 toLeader;
public Vector3 target;
// You can tweak these in the inspector.
public float mass = 1f; // higher mass - more force needed to get moving
public float radius = 0.25f;
public float speedLimit = 0.125f;
public float slowRadius = 0.5f;
void Start () {
// no forces to start off
velocity = Vector3.zero;
lastGoodVelocity = Vector3.up;
}
void ClampVelocity() {
float mag = velocity.magnitude;
if (mag > speedLimit) {
float scale = speedLimit / mag;
velocity *= scale;
}
}
public void Arrive() {
// find the direction we want to travel
Vector3 desired = target - transform.position;
// if I'm far enough to not need to slow down
if (desired.magnitude > slowRadius) {
// full steam ahead!
velocity = desired.normalized * speedLimit;
} else {
// set velocity such that it approaches zero as we get closer to our target
float percentToTarget = desired.magnitude / slowRadius;
velocity = desired.normalized * (percentToTarget * speedLimit);
}
}
void LateUpdate () {
// obey the speed limit
ClampVelocity ();
// update position by velocity (respecting velocity as units per second)
transform.position += velocity * Time.deltaTime;
// set followPos based on a velocity that was actually moving
this.followPos = transform.position - (lastGoodVelocity.normalized * 0.75f);
// compare to
// this.followPos = transform.position - (velocity.normalized * 0.75f);
// update our lastGoodVelocity if actually moving
if (velocity.sqrMagnitude > 0.125f) {
lastGoodVelocity = velocity;
}
}
void OnDrawGizmos() {
Gizmos.color = Color.green;
Gizmos.DrawWireSphere (transform.position, radius);
Gizmos.DrawLine (transform.position, this.followPos);
}
}
| 28.710843
| 78
| 0.722199
|
305cf5bc099ce44411fcfa2f11fbf8dcbb6b19bf
| 1,006
|
swift
|
Swift
|
Example/swiftExample/swiftddp/AddViewController.swift
|
hiddenswitch/ObjectiveDDP
|
3352368a1ba830fc9f931a2da7d21ac42091b40e
|
[
"MIT"
] | 1
|
2015-04-01T05:40:25.000Z
|
2015-04-01T05:40:25.000Z
|
Example/swiftExample/swiftddp/AddViewController.swift
|
hiddenswitch/ObjectiveDDP
|
3352368a1ba830fc9f931a2da7d21ac42091b40e
|
[
"MIT"
] | null | null | null |
Example/swiftExample/swiftddp/AddViewController.swift
|
hiddenswitch/ObjectiveDDP
|
3352368a1ba830fc9f931a2da7d21ac42091b40e
|
[
"MIT"
] | null | null | null |
//
// AddViewController.swift
// swiftddp
//
// Created by Michael Arthur on 13/08/14.
// Copyright (c) 2014. All rights reserved.
//
import Foundation
import UIKit
class AddViewController : UIViewController {
@IBOutlet weak var messageTextView: UITextView!
var delegate:AddViewControllerDelegate!
required init(coder aDecoder: NSCoder!) {
fatalError("NSCoding not supported")
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
if (self != nil) {
}
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
self.view.endEditing(true)
}
@IBAction func didTouchAddButton(sender: AnyObject!) {
self.delegate.didAddThing(self.messageTextView.text)
}
}
protocol AddViewControllerDelegate {
func didAddThing(message:NSString!)
}
| 21.404255
| 84
| 0.644135
|
4376d8fb705e984c4f3357868816304a765dab5b
| 1,045
|
ts
|
TypeScript
|
projects/netgrif-components-core/src/lib/task-content/model/task-event-notification.ts
|
netgrif/components
|
4a11b424ea2b88532fa70d86005f26f84884a019
|
[
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 1
|
2022-02-16T16:58:13.000Z
|
2022-02-16T16:58:13.000Z
|
projects/netgrif-components-core/src/lib/task-content/model/task-event-notification.ts
|
netgrif/components
|
4a11b424ea2b88532fa70d86005f26f84884a019
|
[
"Apache-2.0",
"CC0-1.0",
"MIT"
] | 29
|
2022-02-12T20:54:38.000Z
|
2022-03-31T21:23:25.000Z
|
projects/netgrif-components-core/src/lib/task-content/model/task-event-notification.ts
|
netgrif/components
|
4a11b424ea2b88532fa70d86005f26f84884a019
|
[
"Apache-2.0",
"CC0-1.0",
"MIT"
] | null | null | null |
import {TaskEvent} from './task-event';
import {Task} from '../../resources/public-api';
/**
* Holds the information about an event that occurred to some {@link Task} resource.
*
* Task events correspond more or less 1-to-1 to backend calls and their results.
*/
export interface TaskEventNotification {
/**
* StringId of the affected {@link Task}
*/
taskId: string;
/**
* StringId of the Transition
*/
transitionId: string;
/**
* The event that occurred
*/
event: TaskEvent;
/**
* Success state of the event
*/
success: boolean;
}
/**
* @param task affected Task object
* @param event the reported Task event
* @param success success state of the reported event
* @returns the notification informing about the event
*/
export function createTaskEventNotification(task: Task, event: TaskEvent, success: boolean): TaskEventNotification {
return {
taskId: task.stringId,
transitionId: task.transitionId,
event,
success
};
}
| 24.880952
| 116
| 0.651675
|