hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequencelengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequencelengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequencelengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1bf32b197365408c8c29824b8698e507ddfe93b6 | 792 | dart | Dart | lib/src/key_widget.dart | de-men/piano_widget | 290e1f039f9a88b53cf94b9585005c080f5b3aff | [
"BSD-3-Clause"
] | 1 | 2022-01-03T11:11:18.000Z | 2022-01-03T11:11:18.000Z | lib/src/key_widget.dart | de-men/piano_widget | 290e1f039f9a88b53cf94b9585005c080f5b3aff | [
"BSD-3-Clause"
] | null | null | null | lib/src/key_widget.dart | de-men/piano_widget | 290e1f039f9a88b53cf94b9585005c080f5b3aff | [
"BSD-3-Clause"
] | null | null | null | import 'package:flutter/material.dart';
class KeyWidget extends StatelessWidget {
final double width;
final double height;
final MapEntry<String, int> pitch;
const KeyWidget({
required this.width,
required this.height,
required this.pitch,
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: width,
height: height,
decoration: BoxDecoration(
color: (pitch.key.contains('#') ? Colors.black : Colors.white),
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(2),
bottomRight: Radius.circular(2),
),
),
);
}
}
typedef KeyBuilder = Widget Function(
double width,
double height,
MapEntry<String, int> pitch,
);
| 22 | 71 | 0.646465 |
59b8179eeade35e18323d44b93de9172eb5c66e3 | 3,045 | ps1 | PowerShell | tests/Update-AgreementVisibility.tests.ps1 | telstrapurple/PwshAdobeSign | 03a6ac10c7e7a4cf6de3a29d2ac02495afc4ee06 | [
"MIT"
] | null | null | null | tests/Update-AgreementVisibility.tests.ps1 | telstrapurple/PwshAdobeSign | 03a6ac10c7e7a4cf6de3a29d2ac02495afc4ee06 | [
"MIT"
] | null | null | null | tests/Update-AgreementVisibility.tests.ps1 | telstrapurple/PwshAdobeSign | 03a6ac10c7e7a4cf6de3a29d2ac02495afc4ee06 | [
"MIT"
] | 1 | 2021-12-14T03:10:07.000Z | 2021-12-14T03:10:07.000Z | [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
Param()
$IsInteractive = [Environment]::GetCommandLineArgs() -join ' ' -notmatch '-NonI'
Describe 'Update-AgreementVisibility' {
BeforeAll {
. $PSCommandPath.Replace('.tests.ps1', '.ps1').Replace('tests', 'functions')
$validId = 'hXy4R2NaYnvTaftrEhaD4ZAJrxh3YM8kuf8CupEouFoK'
function Invoke-Method ($Method = 'Get', $Path, $Body) { }
}
It 'Requires an Id to be supplied' -Skip:$IsInteractive {
{ Update-AgreementVisibility -Visibility 'Hide' } | Should -Throw
}
It 'Requires a Visibility to be supplied' -Skip:$IsInteractive {
{ Update-AgreementVisibility -Id $validId } | Should -Throw
}
It 'Requires Id to not be $null' {
{ Update-AgreementVisibility -Id $null -Visibility 'Hide' } | Should -Throw
}
It 'Requires Visibility to not be $null' {
{ Update-AgreementVisibility -Id $validId -Visibility $null } | Should -Throw
}
It "Requires Visibility to be 'Hide' or 'Show'" {
Mock Invoke-Method { }
{ Update-AgreementVisibility -Id $validId -Visibility 'Fox' } | Should -Throw
Update-AgreementVisibility -Id $validId -Visibility 'Hide'
Update-AgreementVisibility -Id $validId -Visibility 'Show'
Should -Invoke Invoke-Method -Exactly 2
}
It 'Handles a Id up to 512 characters' {
Mock Invoke-Method { }
Update-AgreementVisibility -Visibility 'Hide' -Id 'WvbdOsJLKEBlga438kZK/N8eJ+qPkmrnXpfq8MNdbae45SjyzMFsTQAspOxgF7eMUj6s7DEKIm728gNU+sv7FWXa0C73DOmJiF/GJTD7QvGr7N74z0H6OYe6qr6gwEBj697buszCZIZYMXC+ZIAJ03kuNjGhfU/rn+eQwphLyMWKCYNRcz1JWVnp/XOctqugaqqjj1GGhtjM4dV+EAorrsiUMmIhbK/XtIA9S5fZJbWL6C1+NEu3w6I/MoqYdk4ZeW5enFk9ugXO0RYfEn5yeHQRTEeB9UppeKKlT9MCXNDxcPQdLfTaZlEypmKklrYNB4ah9po/7k+PaYzgXN3tdponXKx/EWwT+DGnUEBDN04vkjDo7giNf7Yfi+gQgbdWNGcB5i88fNKjbnA/i83membnrKnXRmF7T9MnbqLG1OL34P0uTzxeEFdj1ZQ8IB/PnB8iVZ3+5t+zLthyvFv+aXJikmDA7XlDwsCFLtLhVGsLziLVNSV4B/GOdb2ME8c6'
Should -Invoke Invoke-Method -Exactly 1
}
It 'Hits the correct endpoint' {
Mock Invoke-Method { } -ParameterFilter { $Path -match '/agreements/[^/]+/me/visibility$' }
Update-AgreementVisibility -Id $validId -Visibility 'Hide'
Should -Invoke Invoke-Method -Exactly 1
}
It 'Uses the correct method' {
Mock Invoke-Method { } -ParameterFilter { $Method -eq 'Put' }
Update-AgreementVisibility -Id $validId -Visibility 'Hide'
Should -Invoke Invoke-Method -Exactly 1
}
It 'Passes on the Id' {
Mock Invoke-Method { } -ParameterFilter { $Path -match "/$validId/" }
Update-AgreementVisibility -Id $validId -Visibility 'Hide'
Should -Invoke Invoke-Method -Exactly 1
}
It 'Passes on the Visibility' {
Mock Invoke-Method { } -ParameterFilter { $Body.visibility -eq 'Hide' }
Update-AgreementVisibility -Id $validId -Visibility 'Hide'
Should -Invoke Invoke-Method -Exactly 1
}
}
| 43.5 | 572 | 0.700821 |
529ff30e7504d9d5c7e5662f6469654b421a58a3 | 523 | swift | Swift | Animate Table/Animate Table/DetailItemCell.swift | tandinhlee/iOS-Tutorials | a9bc217917264297b0ce6f0191e273a627554935 | [
"MIT"
] | null | null | null | Animate Table/Animate Table/DetailItemCell.swift | tandinhlee/iOS-Tutorials | a9bc217917264297b0ce6f0191e273a627554935 | [
"MIT"
] | null | null | null | Animate Table/Animate Table/DetailItemCell.swift | tandinhlee/iOS-Tutorials | a9bc217917264297b0ce6f0191e273a627554935 | [
"MIT"
] | null | null | null | //
// DetailItemCell.swift
// Animate Table
//
// Created by Dinh Le on 13/03/16.
// Copyright © 2016 Dinh Le. All rights reserved.
//
import UIKit
class DetailItemCell: UITableViewCell {
@IBOutlet weak var priceLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| 20.92 | 63 | 0.665392 |
ff2b4b12ae677ccbc8b5de94a62fa566d119d307 | 2,936 | py | Python | setup.py | sparkur/python-sasl3 | 19f930e312a69fcaeb90bc28aeb9e4b1e5e7f900 | [
"Apache-2.0"
] | 1 | 2019-11-29T20:13:14.000Z | 2019-11-29T20:13:14.000Z | setup.py | sparkur/python-sasl | 19f930e312a69fcaeb90bc28aeb9e4b1e5e7f900 | [
"Apache-2.0"
] | null | null | null | setup.py | sparkur/python-sasl | 19f930e312a69fcaeb90bc28aeb9e4b1e5e7f900 | [
"Apache-2.0"
] | 2 | 2020-09-09T13:04:12.000Z | 2021-05-10T13:39:43.000Z | #
# 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.
from distutils.sysconfig import get_config_var
from distutils.version import LooseVersion
import os
import platform
from setuptools import setup, Extension
import sys
version = '0.2.11'
# From https://github.com/pandas-dev/pandas/pull/24274:
# For mac, ensure extensions are built for macos 10.9 when compiling on a
# 10.9 system or above, overriding distuitls behaviour which is to target
# the version that python was built for. This may be overridden by setting
# MACOSX_DEPLOYMENT_TARGET before calling setup.py
if sys.platform == 'darwin':
if 'MACOSX_DEPLOYMENT_TARGET' not in os.environ:
current_system = LooseVersion(platform.mac_ver()[0])
python_target = LooseVersion(
get_config_var('MACOSX_DEPLOYMENT_TARGET'))
if python_target < '10.9' and current_system >= '10.9':
os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.9'
sasl_module = Extension('sasl.saslwrapper',
sources=['sasl/saslwrapper.cpp'],
include_dirs=["sasl"],
libraries=["sasl2"],
language="c++")
try:
with open("README.md", "r") as fh:
long_description = fh.read()
except FileNotFoundError:
long_description = ''
setup(name='sasl3',
version=version,
url="http://github.com/sparkur/python-sasl3",
maintainer="Ruslan Dautkhanov",
maintainer_email="[email protected]",
description="""Cyrus-SASL bindings for Python""",
long_description=long_description,
long_description_content_type="text/markdown",
classifiers=[
'Programming Language :: Python :: 3',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
],
download_url="https://github.com/sparkur/python-sasl3/archive/v{}.tar.gz".format(version),
packages=['sasl'],
install_requires=['six'],
ext_modules=[sasl_module],
include_package_data=True
)
| 38.12987 | 96 | 0.669959 |
aa30ee34086ced3bab6540a06ff680a3c982682c | 9,852 | rb | Ruby | spec/functional/licensing_spec.rb | strangelittlemonkey/omnibus | a36e70caedceadfcf0d85e2adef44ba0218a60a6 | [
"Apache-2.0"
] | 1 | 2016-05-23T23:28:25.000Z | 2016-05-23T23:28:25.000Z | spec/functional/licensing_spec.rb | strangelittlemonkey/omnibus | a36e70caedceadfcf0d85e2adef44ba0218a60a6 | [
"Apache-2.0"
] | null | null | null | spec/functional/licensing_spec.rb | strangelittlemonkey/omnibus | a36e70caedceadfcf0d85e2adef44ba0218a60a6 | [
"Apache-2.0"
] | null | null | null | require "spec_helper"
module Omnibus
describe Licensing do
let(:license) { nil }
let(:license_file_path) { nil }
let(:license_file) { nil }
let(:zlib_version_override) { nil }
let(:install_dir) { File.join(tmp_path, "install_dir") }
let(:software_project_dir) { File.join(tmp_path, "software_project_dir") }
let(:expected_project_license_path) { "LICENSE" }
let(:expected_project_license) { "Unspecified" }
let(:expected_project_license_content) { "" }
before do
FileUtils.mkdir_p(install_dir)
FileUtils.mkdir_p(software_project_dir)
allow_any_instance_of(Software).to receive(:project_dir).and_return(software_project_dir)
%w{LICENSE NOTICE APACHE}.each do |file|
File.open(File.join(software_project_dir, file), "w+") do |f|
f.puts "This file is #{file}."
end
end
end
shared_examples "correctly created licenses" do
it "creates the main license file for the project correctly" do
create_licenses
project_license = File.join(install_dir, expected_project_license_path)
expect(File.exist?(project_license)).to be(true)
project_license = File.read(project_license)
expect(project_license).to match /test-project 1.2.3 license: "#{expected_project_license}"/
expect(project_license).to match /#{expected_project_license_content}/
expect(project_license).to match /This product bundles private_code 1.7.2,\nwhich is available under a "Unspecified"/
expect(project_license).to match /This product bundles snoopy 1.0.0,\nwhich is available under a "GPL v2"/
expect(project_license).not_to match /preparation/
expect(project_license).to match /LICENSES\/snoopy-artistic.html/
expect(project_license).to match /LICENSES\/snoopy-NOTICE/
if zlib_version_override
expect(project_license).to match /This product bundles zlib 1.8.0,\nwhich is available under a "Apache-2.0"/
expect(project_license).to match /LICENSES\/zlib-APACHE/
else
expect(project_license).to match /This product bundles zlib 1.7.2,\nwhich is available under a "Zlib"/
expect(project_license).to match /LICENSES\/zlib-LICENSE/
end
end
it "creates the license files of software components correctly" do
create_licenses
license_dir = File.join(install_dir, "LICENSES")
expect(Dir.glob("#{license_dir}/**/*").length).to be(3)
license_names = [ "snoopy-NOTICE" ]
if zlib_version_override
license_names << "zlib-APACHE"
else
license_names << "zlib-LICENSE"
end
license_names.each do |software_license|
license_path = File.join(license_dir, software_license)
expect(File.exist?(license_path)).to be(true)
expect(File.world_readable?(license_path)).to be_truthy
expect(File.read(license_path)).to match /#{software_license.split("-").last}/
end
remote_license_file = File.join(license_dir, "snoopy-artistic.html")
remote_license_file_contents = File.read(remote_license_file)
expect(File.exist?(remote_license_file)).to be(true)
expect(remote_license_file_contents).to match /The "Artistic License" - dev.perl.org/
end
it "warns for non-standard software license info" do
output = capture_logging { create_licenses }
expect(output).to include("Software 'snoopy' uses license 'GPL v2' which is not one of the standard licenses")
end
it "warns for missing software license info" do
output = capture_logging { create_licenses }
expect(output).to include("Software 'private_code' does not contain licensing information.")
end
end
let(:project) do
Project.new.tap do |project|
project.name("test-project")
project.install_dir(install_dir)
project.license(license) unless license.nil?
project.license_file_path(license_file_path) unless license_file_path.nil?
project.license_file(license_file) unless license_file.nil?
project.build_version("1.2.3")
if zlib_version_override
project.override :zlib, version: zlib_version_override
end
end
end
let(:private_code) do
Software.new(project, "private_code.rb").evaluate do
name "private_code"
default_version "1.7.2"
end
end
let(:zlib) do
Software.new(project, "zlib.rb").evaluate do
name "zlib"
default_version "1.7.2"
license "Zlib"
license_file "LICENSE"
version "1.8.0" do
license "Apache-2.0"
license_file "APACHE"
end
end
end
let(:snoopy) do
Software.new(project, "snoopy.rb").evaluate do
name "snoopy"
default_version "1.0.0"
license "GPL v2"
license_file "http://dev.perl.org/licenses/artistic.html"
license_file "NOTICE"
end
end
let(:preparation) do
Software.new(project, "preparation.rb").evaluate do
name "preparation"
default_version "1.0.0"
license :project_license
end
end
let(:software_with_warnings) { nil }
def create_licenses
project.library.component_added(preparation)
project.library.component_added(snoopy)
project.library.component_added(zlib)
project.library.component_added(private_code)
project.library.component_added(software_with_warnings) if software_with_warnings
Licensing.create!(project)
end
describe "without license definitions in the project" do
it_behaves_like "correctly created licenses"
it "warns for missing project license" do
output = capture_logging { create_licenses }
expect(output).to include("Project 'test-project' does not contain licensing information.")
end
end
describe "with license definitions in the project" do
let(:license) { "Custom Chef" }
let(:license_file_path) { "CHEF.LICENSE" }
let(:license_file) { "CUSTOM_CHEF" }
let(:expected_project_license_path) { license_file_path }
let(:expected_project_license) { license }
let(:expected_project_license_content) { "Chef Custom License" }
before do
File.open(File.join(Config.project_root, license_file), "w+") do |f|
f.puts "Chef Custom License is awesome."
end
end
after do
FileUtils.rm_rf(license_file)
end
it_behaves_like "correctly created licenses"
it "warns for non-standard project license" do
output = capture_logging { create_licenses }
expect(output).to include("Project 'test-project' is using 'Custom Chef' which is not one of the standard licenses")
end
context "with a version override" do
let(:zlib_version_override) { "1.8.0" }
it_behaves_like "correctly created licenses"
end
end
describe "with a local license file that does not exist" do
let(:software_with_warnings) do
Software.new(project, "problematic.rb").evaluate do
name "problematic"
default_version "0.10.2"
license_file "NOT_EXISTS"
end
end
it_behaves_like "correctly created licenses"
it "should log a warning for the missing file" do
output = capture_logging { create_licenses }
expect(output).to match /License file (.*)NOT_EXISTS' does not exist for software 'problematic'./
end
end
describe "with a remote license file that does not exist" do
before do
Omnibus::Config.fetcher_retries(1)
end
let(:software_with_warnings) do
Software.new(project, "problematic.rb").evaluate do
name "problematic"
default_version "0.10.2"
license_file "https://downloads.chef.io/LICENSE"
end
end
it_behaves_like "correctly created licenses"
it "should log a warning for the missing file" do
output = capture_logging { create_licenses }
expect(output).to match(/Retrying failed download/)
expect(output).to match(/Can not download license file 'https:\/\/downloads.chef.io\/LICENSE' for software 'problematic'./)
end
end
describe "with a software with no license files" do
let(:software_with_warnings) do
Software.new(project, "problematic.rb").evaluate do
name "problematic"
default_version "0.10.2"
license "Zlib"
end
end
it_behaves_like "correctly created licenses"
it "should log a warning for the missing file pointers" do
output = capture_logging { create_licenses }
expect(output).to include("Software 'problematic' does not point to any license files.")
end
end
describe "with a project with no license files" do
let(:license) { "Zlib" }
let(:expected_project_license_path) { "LICENSE" }
let(:expected_project_license) { license }
let(:expected_project_license_content) { "" }
it_behaves_like "correctly created licenses"
it "warns for missing license files" do
output = capture_logging { create_licenses }
expect(output).to include("Project 'test-project' does not point to a license file.")
end
end
describe "with :fatal_licensing_warnings set and without license definitions in the project" do
before do
Omnibus::Config.fatal_licensing_warnings(true)
end
it "fails the omnibus build" do
expect { create_licenses }.to raise_error(Omnibus::LicensingError, /Project 'test-project' does not contain licensing information.\s{1,}Software 'private_code' does not contain licensing information./)
end
end
end
end
| 35.695652 | 209 | 0.667885 |
46e2a4d681e3d62649b1d536fee6518ba44724ff | 27,502 | py | Python | documentation/Example_Scripts/DCE_Database.py | QTIM-Lab/qtim_tools | 92bd15ec7a81c5eda70d11a015f74538f3c41e22 | [
"Apache-2.0"
] | 12 | 2017-03-29T18:17:24.000Z | 2020-03-19T05:28:56.000Z | documentation/Example_Scripts/DCE_Database.py | QTIM-Lab/qtim_tools | 92bd15ec7a81c5eda70d11a015f74538f3c41e22 | [
"Apache-2.0"
] | 7 | 2017-03-08T21:06:01.000Z | 2017-06-21T19:01:58.000Z | documentation/Example_Scripts/DCE_Database.py | QTIM-Lab/qtim_tools | 92bd15ec7a81c5eda70d11a015f74538f3c41e22 | [
"Apache-2.0"
] | 5 | 2017-03-02T09:08:21.000Z | 2019-10-26T05:37:39.000Z | import numpy as np
import os
import glob
import csv
from shutil import copy, move
from sklearn.metrics import r2_score
from qtim_tools.qtim_utilities.format_util import convert_input_2_numpy
from qtim_tools.qtim_utilities.file_util import replace_suffix
from qtim_tools.qtim_utilities.nifti_util import nifti_resave, save_numpy_2_nifti
from collections import defaultdict
# Categorical
BLUR = ['blur_' + x for x in ['0','0.2','0.8','1.2']]
PCA = ['pca_' + x for x in ['0','1','2','3','4']]
THRESHOLD = ['threshold_' + x for x in ['-1', '0.01']]
ALGORITHM = ['simplex', 'lm']
INTEGRATION = ['recursive','conv']
AIF = ['autoAIF', 'popAIF', 'sameAutoAIF']
T1MAP = ['t1map','t1static']
# All
ALL_VARS = [BLUR, PCA, THRESHOLD, ALGORITHM, INTEGRATION, AIF, T1MAP]
def Copy_SameAIF_Visit1_Tumors(input_directory):
""" For one vs. all comparisons, it will be easier to code if we have duplicate
visit 1 entries for the "SameAIF" mode. Because SameAIF uses the AIF from visit
1 in both entries, visit 1 should be unchanged with this option.
"""
visit_1_file_database = glob.glob(os.path.join(input_directory, '*VISIT_01_autoAIF*.nii*'))
for filename in visit_1_file_database:
old_filename = str.split(filename, 'VISIT_01')[0] + '_sameAIF_' + str.split(filename, 'VISIT_01')[-1]
new_filename = str.split(filename, 'VISIT_01')[0] + 'VISIT_01_sameAIF_' + str.split(filename, 'VISIT_01')[-1]
copy(filename, new_filename)
os.remove(old_filename)
def Rename_LM_Files(data_directory):
lm_file_database = glob.glob(os.path.join(data_directory, '*lm*lm*.nii*'))
for filename in lm_file_database:
# split_file = str.split(filename, '_lm_')
# print split_file
# new_filename = split_file[0] + '_' + split_file[1] + '_lm_' + split_file[2]
print filename
# copy(filename, new_filename)
# os.remove(filename)
return
def Delete_Extra_Files(data_directory):
file_database = glob.glob(os.path.join(data_directory, '*.nii*'))
for files in file_database:
if '__lm__' not in files and 'simplex' not in files:
# print os.path.basename(os.path.normpath(files))
os.remove(files)
return
def Recode_With_Binary_Labels(data_directory):
file_database = glob.glob(os.path.join(data_directory, '*.nii*'))
for filename in file_database:
if 'autoAIF' not in filename and 'studyAIF' not in filename and 'same' not in filename and '_popAIF' not in filename:
print filename
split_file = str.split(filename, 'VISIT_0')
new_filename = split_file[0] + 'VISIT_0' + split_file[1][0] + '_popAIF_' + split_file[1][2:]
print new_filename
# move(filename, new_filename)
filename = new_filename
if 't1map' not in filename and 't1static' not in filename:
split_file = str.split(filename, 'VISIT_0')
new_filename = split_file[0] + 'VISIT_0' + split_file[1][0] + '_t1static_' + split_file[1][2:]
print new_filename
move(filename, new_filename)
filename = new_filename
if 't1static_t1static_' in filename:
new_filename = filename.replace('t1static_t1static_', 't1static_')
print filename
print new_filename
move(filename, new_filename)
filename = new_filename
if 'sameAIF__autoAIF' in filename:
new_filename = filename.replace('sameAIF__autoAIF', 'sameAutoAIF')
print filename
print new_filename
# move(filename, new_filename)
filename = new_filename
if 'threshold_-1' in filename:
new_filename = filename.replace('threshold_-1', 'threshold_none')
move(filename, new_filename)
print new_filename
filename = new_filename
if 'threshold_0.01' in filename:
new_filename = filename.replace('threshold_0.01', 'threshold_PCA')
move(filename, new_filename)
print new_filename
filename = new_filename
return
def Create_Resource_Directories(CED_directory, NHX_directory, ROI_folder, AIF_folder, T1MAP_folder, DCE_Folder):
""" Move all ROIs/AIFs/T1MAPs for the DCE script from their idiosyncratic locations
to a set folder.
"""
output_folders = [ROI_folder, AIF_folder, T1MAP_folder, DCE_Folder]
for output_folder in output_folders:
if not os.path.exists(output_folder):
os.mkdir(output_folder)
NHX_CED_dirs = glob.glob(os.path.join(CED_directory, 'CED*/')) + glob.glob(os.path.join(NHX_directory, 'NHX*/'))
visits = ['VISIT_01', 'VISIT_02']
for visit in visits:
for subdir in NHX_CED_dirs:
ROI = os.path.join(subdir, visit, 'ROISTATS', 'T1AxialPost', 'rT1AxialPostROI.nii')
output_path = os.path.join(ROI_folder, os.path.basename(os.path.normpath(subdir)) + '_' + visit + '_ROI.nii')
if os.path.exists(ROI):
print output_path
copy(ROI, output_path)
# AIF = os.path.join(subdir, visit, 'MAPS', 'NORDIC_ICE_AIF.txt')
# output_path = os.path.join(AIF_folder, os.path.basename(os.path.normpath(subdir)) + '_' + visit + '_AIF.txt')
# if os.path.exists(AIF):
# print output_path
# copy(AIF, output_path)
# T1MAP = os.path.join(subdir, visit, 'MAPS', 'T1inDCE.nii')
# output_path = os.path.join(output_folder, os.path.basename(os.path.normpath(subdir)) + '_' + visit + '_T1inDCE.nii')
# if os.path.exists(T1MAP):
# print output_path
# copy(T1MAP, output_path)
DCE = os.path.join(subdir, visit, 'MAPS', 'dce_mc_st_eco1.nii')
output_path = os.path.join(output_folder, os.path.basename(os.path.normpath(subdir)) + '_' + visit + '_DCE_ECHO1.nii')
if os.path.exists(DCE):
print output_path
copy(DCE, output_path)
def Convert_NordicIce_AIF(AIF_directory, output_suffix='_AIF'):
AIF_list = glob.glob(os.path.join(AIF_directory, '*VISIT*.txt'))
AIF_numpy_list = [[np.loadtxt(AIF, dtype=float), AIF] for AIF in AIF_list]
for AIF in AIF_numpy_list:
print AIF[1]
print AIF[0].shape
np.savetxt(replace_suffix(AIF[1], '', output_suffix), AIF[0][None], fmt='%2.5f', delimiter=';')
def Create_Study_AIF(AIF_directory, output_AIF):
""" Average all AIFs into one AIF.
"""
AIF_list = glob.glob(os.path.join(AIF_directory, '*VISIT*.txt'))
AIF_numpy_list = [[np.loadtxt(AIF, delimiter=';', dtype=object), AIF] for AIF in AIF_list]
AIF_array = np.zeros((len(AIF_numpy_list), 60), dtype=object)
for row_idx, row in enumerate(AIF_array):
print len(AIF_numpy_list[row_idx][0])
print AIF_numpy_list[row_idx][1]
print AIF_numpy_list[row_idx][0]
AIF_array[row_idx, :] = AIF_numpy_list[row_idx][0][0:60]
np.set_printoptions(suppress=True)
AIF_array = AIF_array.astype(float)
print AIF_array.shape
print np.mean(AIF_array, axis=0)
print np.mean(AIF_array, axis=0).T.shape
np.savetxt(output_AIF, np.mean(AIF_array, axis=0)[None], fmt='%2.5f', delimiter=';')
return
def Create_Average_AIF(AIF_directory, output_AIF_directory):
""" Create a patient-averaged AIF.
"""
AIF_list = glob.glob(os.path.join(AIF_directory, '*VISIT*.txt'))
for AIF_idx, AIF in enumerate(AIF_list):
# print AIF
if 'VISIT_01' in AIF:
split_AIF = str.split(os.path.basename(AIF), '_')
split_AIF[3] = '02'
visit_2_AIF = os.path.join(AIF_directory, '_'.join(split_AIF))
print visit_2_AIF
if not os.path.exists(visit_2_AIF):
continue
AIF_numpy_1, AIF_numpy_2 = np.loadtxt(AIF, delimiter=';', dtype=object), np.loadtxt(visit_2_AIF, delimiter=';', dtype=object)
print AIF_numpy_1
print AIF_numpy_2
output_AIF = (AIF_numpy_1[0:60].astype(float) + AIF_numpy_2[0:60].astype(float)) / 2.0
output_filename = os.path.join(output_AIF_directory, '_'.join(split_AIF[0:4]) + '_AIF_average.txt')
np.savetxt(output_filename, output_AIF[None], fmt='%2.5f', delimiter=';')
return
def Store_Unneeded_Codes(data_directory, storage_directory):
file_database = glob.glob(os.path.join(storage_directory, '*.nii*'))
if not os.path.exists(storage_directory):
os.mkdir(storage_directory)
i = 0
for file in file_database:
if 'pca_0' in file and ('blur_0.2' in file or 'blur_0_' in file) and ('threshold_-1' in file or 'threshold_none' in file):
# print os.path.basename(file)
move(file, os.path.join(data_directory, os.path.basename(file)))
print i
def Store_and_Retrieve(data_directory, storage_directory):
# Store
file_database = glob.glob(os.path.join(data_directory, '*.nii*'))
for file in file_database:
if 'blur_0.8' in file or 'lm' in file or 'conv' in file:
print os.path.basename(file)
move(file, os.path.join(storage_directory, os.path.basename(file)))
# Retrieve
file_database = glob.glob(os.path.join(storage_directory, '*.nii*'))
for file in file_database:
if 'pca_0' in file and ('blur_0.2' in file or 'blur_0_' in file) and ('simplex' in file and 'recursive' in file) and ('threshold_-1' in file or 'threshold_none' in file):
print os.path.basename(file)
move(file, os.path.join(data_directory, os.path.basename(file)))
def Determine_R2_Cutoff_Point(input_directory, ROI_directory):
""" Save ROI statistics into a giant csv file.
"""
file_database = glob.glob(os.path.join(input_directory, '*.nii*'))
output_headers = ['filename','mean','median','std','min','max','total_voxels','removed_values', 'removed_percent', 'low_values', 'low_percent']
output_data = np.zeros((1+len(file_database), len(output_headers)),dtype=object)
output_data[0,:] = output_headers
ROI_dict = {}
for ROI in glob.glob(os.path.join(ROI_directory, '*.nii*')):
ROI_dict[os.path.basename(os.path.normpath(ROI))[0:15]] = convert_input_2_numpy(ROI)
r2_masked_num, r2_total_num = [0]*100, [0]*100
np.set_printoptions(precision=2)
np.set_printoptions(suppress=True)
for row_idx, filename in enumerate(file_database):
if 'ktrans' not in filename or '0.2' in filename:
continue
data_array = convert_input_2_numpy(filename)
r2_array = convert_input_2_numpy(replace_suffix(filename, input_suffix=None, output_suffix='r2', suffix_delimiter='_'))
# print replace_suffix(filename, input_suffix=None, output_suffix='r2', suffix_delimiter='_')
patient_visit_code = os.path.basename(os.path.normpath(filename))[0:15]
roi_array = ROI_dict[patient_visit_code]
for r2_idx, r2_threshold in enumerate(np.arange(0,1,.01)):
r2_masked_num[r2_idx] += ((r2_array <= r2_threshold) & (roi_array > 0)).sum()
r2_total_num[r2_idx] += (roi_array > 0).sum()
print np.array(r2_masked_num, dtype=float) / np.array(r2_total_num, dtype=float)
r2_percent_num = np.array(r2_masked_num, dtype=float) / np.array(r2_total_num, dtype=float)
for r2_idx, r2_threshold in enumerate(xrange(0,1,.01)):
print r2_threshold
print r2_percent_num[r2_idx]
return
def Rename_Files(input_directory):
files = glob.glob(os.path.join(input_directory, '*.nii*'))
for file in files:
new_path = file.replace('0.2', '02')
move(file, new_path)
def Preprocess_Volumes(input_directory, output_directory, r2_threshold=.9):
if not os.path.exists(output_directory):
os.mkdir(output_directory)
file_database = glob.glob(os.path.join(input_directory, '*r2*.nii*'))
print os.path.join(input_directory, '*r2*.nii*')
for file in file_database:
print file
input_ktrans = replace_suffix(file, 'r2', 'ktrans')
input_ve = replace_suffix(file, 'r2', 've')
output_ktrans = os.path.join(output_directory, replace_suffix(os.path.basename(file), 'r2', 'ktrans_r2_' + str(r2_threshold)))
output_ve = os.path.join(output_directory, replace_suffix(os.path.basename(file), 'r2', 've_r2_' + str(r2_threshold)))
output_kep = os.path.join(output_directory, replace_suffix(os.path.basename(file), 'r2', 'kep_r2_' + str(r2_threshold)))
output_r2 = os.path.join(output_directory, replace_suffix(os.path.basename(file), 'r2', 'r2_r2_' + str(r2_threshold)))
print input_ktrans
r2_map = np.nan_to_num(convert_input_2_numpy(file))
ktrans_map = convert_input_2_numpy(input_ktrans)
ve_map = convert_input_2_numpy(input_ve)
print (r2_map < r2_threshold).sum()
ve_map[ktrans_map > 10] = 0
ktrans_map[ktrans_map > 10] = 0
ktrans_map[ve_map > 1] = 0
ve_map[ve_map > 1] = 0
ktrans_map[r2_map < r2_threshold] = -.01
ve_map[r2_map < r2_threshold] = -.01
kep_map = np.nan_to_num(ktrans_map / ve_map)
kep_map[r2_map < r2_threshold] = -.01
save_numpy_2_nifti(ktrans_map, input_ktrans, output_ktrans)
save_numpy_2_nifti(ve_map, input_ktrans, output_ve)
save_numpy_2_nifti(kep_map, input_ktrans, output_kep)
save_numpy_2_nifti(r2_map, input_ktrans, output_r2)
def Save_Directory_Statistics(input_directory, ROI_directory, output_csv, mask=False, mask_suffix='_mask', r2_thresholds=[.9]):
""" Save ROI statistics into a giant csv file.
"""
# exclude_patients = ['CED_19', ]
file_database = glob.glob(os.path.join(input_directory, '*blur*r2_' + str(r2_thresholds[0]) + '.nii*'))
output_headers = ['filename','mean','median','min','max','std', 'total_voxels','removed_values', 'removed_percent', 'low_values', 'low_percent']
ROI_dict = {}
for ROI in glob.glob(os.path.join(ROI_directory, '*.nii*')):
ROI_dict[os.path.basename(os.path.normpath(ROI))[0:15]] = convert_input_2_numpy(ROI)
for r2 in r2_thresholds:
output_data = np.zeros((1+len(file_database), len(output_headers)),dtype=object)
output_data[0,:] = output_headers
with open(replace_suffix(output_csv, '', '_' + str(r2)), 'wb') as writefile:
csvfile = csv.writer(writefile, delimiter=',')
csvfile.writerow(output_data[0,:])
for row_idx, filename in enumerate(file_database):
data_array = convert_input_2_numpy(filename)
patient_visit_code = os.path.basename(os.path.normpath(filename))[0:15]
roi_array = ROI_dict[patient_visit_code]
r2_filename = str.split(filename, '_')
r2_filename[-3] = 'r2'
r2_filename = '_'.join(r2_filename)
r2_array = convert_input_2_numpy(r2_filename)
data_array[data_array<0] = -.01
data_array[r2_array<=r2] = -.01
data_array[roi_array<=0] = -.01
masked_data_array_ROI = np.ma.masked_where(data_array < 0, data_array)
ROI_values = [np.ma.mean(masked_data_array_ROI),
np.ma.median(masked_data_array_ROI),
np.ma.min(masked_data_array_ROI),
np.ma.max(masked_data_array_ROI),
np.ma.std(masked_data_array_ROI),
(roi_array > 0).sum(),
((data_array <= 0) & (roi_array > 0)).sum(),
float(((data_array <= 0) & (roi_array > 0)).sum()) / float((roi_array > 0).sum()),
((r2_array >= r2) & (roi_array > 0)).sum(),
float(((r2_array >= r2) & (roi_array > 0)).sum()) / float((roi_array > 0).sum())]
print ROI_values
output_data[row_idx+1] = [filename] + ROI_values
csvfile.writerow(output_data[row_idx+1])
return
def Paired_Visits_Worksheet(input_csv, output_csv, grab_column=2, r2_thresholds=[.9]):
print r2_thresholds
for r2 in r2_thresholds:
input_data = np.genfromtxt(replace_suffix(input_csv, '', '_' + str(r2)), delimiter=',', dtype=object, skip_header=1)
print input_data
visit_1_list = [x for x in input_data[:,0] if 'VISIT_01' in x]
output_data = np.zeros((len(visit_1_list)+1, 3), dtype=object)
output_data[0,:] = ['method_code', 'visit_1', 'visit_2']
with open(replace_suffix(output_csv, '', '_' + str(r2)), 'wb') as writefile:
csvfile = csv.writer(writefile, delimiter=',')
csvfile.writerow(output_data[0,:])
for visit_idx, visit in enumerate(visit_1_list):
if 'r2_r2' in visit:
continue
split_visit = str.split(visit, 'VISIT_01')
new_visit = split_visit[0] + 'VISIT_02' + split_visit[1]
if new_visit in input_data[:,0]:
print np.where(input_data == visit)[0][0]
output_data[visit_idx+1, 0] = visit
output_data[visit_idx+1, 1] = input_data[np.where(input_data == visit)[0][0], grab_column]
output_data[visit_idx+1, 2] = input_data[np.where(input_data == new_visit)[0][0], grab_column]
if output_data[visit_idx+1, 0] != 0 and output_data[visit_idx+1, 0] != '0' and input_data[np.where(input_data == visit)[0][0], -1] != '0' and input_data[np.where(input_data == new_visit)[0][0], -1] != '0':
csvfile.writerow(output_data[visit_idx+1,:])
def Coeffecient_of_Variation_Worksheet(input_csv, output_csv, r2_thresholds=[.9]):
for r2 in r2_thresholds:
input_data = np.genfromtxt(replace_suffix(input_csv, '', '_' + str(r2)), delimiter=',', dtype=object, skip_header=1)
headers = ['method', 'RMS_COV', 'LOG_COV', 'SD_COV', 'CCC', 'R2', 'LOA_pos', 'LOS_neg', 'RC', 'mean_all_vals', 'n_measurements']
output_data = np.zeros((3000, len(headers)), dtype=object)
output_data[0,:] = headers
methods, finished_methods = [], []
# Get all methods
for row in input_data:
if row[0] == '0' or '--' in row:
continue
methods += [str.split(row[0], '/')[-1][15:]]
method_dict = defaultdict(set)
for method in methods:
patient_list = [method == str.split(x, '/')[-1][15:] for x in input_data[:,0]]
patient_list = input_data[patient_list, :]
not_masked = [(x[1] != '--' and x[2] != '--') for x in patient_list]
not_masked_patient_list = patient_list[not_masked, :]
for row in not_masked_patient_list:
method_dict[method].add(str.split(row[0], '/')[-1][0:15])
available_patients = []
for key, value in method_dict.iteritems():
print key
if len(value) < 5:
continue
if available_patients == []:
available_patients = value
if len(value) < len(available_patients):
available_patients = value
print available_patients
print len(available_patients)
new_input_data = np.zeros((1,3), dtype=object)
for row_idx, row in enumerate(input_data):
patient = str.split(row[0], '/')[-1][0:15]
if patient in available_patients:
new_input_data = np.vstack((new_input_data, row))
input_data = new_input_data[1:,:]
with open(replace_suffix(output_csv, '', '_' + str(r2)), 'wb') as writefile:
csvfile = csv.writer(writefile, delimiter=',')
csvfile.writerow(output_data[0,:])
row_idx = 0
for row in input_data:
if row[0] == '0' or '--' in row or row[0] == 0:
continue
patient = str.split(row[0], '/')[-1][0:15]
if patient not in available_patients:
continue
method = str.split(row[0], '/')[-1][15:]
if 't1map' in method:
continue
aif_method = str.split(method, '_')
aif_method[1] = 'sameAIF21'
aif_method = '_'.join(aif_method)
for row2 in input_data:
if aif_method in row2:
continue
if method not in finished_methods:
# patient_list = np.where(method in input_data)
patient_list = [method == str.split(x, '/')[-1][15:] for x in input_data[:,0]]
patient_list = input_data[patient_list, :]
# print 'METHOD', method
# Non-Iterative Equations
not_masked = [(x[1] != 'nan' and x[2] != 'nan') for x in patient_list]
# print not_masked
not_masked_patient_list = patient_list[not_masked, :]
# print not_masked_patient_list
x, y = not_masked_patient_list[:,1].astype(float), not_masked_patient_list[:,2].astype(float)
if not_masked_patient_list.shape[0] < 10:
continue
# CCC
mean_x = np.mean(x)
mean_y = np.mean(y)
std_x = np.std(x)
std_y = np.std(y)
correl = np.ma.corrcoef(x,y)[0,1]
CCC = (2 * correl * std_x * std_y) / (np.ma.var(x) + np.ma.var(y) + np.square(mean_x - mean_y))
# Mean all values
mean_all_vals = np.mean(not_masked_patient_list[:,1:].astype(float))
# R2
R2_score = r2_score(y, x)
# Limits of Agreement (LOA)
differences = x - y
mean_diff = np.mean(differences)
std_diff = np.std(differences)
LOA_neg, LOA_pos = mean_diff - 2*std_diff, mean_diff + 2*std_diff
# Covariance and Repeatability Coeffecient
RMS_sum = 0
LOG_sum = 0
SD_sum_1 = 0
SD_sum_2 = 0
RC_sum = 0
n = 0
for patient in not_masked_patient_list:
data_points = [float(d) for d in patient[1:]]
skip=False
for d in data_points:
if d == 0:
skip = True
if skip:
continue
print data_points
RMS_sum += np.power(abs(data_points[0] - data_points[1]) / np.mean(data_points), 2)
LOG_sum += np.power(np.log(data_points[0]) - np.log(data_points[1]), 2)
SD_sum_1 += np.power(data_points[0] - data_points[1], 2)
SD_sum_2 += np.sum(data_points)
n += 1
RMS_COV = 100 * np.sqrt(RMS_sum / (2*n))
LOG_COV = 100 * np.exp(np.sqrt(LOG_sum / (2*n)) - 1)
SD_COV = 100 * np.sqrt(SD_sum_1 / (2*n)) / (SD_sum_2 / (2*n))
RC = (SD_sum_1 / n) * 1.96
output_data[row_idx+1, :] = [method, RMS_COV, LOG_COV, SD_COV, CCC, R2_score, LOA_pos, LOA_neg, RC, mean_all_vals, n]
# print output_data[row_idx+1, :]
finished_methods += [method]
# print methods
if output_data[row_idx+1, 0] != 0 and output_data[row_idx+1, 0] != '0':
print 'nice'
csvfile.writerow(output_data[row_idx+1,:])
row_idx += 1
else:
# print 'SKIPPED!!!!'
continue
return
# def Equalize_Patient_Number(input_csv, output_csv, r2=.9):
# input_data = np.genfromtxt(replace_suffix(input_csv, '', '_' + str(r2)), delimiter=',', dtype=object, skip_header=1)
# output_data = np.zeros((len(visit_1_list)+1, 3), dtype=object)
# for row in input_data:
# patient_num = os.path.basename(row[0])
# patient_num = patient_num[0:6]
# if patient
# return
if __name__ == '__main__':
data_directory = '/home/abeers/Data/DCE_Package/Test_Results/OLD/New_AIFs/Echo1'
storage_directory = '/home/abeers/Data/DCE_Package/Test_Results/Echo1/Storage'
preprocess_directory = '/home/abeers/Data/DCE_Package/Test_Results/New_AIFs/Echo1/PreProcess'
data_directory = '/home/abeers/Data/DCE_Package/Test_Results/Old_AIFs_Minor_Blur/Echo1'
preprocess_directory = '/home/abeers/Data/DCE_Package/Test_Results/Old_AIFs_Minor_Blur/Echo1/Preprocess'
NHX_directory = '/qtim2/users/data/NHX/ANALYSIS/DCE/'
CED_directory = '/qtim/users/data/CED/ANALYSIS/DCE/PREPARATION_FILES/'
ROI_directory = '/home/abeers/Data/DCE_Package/Test_Results/ROIs'
AIF_directory = '/home/abeers/Data/DCE_Package/Test_Results/AIFs'
T1MAP_directory = '/home/abeers/Data/DCE_Package/Test_Results/T1Maps'
DCE_directory = '/home/abeers/Data/DCE_Package/Test_Results/DCE_Echo1'
ALT_AIF_directory = '/home/abeers/Data/DCE_Package/Test_Results/DCE_Echo1/AIFS'
output_csv = '/home/abeers/Requests/Jayashree/DCE_Repeatability_Data/DCE_Assay_Patient_Level_Statistics_old_blur.csv'
paired_csv = '/home/abeers/Requests/Jayashree/DCE_Repeatability_Data/DCE_Assay_Visit_Level_Statistics_old_blur.csv'
cov_csv = '/home/abeers/Requests/Jayashree/DCE_Repeatability_Data/DCE_Assay_Repeatability_Measures_old_blur.csv'
r2_thresholds = [0.6]
for r2 in r2_thresholds:
Rename_Files(data_directory)
Preprocess_Volumes(data_directory, preprocess_directory, r2_threshold = r2)
# Determine_R2_Cutoff_Point(data_directory, ROI_directory)
# Create_Average_AIF(ALT_AIF_directory, ALT_AIF_directory)
# Rename_LM_Files(data_directory)
# Copy_SameAIF_Visit1_Tumors(data_directory)
# Convert_NordicIce_AIF(ALT_AIF_directory)
# Create_Resource_Directories(CED_directory, NHX_directory, ROI_directory, AIF_directory, T1MAP_directory, DCE_directory)
# Create_Study_AIF(ALT_AIF_directory, '/home/abeers/Data/DCE_Package/Test_Results/DCE_Echo1/AIFS/Study_AIF.txt')
# Store_Unneeded_Codes(data_directory, storage_directory)
Save_Directory_Statistics(preprocess_directory, ROI_directory, output_csv, r2_thresholds = [r2])
# Reshape_Statisticts_Worksheet(output_csv, reshaped_output_csv, ROI_directory)
# Delete_Extra_Files(data_directory)
Paired_Visits_Worksheet(output_csv, paired_csv, r2_thresholds = [r2])
Coeffecient_of_Variation_Worksheet(paired_csv, cov_csv, r2_thresholds = [r2])
# Coeffecient_of_Variation_Worksheet(paired_reduced_csv, cov_reduced_csv)
# Recode_With_Binary_Labels(data_directory)
# Store_and_Retrieve(data_directory, storage_directory)
pass | 39.514368 | 221 | 0.609847 |
7dd256a671115946ca74e129839a60ef269b97b9 | 101 | css | CSS | app/javascript/stocks/src/css/components/stocks/index.css | michael-software-engr/demo | f5b9c43b066e56b9fdc80a88628706357771f971 | [
"MIT"
] | null | null | null | app/javascript/stocks/src/css/components/stocks/index.css | michael-software-engr/demo | f5b9c43b066e56b9fdc80a88628706357771f971 | [
"MIT"
] | null | null | null | app/javascript/stocks/src/css/components/stocks/index.css | michael-software-engr/demo | f5b9c43b066e56b9fdc80a88628706357771f971 | [
"MIT"
] | null | null | null | .App--Stocks--StocksTable {
border: 1px solid red;
background-color: red;
margin-top: 10rem; }
| 20.2 | 27 | 0.683168 |
195c983497588efbac1b76a0fdd03eb9786d04cb | 463 | swift | Swift | Pod/Classes/Views/Polygon/PolygonButton.swift | ipraba/EPShapes | 43cc0948095db8666be30dad590588d74e9758be | [
"MIT"
] | 432 | 2016-02-08T11:14:42.000Z | 2021-07-09T15:32:38.000Z | Pod/Classes/Views/Polygon/PolygonButton.swift | ipraba/EPShapes | 43cc0948095db8666be30dad590588d74e9758be | [
"MIT"
] | 3 | 2016-02-11T07:47:03.000Z | 2019-05-27T05:17:54.000Z | Pod/Classes/Views/Polygon/PolygonButton.swift | ipraba/EPShapes | 43cc0948095db8666be30dad590588d74e9758be | [
"MIT"
] | 36 | 2016-02-09T15:35:18.000Z | 2020-04-02T15:21:51.000Z | //
// PolygonButton.swift
// Pods
//
// Created by Prabaharan Elangovan on 08/02/16.
//
//
import Foundation
@IBDesignable open class PolygonButton: ShapeButton, PolygonDesignable {
@IBInspectable open var sides: Int = 4
@IBInspectable open var shapeMask: Bool = false
@IBInspectable open var fillColor: UIColor = UIColor.clear
override open func config() {
if sides > 0 {
drawPolygon()
}
}
}
| 17.807692 | 72 | 0.63067 |
60a1afaf71f4c62d1894dd718626be7dd858a8d4 | 2,162 | h | C | exportNF/release/windows/obj/include/flixel/util/FlxUnicodeUtil.h | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/include/flixel/util/FlxUnicodeUtil.h | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/include/flixel/util/FlxUnicodeUtil.h | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | // Generated by Haxe 4.2.1+bf9ff69
#ifndef INCLUDED_flixel_util_FlxUnicodeUtil
#define INCLUDED_flixel_util_FlxUnicodeUtil
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS2(flixel,util,FlxUnicodeUtil)
namespace flixel{
namespace util{
class HXCPP_CLASS_ATTRIBUTES FlxUnicodeUtil_obj : public ::hx::Object
{
public:
typedef ::hx::Object super;
typedef FlxUnicodeUtil_obj OBJ_;
FlxUnicodeUtil_obj();
public:
enum { _hx_ClassId = 0x2deb6c2b };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="flixel.util.FlxUnicodeUtil")
{ return ::hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return ::hx::Object::operator new(inSize+extra,false,"flixel.util.FlxUnicodeUtil"); }
inline static ::hx::ObjectPtr< FlxUnicodeUtil_obj > __new() {
::hx::ObjectPtr< FlxUnicodeUtil_obj > __this = new FlxUnicodeUtil_obj();
__this->__construct();
return __this;
}
inline static ::hx::ObjectPtr< FlxUnicodeUtil_obj > __alloc(::hx::Ctx *_hx_ctx) {
FlxUnicodeUtil_obj *__this = (FlxUnicodeUtil_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(FlxUnicodeUtil_obj), false, "flixel.util.FlxUnicodeUtil"));
*(void **)__this = FlxUnicodeUtil_obj::_hx_vtable;
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(::hx::DynamicArray inArgs);
//~FlxUnicodeUtil_obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, ::hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("FlxUnicodeUtil",8d,20,33,eb); }
static int uLength(::String s);
static ::Dynamic uLength_dyn();
static bool uEquals(::String a,::String b);
static ::Dynamic uEquals_dyn();
static ::String uSub(::String s,int pos,int len);
static ::Dynamic uSub_dyn();
static ::Dynamic uCharCodeAt(::String s,int index);
static ::Dynamic uCharCodeAt_dyn();
};
} // end namespace flixel
} // end namespace util
#endif /* INCLUDED_flixel_util_FlxUnicodeUtil */
| 30.027778 | 146 | 0.734043 |
3937a770d6f53cb773d66f26b02d452ab8a97ac2 | 4,008 | py | Python | mirage/libs/ble_utils/scapy_hci_layers.py | epablosensei/mirage | 3c0d2fb0f0e570356e7126c999e83e0256920420 | [
"MIT"
] | null | null | null | mirage/libs/ble_utils/scapy_hci_layers.py | epablosensei/mirage | 3c0d2fb0f0e570356e7126c999e83e0256920420 | [
"MIT"
] | null | null | null | mirage/libs/ble_utils/scapy_hci_layers.py | epablosensei/mirage | 3c0d2fb0f0e570356e7126c999e83e0256920420 | [
"MIT"
] | 1 | 2020-06-08T15:50:31.000Z | 2020-06-08T15:50:31.000Z | from scapy.all import *
'''
This module contains some scapy definitions for communicating with an HCI device.
'''
#split_layers(HCI_Command_Hdr, HCI_Cmd_LE_Set_Advertising_Data)
#split_layers(HCI_Command_Hdr, HCI_Cmd_LE_Set_Scan_Response_Data)
class HCI_Cmd_LE_Rand(Packet):
name = "HCI Command LE Rand"
fields_desc = []
class HCI_LE_Meta_Enhanced_Connection_Complete(Packet):
name = "Enhanced Connection Complete"
fields_desc = [ByteEnumField("status", 0, {0: "success"}),
LEShortField("handle", 0),
ByteEnumField("role", 0, {0: "master"}),
ByteEnumField("patype", 0, {0: "public", 1: "random"}),
LEMACField("paddr", None),
LEMACField("localresolvprivaddr", None),
LEMACField("peerresolvprivaddr", None),
LEShortField("interval", 54),
LEShortField("latency", 0),
LEShortField("supervision", 42),
XByteField("clock_latency", 5), ]
def answers(self, other):
if HCI_Cmd_LE_Create_Connection not in other:
return False
return (other[HCI_Cmd_LE_Create_Connection].patype == self.patype and
other[HCI_Cmd_LE_Create_Connection].paddr == self.paddr)
class New_HCI_Cmd_LE_Set_Advertising_Data(Packet):
name = "LE Set Advertising Data"
fields_desc = [FieldLenField("len", None, length_of="data", fmt="B"),
PadField(
PacketListField("data", [], EIR_Hdr,
length_from=lambda pkt:pkt.len),
align=31, padwith=b"\0"), ]
class New_HCI_Cmd_LE_Set_Scan_Response_Data(Packet):
name = "LE Set Scan Response Data"
fields_desc = [FieldLenField("len", None, length_of="data", fmt="B"),
StrLenField("data", "", length_from=lambda pkt:pkt.len), ]
class SM_Security_Request(Packet):
name = "Security Request"
fields_desc = [BitField("authentication", 0, 8)]
class New_ATT_Handle_Value_Notification(Packet):
name = "Handle Value Notification"
fields_desc = [ XLEShortField("gatt_handle", 0),
StrField("value", ""), ]
class New_ATT_Handle_Value_Indication(Packet):
name = "Handle Value Indication"
fields_desc = [
XLEShortField("gatt_handle", 0),
StrField("value", ""),
]
class New_ATT_Read_Blob_Request(Packet):
name = "Read Blob Request"
fields_desc = [
XLEShortField("gatt_handle", 0),
LEShortField("offset", 0)
]
class New_ATT_Read_Blob_Response(Packet):
name = "Read Blob Response"
fields_desc = [
StrField("value", "")
]
class New_ATT_Handle_Value_Confirmation(Packet):
name = "Handle Value Confirmation"
fields_desc = []
bind_layers(HCI_Command_Hdr, HCI_Cmd_LE_Rand, opcode=0x2018)
bind_layers(HCI_Event_LE_Meta, HCI_LE_Meta_Enhanced_Connection_Complete, event = 0xa)
bind_layers(SM_Hdr, SM_Security_Request, sm_command=0xb)
bind_layers(HCI_Command_Hdr, New_HCI_Cmd_LE_Set_Advertising_Data, opcode=0x2008)
bind_layers(HCI_Command_Hdr, New_HCI_Cmd_LE_Set_Scan_Response_Data, opcode=0x2009)
split_layers(ATT_Hdr,ATT_Handle_Value_Notification)
bind_layers( ATT_Hdr,New_ATT_Handle_Value_Notification, opcode=0x1b)
if hasattr(scapy.all,"ATT_Handle_Value_Indication"):
split_layers(ATT_Hdr,ATT_Handle_Value_Indication)
bind_layers( ATT_Hdr,New_ATT_Handle_Value_Indication, opcode=0x1d)
if hasattr(scapy.all,"ATT_ReadBlobReq"):
split_layers(ATT_Hdr,ATT_ReadBlobReq)
if hasattr(scapy.all,"ATT_ReadBlobResp"):
split_layers(ATT_Hdr,ATT_ReadBlobResp)
if hasattr(scapy.all,"ATT_Read_Blob_Request"):
split_layers(ATT_Hdr,ATT_Read_Blob_Request)
if hasattr(scapy.all,"ATT_Read_Blob_Response"):
split_layers(ATT_Hdr,ATT_Read_Blob_Response)
bind_layers(ATT_Hdr, New_ATT_Read_Blob_Request, opcode=0xc)
bind_layers(ATT_Hdr, New_ATT_Read_Blob_Response, opcode=0xd)
bind_layers(ATT_Hdr, New_ATT_Handle_Value_Confirmation, opcode=0x1e)
| 35.469027 | 85 | 0.698852 |
a3c9ff9c0eeae09df18e532e2bf98b04ede1267f | 917 | java | Java | src/main/java/com/bymarcin/openglasses/proxy/ClientProxy.java | Florexiz/OCGlasses | 1a04e08ddf103106ef50bc3fdf91683fad235712 | [
"Zlib"
] | 1 | 2022-02-07T04:53:50.000Z | 2022-02-07T04:53:50.000Z | src/main/java/com/bymarcin/openglasses/proxy/ClientProxy.java | Florexiz/OCGlasses | 1a04e08ddf103106ef50bc3fdf91683fad235712 | [
"Zlib"
] | 1 | 2022-02-10T22:35:27.000Z | 2022-02-10T22:36:04.000Z | src/main/java/com/bymarcin/openglasses/proxy/ClientProxy.java | Florexiz/OCGlasses | 1a04e08ddf103106ef50bc3fdf91683fad235712 | [
"Zlib"
] | 3 | 2020-10-27T12:44:20.000Z | 2021-11-11T06:42:54.000Z | package com.bymarcin.openglasses.proxy;
import net.minecraft.client.Minecraft;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import com.bymarcin.openglasses.event.ClientEventHandler;
import com.bymarcin.openglasses.surface.ClientSurface;
import cpw.mods.fml.common.FMLCommonHandler;
public class ClientProxy extends CommonProxy {
@Override
public void init() {
ClientEventHandler eh = new ClientEventHandler();
FMLCommonHandler.instance().bus().register(eh);
MinecraftForge.EVENT_BUS.register(eh);
MinecraftForge.EVENT_BUS.register(ClientSurface.instances);
}
@Override
public World getWorld(int dimensionId) {
if (getCurrentClientDimension() != dimensionId) {
return null;
} else
return Minecraft.getMinecraft().theWorld;
}
@Override
public int getCurrentClientDimension() {
return Minecraft.getMinecraft().theWorld.provider.dimensionId;
}
}
| 26.2 | 64 | 0.790622 |
e2224f78c868079aa509a1242a35ba53751e3021 | 4,019 | py | Python | integer_to_roman.py | SBHKoda/Integer_to_Roman | 2e52c1a92402edad17f87a36f5dd133e026ee9e8 | [
"Apache-2.0"
] | null | null | null | integer_to_roman.py | SBHKoda/Integer_to_Roman | 2e52c1a92402edad17f87a36f5dd133e026ee9e8 | [
"Apache-2.0"
] | null | null | null | integer_to_roman.py | SBHKoda/Integer_to_Roman | 2e52c1a92402edad17f87a36f5dd133e026ee9e8 | [
"Apache-2.0"
] | null | null | null | """
Author: Alberto Marci
"""
class DecimalToRoman:
# convert number from 0 to 9
def __zero_to_nine(self, number):
if number == '0':
return ''
if number == '1':
return 'I'
if number == '2':
return 'II'
if number == '3':
return 'III'
if number == '4':
return 'IV'
if number == '5':
return 'V'
if number == '6':
return 'VI'
if number == '7':
return 'VII'
if number == '8':
return 'VIII'
if number == '9':
return 'IX'
# convert number from 10 to 90
def __ten_to_ninety(self, number):
if number == '0':
return ''
if number == '1':
return 'X'
if number == '2':
return 'XX'
if number == '3':
return 'XXX'
if number == '4':
return 'XL'
if number == '5':
return 'L'
if number == '6':
return 'LX'
if number == '7':
return 'LXX'
if number == '8':
return 'LXXX'
if number == '9':
return 'XC'
# convert number from 100 to 900
def __one_hundred_to_nine_hundred(self, number):
if number == '0':
return ''
if number == '1':
return 'C'
if number == '2':
return 'CC'
if number == '3':
return 'CCC'
if number == '4':
return 'CD'
if number == '5':
return 'D'
if number == '6':
return 'DC'
if number == '7':
return 'DCC'
if number == '8':
return 'DCCC'
if number == '9':
return 'CM'
# convert number from 1000 to 3000
def __one_thousand_to_three_thousand(self, number):
if number == '1':
return 'M'
if number == '2':
return 'MM'
if number == '3':
return 'MMM'
# return roman string
def integer_to_roman(self, number):
tmp = str(number)
str_len = len(tmp)
if str_len == 1:
return self.__zero_to_nine(tmp[0])
if str_len == 2:
roman_str0 = self.__zero_to_nine(tmp[1])
roman_str1 = self.__ten_to_ninety(tmp[0])
return roman_str1 + roman_str0
if str_len == 3:
roman_str0 = self.__zero_to_nine(tmp[2])
roman_str1 = self.__ten_to_ninety(tmp[1])
roman_str2 = self.__one_hundred_to_nine_hundred(tmp[0])
return roman_str2 + roman_str1 + roman_str0
if str_len == 4:
roman_str0 = self.__zero_to_nine(tmp[3])
roman_str1 = self.__ten_to_ninety(tmp[2])
roman_str2 = self.__one_hundred_to_nine_hundred(tmp[1])
roman_str3 = self.__one_thousand_to_three_thousand(tmp[0])
return roman_str3 + roman_str2 + roman_str1 + roman_str0
def test(self):
print(self.integer_to_roman(13))
print('-------------------------------------------')
print(self.integer_to_roman(48))
print('-------------------------------------------')
print(self.integer_to_roman(444))
print('-------------------------------------------')
print(self.integer_to_roman(3444))
print('-------------------------------------------')
print(self.integer_to_roman(3999))
print('-------------------------------------------')
print(self.integer_to_roman(100))
# ----------------------------------------------------------------------------------------------------------------------
converter = DecimalToRoman()
converter.test()
print('-------------------------------------------')
print('-------------------------------------------')
print(converter.integer_to_roman(1234))
| 31.645669 | 121 | 0.424484 |
43aea9bab0a18fe6d11737c84ef1f5009c1e71bb | 1,467 | ts | TypeScript | chat-app-client/src/app/main/ui/cards/cards.module.ts | md-rubel-mia/chat-app-MEAN-stack | 3f9e0e19e3cc2962013e890289bfd7009ce1e3d1 | [
"Apache-2.0"
] | 1 | 2021-12-10T01:30:49.000Z | 2021-12-10T01:30:49.000Z | chat-app-client/src/app/main/ui/cards/cards.module.ts | md-rubel-mia/chat-app-MEAN-stack | 3f9e0e19e3cc2962013e890289bfd7009ce1e3d1 | [
"Apache-2.0"
] | null | null | null | chat-app-client/src/app/main/ui/cards/cards.module.ts | md-rubel-mia/chat-app-MEAN-stack | 3f9e0e19e3cc2962013e890289bfd7009ce1e3d1 | [
"Apache-2.0"
] | null | null | null | import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatSelectModule } from '@angular/material/select';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTabsModule } from '@angular/material/tabs';
import { FuseSharedModule } from '@fuse/shared.module';
import { FuseDemoModule } from '@fuse/components/demo/demo.module';
import { FuseHighlightModule } from '@fuse/components';
import { CardsComponent } from 'app/main/ui/cards/cards.component';
import { NgxChartsModule } from '@swimlane/ngx-charts';
const routes: Routes = [
{
path : 'cards',
component: CardsComponent
}
];
@NgModule({
declarations: [
CardsComponent
],
imports : [
RouterModule.forChild(routes),
MatButtonModule,
MatButtonToggleModule,
MatIconModule,
MatListModule,
MatMenuModule,
MatSelectModule,
MatSlideToggleModule,
MatTabsModule,
NgxChartsModule,
FuseSharedModule,
FuseDemoModule,
FuseHighlightModule,
]
})
export class UICardsModule
{
}
| 28.211538 | 72 | 0.683027 |
fe157ab1964d6fa5c7becfea444b24917c74a0bd | 11,607 | dart | Dart | spdorm/lib/mainHomeFragment.dart | spdorm/spdorm.github.io | 4b81b0878c2a09af6a7a49f14d17dad8223a6e54 | [
"MIT"
] | null | null | null | spdorm/lib/mainHomeFragment.dart | spdorm/spdorm.github.io | 4b81b0878c2a09af6a7a49f14d17dad8223a6e54 | [
"MIT"
] | 14 | 2019-08-13T02:50:33.000Z | 2019-11-21T09:40:02.000Z | spdorm/lib/mainHomeFragment.dart | spdorm/spdorm.github.io | 4b81b0878c2a09af6a7a49f14d17dad8223a6e54 | [
"MIT"
] | 3 | 2019-09-02T19:04:37.000Z | 2021-07-14T05:12:03.000Z | import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as prefix0;
import 'package:shared_preferences/shared_preferences.dart';
import 'AddDormpage.dart';
import 'VendingHome.dart';
import 'Add_AccountIncome.dart';
import 'Datadorm_fragment.dart';
import 'InfromAlert.dart';
import 'firstPage.dart';
import 'home_fragment.dart';
import 'NewsDorm.dart';
import 'StaticVendingMachine.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'config.dart';
import 'listCustumerManageAll.dart';
class MainHomeFragment extends StatefulWidget {
int _dormId, _userId;
MainHomeFragment(int dormId, int userId) {
this._dormId = dormId;
this._userId = userId;
}
@override
State<StatefulWidget> createState() {
return new _MainHomeFragment(_dormId, _userId);
}
}
class _MainHomeFragment extends State<MainHomeFragment> {
int _dormId, _userId;
_MainHomeFragment(int dormId, int userId) {
this._dormId = dormId;
this._userId = userId;
}
String _dormName, _name_image = "", _userName = "";
void initState() {
super.initState();
http.post('${config.API_url}/dorm/findImageDorm',
body: {"dormId": _dormId.toString()}).then((response) {
Map jsonData = jsonDecode(response.body) as Map;
if (jsonData['status'] == 0) {
setState(() {
_name_image = jsonData['data'];
});
} else {
setState(() {
_name_image = "";
});
}
});
http.post('${config.API_url}/dorm/list',
body: {"dormId": _dormId.toString()}).then((response) {
print(response.body);
Map jsonData = jsonDecode(response.body) as Map;
Map<String, dynamic> data = jsonData['data'];
if (jsonData['status'] == 0) {
http.post('${config.API_url}/user/list',
body: {"userId": _userId.toString()}).then((response) {
Map jsonData = jsonDecode(response.body) as Map;
Map<String, dynamic> dataUsername = jsonData['data'];
if (jsonData['status'] == 0) {
setState(() {
_dormName = data['dormName'];
_userName = dataUsername['userFirstname'] +
' ' +
dataUsername['userLastname'];
});
}
});
}
});
}
Future<void> _logout() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('id', null);
}
Future<bool> onLogOut() {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('คุณต้องการออกจากระบบ ?'),
actions: <Widget>[
FlatButton(
child: Text('ไม่ใช่'),
onPressed: () => Navigator.pop(context, false),
),
FlatButton(
child: Text('ใช่'),
onPressed: () => {
_logout().then((res) => {
Navigator.pop(context),
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext) => Login()))
}),
},
),
],
));
}
int selectedDrawerIndex = 1;
onSelectItem(int index) {
setState(() => selectedDrawerIndex = index);
switch (selectedDrawerIndex) {
case 1:
return Navigator.pop(context);
case 2:
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext) =>
listManageCustumerAllPage(_dormId, _userId)));
case 3:
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext) => InformAlertPage(_dormId, _userId)));
case 4:
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext) => NewsDorm(_dormId, _userId)));
case 5:
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext) => DataDormFragment(_dormId, _userId)));
case 6:
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext) =>
AccountIncomeFragment(_dormId, _userId)));
case 7:
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext) => VendingHomePage(_dormId, _userId)));
case 8:
return Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext) =>
StaticVendingPage(_dormId, _userId)));
default:
return new Text('ERROR');
}
}
@override
Widget build(BuildContext context) {
int bIndex = 0;
Future<void> _logout() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('login', false);
}
Future<bool> onLogOut() {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text('คุณต้องการออกจากระบบ ?'),
actions: <Widget>[
FlatButton(
child: Text('ใช่'),
onPressed: () => {
_logout().then((res) => {
Navigator.pop(context),
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext) => Login()))
}),
},
),
FlatButton(
child: Text('ไม่ใช่'),
onPressed: () => Navigator.pop(context, false),
),
],
));
}
void _onTab(int index) {
setState(() {
bIndex = index;
});
if (bIndex == 0) {
Navigator.pop(context);
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext) => AddDormPage(_userId)));
} else if (bIndex == 1) {
onLogOut();
}
}
return new WillPopScope(
onWillPop: () async => false,
child: new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.red[300],
title: new Text('หน้าหลัก'),
// actions: <Widget>[
// IconButton(
// icon: Icon(Icons.settings),
// onPressed: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (BuildContext) => NotificationsPage(_userId)));
// },
// ),
// ],
),
body: new HomeFragment(_dormId),
drawer: new Drawer(
child: new ListView(
padding: EdgeInsets.all(0),
children: <Widget>[
new UserAccountsDrawerHeader(
decoration: new BoxDecoration(
color: prefix0.Colors.red[300]
),
currentAccountPicture: _name_image != ""
? new Container(
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.cover,
image: new NetworkImage(
"${config.API_url}/dorm/image/?nameImage=${_name_image}",
),
),
),
)
: new Container(
decoration: new BoxDecoration(
shape: BoxShape.circle,
image: new DecorationImage(
fit: BoxFit.fill,
image: new AssetImage("images/no_image.png"),
),
),
),
accountName: new Text('${_dormName}',
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 18)),
accountEmail: Text('${_userName}'),
),
new ListTile(
title: new Text('หน้าหลัก'),
leading: new Icon(Icons.home),
selected: true,
onTap: () => onSelectItem(1),
),
new ListTile(
title: new Text('จัดการค่ามัดจำ'),
leading: new Icon(Icons.insert_drive_file),
// selected: 2 == selectedDrawerIndex,
onTap: () {
Navigator.pop(context);
onSelectItem(2);
},
),
new ListTile(
title: new Text('แจ้งซ่อม'),
leading: new Icon(Icons.settings),
// selected: 3 == selectedDrawerIndex,
onTap: () {
Navigator.pop(context);
onSelectItem(3);
},
),
new ListTile(
title: new Text('เพิ่มข้อมูลข่าวสาร'),
leading: new Icon(Icons.public),
// selected: 4 == selectedDrawerIndex,
onTap: () {
Navigator.pop(context);
onSelectItem(4);
},
),
new ListTile(
title: new Text('ข้อมูลหอพัก'),
leading: new Icon(Icons.perm_device_information),
// selected: 5 == selectedDrawerIndex,
onTap: () {
Navigator.pop(context);
onSelectItem(5);
},
),
new ListTile(
title: new Text('บัญชีรายรับรายจ่าย'),
leading: new Icon(Icons.note),
// selected: 6 == selectedDrawerIndex,
onTap: () {
Navigator.pop(context);
onSelectItem(6);
},
),
new ListTile(
title: new Text('เครื่องหยอดเหรียญ'),
leading: new Icon(Icons.note_add),
// selected: 7 == selectedDrawerIndex,
onTap: () {
Navigator.pop(context);
onSelectItem(7);
},
),
new ListTile(
title: new Text('สถิตเครื่องหยอดเหรียญ'),
leading: new Icon(Icons.insert_chart),
// selected: 8 == selectedDrawerIndex,
onTap: () {
Navigator.pop(context);
onSelectItem(8);
},
)
],
),
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: bIndex, // this will be set when a new tab is tapped
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home),
title: new Text('หอพักทั้งหมด'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.exit_to_app),
title: new Text('ออกจากระบบ'),
),
],
onTap: (index) {
_onTab(index);
},
),
),
);
}
}
| 32.788136 | 87 | 0.463341 |
b00709cfcd2390ee9d65927e10fce5a3163fcad2 | 2,732 | py | Python | mydb/mydb_setup.py | dappsunilabs/DB4SCI | 54bdd03aaa12957e622c921b263e187740a8b2ae | [
"Apache-2.0"
] | 7 | 2018-12-05T19:18:20.000Z | 2020-11-21T07:27:54.000Z | mydb/mydb_setup.py | dappsunilabs/DB4SCI | 54bdd03aaa12957e622c921b263e187740a8b2ae | [
"Apache-2.0"
] | 8 | 2018-04-25T06:02:41.000Z | 2020-09-08T21:55:56.000Z | mydb/mydb_setup.py | FredHutch/DB4SCI | cc950a36b6b678fe16c1c91925ec402581636fc0 | [
"Apache-2.0"
] | 2 | 2019-11-14T02:09:09.000Z | 2021-12-28T19:05:51.000Z | #!/usr/bin/python
import os
import time
import postgres_util
import container_util
import admin_db
from send_mail import send_mail
from config import Config
"""
import mydb_setup
mydb_setup.mydb_setup()
"""
def mydb_setup():
"""Create mydb_admin database if it does not exist.
DB4SCI depends on mydb_admin database.
"""
if container_util.container_exists('mydb_admin'):
print('Administrative DB is running.\nStarting DB4Sci')
return
print('Create Administrative DB')
params = setup_data()
dbtype = params['dbtype']
con_name = params['dbname']
result = postgres_util.create(params)
# wait for container to startup
print('Container Id: %s' % params['con']['Id'] )
print('Waiting for mydb_admin to start')
time.sleep(20)
badness = 0
status = False
while (not status) and (badness < 6):
badness += 1
status = postgres_util.auth_check(params['dbuser'],
params['dbuserpass'],
params['port'])
print('mydb_admin setup status: %s count: %d' % (status, badness))
time.sleep(5)
if not status:
print('mydb_admin restart error. Could not setup db')
return
print('Setup mydb_admin tables')
admin_db.init_db()
inspect = container_util.inspect_con(params['con']['Id'])
c_id = admin_db.add_container(inspect, params)
state_info = admin_db.get_container_state(con_name)
description = 'created %s by user %s' % (con_name, params['username'])
admin_db.add_container_log(c_id, con_name, 'created', description)
def setup_data():
""" create parameters for admin database
"""
dbtype = 'Postgres'
params = {'dbname': 'mydb_admin',
'dbtype': dbtype,
'dbengine': dbtype,
'port': Config.admin_port,
'dbuser': Config.accounts['admindb']['admin'],
'dbuserpass': Config.accounts['admindb']['admin_pass'],
'db_vol': "/opt/DB4SCI/",
'bak_vol': "/opt/DB4SCI/backup",
'support': 'Basic',
'owner': Config.accounts['admindb']['owner'],
'description': 'Test the Dev',
'contact': Config.accounts['admindb']['contact'],
'life': 'long',
'backup_type': 'User',
'backup_freq': 'Daily',
'backup_life': '6',
'backup_window': 'any',
'phi': 'No',
'pitr': 'n',
'maintain': 'standard',
'username': Config.accounts['admindb']['admin'],
'image': Config.info[dbtype]['images'][0][1],
}
return params
| 33.728395 | 74 | 0.572474 |
c81ac0a63b1cfbd4a5899221057d1cd5c33bd1b0 | 1,080 | dart | Dart | lib/services/dialog-handler.dart | LeonardoBerlatto/flutter-todo-list | fffa2de72c102190959e3d12e4aaa8e3611b7d64 | [
"MIT"
] | 2 | 2020-03-04T16:38:43.000Z | 2020-03-05T03:19:00.000Z | lib/services/dialog-handler.dart | LeonardoBerlatto/flutter-todo-list | fffa2de72c102190959e3d12e4aaa8e3611b7d64 | [
"MIT"
] | null | null | null | lib/services/dialog-handler.dart | LeonardoBerlatto/flutter-todo-list | fffa2de72c102190959e3d12e4aaa8e3611b7d64 | [
"MIT"
] | null | null | null | import 'package:flutter/material.dart';
import 'package:todo_list/components/dialog/add-todo-dialog.dart';
import 'package:todo_list/components/dialog/error-dialog.dart';
import 'package:todo_list/models/todo.dart';
class DialogHandler {
Future<void> _displayDialog(BuildContext context, Widget dialog) {
return showGeneralDialog<void>(
context: context,
transitionBuilder: (context, firstAnimation, secondAnimation, widget) {
return Transform.scale(
scale: firstAnimation.value,
child: dialog,
);
},
transitionDuration: Duration(milliseconds: 250),
barrierDismissible: false,
barrierLabel: '',
pageBuilder: (context, animation1, animation2) {
return null;
});
}
void displayAddTodoDialog(BuildContext context, Function(ToDo) function) async {
await _displayDialog(context, AddToDoDialog(callback: function));
}
void displayErrrorDialog(BuildContext context, String text) async {
await _displayDialog(context, ErrorDialog(text));
}
}
| 32.727273 | 82 | 0.693519 |
14f33929387a0754bea0214b7adc149b782a6ccb | 284 | ts | TypeScript | src/entities/user-detail/user-detail.module.ts | ctorresm96/appnout-backend | 94a7c66f5d57edfe2c576021a743e87b44517e2c | [
"MIT"
] | null | null | null | src/entities/user-detail/user-detail.module.ts | ctorresm96/appnout-backend | 94a7c66f5d57edfe2c576021a743e87b44517e2c | [
"MIT"
] | null | null | null | src/entities/user-detail/user-detail.module.ts | ctorresm96/appnout-backend | 94a7c66f5d57edfe2c576021a743e87b44517e2c | [
"MIT"
] | null | null | null | import { Module } from '@nestjs/common';
import { UserDetailService } from './user-detail.service';
import { UserDetailController } from './user-detail.controller';
@Module({
controllers: [UserDetailController],
providers: [UserDetailService]
})
export class UserDetailModule {}
| 28.4 | 64 | 0.746479 |
0dc9ad1b07f5a392f5b4ff6cdac3ea2a21b154b8 | 2,050 | cs | C# | src/SFA.DAS.AssessorService.Web.UnitTests/StandardControllerTests/When_ConfirmStandard_Is_Posted_To_With_Specific_Version.cs | SkillsFundingAgency/das-assessor-service | c2587b4055d45024a02ea24d85323980383f2cd7 | [
"MIT"
] | 6 | 2018-07-17T15:53:24.000Z | 2022-02-20T13:14:31.000Z | src/SFA.DAS.AssessorService.Web.UnitTests/StandardControllerTests/When_ConfirmStandard_Is_Posted_To_With_Specific_Version.cs | SkillsFundingAgency/das-assessor-service | c2587b4055d45024a02ea24d85323980383f2cd7 | [
"MIT"
] | 503 | 2018-02-27T20:05:09.000Z | 2022-03-09T11:31:00.000Z | src/SFA.DAS.AssessorService.Web.UnitTests/StandardControllerTests/When_ConfirmStandard_Is_Posted_To_With_Specific_Version.cs | SkillsFundingAgency/das-assessor-service | c2587b4055d45024a02ea24d85323980383f2cd7 | [
"MIT"
] | 3 | 2020-01-20T13:55:38.000Z | 2021-04-11T08:33:04.000Z | using Moq;
using NUnit.Framework;
using SFA.DAS.AssessorService.Api.Types.Models.AO;
using SFA.DAS.AssessorService.ApplyTypes;
using SFA.DAS.AssessorService.Domain.Consts;
using SFA.DAS.AssessorService.Web.ViewModels.Apply;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SFA.DAS.AssessorService.Web.UnitTests.StandardControllerTests
{
[TestFixture]
public class When_ConfirmStandard_Is_Posted_To_With_Specific_Version : StandardControllerTestBase
{
[Test]
public async Task Then_UpdateStandardData_Is_Called()
{
// Arrange
_mockOrgApiClient
.Setup(r => r.GetAppliedStandardVersionsForEPAO(It.IsAny<string>(), "ST0001"))
.ReturnsAsync(new List<AppliedStandardVersion> {
new AppliedStandardVersion { IFateReferenceNumber = "ST0001", Title = "Title 1", Version = "1.0", LarsCode = 1, EPAChanged = false, ApprovedStatus = ApprovedStatus.NotYetApplied},
new AppliedStandardVersion { IFateReferenceNumber = "ST0001", Title = "Title 1", Version = "1.1", LarsCode = 1, EPAChanged = false, ApprovedStatus = ApprovedStatus.Approved},
new AppliedStandardVersion { IFateReferenceNumber = "ST0001", Title = "Title 1", Version = "1.2", LarsCode = 1, EPAChanged = false, ApprovedStatus = ApprovedStatus.NotYetApplied},
});
// Act
var model = new StandardVersionViewModel()
{
IsConfirmed = true,
};
await _sut.ConfirmStandard(model, Guid.NewGuid(), "ST0001", "1.2");
// Assert
_mockApiClient.Verify(m => m.UpdateStandardData(It.IsAny<Guid>(), 1, "ST0001", "Title 1",
It.Is<List<string>>(x => x.Count == 1 && x[0] == "1.2"), StandardApplicationTypes.Version));
_mockQnaApiClient.Verify(m => m.UpdateApplicationData(It.IsAny<Guid>(), It.Is<ApplicationData>(x => x.ApplicationType == StandardApplicationTypes.Version)));
}
}
}
| 47.674419 | 198 | 0.659024 |
1a5a8ab21d287d7d763ab7108f93e48bc1c7d53e | 237 | py | Python | Validation/HGCalValidation/python/hgcalDigiValidationEE_cfi.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | Validation/HGCalValidation/python/hgcalDigiValidationEE_cfi.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | Validation/HGCalValidation/python/hgcalDigiValidationEE_cfi.py | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | import FWCore.ParameterSet.Config as cms
from Validation.HGCalValidation.hgcalDigiValidationEEDefault_cfi import hgcalDigiValidationEEDefault as _hgcalDigiValidationEEDefault
hgcalDigiValidationEE = _hgcalDigiValidationEEDefault.clone()
| 59.25 | 133 | 0.911392 |
c39ba5f7951b5a475336fadfa8314c94350f61c4 | 1,674 | cs | C# | src/Gwi.OpenGL/Gwi.OpenGL/generated/enums/ProgramPropertyArb.cs | odalet/Gwi | 5761e1465ed307eabc068f031e09a6e484f6128e | [
"MIT"
] | null | null | null | src/Gwi.OpenGL/Gwi.OpenGL/generated/enums/ProgramPropertyArb.cs | odalet/Gwi | 5761e1465ed307eabc068f031e09a6e484f6128e | [
"MIT"
] | null | null | null | src/Gwi.OpenGL/Gwi.OpenGL/generated/enums/ProgramPropertyArb.cs | odalet/Gwi | 5761e1465ed307eabc068f031e09a6e484f6128e | [
"MIT"
] | null | null | null | // This file is auto generated, do not edit.
using System;
#pragma warning disable CA1069 // Enums values should not be duplicated
namespace Gwi.OpenGL
{
public enum ProgramPropertyArb : uint
{
ComputeWorkGroupSize = GLConstants.GL_COMPUTE_WORK_GROUP_SIZE,
ProgramBinaryLength = GLConstants.GL_PROGRAM_BINARY_LENGTH,
GeometryVerticesOut = GLConstants.GL_GEOMETRY_VERTICES_OUT,
GeometryInputType = GLConstants.GL_GEOMETRY_INPUT_TYPE,
GeometryOutputType = GLConstants.GL_GEOMETRY_OUTPUT_TYPE,
ActiveUniformBlockMaxNameLength = GLConstants.GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH,
ActiveUniformBlocks = GLConstants.GL_ACTIVE_UNIFORM_BLOCKS,
DeleteStatus = GLConstants.GL_DELETE_STATUS,
LinkStatus = GLConstants.GL_LINK_STATUS,
ValidateStatus = GLConstants.GL_VALIDATE_STATUS,
InfoLogLength = GLConstants.GL_INFO_LOG_LENGTH,
AttachedShaders = GLConstants.GL_ATTACHED_SHADERS,
ActiveUniforms = GLConstants.GL_ACTIVE_UNIFORMS,
ActiveUniformMaxLength = GLConstants.GL_ACTIVE_UNIFORM_MAX_LENGTH,
ActiveAttributes = GLConstants.GL_ACTIVE_ATTRIBUTES,
ActiveAttributeMaxLength = GLConstants.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH,
TransformFeedbackVaryingMaxLength = GLConstants.GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH,
TransformFeedbackBufferMode = GLConstants.GL_TRANSFORM_FEEDBACK_BUFFER_MODE,
TransformFeedbackVaryings = GLConstants.GL_TRANSFORM_FEEDBACK_VARYINGS,
ActiveAtomicCounterBuffers = GLConstants.GL_ACTIVE_ATOMIC_COUNTER_BUFFERS
}
}
#pragma warning restore CA1069 // Enums values should not be duplicated
| 52.3125 | 97 | 0.789128 |
dd9ca03a9a403aca3dfb6b455551d8a683f75886 | 12,245 | java | Java | DroidDLNA/src/main/java/org/fourthline/cling/android/AndroidRouter.java | guibiaoguo/TVRemotePlay | ecb909457769905285cdf720298171c9e51d6081 | [
"MIT"
] | 23 | 2018-07-05T09:14:32.000Z | 2022-02-23T03:14:16.000Z | DroidDLNA/src/main/java/org/fourthline/cling/android/AndroidRouter.java | guibiaoguo/TVRemotePlay | ecb909457769905285cdf720298171c9e51d6081 | [
"MIT"
] | 4 | 2019-04-12T09:13:22.000Z | 2022-01-26T15:50:46.000Z | DroidDLNA/src/main/java/org/fourthline/cling/android/AndroidRouter.java | guibiaoguo/TVRemotePlay | ecb909457769905285cdf720298171c9e51d6081 | [
"MIT"
] | 24 | 2018-08-22T12:09:00.000Z | 2022-03-21T07:34:42.000Z | /*
* Copyright (C) 2013 4th Line GmbH, Switzerland
*
* The contents of this file are subject to the terms of either the GNU
* Lesser General Public License Version 2 or later ("LGPL") or the
* Common Development and Distribution License Version 1 or later
* ("CDDL") (collectively, the "License"). You may not use this file
* except in compliance with the License. See LICENSE.txt for more
* information.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
package org.fourthline.cling.android;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import org.fourthline.cling.UpnpServiceConfiguration;
import org.fourthline.cling.model.ModelUtil;
import org.fourthline.cling.protocol.ProtocolFactory;
import org.fourthline.cling.transport.Router;
import org.fourthline.cling.transport.RouterException;
import org.fourthline.cling.transport.RouterImpl;
import org.fourthline.cling.transport.spi.InitializationException;
import org.seamless.util.Exceptions;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Monitors all network connectivity changes, switching the router accordingly.
*
* @author Michael Pujos
* @author Christian Bauer
*/
public class AndroidRouter extends RouterImpl {
final private static Logger log = Logger.getLogger(Router.class.getName());
final private Context context;
final private WifiManager wifiManager;
protected WifiManager.MulticastLock multicastLock;
protected WifiManager.WifiLock wifiLock;
protected NetworkInfo networkInfo;
protected BroadcastReceiver broadcastReceiver;
public AndroidRouter(UpnpServiceConfiguration configuration,
ProtocolFactory protocolFactory,
Context context) throws InitializationException {
super(configuration, protocolFactory);
this.context = context;
this.wifiManager = ((WifiManager) context.getSystemService(Context.WIFI_SERVICE));
this.networkInfo = NetworkUtils.getConnectedNetworkInfo(context);
// Only register for network connectivity changes if we are not running on emulator
if (!ModelUtil.ANDROID_EMULATOR) {
this.broadcastReceiver = new ConnectivityBroadcastReceiver();
context.registerReceiver(broadcastReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}
}
@Override
protected int getLockTimeoutMillis() {
return 15000;
}
@Override
public void shutdown() throws RouterException {
super.shutdown();
unregisterBroadcastReceiver();
}
@Override
public boolean enable() throws RouterException {
lock(writeLock);
try {
boolean enabled;
if ((enabled = super.enable())) {
// Enable multicast on the WiFi network interface,
// requires android.permission.CHANGE_WIFI_MULTICAST_STATE
if (isWifi()) {
setWiFiMulticastLock(true);
setWifiLock(true);
}
}
return enabled;
} finally {
unlock(writeLock);
}
}
@Override
public boolean disable() throws RouterException {
lock(writeLock);
try {
// Disable multicast on WiFi network interface,
// requires android.permission.CHANGE_WIFI_MULTICAST_STATE
if (isWifi()) {
setWiFiMulticastLock(false);
setWifiLock(false);
}
return super.disable();
} finally {
unlock(writeLock);
}
}
public NetworkInfo getNetworkInfo() {
return networkInfo;
}
public boolean isMobile() {
return NetworkUtils.isMobile(networkInfo);
}
public boolean isWifi() {
return NetworkUtils.isWifi(networkInfo);
}
public boolean isEthernet() {
return NetworkUtils.isEthernet(networkInfo);
}
public boolean enableWiFi() {
log.info("Enabling WiFi...");
try {
return wifiManager.setWifiEnabled(true);
} catch (Throwable t) {
// workaround (HTC One X, 4.0.3)
//java.lang.SecurityException: Permission Denial: writing com.android.providers.settings.SettingsProvider
// uri content://settings/system from pid=4691, uid=10226 requires android.permission.WRITE_SETTINGS
// at android.os.Parcel.readException(Parcel.java:1332)
// at android.os.Parcel.readException(Parcel.java:1286)
// at android.net.wifi.IWifiManager$Stub$Proxy.setWifiEnabled(IWifiManager.java:1115)
// at android.net.wifi.WifiManager.setWifiEnabled(WifiManager.java:946)
log.log(Level.WARNING, "SetWifiEnabled failed", t);
return false;
}
}
public void unregisterBroadcastReceiver() {
if (broadcastReceiver != null) {
context.unregisterReceiver(broadcastReceiver);
broadcastReceiver = null;
}
}
protected void setWiFiMulticastLock(boolean enable) {
if (multicastLock == null) {
multicastLock = wifiManager.createMulticastLock(getClass().getSimpleName());
}
if (enable) {
if (multicastLock.isHeld()) {
log.warning("WiFi multicast lock already acquired");
} else {
log.info("WiFi multicast lock acquired");
multicastLock.acquire();
}
} else {
if (multicastLock.isHeld()) {
log.info("WiFi multicast lock released");
multicastLock.release();
} else {
log.warning("WiFi multicast lock already released");
}
}
}
protected void setWifiLock(boolean enable) {
if (wifiLock == null) {
wifiLock = createWiFiLock();
}
if (enable) {
if (wifiLock.isHeld()) {
log.warning("WiFi lock already acquired");
} else {
log.info("WiFi lock acquired");
wifiLock.acquire();
}
} else {
if (wifiLock.isHeld()) {
log.info("WiFi lock released");
wifiLock.release();
} else {
log.warning("WiFi lock already released");
}
}
}
protected WifiManager.WifiLock createWiFiLock() {
int wifiMode = WifiManager.WIFI_MODE_FULL;
try {
// TODO: What's this?
Field f = WifiManager.class.getField("WIFI_MODE_FULL_HIGH_PERF");
wifiMode = f.getInt(null);
} catch (Exception e) {
// Ignore
}
WifiManager.WifiLock wifiLock =
wifiManager.createWifiLock(wifiMode, getClass().getSimpleName());
log.info("Created WiFi lock, mode: " + wifiMode);
return wifiLock;
}
/**
* Can be overriden by subclasses to do additional work.
*
* @param oldNetwork <code>null</code> when first called by constructor.
*/
protected void onNetworkTypeChange(NetworkInfo oldNetwork, NetworkInfo newNetwork) throws RouterException {
log.info(String.format("Network type changed %s => %s",
oldNetwork == null ? "" : oldNetwork.getTypeName(),
newNetwork == null ? "NONE" : newNetwork.getTypeName()));
if (disable()) {
log.info(String.format(
"Disabled router on network type change (old network: %s)",
oldNetwork == null ? "NONE" : oldNetwork.getTypeName()
));
}
networkInfo = newNetwork;
if (enable()) {
// Can return false (via earlier InitializationException thrown by NetworkAddressFactory) if
// no bindable network address found!
log.info(String.format(
"Enabled router on network type change (new network: %s)",
newNetwork == null ? "NONE" : newNetwork.getTypeName()
));
}
}
protected void handleRouterExceptionOnNetworkTypeChange(RouterException ex) {
Throwable cause = Exceptions.unwrap(ex);
if (cause instanceof InterruptedException) {
log.log(Level.INFO, "Router was interrupted: " + ex, cause);
} else {
throw new RuntimeException("Router error on network change: " + ex, ex);
}
}
class ConnectivityBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION))
return;
displayIntentInfo(intent);
NetworkInfo newNetworkInfo = NetworkUtils.getConnectedNetworkInfo(context);
// When Android switches WiFI => MOBILE, sometimes we may have a short transition
// with no network: WIFI => NONE, NONE => MOBILE
// The code below attempts to make it look like a single WIFI => MOBILE
// transition, retrying up to 3 times getting the current network.
//
// Note: this can block the UI thread for up to 3s
if (networkInfo != null && newNetworkInfo == null) {
for (int i = 1; i <= 3; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return;
}
log.warning(String.format(
"%s => NONE network transition, waiting for new network... retry #%d",
networkInfo.getTypeName(), i
));
newNetworkInfo = NetworkUtils.getConnectedNetworkInfo(context);
if (newNetworkInfo != null)
break;
}
}
if (isSameNetworkType(networkInfo, newNetworkInfo)) {
log.info("No actual network change... ignoring event!");
} else {
try {
onNetworkTypeChange(networkInfo, newNetworkInfo);
} catch (RouterException ex) {
handleRouterExceptionOnNetworkTypeChange(ex);
}
}
}
protected boolean isSameNetworkType(NetworkInfo network1, NetworkInfo network2) {
if (network1 == null && network2 == null)
return true;
if (network1 == null || network2 == null)
return false;
return network1.getType() == network2.getType();
}
protected void displayIntentInfo(Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
log.info("Connectivity change detected...");
log.info("EXTRA_NO_CONNECTIVITY: " + noConnectivity);
log.info("EXTRA_REASON: " + reason);
log.info("EXTRA_IS_FAILOVER: " + isFailover);
log.info("EXTRA_NETWORK_INFO: " + (currentNetworkInfo == null ? "none" : currentNetworkInfo));
log.info("EXTRA_OTHER_NETWORK_INFO: " + (otherNetworkInfo == null ? "none" : otherNetworkInfo));
log.info("EXTRA_EXTRA_INFO: " + intent.getStringExtra(ConnectivityManager.EXTRA_EXTRA_INFO));
}
}
} | 37.446483 | 129 | 0.611433 |
0cbc4b7ce5b4fde8324026ccc299428535d554fa | 2,855 | lua | Lua | src/tools/conf2conv/bak/__tpfestival_bingtest_endlesstower.lua | neyu/excel_tool | 6f511ea3de8d1a3ef4a61b0ef5d51ac809d4d5b7 | [
"MIT"
] | null | null | null | src/tools/conf2conv/bak/__tpfestival_bingtest_endlesstower.lua | neyu/excel_tool | 6f511ea3de8d1a3ef4a61b0ef5d51ac809d4d5b7 | [
"MIT"
] | null | null | null | src/tools/conf2conv/bak/__tpfestival_bingtest_endlesstower.lua | neyu/excel_tool | 6f511ea3de8d1a3ef4a61b0ef5d51ac809d4d5b7 | [
"MIT"
] | null | null | null | local Festival_BingTest_EndlessTower = {
[1] = {ID = 1, Stage = 1, FLOOR = 1, BOUNS = "0:2:5;", },
[2] = {ID = 2, Stage = 1, FLOOR = 2, BOUNS = "0:2:5;", },
[3] = {ID = 3, Stage = 1, FLOOR = 3, BOUNS = "0:2:5;", },
[4] = {ID = 4, Stage = 1, FLOOR = 4, BOUNS = "0:2:5;", },
[5] = {ID = 5, Stage = 1, FLOOR = 5, BOUNS = "0:2:5;", },
[6] = {ID = 6, Stage = 1, FLOOR = 6, BOUNS = "0:2:10;", },
[7] = {ID = 7, Stage = 1, FLOOR = 7, BOUNS = "0:2:10;", },
[8] = {ID = 8, Stage = 1, FLOOR = 8, BOUNS = "0:2:10;", },
[9] = {ID = 9, Stage = 1, FLOOR = 9, BOUNS = "0:2:10;", },
[10] = {ID = 10, Stage = 1, FLOOR = 10, BOUNS = "0:2:10;", },
[11] = {ID = 11, Stage = 2, FLOOR = 1, BOUNS = "0:2:5;0:1:5000;", },
[12] = {ID = 12, Stage = 2, FLOOR = 2, BOUNS = "0:2:5;0:1:10000;", },
[13] = {ID = 13, Stage = 2, FLOOR = 3, BOUNS = "0:2:5;0:1:15000;", },
[14] = {ID = 14, Stage = 2, FLOOR = 4, BOUNS = "0:2:5;0:1:20000;", },
[15] = {ID = 15, Stage = 2, FLOOR = 5, BOUNS = "0:2:5;0:1:25000;", },
[16] = {ID = 16, Stage = 2, FLOOR = 6, BOUNS = "0:2:10;0:1:30000;", },
[17] = {ID = 17, Stage = 2, FLOOR = 7, BOUNS = "0:2:10;0:1:35000;", },
[18] = {ID = 18, Stage = 2, FLOOR = 8, BOUNS = "0:2:10;0:1:40000;", },
[19] = {ID = 19, Stage = 2, FLOOR = 9, BOUNS = "0:2:10;0:1:45000;", },
[20] = {ID = 20, Stage = 2, FLOOR = 10, BOUNS = "0:2:10;0:1:50000;", },
[21] = {ID = 21, Stage = 3, FLOOR = 1, BOUNS = "0:2:10;0:1:20000;", },
[22] = {ID = 22, Stage = 3, FLOOR = 2, BOUNS = "0:2:10;0:1:30000;", },
[23] = {ID = 23, Stage = 3, FLOOR = 3, BOUNS = "0:2:10;0:1:40000;", },
[24] = {ID = 24, Stage = 3, FLOOR = 4, BOUNS = "0:2:10;0:1:50000;", },
[25] = {ID = 25, Stage = 3, FLOOR = 5, BOUNS = "0:2:10;0:1:60000;", },
[26] = {ID = 26, Stage = 3, FLOOR = 6, BOUNS = "0:2:15;0:1:80000;", },
[27] = {ID = 27, Stage = 3, FLOOR = 7, BOUNS = "0:2:15;0:1:100000;", },
[28] = {ID = 28, Stage = 3, FLOOR = 8, BOUNS = "0:2:15;0:1:120000;", },
[29] = {ID = 29, Stage = 3, FLOOR = 9, BOUNS = "0:2:15;0:1:140000;", },
[30] = {ID = 30, Stage = 3, FLOOR = 10, BOUNS = "0:2:15;0:1:160000;", },
[31] = {ID = 31, Stage = 7, FLOOR = 1, BOUNS = "0:2:20;0:1:50000;", },
[32] = {ID = 32, Stage = 7, FLOOR = 2, BOUNS = "0:2:20;0:1:60000;", },
[33] = {ID = 33, Stage = 7, FLOOR = 3, BOUNS = "0:2:20;0:1:70000;", },
[34] = {ID = 34, Stage = 7, FLOOR = 4, BOUNS = "0:2:20;0:1:80000;", },
[35] = {ID = 35, Stage = 7, FLOOR = 5, BOUNS = "0:1:90000;0:20000007:1;", },
[36] = {ID = 36, Stage = 7, FLOOR = 6, BOUNS = "0:2:30;0:1:110000;", },
[37] = {ID = 37, Stage = 7, FLOOR = 7, BOUNS = "0:2:30;0:1:130000;", },
[38] = {ID = 38, Stage = 7, FLOOR = 8, BOUNS = "0:2:30;0:1:150000;", },
[39] = {ID = 39, Stage = 7, FLOOR = 9, BOUNS = "0:2:30;0:1:170000;", },
[40] = {ID = 40, Stage = 7, FLOOR = 10, BOUNS = "0:1:190000;0:20000042:1;", }
}
return Festival_BingTest_EndlessTower | 66.395349 | 77 | 0.475306 |
bafb6bd92e2447aec3212abdb445adc3c52064f7 | 295 | lua | Lua | MMOCoreORB/bin/scripts/object/custom_content/tangible/furniture/all/frn_all_technical_console_s02.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/bin/scripts/object/custom_content/tangible/furniture/all/frn_all_technical_console_s02.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/bin/scripts/object/custom_content/tangible/furniture/all/frn_all_technical_console_s02.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z | object_tangible_furniture_all_frn_all_technical_console_s02 = object_tangible_furniture_all_shared_frn_all_technical_console_s02:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_all_frn_all_technical_console_s02, "object/tangible/furniture/all/frn_all_technical_console_s02.iff")
| 49.166667 | 155 | 0.918644 |
53ec618edacbc0bea23f8506d889fa5e08b35ade | 11,942 | swift | Swift | Sources/STU3/BackboneElement/CapabilityStatementRestResource.swift | samanthaerachelb/alexandria | 4bd7eb87c0719a28e11057e03eb7c77287ff1556 | [
"Apache-2.0"
] | null | null | null | Sources/STU3/BackboneElement/CapabilityStatementRestResource.swift | samanthaerachelb/alexandria | 4bd7eb87c0719a28e11057e03eb7c77287ff1556 | [
"Apache-2.0"
] | null | null | null | Sources/STU3/BackboneElement/CapabilityStatementRestResource.swift | samanthaerachelb/alexandria | 4bd7eb87c0719a28e11057e03eb7c77287ff1556 | [
"Apache-2.0"
] | null | null | null | //
// CapabilityStatementRestResource.swift
// Asclepius
// Module: STU3
//
// Copyright (c) 2022 Bitmatic Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import AsclepiusCore
/// A specification of the restful capabilities of the solution for a specific resource type
open class CapabilityStatementRestResource: BackboneElement {
/// A type of resource exposed via the restful interface
public var type: AsclepiusPrimitive<ResourceType>
/// Base system profile for all uses of resource
public var profile: AsclepiusPrimitive<Canonical>?
/// Profiles for use case suported
public var supportedProfile: [AsclepiusPrimitive<Canonical>]?
/// Additional information about the use of the resouce type
public var documentation: AsclepiusPrimitive<AsclepiusString>?
/// What operations are supported?
public var interaction: [CapabilityStatementRestResourceInteraction]?
/**
This filed is set to `no-version` to specify that the system does not support (server) or use (client)
versioning for this resouce type. If this has some other value, the server must at least correctly track and
populate the versionId meta-property on resources. If the value is `versioned-update` then the server
supports all the versioning features, including using e-tags for version integrity in the API
*/
public var versioning: AsclepiusPrimitive<ResourceVersionPolicy>?
/// Wheter vRead can return past versions
public var readHistory: AsclepiusPrimitive<AsclepiusBool>?
/// If update can commit to a new identity
public var updateCreate: AsclepiusPrimitive<AsclepiusBool>?
/// If allow/uses conditional create
public var conditionalCreate: AsclepiusPrimitive<AsclepiusBool>?
/// A code that indicates how the server supports conditional read
public var conditionalRead: AsclepiusPrimitive<ConditionalReadStatus>?
/// If allows/uses conditional update
public var conditionalUpdate: AsclepiusPrimitive<AsclepiusBool>?
/// A code that indicates how the server supports conditional delete
public var conditionalDelete: AsclepiusPrimitive<ConditionalDeleteStatus>?
/// A set of flags that defins how references are supported
public var referencePolicy: [AsclepiusPrimitive<ReferenceHandlingPolicy>]?
/// `_include` values supported by the server
public var searchInclude: [AsclepiusPrimitive<AsclepiusString>]?
/// `_revinclude` values suported by the server
public var searchRevInclude: [AsclepiusPrimitive<AsclepiusString>]?
/// search parameters supported by the implementation
public var searchParam: [CapabilityStatementRestResourceSearchParam]?
/// definition of a resource operation
public var operation: [CapabilityStatementRestResourceOperation]?
public init(type: AsclepiusPrimitive<ResourceType>) {
self.type = type
super.init()
}
public convenience init(
fhirExtension: [Extension]? = nil,
modifierExtension: [Extension]? = nil,
fhirId: AsclepiusPrimitive<AsclepiusString>? = nil,
type: AsclepiusPrimitive<ResourceType>,
profile: AsclepiusPrimitive<Canonical>? = nil,
supportedProfile: [AsclepiusPrimitive<Canonical>]? = nil,
documentation: AsclepiusPrimitive<AsclepiusString>? = nil,
interaction: [CapabilityStatementRestResourceInteraction]? = nil,
versioning: AsclepiusPrimitive<ResourceVersionPolicy>? = nil,
readHistory: AsclepiusPrimitive<AsclepiusBool>? = nil,
updateCreate: AsclepiusPrimitive<AsclepiusBool>? = nil,
conditionalCreate: AsclepiusPrimitive<AsclepiusBool>? = nil,
conditionalRead: AsclepiusPrimitive<ConditionalReadStatus>? = nil,
conditionalUpdate: AsclepiusPrimitive<AsclepiusBool>? = nil,
conditionalDelete: AsclepiusPrimitive<ConditionalDeleteStatus>? = nil,
referencePolicy: [AsclepiusPrimitive<ReferenceHandlingPolicy>]? = nil,
searchInclude: [AsclepiusPrimitive<AsclepiusString>]? = nil,
searchRevInclude: [AsclepiusPrimitive<AsclepiusString>]? = nil,
searchParam: [CapabilityStatementRestResourceSearchParam]? = nil,
operation: [CapabilityStatementRestResourceOperation]? = nil
) {
self.init(type: type)
self.fhirExtension = fhirExtension
self.modifierExtension = modifierExtension
self.fhirId = fhirId
self.profile = profile
self.supportedProfile = supportedProfile
self.documentation = documentation
self.interaction = interaction
self.versioning = versioning
self.readHistory = readHistory
self.updateCreate = updateCreate
self.conditionalCreate = conditionalCreate
self.conditionalRead = conditionalRead
self.conditionalUpdate = conditionalUpdate
self.conditionalDelete = conditionalDelete
self.referencePolicy = referencePolicy
self.searchInclude = searchInclude
self.searchRevInclude = searchRevInclude
self.searchParam = searchParam
self.operation = operation
}
// MARK: - Codable
private enum CodingKeys: String, CodingKey {
case type; case _type
case profile; case _profile
case supportedProfile; case _supportedProfile
case documentation; case _documentation
case interaction
case versioning; case _versioning
case readHistory; case _readHistory
case updateCreate; case _updateCreate
case conditionalCreate; case _conditionalCreate
case conditionalRead; case _conditionalRead
case conditionalUpdate; case _conditionalUpdate
case conditionalDelete; case _conditionalDelete
case referencePolicy; case _referencePolicy
case searchInclude; case _searchInclude
case searchRevInclude; case _searchRevInclude
case searchParam
case operation
}
public required init(from decoder: Decoder) throws {
let codingKeyContainer = try decoder.container(keyedBy: CodingKeys.self)
self.type = try AsclepiusPrimitive<ResourceType>(from: codingKeyContainer, forKey: .type, auxKey: ._type)
self.profile = try AsclepiusPrimitive<Canonical>(from: codingKeyContainer, forKeyIfPresent: .profile, auxKey: ._profile)
self.supportedProfile = try [AsclepiusPrimitive<Canonical>](from: codingKeyContainer, forKeyIfPresent: .supportedProfile, auxKey: ._supportedProfile)
self.documentation = try AsclepiusPrimitive<AsclepiusString>(from: codingKeyContainer, forKeyIfPresent: .documentation, auxKey: ._documentation)
self.interaction = try [CapabilityStatementRestResourceInteraction](from: codingKeyContainer, forKeyIfPresent: .interaction)
self.versioning = try AsclepiusPrimitive<ResourceVersionPolicy>(from: codingKeyContainer, forKeyIfPresent: .versioning, auxKey: ._versioning)
self.readHistory = try AsclepiusPrimitive<AsclepiusBool>(from: codingKeyContainer, forKeyIfPresent: .readHistory, auxKey: ._readHistory)
self.conditionalCreate = try AsclepiusPrimitive<AsclepiusBool>(from: codingKeyContainer, forKeyIfPresent: .conditionalCreate, auxKey: ._conditionalCreate)
self.conditionalRead = try AsclepiusPrimitive<ConditionalReadStatus>(from: codingKeyContainer, forKeyIfPresent: .conditionalRead, auxKey: ._conditionalRead)
self.conditionalUpdate = try AsclepiusPrimitive<AsclepiusBool>(from: codingKeyContainer, forKeyIfPresent: .conditionalUpdate, auxKey: ._conditionalUpdate)
self.conditionalDelete = try AsclepiusPrimitive<ConditionalDeleteStatus>(from: codingKeyContainer, forKeyIfPresent: .conditionalDelete, auxKey: ._conditionalDelete)
self.referencePolicy = try [AsclepiusPrimitive<ReferenceHandlingPolicy>](from: codingKeyContainer, forKeyIfPresent: .referencePolicy, auxKey: ._referencePolicy)
self.searchInclude = try [AsclepiusPrimitive<AsclepiusString>](from: codingKeyContainer, forKeyIfPresent: .searchInclude, auxKey: ._searchInclude)
self.searchRevInclude = try [AsclepiusPrimitive<AsclepiusString>](from: codingKeyContainer, forKeyIfPresent: .searchRevInclude, auxKey: ._searchRevInclude)
self.searchParam = try [CapabilityStatementRestResourceSearchParam](from: codingKeyContainer, forKeyIfPresent: .searchParam)
self.operation = try [CapabilityStatementRestResourceOperation](from: codingKeyContainer, forKeyIfPresent: .operation)
try super.init(from: decoder)
}
override public func encode(to encoder: Encoder) throws {
var codingKeyContainer = encoder.container(keyedBy: CodingKeys.self)
try type.encode(on: &codingKeyContainer, forKey: .type, auxKey: ._type)
try profile?.encode(on: &codingKeyContainer, forKey: .profile, auxKey: ._profile)
try supportedProfile?.encode(on: &codingKeyContainer, forKey: .profile, auxKey: ._profile)
try documentation?.encode(on: &codingKeyContainer, forKey: .documentation, auxKey: ._documentation)
try interaction?.encode(on: &codingKeyContainer, forKey: .interaction)
try versioning?.encode(on: &codingKeyContainer, forKey: .versioning, auxKey: ._versioning)
try readHistory?.encode(on: &codingKeyContainer, forKey: .readHistory, auxKey: ._readHistory)
try conditionalCreate?.encode(on: &codingKeyContainer, forKey: .conditionalCreate, auxKey: ._conditionalCreate)
try conditionalRead?.encode(on: &codingKeyContainer, forKey: .conditionalRead, auxKey: ._conditionalRead)
try conditionalUpdate?.encode(on: &codingKeyContainer, forKey: .conditionalUpdate, auxKey: ._conditionalUpdate)
try conditionalDelete?.encode(on: &codingKeyContainer, forKey: .conditionalDelete, auxKey: ._conditionalDelete)
try referencePolicy?.encode(on: &codingKeyContainer, forKey: .referencePolicy, auxKey: ._referencePolicy)
try searchInclude?.encode(on: &codingKeyContainer, forKey: .searchInclude, auxKey: ._searchInclude)
try searchRevInclude?.encode(on: &codingKeyContainer, forKey: .searchRevInclude, auxKey: ._searchRevInclude)
try searchParam?.encode(on: &codingKeyContainer, forKey: .searchParam)
try operation?.encode(on: &codingKeyContainer, forKey: .operation)
try super.encode(to: encoder)
}
// MARK: - Equatable
override public func isEqual(to _other: Any?) -> Bool {
guard let _other = _other as? CapabilityStatementRestResource else {
return false
}
guard super.isEqual(to: _other) else {
return false
}
return type == _other.type
&& profile == _other.profile
&& supportedProfile == _other.supportedProfile
&& documentation == _other.documentation
&& interaction == _other.interaction
&& versioning == _other.versioning
&& readHistory == _other.readHistory
&& conditionalCreate == _other.conditionalCreate
&& conditionalRead == _other.conditionalRead
&& conditionalUpdate == _other.conditionalUpdate
&& conditionalDelete == _other.conditionalDelete
&& referencePolicy == _other.referencePolicy
&& searchInclude == _other.searchInclude
&& searchRevInclude == _other.searchRevInclude
&& operation == _other.operation
}
// MARK: - Hashable
override public func hash(into hasher: inout Hasher) {
super.hash(into: &hasher)
hasher.combine(type)
hasher.combine(profile)
hasher.combine(documentation)
hasher.combine(interaction)
hasher.combine(versioning)
hasher.combine(readHistory)
hasher.combine(conditionalCreate)
hasher.combine(conditionalRead)
hasher.combine(conditionalUpdate)
hasher.combine(conditionalDelete)
hasher.combine(referencePolicy)
hasher.combine(searchInclude)
hasher.combine(searchRevInclude)
hasher.combine(operation)
}
}
| 49.966527 | 168 | 0.768883 |
08b3b3990163f51ebac4d6093590206576a24f5b | 11,606 | css | CSS | src/main/webapp/resources/cmmnty/english/css/contents.css | tenbirds/OPENWORKS-3.0 | d9ea72589854380d7ad95a1df7e5397ad6d726a6 | [
"Apache-2.0"
] | null | null | null | src/main/webapp/resources/cmmnty/english/css/contents.css | tenbirds/OPENWORKS-3.0 | d9ea72589854380d7ad95a1df7e5397ad6d726a6 | [
"Apache-2.0"
] | null | null | null | src/main/webapp/resources/cmmnty/english/css/contents.css | tenbirds/OPENWORKS-3.0 | d9ea72589854380d7ad95a1df7e5397ad6d726a6 | [
"Apache-2.0"
] | null | null | null | @charset "utf-8";
/* =============================================================================
contents.css는 1depth까지만 주석으로 되어있습니다. (중요부분 예외처리)
========================================================================== */
/* ------------------------------------------------------------------
* 커뮤니티 메인
* ------------------------------------------------------------------*/
#contents h2{height:22px; margin-bottom:25px; color:#262425; font-weight:normal; font-family:'NanumGothicBold'; font-size:20px;}
#contents .notice_area .notice h2{height:15px; margin-bottom:0; padding-bottom:10px; border-bottom:2px solid #2b2b2b; font-size:14px;}
.community_Join{width:200px; height:63px; padding-top:30px; background:url('/resources/cmmnty/english/images/common/bg/bg_login_before.gif') no-repeat left top; text-align:center;}
.main >*:first-child{margin-top:0;}
.notice_area{overflow:hidden; width:100%; margin-top:50px;}
.notice_area .notice{position:relative; float:left; width:360px; margin-left:35px;}
.notice_area >*:first-child{margin-left:0;}
.notice_area .notice ul.list{overflow:hidden; min-height:112px; margin-top:12px; padding-bottom:21px; border-bottom:1px solid #e4e4e4;}
.notice_area .notice ul.list li{display:inline-block; width:348px; height:14px; margin-top:11px; padding-left:12px; background:url('/resources/cmmnty/english/images/common/bul/bul_squ_cb.gif') no-repeat left 4px;}
.notice_area .notice ul.list li a{float:left; color:#737373;}
.notice_area .notice ul.list li .tit{float:left; min-width:48px; color:#acacac;}
.notice_area .notice ul.list li em{color:#ff7a00;}
.notice_area .notice ul.list li .date{float:right; color:#acacac; font-size:11px; font-family:'Dotum';}
.notice_area .notice .btn_more{position:absolute; top:2px; right:0;}
.notice_area .notice ul.photo_list{margin-top:14px;}
.notice_area .notice ul.photo_list >*:first-child{margin-left:0;}
.notice_area .notice ul.photo_list > li{float:left; width:109px; margin-left:15px;}
.notice_area .notice ul.photo_list .photo img{width:109px; height:82px;}
.notice_area .notice ul.photo_list > li > ul > li{font-size:11px;}
.notice_area .notice ul.photo_list > li > ul > li.date{margin-top:10px; color:#acacac; font-family:'Dotum';}
.notice_area .notice ul.photo_list > li > ul > li.inquiry{margin-top:4px; color:#acacac; font-family:'Dotum';}
.notice_area .notice ul.photo_list > li > ul > li.inquiry .name{padding-left:7px; background:url('/resources/cmmnty/english/images/common/bul/bul_e4.gif') no-repeat left 2px;}
.notice_area .notice ul.photo_list > li > ul > li.name{margin-top:2px; color:#737373;}
/* ------------------------------------------------------------------
* 커뮤니티 정보
* ------------------------------------------------------------------*/
.community_Login{position:relative; width:200px; height:105px; background:url('/resources/cmmnty/english/images/common/bg/bg_login_after.gif') no-repeat left top;}
.community_Login p{height:44px; padding-left:15px; color:#737373; line-height:44px;}
.community_Login p.ico{margin-left:15px; padding-left:20px; background:url('/resources/cmmnty/english/images/common/ico/ico_admin.png') no-repeat left center; color:#333; font-weight:normal; font-family:'NanumGothicBold';}
.community_Login strong{color:#333; font-family:'NanumGothicBold'; font-weight:normal;}
.community_Login ul{overflow:hidden; width:185px; margin:7px 0 0 15px;}
.community_Login ul li{overflow:hidden; margin-top:7px; padding-left:15px; background:url('/resources/cmmnty/english/images/common/ico/ico_write.gif') no-repeat left 1px; color:#737373; font-size:11px;}
.community_Login ul li .txt{float:left; width:100px;}
.community_Login ul li .num{float:right; margin-right:15px;}
.community_Login ul li .num em{font-family:'NanumGothicBold'; font-weight:normal;}
.community_Login .setting{position:absolute; top:15px; right:15px;}
.community_Login .admin{margin-top:7px; text-align:center;}
.community_Login .admin .txt{margin-bottom:5px; color:#333; font-size:14px; font-family:'NanumGothicBold'; font-weight:normal;}
.community_Login .join{width:100%; height:60px; text-align:center;}
.community_Login .join .btn_light_gray{margin-top:17px;}
.cont_wrap{position:absolute; top:0; right:0;}
.cont_wrap .selected{float:left; margin:0 10px 0 0;}
.cont_wrap .selected .selectbox_title{padding:6px 10px 6px; background:url('/resources/cmmnty/english/images/btn/btn_select_02.gif') no-repeat right center;}
.cont_wrap .search{float:left;}
.cont_wrap .btn_org{float:left; margin-left:15px;}
.search{width:233px; height:29px; border:1px solid #d5d5d5; background:url('/resources/cmmnty/english/images/btn/btn_search_02.gif') no-repeat right top;}
.search .input{float:left; width:185px; height:27px; padding-left:5px; border:none; color:#666; line-height:27px;}
.search .btn{float:right; width:30px; height:29px; padding:0; background:none; border:none; text-indent:-9999px; cursor:pointer;}
.btn_area{overflow:hidden; width:100%; height:32px; margin-top:20px; text-align:center;}
.btn_area .btn_l{float:left;}
.btn_area .btn_r{float:right;}
.closing{width:85px; margin:30px 0 0 15px; background:url('/resources/cmmnty/english/images/common/bul/bul_arrow.gif') no-repeat right 3px;; color:#848383; font-size:12px;}
.closing a{color:#848383; text-decoration:none;}
.closing a.on{color:#ff7a00;}
/* ------------------------------------------------------------------
* 게시판
* ------------------------------------------------------------------*/
/* 기본형 게시판 상세 */
.reply_box{/*margin-top:60px;*/ width:100%;}
.comment_area{padding:0 20px 20px; background:#f7f7f7;}
.comment_area .textarea{position:relative; width:714px; height:62px; margin-top:20px; border:1px solid #e4e4e4; background:#fff;}
.comment_area .textarea textarea{width:634px; height:62px; border:none; line-height:16px;}
.comment_area .textarea input{position:absolute; top:0; right:0;}
.comment_area .textarea img{position:absolute; top:0; right:0;}
.comment_area .comment_list{overflow:hidden; width:100%;}
.comment_area .comment_list ul li{overflow:hidden; padding:18px 0 0 0;}
.comment_area .comment_list ul li.comment:last-child{padding-bottom:0; border-bottom:none;}
.comment_area .comment_list ul li.comment{padding:15px 0 17px 0; border-bottom:1px dotted #bbb; color:#737373; line-height:18px;}
.comment_area .comment_list ul li.comment .reply{padding:0 35px;}
.comment_area .comment_list ul li .cont_l ul li{overflow:hidden; padding-bottom:17px; border-bottom:1px dotted #bbb;}
.comment_area .comment_list ul li .cont_l{float:left;}
.comment_area .comment_list ul li .cont_l strong{float:left; color:#333; font-weight:normal; font-family:'NanumGothicBold';}
.comment_area .comment_list ul li .cont_l .date{float:left; margin-left:12px; color:#acacac; font-size:11px;}
.comment_area .comment_list ul li .cont_l .btn_reply{float:left; margin:2px 0 0 30px; padding-left:12px; background:url('/resources/cmmnty/english/images/common/ico/ico_reply.gif') no-repeat left 2px; color:#737373; font-size:11px;}
.comment_area .comment_list ul li .cont_l .btn_reply a{color:#737373; text-decoration:none;}
.comment_area .comment_list ul li .cont_r{float:right;}
.comment_area .comment_list ul li .cont_r ul li{float:left; margin:0 0 0 6px; padding:0 0 0 6px; background:url('/resources/cmmnty/english/images/common/bul/bul_d.gif') no-repeat left 2px; font-size:11px;}
.comment_area .comment_list ul li .cont_r ul >*:first-child{margin-left:0; padding-left:0; background:none;}
.comment_area .comment_list ul li .cont_r ul li a{color:#737373; text-decoration:none;}
.comment_area .comment_list ul li.reply{padding:0 20px;}
.comment_area .comment_list ul li.reply .textarea{width:674px;}
.comment_area .comment_list ul li.reply .textarea textarea{width:594px;}
.comment_area .comment_list ul li.reply_list{padding:18px 20px 0;}
.comment_area .comment_list ul li.reply_list .cont_l strong{padding-left:14px; background:url('/resources/cmmnty/english/images/common/ico/ico_reply_arrow.gif') no-repeat left 4px;}
/* 사진게시판 */
.photo_area{overflow:hidden; border-top:2px solid #ff7a00;}
.photo_area > ul > li{float:left; width:100%; padding:15px 0; border-bottom:1px solid #e4e4e4;}
.photo_area > ul > li .photo{width:168px; height:125px; border:1px solid #e4e4e4; text-align:center; line-height:125px;}
.photo_area > ul > li .photo img{vertical-align:middle;}
.photo_area > ul > li > ul > li{float:left; margin-left:15px; color:#737373;}
.photo_area > ul > li > ul > li .date{margin-top:12px;}
.photo_area > ul > li > ul > li .inquiry{margin-top:6px;}
.photo_area > ul > li > ul > li .inquiry .num{display:inline-block; margin-left:6px; padding-left:7px; background:url('/resources/cmmnty/english/images/common/bul/bul_e4.gif') no-repeat left 2px;}
.photo_area > ul > li > ul > li .name{margin-top:3px;}
/* 커뮤니티 폐쇄 */
.postpone{padding:15px 0 15px 10px; border-top:2px solid #ff8a00; border-bottom:1px solid #e4e4e4; color:#737373; line-height:21px;}
.postpone .notice{color:#333; font-weight:normal; font-family:'NanumGothicBold'; font-size:13px;}
.postpone .notice .day{color:#ff7a00;}
.postpone ul {overflow:hidden; margin:30px 0;}
.postpone ul li{padding-left:8px; background:url('/resources/cmmnty/english/images/common/bul/bul_84.gif') no-repeat left 7px;}
.postpone ul li span{display:inline-block; width:120px;}
.postpone .point{color:#ff8a00;}
.postpone .reason{margin:30px 0 10px; color:#333; font-family:'NanumGothicBold';}
.postpone .reason textarea{display:block; margin-top:10px;}
/* 통계 */
.statistics{overflow:hidden; padding:20px 15px; border-top:2px solid #ff8a00; border-bottom:1px solid #e4e4e4;}
.statistics .btn{float:left;}
.statistics .btn .btn_light_gray02{margin-left:6px;}
.statistics .btn_light_gray02 .daily{color:#ff7a00;}
.statistics .select{float:left; margin-left:10px;}
.statistics .btn_search{float:left; margin-left:10px;}
.statistics .graph{clear:both; width:755px; padding-top:15px;}
/* 게시판 */
.board{overflow:hidden; padding:20px 15px; border-top:2px solid #ff8a00; border-bottom:1px solid #e4e4e4;}
.board .menu{float:left; width:208px; min-height:494px; border:1px solid #e4e4e4;}
.board .menu .function{height:33px; padding-top:9px; background:#f7f7f7; text-align:center;}
.board .menu ul{width:163px; margin:0 auto;}
.board .menu ul li{border-bottom:1px dotted #b9b9b9; font-family:'NanumGothicBold';}
.board .menu ul li a{display:block; padding:13px 0 13px 0; text-decoration:none;}
.board .menu ul li a.on{color:#ff7a00;}
.board .menu ul >*:first-child a{padding-left:8px; background:url('/resources/cmmnty/english/images/common/bul/bul_squ_black.gif') no-repeat left center;}
.board .menu ul >*:first-child + * a{padding-left:8px; background:url('/resources/cmmnty/english/images/common/bul/bul_squ_black.gif') no-repeat left center;}
.board .menu ul >*:first-child + * + * a{padding-left:8px; background:url('/resources/cmmnty/english/images/common/bul/bul_squ_black.gif') no-repeat left center;}
.board .write{float:left; width:504px; margin-left:12px;}
.board .write table{width:100%; border-top:1px solid #e4e4e4;}
.board .write table td{height:14px; padding:14px 0 14px 15px; border-bottom:1px solid #e4e4e4; text-align:left;}
.board .write table td.tit{padding-left:25px; border-right:1px dotted #c7c7c7; color:#333;}
.board .write table td .point{margin-left:-10px; padding-left:10px; background:url('/resources/cmmnty/english/images/common/bul/bul_star.gif') no-repeat left 4px;}
.board .write table td .byte{display:block; margin:6px 29px 0 0; color:#aaa8a8; font-family:'Dotum'; font-size:11px; text-align:right;}
.board .write table td .byte em{color:#ff8a00;} | 76.355263 | 232 | 0.721868 |
cdeecf9abeaecf68db493f828e78bf94a01782be | 222 | cs | C# | firstDuplicateNumber.cs | JackieG19/codesignal | 270216414208b660c3c4e440315248decd6456a9 | [
"MIT"
] | null | null | null | firstDuplicateNumber.cs | JackieG19/codesignal | 270216414208b660c3c4e440315248decd6456a9 | [
"MIT"
] | null | null | null | firstDuplicateNumber.cs | JackieG19/codesignal | 270216414208b660c3c4e440315248decd6456a9 | [
"MIT"
] | null | null | null | int firstDuplicateNumber(int[] array) {
for(int i = 0; i < array.length; i++)
{
for(int j = 0; j < i; j++)
{
if(array[i] == array[j])
{
return array[i];
}
}
return -1;
}
}
| 15.857143 | 39 | 0.432432 |
b1394faad06d2bd397916fde81036a497628f87c | 1,479 | py | Python | setup.py | CWE0/rainflow | 7048f1c637f4fd40302c517e54deb3d6eddd6b21 | [
"MIT"
] | null | null | null | setup.py | CWE0/rainflow | 7048f1c637f4fd40302c517e54deb3d6eddd6b21 | [
"MIT"
] | null | null | null | setup.py | CWE0/rainflow | 7048f1c637f4fd40302c517e54deb3d6eddd6b21 | [
"MIT"
] | null | null | null | from setuptools import setup
import os
this_dir = os.path.dirname(__file__)
with open(os.path.join(this_dir, "README.md"), "rb") as fo:
long_description = fo.read().decode("utf8")
setup(
name='rainflow',
package_dir={"": "src"},
py_modules=['rainflow'],
description='Implementation of ASTM E1049-85 rainflow cycle counting algorithm',
install_requires=["importlib_metadata ; python_version < '3.8'"],
extras_require={"dev": ["pytest ~= 4.6"]},
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, <4",
setup_requires=["setuptools_scm"],
use_scm_version=True,
long_description=long_description,
long_description_content_type='text/markdown',
author='Piotr Janiszewski',
url='https://github.com/iamlikeme/rainflow/',
license="MIT",
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Topic :: Scientific/Engineering",
"Topic :: Software Development :: Libraries :: Python Modules",
],
)
| 36.073171 | 84 | 0.628127 |
d05a883ddf9c9707c89ad87fd2660c45d3b9ae24 | 10,981 | cc | C++ | src/tools/detector_repeatability.cc | jackyspeed/libmv | aae2e0b825b1c933d6e8ec796b8bb0214a508a84 | [
"MIT"
] | 160 | 2015-01-16T19:35:28.000Z | 2022-03-16T02:55:30.000Z | src/tools/detector_repeatability.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 3 | 2015-04-04T17:54:35.000Z | 2015-12-15T18:09:03.000Z | src/tools/detector_repeatability.cc | rgkoo/libmv-blender | cdf65edbb80d8904e2df9a20116d02546df93a81 | [
"MIT"
] | 51 | 2015-01-12T08:38:12.000Z | 2022-02-19T06:37:25.000Z | // Copyright (c) 2010 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <fstream>
#include <iostream>
#include "libmv/base/scoped_ptr.h"
#include "libmv/base/vector.h"
#include "libmv/base/vector_utils.h"
#include "libmv/correspondence/feature.h"
#include "libmv/detector/detector.h"
#include "libmv/detector/fast_detector.h"
#include "libmv/detector/star_detector.h"
#include "libmv/detector/surf_detector.h"
#include "libmv/image/image.h"
#include "libmv/image/image_converter.h"
#include "libmv/image/image_drawing.h"
#include "libmv/image/image_io.h"
#include "libmv/tools/tool.h"
using namespace libmv;
using namespace std;
void usage() {
LOG(ERROR) << " repreatability ImageReference ImageA ImageB ... " <<std::endl
<< " ImageReference : the input image on which features will be extrated,"
<< std::endl
<< " ImageA : an image to test repeatability with ImageReference"
<< std::endl
<< " ImageB : an image to test repeatability with ImageReference"
<< std::endl
<< " ... : images names to test repeatability with ImageReference"
<< std::endl
<< " Gound truth transformation between ImageReference and ImageX is named\
in ImageX.txt"
<< " INFO : !!! experimental !!! ." << std::endl;
}
enum eDetectorType
{
FAST_DETECTOR = 0,
SURF_DETECTOR = 1,
STAR_DETECTOR = 2
};
// Detect features over the image im with the choosen detector type.
bool detectFeatures(const eDetectorType DetectorType,
const Image & im,
libmv::vector<libmv::Feature *> * featuresOut);
// Search how many feature are considered as repeatable.
// Ground Truth transformation is encoded in a matrix saved into a file.
// Example : ImageNameB.jpg.txt encode the transformation matrix from
// imageReference to ImageNameB.jpg.
bool testRepeatability(const libmv::vector<libmv::Feature *> & featuresA,
const libmv::vector<libmv::Feature *> & featuresB,
const string & ImageNameB,
const Image & imageB,
libmv::vector<double> * exportedData = NULL,
ostringstream * stringStream = NULL);
int main(int argc, char **argv) {
libmv::Init("Extract features from on images series and test detector \
repeatability", &argc, &argv);
if (argc < 3 ||
(GetFormat(argv[1])==Unknown && GetFormat(argv[2])==Unknown)) {
usage();
LOG(ERROR) << "Missing parameters or errors in the command line.";
return 1;
}
// Parse input parameter.
const string sImageReference = argv[1];
ByteImage byteImage;
if ( 0 == ReadImage( sImageReference.c_str(), &byteImage) ) {
LOG(ERROR) << "Invalid inputImage.";
return 1;
}
Image imageReference(new ByteImage(byteImage));
if( byteImage.Depth() == 3)
{
// Convert Image to desirable format => uchar 1 gray channel
ByteImage byteImageGray;
Rgb2Gray(byteImage, &byteImageGray);
imageReference=Image(new ByteImage(byteImageGray));
}
eDetectorType DETECTOR_TYPE = FAST_DETECTOR;
libmv::vector<libmv::Feature *> featuresRef;
if ( !detectFeatures( DETECTOR_TYPE,
imageReference,
&featuresRef))
{
LOG(ERROR) << "No feature found on Reference Image.";
return 1;
}
libmv::vector<double> repeatabilityStat;
// Run repeatability test on the N remaining images.
for(int i = 2; i < argc; ++i)
{
const string sImageToCompare = argv[i];
libmv::vector<libmv::Feature *> featuresToCompare;
if ( 0 == ReadImage( sImageToCompare.c_str(), &byteImage) ) {
LOG(ERROR) << "Invalid inputImage (Image to compare to reference).";
return 1;
}
Image imageToCompare(new ByteImage(byteImage));
if( byteImage.Depth() == 3)
{
// Convert Image to desirable format => uchar 1 gray channel
ByteImage byteImageGray;
Rgb2Gray(byteImage, &byteImageGray);
imageToCompare = Image(new ByteImage(byteImageGray));
}
if (detectFeatures(DETECTOR_TYPE,
imageToCompare,
&featuresToCompare))
{
testRepeatability( featuresRef,
featuresToCompare,
sImageToCompare + string(".txt"),
imageToCompare,
&repeatabilityStat);
}
else
{
LOG(INFO) << "Image : " << sImageToCompare
<< " have no feature detected with the choosen detector.";
}
DeleteElements(&featuresToCompare);
}
// Export data :
ofstream fileStream("Repeatability.xls");
fileStream << "RepeatabilityStats" << endl;
fileStream << "ImageName \t Feature In Reference \t Features In ImageName \
\t Position Repeatability \t Position Accuracy" << endl;
int cpt=0;
for (int i = 2; i < argc; ++i) {
fileStream << argv[i] << "\t";
for (int j=0; j < repeatabilityStat.size()/(argc-2); ++j) {
fileStream << repeatabilityStat[cpt] << "\t";
cpt++;
}
fileStream << endl;
}
DeleteElements(&featuresRef);
fileStream.close();
}
bool detectFeatures(const eDetectorType DetectorType,
const Image & im,
libmv::vector<libmv::Feature *> * featuresOut)
{
using namespace detector;
switch (DetectorType) {
case FAST_DETECTOR:
{
scoped_ptr<Detector> detector(CreateFastDetector(9, 30));
detector->Detect( im, featuresOut, NULL);
}
break;
case SURF_DETECTOR:
{
scoped_ptr<Detector> detector(CreateSURFDetector());
detector->Detect( im, featuresOut, NULL);
}
break;
case STAR_DETECTOR:
{
scoped_ptr<Detector> detector(CreateStarDetector());
detector->Detect( im, featuresOut, NULL);
}
break;
default:
{
scoped_ptr<Detector> detector(CreateFastDetector(9, 30));
detector->Detect( im, featuresOut, NULL);
}
}
return (featuresOut->size() >= 1);
}
bool testRepeatability(const libmv::vector<libmv::Feature *> & featuresA,
const libmv::vector<libmv::Feature *> & featuresB,
const string & ImageNameB,
const Image & imageB,
libmv::vector<double> * exportedData,
ostringstream * stringStream)
{
// Config Threshold for repeatability
const double distThreshold = 1.5;
//
Mat3 transfoMatrix;
if(ImageNameB.size() > 0 ) {
// Read transformation matrix from data
ifstream file( ImageNameB.c_str());
if(file.is_open()) {
for(int i=0; i<3*3; ++i) {
file>>transfoMatrix(i);
}
// Transpose cannot be used inplace.
Mat3 temp = transfoMatrix.transpose();
transfoMatrix = temp;
}
else {
LOG(ERROR) << "Invalid input transformation file.";
if (stringStream) {
(*stringStream) << "Invalid input transformation file.";
}
if(exportedData) {
exportedData->push_back(featuresA.size());
exportedData->push_back(featuresB.size());
exportedData->push_back(0);
exportedData->push_back(0);
}
return 0;
}
}
int nbRepeatable = 0;
int nbRepeatablePossible = 0;
double localisationError = 0;
for (int iA=0; iA < featuresA.size(); ++iA) {
const libmv::PointFeature * featureA =
dynamic_cast<libmv::PointFeature *>( featuresA[iA] );
// Project A into the image coord system B.
Vec3 pos; pos << featureA->x(), featureA->y(), 1.0;
Vec3 transformed = transfoMatrix * pos;
transformed/=transformed(2);
//Search the nearest featureB
double distanceSearch = std::numeric_limits<double>::max();
int indiceFound = -1;
// Check if imageB Contain the projected point.
if ( imageB.AsArray3Du()->Contains(pos(0), pos(1)) ) {
++nbRepeatablePossible; //This feature could be detected in imageB also
for (int iB=0; iB < featuresB.size(); ++iB) {
const libmv::PointFeature * featureB =
dynamic_cast<libmv::PointFeature *>( featuresB[iB] );
Vec3 posB; posB << featureB->x(), featureB->y(), 1.0;
//Test distance over the two points.
double distance = DistanceL2(transformed,posB);
//If small enough consider the point can be the same
if ( distance <= distThreshold ) {
distanceSearch = distance;
indiceFound = iB;
}
}
}
if ( indiceFound != -1 ) {
//(test other parameter scale, orientation if any)
++nbRepeatable;
const libmv::PointFeature * featureB =
dynamic_cast<libmv::PointFeature *>( featuresB[indiceFound] );
Vec3 posB; posB << featureB->x(), featureB->y(), 1.0;
//Test distance over the two points.
double distance = DistanceL2(transformed,posB);
//cout << endl << distance;
localisationError += distance;
}
}
if( nbRepeatable >0 ) {
localisationError/= nbRepeatable;
}
else {
localisationError = 0;
}
nbRepeatablePossible = min(nbRepeatablePossible, featuresB.size());
ostringstream os;
os<< endl << " Feature Repeatability " << ImageNameB << endl
<< " ---------------------- " << endl
<< " Image A get\t" << featuresA.size() << "\tfeatures" << endl
<< " Image B get\t" << featuresB.size() << "\tfeatures" << endl
<< " ---------------------- " << endl
<< " Position repeatability :\t" <<
nbRepeatable / (double) nbRepeatablePossible * 100 << endl
<< " Position mean error :\t" << localisationError << endl;
cout << os.str();
if (stringStream) {
(*stringStream) << os.str();
}
if(exportedData) {
exportedData->push_back(featuresA.size());
exportedData->push_back(featuresB.size());
exportedData->push_back(nbRepeatable/(double) nbRepeatablePossible * 100);
exportedData->push_back(localisationError);
}
return (nbRepeatable != 0);
}
| 34.315625 | 79 | 0.63282 |
1284361b84cfd8f1c0ffe9a9f76987caf4f50d32 | 548 | swift | Swift | Sources/SmartLights/UserSubsystem/Handler/UserRegistrationHandler.swift | Supereg/Apodini-REST-SmartLights | d4dd2c3681406b550db33ab1fada710a35837453 | [
"MIT"
] | 2 | 2021-02-06T22:54:43.000Z | 2021-02-12T15:18:26.000Z | Sources/SmartLights/UserSubsystem/Handler/UserRegistrationHandler.swift | Supereg/Apodini-REST-SmartLights | d4dd2c3681406b550db33ab1fada710a35837453 | [
"MIT"
] | null | null | null | Sources/SmartLights/UserSubsystem/Handler/UserRegistrationHandler.swift | Supereg/Apodini-REST-SmartLights | d4dd2c3681406b550db33ab1fada710a35837453 | [
"MIT"
] | null | null | null | //
// Created by Andreas Bauer on 06.02.21.
//
import Foundation
import Apodini
import NIO
import FluentKit
struct UserRegistrationHandler: Handler {
@Parameter
var registration: UserRegistration
@Environment(\.database)
var database: Database
func handle() -> EventLoopFuture<User> {
let user = UserModel(from: registration)
return user
.save(on: database)
.map {
User(from: user)
}
}
var metadata: Metadata {
Operation(.create)
}
}
| 17.677419 | 48 | 0.60219 |
6b60661a5bcceb05eefe7759c2635c541994b19c | 670 | js | JavaScript | src/copy-entries-to-dir.js | ForbesLindesay/run-on-ssh | 3378798dd224d881fd316d6a87faf89d62bdfde2 | [
"MIT"
] | 1 | 2016-08-24T14:34:59.000Z | 2016-08-24T14:34:59.000Z | src/copy-entries-to-dir.js | ForbesLindesay/run-on-ssh | 3378798dd224d881fd316d6a87faf89d62bdfde2 | [
"MIT"
] | null | null | null | src/copy-entries-to-dir.js | ForbesLindesay/run-on-ssh | 3378798dd224d881fd316d6a87faf89d62bdfde2 | [
"MIT"
] | null | null | null | import Promise from 'promise';
export default function copy(ssh, entries, destinationDirectory) {
return ssh.exec('mkdir ' + destinationDirectory).then(
() => new Promise((resolve, reject) => {
function next(i) {
if (i >= entries.length) {
return resolve();
}
const entry = entries[i];
const result = (
entry.type === 'directory'
? ssh.exec('mkdir ' + destinationDirectory + entry.path.substr(1))
: ssh.exec('cat > ' + destinationDirectory + entry.path.substr(1), {stdin: entry.content})
);
result.done(() => next(i + 1), reject);
}
next(0);
}),
);
}
| 30.454545 | 100 | 0.553731 |
5891956d1c92d8f094a84bc0f034f9f5133a5952 | 15,207 | css | CSS | public/Home/css/index/eight/eightService.css | mengzhaolis/zhongyan | b3ab4656c59db489be95e74b70dbb1231713b554 | [
"MIT"
] | null | null | null | public/Home/css/index/eight/eightService.css | mengzhaolis/zhongyan | b3ab4656c59db489be95e74b70dbb1231713b554 | [
"MIT"
] | null | null | null | public/Home/css/index/eight/eightService.css | mengzhaolis/zhongyan | b3ab4656c59db489be95e74b70dbb1231713b554 | [
"MIT"
] | null | null | null | html,
body {
height: 100%;
overflow: hidden;
}
body {
min-width: 1200px;
}
.positionRight {
height: 390px;
position: fixed;
right: 20px;
top: 50%;
margin-top: -193px;
z-index: 100;
}
.positionRight p {
margin-left: 54px;
cursor: pointer;
}
.positionRight ul {
margin: 10px 0 16px;
}
.positionRight ul li a {
display: block;
width: 128px;
height: 36px;
background-color: rgba(68, 90, 154, 0.7);
margin-top: 6px;
font-size: 18px;
line-height: 36px;
text-align: center;
color: #fff;
cursor: pointer;
}
.positionRight ul .change {
background: #5b78cd;
}
#container {
top: 0%;
}
#container,
.sections,
.section {
position: relative;
height: 100%;
}
.section {
background-color: #000;
background-size: cover;
background-position: 50% 50%;
padding-top: 20px;
}
.inner {
width: 62.5%;
height: 100%;
margin: 0 auto;
position: relative;
padding-top: 4%;
}
.logo {
position: absolute;
margin-left: 2.6%;
z-index: 10;
}
h3 {
font-size: 3.6vh;
text-align: center;
height: 8vmin;
color: #fff;
background: url(/Home/images/index/eight/trilateralWhite.png) no-repeat center bottom;
}
.bottomImg {
width: 100%;
position: absolute;
bottom: -0.6vmin;
left: 0;
z-index: 200;
}
.bottomImg a {
display: block;
}
.bottomImg img {
width: 100%;
height: 100%;
}
/*八大服务体系*/
.know {
background: url(/Home/images/index/eight/eightServiceBG.png) no-repeat;
background-size: 100% 100%;
}
.know .inner {
z-index: 1;
}
.knowCenter {
position: absolute;
top: -20px;
left: 0;
right: 0;
transform: translate(7%, 0);
bottom: 0;
z-index: 5;
}
.knowCenter img {
height: 100%;
}
.neirong {
position: absolute;
top: 11.2%;
bottom: 0;
left: 0;
right: 0;
z-index: 20;
}
.knowContent {
margin-top: 4.2%;
width: 100%;
height: 55%;
background: rgba(255, 255, 255, 0.7);
padding: 4% 4% 0 3%;
}
.knowLeft {
padding: 2.5% 0 3.5%;
width: 35.4%;
border-right: 1px solid #6777a5;
}
.leftOne {
width: 50%;
float: left;
}
.leftTwo {
width: 50%;
float: left;
}
.knowLeft p {
font-size: 2.2vmin;
line-height: 8vmin;
color: #000;
background: url(/Home/images/index/eight/star.png) no-repeat left 3vmin;
padding-left: 30px;
}
.knowLeft p em {
color: #9f0914;
}
.knowRight {
width: 63.6%;
padding-left: 3%;
height: 100%;
padding-top: 1%;
}
.knowImg {
width: 100%;
height: 40%;
margin-bottom: 2%;
}
.knowImg img {
width: 100%;
height: 100%;
}
.rightBottom p {
line-height: 3.2vmin;
font-size: 1.8vmin;
color: #000;
}
/*竞争企业调研*/
.field {
background: url(/Home/images/index/eight/contendBG.png) no-repeat;
background-size: 100% 100%;
}
.fieldContent{
width:91%;
margin:0 auto;
}
.fieldContent ul {
position: relative;
margin-top: 4vmin;
}
.flip_wrap {
display: inline-block;
width: 30vmin;
height: 30vmin;
text-align: center;
perspective: 800px;
-webkit-perspective: 800px;
-moz-perspective: 800px;
-ms-perspective: 800px;
-o-perspective: 800px;
position: absolute;
}
.flip {
display: inline-block;
width: 100%;
height: 100%;
backface-visibility: hidden;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
-o-backface-visibility: hidden;
transition: all 1s ease;
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-ms-transition: all 1s ease;
-o-transition: all 1s ease;
transform-style: preserve-3d;
}
.flip div {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
text-align: center;
}
.list1{
top:0;
left:15.1vmin;
}
.list2{
top:0;
left:45.3vmin;
}
.list3{
top:0;
left:75.5vmin;
}
.list4{
top:15.1vmin;
left:0;
}
.list5{
top:15.1vmin;
left:30.2vmin;
}
.list6{
top:15.1vmin;
left:60.4vmin;
}
.list7{
top:15.1vmin;
left:90.6vmin;
}
.list8{
top:30.2vmin;
left:15.1vmin;
}
.list9{
top:30.2vmin;
left:45.3vmin;
}
.list10{
top:30.2vmin;
left:75.5vmin;
}
.list11{
top:45.3vmin;
left:30.2vmin;
}
.list12{
top:45.3vmin;
left:60.4vmin;
}
.show {
padding-top: 8.5vmin;
cursor: pointer;
text-align: center;
background: url(/Home/images/index/eight/square.png) no-repeat;
background-size: 100% 100%;
}
.show h4 {
display: block;
font-size: 3.6vmin;
color: #5b78cd;
}
.show p {
font-size: 2vmin;
color: #000;
margin-top: 3vmin;
}
.back {
backface-visibility: hidden;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-ms-backface-visibility: hidden;
-o-backface-visibility: hidden;
-webkit-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
-ms-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
background: url(/Home/images/index/eight/squareBian.png) no-repeat;
background-size: 100% 100%;
padding: 17px 10px 0;
cursor: pointer;
}
.back ol {
width: 30%;
margin: 0 auto;
padding-top: 20%;
}
.back ol li {
display: block;
font-size: 1.6vmin;
line-height: 2.6vmin;
text-align: left;
}
.back ol li em {
display: block;
width: 0.5vmin;
height: 0.5vmin;
background-color: #333;
border-radius: 50%;
margin-right: 1vmin;
float: left;
margin-top: 1.2vmin;
}
.flip_wrap:hover .flip {
transform: rotateY(180deg);
(180);
-webkit-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
-ms-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
}
/*行业调研*/
.advantage {
background: url(/Home/images/index/eight/industry.png) no-repeat;
background-size: 100% 100%;
}
.advantageTop{
position: absolute;
top: -20px;
left: 0;
right: 0;
transform: translate(10%, 0);
bottom: 0;
z-index: 100;
}
.advantageTop img{
height:100%;
}
.advantage h3{
z-index: 50;
}
.advantageContent{
position: absolute;
top: 30%;
bottom: 0;
left: 0;
right: 0;
z-index: 200;
height:29.3%;
}
.leftContent{
width:26.6%;
height:100%;
}
.leftContent img{
width:100%;
height:100%;
}
.rightContent{
width:73.4%;
height:100%;
}
.rightContent ul{
width:75%;
height:100%;
float: left;
}
.rightContent ul p{
float: left;
}
.rightContent ul li{
float: left;
width:33.3%;
height:50%;
font-size: 2.4vmin;
color: #000;
text-align: center;
line-height: 12vmin;
}
.changeHeight {
height:100%;
line-height: 30vmin;
text-align: center;
font-size: 2.4vmin;
color: #000;
}
.changeHeight:hover,.rightContent ul li:hover{
background: #5b78cd;
color: #fff;
}
.whiteBG{
background-color: #fff;
}
.grayBG{
background-color: #f2f2f2;
}
/*全方位服务*/
.service {
background: url(/Home/images/index/eight/satisficing.png) no-repeat;
background-size: 100% 100%;
}
.serviceContent{
height:55%;
}
.serviceContent>ol{
display: flex;
justify-content: space-between;
position: relative;
margin-top: 4%;
height:100%;
}
.serviceContent>ol>li{
width: 33%;
height:100%;
}
.serviceContent>ol>li>h4{
font-size: 1.8vmin;
font-weight: bold;
color: #010101;
line-height: 2.4vmin;
border-bottom: 1px solid #445a9a;
padding-bottom: 1vmin;
margin:2.5vmin 1.5vmin 2.2vmin;
}
.serviceContent>ol>li>p{
line-height: 2.2vmin;
color: #000;
margin: 0 1.5vmin;
}
.olisOne{
background:url(/Home/images/index/eight/orangeBG.png) no-repeat;
background-size: 100% 100%;
position: absolute;
top:0;
left:0;
}
.olisTwo{
background: url(/Home/images/index/eight/blueBG.png) no-repeat;
background-size: 100% 100%;
position: absolute;
top:0;
left: 33%;
z-index: 10;
}
.serviceContent>ol>.olisThree{
background: url(/Home/images/index/eight/greenBG.png) no-repeat 0 0;
background-size: 100% 100%;
height:50%;
position: absolute;
top:50%;
left: 33%;
z-index: 20;
overflow: hidden;
}
.serviceContent>ol>.olisFour{
position: absolute;
top:0;
left:66%;
width: 34%;
background:url(/Home/images/index/eight/pinkBG.png) no-repeat;
background-size: 100% 100%;
}
.olisThree>.olisImg{
display: none;
}
.serviceContent>ol>.olisThree>.displayChange{
display: block;
}
.olisImg{
width:95%;
position: absolute;
bottom: 1vmin;
left: 1vmin;
z-index: 2;
}
.olisImg img{
width:100%;
}
/*渠道调研*/
.specialist {
background: url(/Home/images/index/eight/channelBG.png) no-repeat;
background-size: 100% 100%;
}
.specialistContent{
margin-top: 5%;
width:65%;
height:70%;
background: url(/Home/images/index/eight/channel.png) no-repeat;
-webkit-background-size: 100% 100%;
background-size: 100% 100%;
margin-left: 4.2%;
position: relative;
}
.nowStudy{
position:absolute;
}
.nowStudy h4{
font-size: 2.4vmin;
color: #000;
margin-bottom: 13.5%;
}
.nowStudy ol li{
font-size: 1.6vmin;
line-height: 4.2vmin;
padding-left: 1vmin;
}
.oneStudy{
top:8%;
left:3%;
}
.twoStudy{
top:30%;
left:32%;
}
.threeStudy{
top:53%;
left:62%;
}
/*客户研究*/
.map {
background: url(/Home/images/index/eight/clientBG.png) no-repeat;
background-size: 100% 100%;
}
.satisfactionContent{
width: 91%;
height:70%;
margin:0 auto;
background: url(/Home/images/index/eight/clientContent.png) no-repeat;
-webkit-background-size: 100% 100%;
background-size: 100% 100%;
margin-top: 5%;
position: relative;
}
.satisfactionContent div{
position: absolute;
}
.satisfaction1{
width:36%;
top:10%;
left:2%;
}
.satisfaction2{
top:10%;
left:72%;
}
.satisfaction3{
top:52%;
left:45.5%;
}
.satisfaction4{
top:54%;
left:72%;
}
.satisfaction1 h4{
font-size: 2.8vmin;
font-weight: bold;
color: #000;
}
.satisfaction1 p{
font-size: 1.75vmin;
color: #000;
line-height: 3vmin;
margin-top: 5%;
}
.alike {
width: 22.6%;
}
.alike h4{
font-size: 1.8vmin;
color: #fff;
font-weight: bold;
margin-bottom: 5%;
}
.alike p,.alike ol li,.alike p span{
font-size: 1.4vmin;
color: #fff;
}
.satisfaction3 p span{
display: block;
}
.satisfaction4 ol li em{
display: block;
width:0.5vmin;
height:0.4vmin;
background: #fff;
border-radius: 50%;
float: left;
margin-top: 1vmin;
margin-right: 0.8vmin;
}
.marginBottom{
margin-bottom: 4%;
}
/*商业模式设计*/
.system {
background: url(/Home/images/index/eight/business.png) no-repeat;
background-size: 100% 100%;
}
.systemContent{
width:100%;
height:77%;
background: rgba(255,255,255,0.8);
margin-top: 4.5%;
position: relative;
padding: 6% 4%;
}
.systemImg{
position: absolute;
z-index: 1;
top:7%;
left:1.3%;
}
.systemContent ul{
display: flex;
flex-wrap: wrap;
height:100%;
}
.systemContent ul li{
width:26%;
height:35%;
margin-right: 11%;
position: relative;
}
.listImg{
width:10%;
height:23%;
position: absolute;
top:-30%;
left:45%;
background: url(/Home/images/index/eight/whiteImg.png) no-repeat;
background-size: 100% 100%;
z-index: 15;
}
.systemContent ul li .changeBG{
background: url(/Home/images/index/eight/blueImg.png) no-repeat;
background-size: 100% 100%;
}
.topSystem{
margin-top: 0;
}
.centerSystem{
margin-top: 3.5%;
}
.bottomSystem{
margin-top:3.5%;
}
.systemContent ul .noMarginRight{
margin-right: 0;
}
.systemContent ul li h4{
text-align: center;
font-size: 1.8vmin;
color: #5b78ce;
font-weight: bold;
}
.systemContent ul li p{
font-size: 1.4vmin;
color: #5b78ce;
margin-top: 2%;
}
/*市场战略咨询*/
.strategic {
background: url(/Home/images/index/eight/strategic.png) no-repeat;
background-size: 100% 100%;
}
.strategicImg{
position: absolute;
width: 100%;
height:100%;
top:0;
left:0;
right:0;
bottom:0;
z-index: -1;
}
.strategicImg img{
width:100%;
height:50%;
}
.strategic2{
margin-top: -0.4vmin;
}
.strategicContent{
position: absolute;
top:2%;
left:0;
right:0;
bottom: 0;
margin:auto;
width:70%;
height:90%;
margin:0 auto;
}
.strategicContent img{
width:100%;
height:100%;
}
/*营销咨询*/
.cooperation {
background: url(/Home/images/index/eight/Marketing.png) no-repeat;
background-size: 100% 100%;
}
.cooperatioContent{
width:100%;
height:38%;
background: rgba(255,255,255,0.5);
margin-top: 4%;
position: relative;
}
.cooperatioContent h4{
width:75%;
height:60%;
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
}
.cooperatioContent h4 img{
width:100%;
height:100%;
}
.cooperatioContent span img{
width:100%;
height:100%;
}
.quotesLeft{
width:7%;
height:15%;
position: absolute;
top:1.5vmin;
left:2vmin;
}
.quotesRight{
width:7%;
height:15%;
position: absolute;
bottom:1.5vmin;
right:2vmin;
}
.cooperatioContent p{
width:78%;
height:15vmin;
position: absolute;
top:14vmin;
left:15vmin;
font-size: 1.8vmin;
line-height: 2.4vmin;
}
/*底部*/
.footer {
position: absolute;
background: #3d518b;
bottom: 0;
left: 0;
width: 100%;
height: 36%;
padding-top: 50px;
border-top: 1px solid #999;
}
.fooer_inner, .footer_bottom {
width: 62.5%;
margin: 0 auto;
}
.footer_copyright {
height: 81.8%;
border-bottom: 1px solid #999;
}
.footer_left_img {
width: 14.5vmin;
height: 12vmin;
padding-right: 4vmin;
border-right: 1px solid #666;
}
.footer_left_img div {
width: 12vmin;
height: 12vmin;
background-color: #5b78ce;
}
.class_left_tel {
margin: 3.7vmin 0 0 2vmin;
}
.class_left_tel p {
color: #eee;
font-size: 1.4vmin;
}
/*.class_left_tel p a{
color:#eee;
}*/
.class_left_tel .telephone {
font-size: 2.4vmin;
}
.footer_right ol {
height: 2.8vmin;
background: url("../images/footer/underline.png") no-repeat left bottom;
margin-bottom: 2vmin;
}
.footer_right ol li {
float: left;
width: 3.3vmin;
line-height: 2.5vmin;
margin-right: 2.5vmin;
font-size: 1.6vmin;
}
.current {
border-bottom: 2px solid #c6cbdb;
}
.footer_right ol li a {
color: #eee;
}
.footer_right_list {
width: 41vmin;
position: relative;
}
.footer_right_list ul {
position: absolute;
top: 0;
left: 0;
}
.footer_right_list ul li {
line-height: 2.3vmin;
color: #eee;
font-size: 1.4vmin;
}
/*.footer_right_list ul li a{
color:#eee;
}*/
.footer_right_list .dalian {
display: none;
}
.item {
display: none;
}
.show {
display: block;
}
.footer_bottom {
line-height: 5vmin;
}
.footer_bottom div {
color: #999;
font-size: 1.2vmin;
}
| 16.710989 | 90 | 0.605116 |
8c82bf9b8a888cdc50456b434c275cce92c2cd3d | 1,208 | go | Go | queue.go | duomi520/utils | e4523ecaadbf0e6a6b70b52f0bcdcd8eeb88a3df | [
"MIT"
] | null | null | null | queue.go | duomi520/utils | e4523ecaadbf0e6a6b70b52f0bcdcd8eeb88a3df | [
"MIT"
] | null | null | null | queue.go | duomi520/utils | e4523ecaadbf0e6a6b70b52f0bcdcd8eeb88a3df | [
"MIT"
] | null | null | null | package utils
import (
"runtime"
"sync/atomic"
)
//LockList 加锁读写数组,适用不频繁写的场景
//修改时新数据原子替换旧数据地址,旧数据由GC回收。
type LockList struct {
//0-unlock 1-lock
mutex int64
slice atomic.Value
}
//NewLockList 新
func NewLockList() *LockList {
l := LockList{}
var data []any
l.slice.Store(data)
return &l
}
//Add 增加
func (l *LockList) Add(element any) {
for {
if atomic.CompareAndSwapInt64(&l.mutex, 0, 1) {
base := l.slice.Load().([]any)
size := len(base)
data := make([]any, size+1)
copy(data[:size], base)
data[size] = element
l.slice.Store(data)
atomic.StoreInt64(&l.mutex, 0)
return
}
runtime.Gosched()
}
}
//Remove 移除
func (l *LockList) Remove(judge func(any) bool) {
for {
if atomic.CompareAndSwapInt64(&l.mutex, 0, 1) {
base := l.slice.Load().([]any)
size := len(base)
data := make([]any, 0, size)
for i := 0; i < size; i++ {
if !judge(base[i]) {
data = append(data, base[i])
}
}
l.slice.Store(data)
atomic.StoreInt64(&l.mutex, 0)
return
}
runtime.Gosched()
}
}
//List 列
func (l *LockList) List() []any {
return l.slice.Load().([]any)
}
// https://github.com/yireyun/go-queue
// https://github.com/Workiva/go-datastructures
| 17.764706 | 49 | 0.620033 |
c646a42aeb680e0760fcb61b72a099e0d199b1a5 | 2,584 | dart | Dart | lib/src/data/extensions/document_snapshot_extensions.dart | HeyKos/train-beers | f96e8edc7ed6da5811815bf49a73c2e95458f837 | [
"MIT"
] | 2 | 2020-03-17T14:17:56.000Z | 2020-03-19T14:39:25.000Z | lib/src/data/extensions/document_snapshot_extensions.dart | HeyKos/train-beers | f96e8edc7ed6da5811815bf49a73c2e95458f837 | [
"MIT"
] | 4 | 2020-10-15T01:13:57.000Z | 2022-01-22T11:17:26.000Z | lib/src/data/extensions/document_snapshot_extensions.dart | HeyKos/train_beers | f96e8edc7ed6da5811815bf49a73c2e95458f837 | [
"MIT"
] | null | null | null | import 'package:cloud_firestore/cloud_firestore.dart';
import '../../domain/entities/event_entity.dart';
import '../../domain/entities/event_participant_entity.dart';
import '../../domain/entities/user_entity.dart';
import '../validators/document_snapshot_validator.dart';
extension Extensions on DocumentSnapshot {
Future<EventEntity> toEvent(String docPath) async {
// Check if we are working with an event document
if (!DocumentSnapshotValidator.isDocumentOfType(this, "events", docPath)) {
return null;
}
var date = data['date'] as Timestamp;
var userRef = data['hostUser'] as DocumentReference;
var hostUser = await userRef
.get()
// Ignore linting to support extension method on DocumentSnapshot.
// ignore: avoid_types_on_closure_parameters
.then((DocumentSnapshot snapshot) => snapshot.toUser(userRef.path));
return EventEntity(
documentID,
date != null ? date.toDate() : null,
hostUser,
data['status'],
);
}
Future<EventParticipantEntity> toEventParticipant(String docPath) async {
// Check if we are working with an event document
var isEventParticipantDoc = DocumentSnapshotValidator.isDocumentOfType(
this, "event_participants", docPath);
if (!isEventParticipantDoc) {
return null;
}
var userRef = data['user'] as DocumentReference;
var hostUser = await userRef
.get()
// Ignore linting to support extension method on DocumentSnapshot.
// ignore: avoid_types_on_closure_parameters
.then((DocumentSnapshot snapshot) => snapshot.toUser(userRef.path));
var eventRef = data['event'] as DocumentReference;
var event = await eventRef
.get()
// Ignore linting to support extension method on DocumentSnapshot.
// ignore: avoid_types_on_closure_parameters
.then((DocumentSnapshot snapshot) => snapshot.toEvent(eventRef.path));
if (event == null) {
return null;
}
return EventParticipantEntity(
documentID,
event.id,
hostUser,
);
}
UserEntity toUser(String docPath) {
// Check if we are working with a user document
if (!DocumentSnapshotValidator.isDocumentOfType(this, "users", docPath)) {
return null;
}
var purchasedOn = data['purchasedOn'] as Timestamp;
return UserEntity(
documentID,
data['avatarPath'],
data['name'],
purchasedOn != null ? purchasedOn.toDate() : null,
data['sequence'],
data['uid'],
isActive: data['isActive'],
);
}
}
| 30.4 | 79 | 0.669118 |
9746f1a56f848efb1081505d5a1083399989fb83 | 317 | go | Go | 12_if-statements/04_init-statement_error/main.go | Botozord/GolangTraining | d14ea3be81f8c5af3ba3b98e6ed5292eb22379b4 | [
"Apache-2.0"
] | null | null | null | 12_if-statements/04_init-statement_error/main.go | Botozord/GolangTraining | d14ea3be81f8c5af3ba3b98e6ed5292eb22379b4 | [
"Apache-2.0"
] | null | null | null | 12_if-statements/04_init-statement_error/main.go | Botozord/GolangTraining | d14ea3be81f8c5af3ba3b98e6ed5292eb22379b4 | [
"Apache-2.0"
] | null | null | null | package main
import "fmt"
func main() {
b := true
if food := "Chocolate"; b {
fmt.Println(food)
}
// so um exemplo contrario do exercicio anterior (03)
// tentando acessar a variavel food fora de sua declaracao, scope
fmt.Println(food)
// # command-line-arguments
// ./main.go:15: undefined: food
}
| 15.095238 | 67 | 0.665615 |
af1ca8cf7f62921d8a59f843069b0cb700470035 | 16,506 | py | Python | fire/helputils.py | bitshares-dex/python-fire | c13d87beee605565a6aece6b7464baa9fc552518 | [
"Apache-2.0"
] | 2 | 2019-02-18T01:57:24.000Z | 2019-02-18T03:08:58.000Z | fire/helputils.py | bitshares-dex/python-fire | c13d87beee605565a6aece6b7464baa9fc552518 | [
"Apache-2.0"
] | null | null | null | fire/helputils.py | bitshares-dex/python-fire | c13d87beee605565a6aece6b7464baa9fc552518 | [
"Apache-2.0"
] | null | null | null | # Copyright (C) 2018 Google Inc.
#
# 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.
"""Utility for producing help strings for use in Fire CLIs.
Can produce help strings suitable for display in Fire CLIs for any type of
Python object, module, class, or function.
There are two types of informative strings: Usage and Help screens.
Usage screens are shown when the user accesses a group or accesses a command
without calling it. A Usage screen shows information about how to use that group
or command. Usage screens are typically short and show the minimal information
necessary for the user to determine how to proceed.
Help screens are shown when the user requests help with the help flag (--help).
Help screens are shown in a less-style console view, and contain detailed help
information.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
from fire import completion
from fire import docstrings
from fire import inspectutils
from fire import value_types
def _NormalizeField(field):
"""Takes a field name and turns it into a human readable name for display.
Args:
field: The field name, used to index into the inspection dict.
Returns:
The human readable name, suitable for display in a help string.
"""
if field == 'type_name':
field = 'type'
return (field[0].upper() + field[1:]).replace('_', ' ')
def _DisplayValue(info, field, padding):
"""Gets the value of field from the dict info for display.
Args:
info: The dict with information about the component.
field: The field to access for display.
padding: Number of spaces to indent text to line up with first-line text.
Returns:
The value of the field for display, or None if no value should be displayed.
"""
value = info.get(field)
if value is None:
return None
skip_doc_types = ('dict', 'list', 'unicode', 'int', 'float', 'bool')
if field == 'docstring':
if info.get('type_name') in skip_doc_types:
# Don't show the boring default docstrings for these types.
return None
elif value == '<no docstring>':
return None
elif field == 'usage':
lines = []
for index, line in enumerate(value.split('\n')):
if index > 0:
line = ' ' * padding + line
lines.append(line)
return '\n'.join(lines)
return value
def _GetFields(trace=None):
"""Returns the field names to include in the help text for a component."""
del trace # Unused.
return [
'type_name',
'string_form',
'file',
'line',
'docstring',
'init_docstring',
'class_docstring',
'call_docstring',
'length',
'usage',
]
def HelpString(component, trace=None, verbose=False):
"""Returns a help string for a supplied component.
The component can be any Python class, object, function, module, etc.
Args:
component: The component to determine the help string for.
trace: The Fire trace leading to this component.
verbose: Whether to include private members in the help string.
Returns:
String suitable for display giving information about the component.
"""
info = inspectutils.Info(component)
# TODO(dbieber): Stop using UsageString in favor of UsageText.
info['usage'] = UsageString(component, trace, verbose)
info['docstring_info'] = docstrings.parse(info['docstring'])
is_error_screen = False
if trace:
is_error_screen = trace.HasError()
if is_error_screen:
# TODO(dbieber): Call UsageText instead of CommonHelpText once ready.
return _CommonHelpText(info, trace)
else:
return _HelpText(info, trace)
def _CommonHelpText(info, trace=None):
"""Returns help text.
This was a copy of previous HelpString function and will be removed once the
correct text formatters are implemented.
Args:
info: The IR object containing metadata of an object.
trace: The Fire trace object containing all metadata of current execution.
Returns:
String suitable for display giving information about the component.
"""
# TODO(joejoevictor): Currently this is just a copy of existing
# HelpString method. We will reimplement this further in later CLs.
fields = _GetFields(trace)
try:
max_size = max(
len(_NormalizeField(field)) + 1
for field in fields
if field in info and info[field])
format_string = '{{field:{max_size}s}} {{value}}'.format(max_size=max_size)
except ValueError:
return ''
lines = []
for field in fields:
value = _DisplayValue(info, field, padding=max_size + 1)
if value:
if lines and field == 'usage':
lines.append('') # Ensure a blank line before usage.
lines.append(format_string.format(
field=_NormalizeField(field) + ':',
value=value,
))
return '\n'.join(lines)
def HelpText(component, info, trace=None, verbose=False):
if inspect.isroutine(component) or inspect.isclass(component):
return HelpTextForFunction(component, info, trace)
else:
return HelpTextForObject(component, info, trace, verbose)
def HelpTextForFunction(component, info, trace=None, verbose=False):
del component, info, trace, verbose
def HelpTextForObject(component, info, trace=None, verbose=False):
"""Generates help text for python objects.
Args:
component: Current component to generate help text for.
info: Info containing metadata of component.
trace: FireTrace object that leads to current component.
verbose: Whether to display help text in verbose mode.
Returns:
Formatted help text for display.
"""
output_template = """NAME
{current_command} - {command_summary}
SYNOPSIS
{synopsis}
DESCRIPTION
{command_description}
{detail_section}
"""
if trace:
current_command = trace.GetCommand()
else:
current_command = None
if not current_command:
current_command = ''
docstring_info = info['docstring_info']
command_summary = docstring_info.summary if docstring_info.summary else ''
if docstring_info.description:
command_description = docstring_info.description
else:
command_description = ''
groups = []
commands = []
values = []
members = completion._Members(component, verbose) # pylint: disable=protected-access
for member_name, member in members:
if value_types.IsGroup(member):
groups.append((member_name, member))
if value_types.IsCommand(member):
commands.append((member_name, member))
if value_types.IsValue(member):
values.append((member_name, member))
possible_actions = []
# TODO(joejoevictor): Add global flags to here. Also, if it's a callable,
# there will be additional flags.
possible_flags = ''
detail_section_string = ''
item_template = """
{name}
{command_summary}
"""
if groups:
# TODO(joejoevictor): Add missing GROUPS section handling
possible_actions.append('GROUP')
if commands:
possible_actions.append('COMMAND')
commands_str_template = """
COMMANDS
COMMAND is one of the followings:
{items}
"""
command_item_strings = []
for command_name, command in commands:
command_docstring_info = docstrings.parse(
inspectutils.Info(command)['docstring'])
command_item_strings.append(
item_template.format(
name=command_name,
command_summary=command_docstring_info.summary))
detail_section_string += commands_str_template.format(
items=('\n'.join(command_item_strings)).rstrip('\n'))
if values:
possible_actions.append('VALUES')
values_str_template = """
VALUES
VALUE is one of the followings:
{items}
"""
value_item_strings = []
for value_name, value in values:
del value
init_docstring_info = docstrings.parse(
inspectutils.Info(component.__class__.__init__)['docstring'])
for arg_info in init_docstring_info.args:
if arg_info.name == value_name:
value_item_strings.append(
item_template.format(
name=value_name, command_summary=arg_info.description))
detail_section_string += values_str_template.format(
items=('\n'.join(value_item_strings)).rstrip('\n'))
possible_actions_string = ' ' + (' | '.join(possible_actions))
synopsis_template = '{current_command}{possible_actions}{possible_flags}'
synopsis_string = synopsis_template.format(
current_command=current_command,
possible_actions=possible_actions_string,
possible_flags=possible_flags)
return output_template.format(
current_command=current_command,
command_summary=command_summary,
synopsis=synopsis_string,
command_description=command_description,
detail_section=detail_section_string)
def UsageText(component, trace=None, verbose=False):
if inspect.isroutine(component) or inspect.isclass(component):
return UsageTextForFunction(component, trace)
else:
return UsageTextForObject(component, trace, verbose)
def UsageTextForFunction(component, trace=None):
"""Returns usage text for function objects.
Args:
component: The component to determine the usage text for.
trace: The Fire trace object containing all metadata of current execution.
Returns:
String suitable for display in error screen.
"""
output_template = """Usage: {current_command} {args_and_flags}
{availability_lines}
For detailed information on this command, run:
{current_command}{hyphen_hyphen} --help
"""
if trace:
command = trace.GetCommand()
is_help_an_arg = trace.NeedsSeparatingHyphenHyphen()
else:
command = None
is_help_an_arg = False
if not command:
command = ''
spec = inspectutils.GetFullArgSpec(component)
args = spec.args
if spec.defaults is None:
num_defaults = 0
else:
num_defaults = len(spec.defaults)
args_with_no_defaults = args[:len(args) - num_defaults]
args_with_defaults = args[len(args) - num_defaults:]
flags = args_with_defaults + spec.kwonlyargs
items = [arg.upper() for arg in args_with_no_defaults]
if flags:
items.append('<flags>')
availability_lines = (
'\nAvailable flags: '
+ ' | '.join('--' + flag for flag in flags) + '\n')
else:
availability_lines = ''
args_and_flags = ' '.join(items)
hyphen_hyphen = ' --' if is_help_an_arg else ''
return output_template.format(
current_command=command,
args_and_flags=args_and_flags,
availability_lines=availability_lines,
hyphen_hyphen=hyphen_hyphen)
def UsageTextForObject(component, trace=None, verbose=False):
"""Returns help text for usage screen for objects.
Construct help text for usage screen to inform the user about error occurred
and correct syntax for invoking the object.
Args:
component: The component to determine the usage text for.
trace: The Fire trace object containing all metadata of current execution.
verbose: Whether to include private members in the usage text.
Returns:
String suitable for display in error screen.
"""
output_template = """Usage: {current_command} <{possible_actions}>
{availability_lines}
For detailed information on this command, run:
{current_command} --help
"""
if trace:
command = trace.GetCommand()
else:
command = None
if not command:
command = ''
groups = []
commands = []
values = []
members = completion._Members(component, verbose) # pylint: disable=protected-access
for member_name, member in members:
if value_types.IsGroup(member):
groups.append(member_name)
if value_types.IsCommand(member):
commands.append(member_name)
if value_types.IsValue(member):
values.append(member_name)
possible_actions = []
availability_lines = []
availability_lint_format = '{header:20s}{choices}'
if groups:
possible_actions.append('groups')
groups_string = ' | '.join(groups)
groups_text = availability_lint_format.format(
header='available groups:',
choices=groups_string)
availability_lines.append(groups_text)
if commands:
possible_actions.append('commands')
commands_string = ' | '.join(commands)
commands_text = availability_lint_format.format(
header='available commands:',
choices=commands_string)
availability_lines.append(commands_text)
if values:
possible_actions.append('values')
values_string = ' | '.join(values)
values_text = availability_lint_format.format(
header='available values:',
choices=values_string)
availability_lines.append(values_text)
possible_actions_string = '|'.join(possible_actions)
availability_lines_string = '\n'.join(availability_lines)
return output_template.format(
current_command=command,
possible_actions=possible_actions_string,
availability_lines=availability_lines_string)
def _HelpText(info, trace=None):
"""Returns help text for extensive help screen.
Construct help text for help screen when user explicitly requesting help by
having -h, --help in the command sequence.
Args:
info: The IR object containing metadata of an object.
trace: The Fire trace object containing all metadata of current execution.
Returns:
String suitable for display in extensive help screen.
"""
# TODO(joejoevictor): Implement real help text construction.
return _CommonHelpText(info, trace)
def _UsageStringFromFullArgSpec(command, spec):
"""Get a usage string from the FullArgSpec for the given command.
The strings look like:
command --arg ARG [--opt OPT] [VAR ...] [--KWARGS ...]
Args:
command: The command leading up to the function.
spec: a FullArgSpec object describing the function.
Returns:
The usage string for the function.
"""
num_required_args = len(spec.args) - len(spec.defaults)
help_flags = []
help_positional = []
for index, arg in enumerate(spec.args):
flag = arg.replace('_', '-')
if index < num_required_args:
help_flags.append('--{flag} {value}'.format(flag=flag, value=arg.upper()))
help_positional.append('{value}'.format(value=arg.upper()))
else:
help_flags.append('[--{flag} {value}]'.format(
flag=flag, value=arg.upper()))
help_positional.append('[{value}]'.format(value=arg.upper()))
if spec.varargs:
help_flags.append('[{var} ...]'.format(var=spec.varargs.upper()))
help_positional.append('[{var} ...]'.format(var=spec.varargs.upper()))
for arg in spec.kwonlyargs:
if arg in spec.kwonlydefaults:
arg_str = '[--{flag} {value}]'.format(flag=arg, value=arg.upper())
else:
arg_str = '--{flag} {value}'.format(flag=arg, value=arg.upper())
help_flags.append(arg_str)
help_positional.append(arg_str)
if spec.varkw:
help_flags.append('[--{kwarg} ...]'.format(kwarg=spec.varkw.upper()))
help_positional.append('[--{kwarg} ...]'.format(kwarg=spec.varkw.upper()))
commands_flags = command + ' '.join(help_flags)
commands_positional = command + ' '.join(help_positional)
commands = [commands_positional]
if commands_flags != commands_positional:
commands.append(commands_flags)
return '\n'.join(commands)
def UsageString(component, trace=None, verbose=False):
"""Returns a string showing how to use the component as a Fire command."""
if trace:
command = trace.GetCommand()
else:
command = None
if command:
command += ' '
else:
command = ''
if inspect.isroutine(component) or inspect.isclass(component):
spec = inspectutils.GetFullArgSpec(component)
return _UsageStringFromFullArgSpec(command, spec)
if isinstance(component, (list, tuple)):
length = len(component)
if length == 0:
return command
if length == 1:
return command + '[0]'
return command + '[0..{cap}]'.format(cap=length - 1)
completions = completion.Completions(component, verbose)
if command:
completions = [''] + completions
return '\n'.join(command + end for end in completions)
| 30.623377 | 87 | 0.70544 |
ea02e6b053ef58284d02af6155755ffead87b3b0 | 24,414 | sql | SQL | ecourse.sql | febiolaputri01/ecourse | 2171b820e3714e5bbe6bc9ea7f3f496559c39e69 | [
"MIT"
] | null | null | null | ecourse.sql | febiolaputri01/ecourse | 2171b820e3714e5bbe6bc9ea7f3f496559c39e69 | [
"MIT"
] | null | null | null | ecourse.sql | febiolaputri01/ecourse | 2171b820e3714e5bbe6bc9ea7f3f496559c39e69 | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Waktu pembuatan: 19 Okt 2021 pada 15.04
-- Versi server: 10.4.20-MariaDB
-- Versi PHP: 7.3.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `ecourse`
--
-- --------------------------------------------------------
--
-- Struktur dari tabel `admin`
--
CREATE TABLE `admin` (
`id_admin` int(5) NOT NULL,
`admin_username` varchar(128) NOT NULL,
`admin_password` varchar(128) NOT NULL,
`admin_view_password` varchar(128) NOT NULL,
`admin_level` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `admin`
--
INSERT INTO `admin` (`id_admin`, `admin_username`, `admin_password`, `admin_view_password`, `admin_level`) VALUES
(1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'admin', 1);
-- --------------------------------------------------------
--
-- Struktur dari tabel `mainmenu`
--
CREATE TABLE `mainmenu` (
`seq` int(11) NOT NULL,
`idmenu` int(11) NOT NULL,
`nama_menu` varchar(50) NOT NULL,
`active_menu` varchar(50) NOT NULL,
`icon_class` varchar(50) NOT NULL,
`link_menu` varchar(50) NOT NULL,
`menu_akses` varchar(12) NOT NULL,
`entry_date` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`entry_user` varchar(50) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `mainmenu`
--
INSERT INTO `mainmenu` (`seq`, `idmenu`, `nama_menu`, `active_menu`, `icon_class`, `link_menu`, `menu_akses`, `entry_date`, `entry_user`) VALUES
(9, 9, 'Beranda', '', 'fas fa-home fa-2x', 'Admin', '', '2020-04-17 23:02:37', NULL),
(10, 10, 'Slider', '', 'fas fa-sliders-h fa-2x', 'C_slider', '', '2020-04-17 14:01:03', NULL),
(11, 11, 'Kursus', '', 'fas fa-book-reader fa-2x', 'C_kursus', '', '2020-04-17 14:24:57', NULL),
(16, 16, 'Kontak', '', 'fa fa-phone fa-2x', 'Kontak', '', '2020-04-17 21:39:42', NULL),
(27, 27, 'Setting Ukuran', '', 'fas fa-cogs fa-2x', 'Setting_ukuran', '', '2020-03-13 13:53:59', NULL),
(21, 21, 'Setting Title', '', 'fas fa-wrench fa-2x', 'Setting_title', '', '2020-03-13 13:51:06', NULL),
(22, 22, 'Setting User', '', 'fas fa-user fa-2x', 'setting_user', '', '2020-03-13 13:51:10', NULL),
(12, 12, 'Pengajar', '', 'fas fa-chalkboard-teacher fa-2x', 'C_pengajar', '', '2020-04-17 20:53:12', NULL),
(15, 15, 'Tentang', '', 'fas fa-info fa-2x', 'C_tentang', '', '2020-04-17 21:42:24', NULL),
(13, 13, 'Member', '', 'fas fa-users fa-2x', 'C_member', '', '2020-04-17 21:24:25', NULL),
(14, 14, 'Pertanyaan', '', 'fas fa-question fa-2x', 'C_pertanyaan', '', '2020-04-17 21:24:32', NULL);
-- --------------------------------------------------------
--
-- Struktur dari tabel `meta_beranda`
--
CREATE TABLE `meta_beranda` (
`id_meta_beranda` int(11) NOT NULL,
`title` text NOT NULL,
`meta_keyword` text NOT NULL,
`meta_description` text NOT NULL,
`link_canonical` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `meta_beranda`
--
INSERT INTO `meta_beranda` (`id_meta_beranda`, `title`, `meta_keyword`, `meta_description`, `link_canonical`) VALUES
(1, 'Berandae', 'keyworde', 'desce', '11');
-- --------------------------------------------------------
--
-- Struktur dari tabel `meta_kontak`
--
CREATE TABLE `meta_kontak` (
`id_meta_kontak` int(11) NOT NULL,
`title` text NOT NULL,
`meta_keyword` text NOT NULL,
`meta_description` text NOT NULL,
`link_canonical` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `meta_kontak`
--
INSERT INTO `meta_kontak` (`id_meta_kontak`, `title`, `meta_keyword`, `meta_description`, `link_canonical`) VALUES
(1, 'Kontake', 'keyworde', 'yryee', '11');
-- --------------------------------------------------------
--
-- Struktur dari tabel `meta_produk`
--
CREATE TABLE `meta_produk` (
`id_meta_produk` int(11) NOT NULL,
`title` text NOT NULL,
`meta_keyword` text NOT NULL,
`meta_description` text NOT NULL,
`link_canonical` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `meta_produk`
--
INSERT INTO `meta_produk` (`id_meta_produk`, `title`, `meta_keyword`, `meta_description`, `link_canonical`) VALUES
(1, 'Produke', 'keyworde', 'oooooe', '11');
-- --------------------------------------------------------
--
-- Struktur dari tabel `meta_struktur`
--
CREATE TABLE `meta_struktur` (
`id_meta_struktur` int(11) NOT NULL,
`title` text NOT NULL,
`meta_keyword` text NOT NULL,
`meta_description` text NOT NULL,
`link_canonical` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `meta_struktur`
--
INSERT INTO `meta_struktur` (`id_meta_struktur`, `title`, `meta_keyword`, `meta_description`, `link_canonical`) VALUES
(1, 'Strukture', 'keyworde', 'alale', '11');
-- --------------------------------------------------------
--
-- Struktur dari tabel `setting_ukuran`
--
CREATE TABLE `setting_ukuran` (
`id_setting_ukuran` int(11) NOT NULL,
`ukuran_foto_slider` char(15) NOT NULL,
`ukuran_foto_tentang` char(15) NOT NULL,
`ukuran_foto_produk` char(15) NOT NULL,
`ukuran_foto_galeri` char(15) NOT NULL,
`footer` char(15) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `setting_ukuran`
--
INSERT INTO `setting_ukuran` (`id_setting_ukuran`, `ukuran_foto_slider`, `ukuran_foto_tentang`, `ukuran_foto_produk`, `ukuran_foto_galeri`, `footer`) VALUES
(1, '1000x500', '1000x1000', '2000x2000', '400x500', '200x200');
-- --------------------------------------------------------
--
-- Struktur dari tabel `submenu`
--
CREATE TABLE `submenu` (
`id_sub` int(11) NOT NULL,
`nama_sub` varchar(50) NOT NULL,
`mainmenu_idmenu` int(11) NOT NULL,
`active_sub` varchar(20) NOT NULL,
`icon_class` varchar(100) NOT NULL,
`link_sub` varchar(50) NOT NULL,
`sub_akses` varchar(12) NOT NULL,
`entry_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`entry_user` varchar(20) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `submenu`
--
INSERT INTO `submenu` (`id_sub`, `nama_sub`, `mainmenu_idmenu`, `active_sub`, `icon_class`, `link_sub`, `sub_akses`, `entry_date`, `entry_user`) VALUES
(1, 'Entry User', 8, '', '', 'User', '', '2017-10-18 14:28:25', NULL),
(2, 'Kategori Produk', 4, '', '', 'Produk', '', '2017-10-18 14:34:17', NULL),
(3, 'Produk', 4, '', '', 'Produk/detail', '', '2017-10-18 14:34:26', NULL),
(4, 'Album', 5, '', '', 'Gallery', '', '2017-10-18 14:34:34', NULL),
(5, 'Foto', 5, '', '', 'Gallery/foto', '', '2017-10-18 14:34:40', NULL);
-- --------------------------------------------------------
--
-- Struktur dari tabel `tab_akses_mainmenu`
--
CREATE TABLE `tab_akses_mainmenu` (
`id` int(11) NOT NULL,
`id_menu` int(11) NOT NULL,
`id_level` int(11) NOT NULL,
`c` int(11) DEFAULT 0,
`r` int(11) DEFAULT 0,
`u` int(11) DEFAULT 0,
`d` int(11) DEFAULT 0,
`entry_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`entry_user` varchar(50) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tab_akses_mainmenu`
--
INSERT INTO `tab_akses_mainmenu` (`id`, `id_menu`, `id_level`, `c`, `r`, `u`, `d`, `entry_date`, `entry_user`) VALUES
(1, 1, 1, NULL, 1, NULL, NULL, '2017-09-26 13:49:01', 'direktur'),
(8, 7, 1, 0, 1, 0, 0, '2017-10-27 17:52:10', ''),
(9, 9, 1, 0, 1, 0, 0, '2018-01-20 19:05:57', ''),
(10, 10, 1, 0, 1, 0, 0, '2018-12-28 01:29:38', ''),
(11, 11, 1, 0, 1, 0, 0, '2018-12-28 01:29:38', ''),
(12, 12, 1, 0, 1, 0, 0, '2018-12-28 01:29:38', ''),
(13, 13, 1, 0, 1, 0, 0, '2019-01-09 02:27:14', ''),
(14, 14, 1, 0, 1, 0, 0, '2019-01-10 01:43:47', ''),
(15, 15, 1, 0, 1, 0, 0, '2019-01-10 05:59:44', ''),
(23, 16, 1, 0, 1, 0, 0, '2019-02-08 01:00:02', ''),
(24, 17, 1, 0, 1, 0, 0, '2020-01-23 16:30:13', ''),
(25, 18, 1, 0, 1, 0, 0, '2020-01-23 16:30:13', ''),
(26, 19, 1, 0, 1, 0, 0, '2020-03-13 13:46:38', ''),
(27, 25, 1, 0, 1, 0, 0, '2020-02-24 03:49:48', '');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tab_akses_submenu`
--
CREATE TABLE `tab_akses_submenu` (
`id` int(11) NOT NULL,
`id_sub_menu` int(11) NOT NULL,
`id_level` int(11) NOT NULL,
`c` int(11) DEFAULT 0,
`r` int(11) DEFAULT 0,
`u` int(11) DEFAULT 0,
`d` int(11) DEFAULT 0,
`entry_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
`entry_user` varchar(30) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tab_akses_submenu`
--
INSERT INTO `tab_akses_submenu` (`id`, `id_sub_menu`, `id_level`, `c`, `r`, `u`, `d`, `entry_date`, `entry_user`) VALUES
(1, 1, 1, 0, 1, 0, 0, '2017-10-14 14:45:40', ''),
(2, 2, 1, 0, 1, 0, 0, '2017-10-16 19:59:02', ''),
(3, 3, 1, 0, 0, 0, 0, '2017-10-19 01:12:32', ''),
(4, 4, 1, 0, 1, 0, 0, '2017-10-16 19:59:16', ''),
(5, 5, 1, 0, 0, 0, 0, '2017-10-19 01:12:33', '');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_beranda`
--
CREATE TABLE `tb_beranda` (
`id_beranda` int(11) NOT NULL,
`file_slider1` text NOT NULL,
`file_slider2` text NOT NULL,
`file_slider3` text NOT NULL,
`file_slider4` text NOT NULL,
`keyword` text NOT NULL,
`jumlah_produk` int(11) NOT NULL,
`judul_tentang` text NOT NULL,
`deskripsi_tentang` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_beranda`
--
INSERT INTO `tb_beranda` (`id_beranda`, `file_slider1`, `file_slider2`, `file_slider3`, `file_slider4`, `keyword`, `jumlah_produk`, `judul_tentang`, `deskripsi_tentang`) VALUES
(1, 'spada.jpg', 'bergabung.jpg', 'materi.jpg', '1.jpg', 'Aptisi', 0, 'Selamat Datang Di SPADA APTISI JATIM', '<p>Official Site APTISI Pusat merupakan website utama dari Asosiasi Perguruan Tinggi Swasta Indonesia. Tidak berbeda dengan official site lainnya untuk menyajikan informasi berupa sebuah berita maupun artikel, official site APTISI Pusat memiliki sebuah artikel, dan saat ini sudah tercatat bahwa terdapat 360 postingan dengan total view mencapai 147238 views dalam official site APTISI Pusat. User yang sering aktif posting berita yaitu Resti Rahmawati dengan total posting sebanyak 117 Post. Terbukti pula bahwa official site APTISI sudah dikenal oleh seluruh anggota, mahasiswa maupun masyarakat luas. Mengapa tidak, subscriber official site APTISI saat ini tercatat sebanyak 288 subscriber. Dalam official site ini tidak hanya untuk melihat berita atau artikel tetapi bisa berkomunkasi dengan sesama pengguna lain dan terbukti dengan adanya 310 comment. Mari kita tingkatkan kualitas official site APTISI Pusat dengan menjadi subscriber dan memberikan feedback berupa comment pada setiap artikel yang ada</p>');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_detail_paket_member`
--
CREATE TABLE `tb_detail_paket_member` (
`id_detail_paket` int(11) NOT NULL,
`id_member` int(11) DEFAULT NULL,
`id_kursus` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_detail_paket_member`
--
INSERT INTO `tb_detail_paket_member` (`id_detail_paket`, `id_member`, `id_kursus`) VALUES
(1, 1, 1),
(2, 1, 2);
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_detail_ujian`
--
CREATE TABLE `tb_detail_ujian` (
`id_detail_ujian` int(11) NOT NULL,
`id_ujian` int(50) NOT NULL,
`id_pertanyaan` int(50) NOT NULL,
`jawaban_ujian` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_detail_ujian`
--
INSERT INTO `tb_detail_ujian` (`id_detail_ujian`, `id_ujian`, `id_pertanyaan`, `jawaban_ujian`) VALUES
(1, 1, 1, 'C'),
(2, 1, 2, 'D'),
(3, 1, 3, 'B'),
(4, 1, 4, 'C'),
(5, 1, 5, 'C');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_kontak`
--
CREATE TABLE `tb_kontak` (
`id_kontak` int(11) NOT NULL,
`deskripsi_kontak` text NOT NULL,
`script_embed_code` text NOT NULL,
`email_kontak` varchar(128) NOT NULL,
`nomor_kontak` varchar(128) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_kontak`
--
INSERT INTO `tb_kontak` (`id_kontak`, `deskripsi_kontak`, `script_embed_code`, `email_kontak`, `nomor_kontak`) VALUES
(1, '<p><span>Alamat : Jl. Kamal Raya Outer Ring Road Komplek Rukan Malibu Blok I No.75, Cengkareng, Jakarta Barat, DKI Jakarta, RT.7/RW.14, Cengkareng Tim., Cengkareng, Kota Jakarta Barat, Daerah Khusus Ibukota Jakarta 11730</span><br /><span>Hari : Senin – Jumat</span><br /><span>Jam Kerja : 09:00 – 16:00</span><br /><span>Telepon : (021) 56944914</span></p>', '<iframe src=\"https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d44704.912996884916!2d112.95773565647879!3d-7.9582352167973385!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x2dd636fe48e2b08b%3A0x19b75487127bd0c6!2sGn.%20Bromo!5e0!3m2!1sid!2sid!4v1587159508186!5m2!1sid!2sid\" width=\"600\" height=\"450\" frameborder=\"0\" style=\"border:0;\" allowfullscreen=\"\" aria-hidden=\"false\" tabindex=\"0\"></iframe>', '[email protected]', '0821 3122 2331');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_kursus`
--
CREATE TABLE `tb_kursus` (
`id_kursus` int(11) NOT NULL,
`foto_kursus` text NOT NULL,
`nama_kursus` text NOT NULL,
`harga_kursus` text NOT NULL,
`deskripsi_kursus` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_kursus`
--
INSERT INTO `tb_kursus` (`id_kursus`, `foto_kursus`, `nama_kursus`, `harga_kursus`, `deskripsi_kursus`) VALUES
(1, 'course_9.jpg', 'Kursus Melukis', '700000', 'Seiring perkembangan sistem pendidikan, lembaga pendidikan non formal mulai digandrungi para orangtua. Mereka memberi pelatihan atau kursus untuk buah hatinya guna mendorong bakat sang anak.\r\n\r\nKursus menggambar dan mewarna menjadi salah satu favorit para orang tua. Maklum, banyak manfaat yang dipetik dari menggambar dan mewarna. Ambil misal, sang anak bisa mengenal warna dan memegang alat tulis dengan benar.\r\n\r\nDianggap potensial, penyedia jasanya pun mulai menjamur. Bahkan, beberapa diantara ada yang menawarkan waralaba. Seperti Ohayolukis. Kursus menggambar dan mewarna yang dibangun Oscar Sumarli ini sudah berjalan sejak 2005 lalu. Gerai pertamanya ada di Jakarta.'),
(2, 'course_3.jpg', 'Kursus Web Design', '2000000', 'Dalam pelatihan ini akan mempelajari bagaimana membuat website dari 0 (nol). Anda akan mempelajari cara pembuatan Website Statis maupun Interaktif menggunakan HTML, CSS, Javascript, Dreamweaver, dan Photoshop.');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_member`
--
CREATE TABLE `tb_member` (
`id_member` int(11) NOT NULL,
`username` varchar(128) NOT NULL,
`password` varchar(128) NOT NULL,
`nama_member` varchar(128) NOT NULL,
`email_member` varchar(128) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_member`
--
INSERT INTO `tb_member` (`id_member`, `username`, `password`, `nama_member`, `email_member`) VALUES
(1, 'febiola', 'acc8fa9c29d777fed7f41c0d31bab06b', 'Febiola Putri Yunita', '[email protected]');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_pengajar`
--
CREATE TABLE `tb_pengajar` (
`id_pengajar` int(11) NOT NULL,
`foto_pengajar` text NOT NULL,
`nama_pengajar` text NOT NULL,
`deskripsi_pengajar` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_pengajar`
--
INSERT INTO `tb_pengajar` (`id_pengajar`, `foto_pengajar`, `nama_pengajar`, `deskripsi_pengajar`) VALUES
(1, 'team_4.jpg', 'Jacke Masito', 'Quantum Mechanics'),
(2, 'team_3.jpg', 'Veronica Vahn', 'Designer & Website'),
(3, 'team_2.jpg', 'Charles', 'Marketing & Management');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_pertanyaan`
--
CREATE TABLE `tb_pertanyaan` (
`id_pertanyaan` int(11) NOT NULL,
`deskripsi_pertanyaan` text NOT NULL,
`jawaban_a` text NOT NULL,
`jawaban_b` text NOT NULL,
`jawaban_c` text NOT NULL,
`jawaban_d` text NOT NULL,
`kunci_jawaban` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_pertanyaan`
--
INSERT INTO `tb_pertanyaan` (`id_pertanyaan`, `deskripsi_pertanyaan`, `jawaban_a`, `jawaban_b`, `jawaban_c`, `jawaban_d`, `kunci_jawaban`) VALUES
(1, 'Dibawah ini yang termasuk rumah tradisional suku Dayak Kalimantan adalah ...', 'Rumah Lantik', 'Rumah Panjang', 'Rumah Joglo', 'Rumah Badui', 'b'),
(2, 'Berikut yang termasuk alat musik petik, kecuali ...', 'Kulintang', 'Gitar', 'Bass', 'Siter', 'a'),
(3, 'Tari Saman merupakan tarian dari daerah ...', 'Jawa Barat', 'Kalimantan', 'Aceh', 'Jawa Tengah', 'c'),
(4, 'Alat musik yang berasal dari Jawa Barat, yaitu ...', 'Gamelan', 'Rebana', 'Seruling', 'Gamelan dan Seruling', 'd'),
(5, '<p>Sudut lancip yang ukuran sudutnya antara 0 dan 90 derajat disebut ...</p>', 'Sudut Lancip ', 'Sudut Tumpul', 'Sudut Siku-siku', 'Sudut Datar', 'c');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_slider`
--
CREATE TABLE `tb_slider` (
`id_slider` int(11) NOT NULL,
`foto_slider` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_slider`
--
INSERT INTO `tb_slider` (`id_slider`, `foto_slider`) VALUES
(1, 'blog_images_1.jpg'),
(2, 'course_5.jpg'),
(3, 'course_4.jpg');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_tentang`
--
CREATE TABLE `tb_tentang` (
`id_tentang` int(11) NOT NULL,
`foto_tentang` text NOT NULL,
`nama_tentang` varchar(128) NOT NULL,
`deskripsi_tentang` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_tentang`
--
INSERT INTO `tb_tentang` (`id_tentang`, `foto_tentang`, `nama_tentang`, `deskripsi_tentang`) VALUES
(1, 'about_1.jpg', 'Our Stories', 'Lorem ipsum dolor sit, consectet adipisi elit, sed do eiusmod tempor for enim en consectet adisipi elit, sed do consectet adipisi elit, sed doadesg, Lorem ipsum dolor sit, consectet adipisi elit, sed do eiusmod tempor for enim en consectet adisipi elit, sed do consectet adipisi elit, sed doadesg, Lorem ipsum dolor sit, consectet adipisi elit, sed do eiusmod tempor for enim en consectet adisipi elit, sed do consectet adipisi elit, sed doadesg'),
(2, 'about_2.jpg', 'Our Mission', 'Lorem ipsum dolor sit, consectet adipisi elit, sed do eiusmod tempor for enim en consectet adisipi elit, sed do consectet adipisi elit, sed doadesg, Lorem ipsum dolor sit, consectet adipisi elit, sed do eiusmod tempor for enim en consectet adisipi elit, sed do consectet adipisi elit, sed doadesg, Lorem ipsum dolor sit, consectet adipisi elit, sed do eiusmod tempor for enim en consectet adisipi elit, sed do consectet adipisi elit, sed doadesg');
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_ujian`
--
CREATE TABLE `tb_ujian` (
`id_ujian` int(11) NOT NULL,
`tanggal_ujian` datetime NOT NULL,
`id_member` int(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data untuk tabel `tb_ujian`
--
INSERT INTO `tb_ujian` (`id_ujian`, `tanggal_ujian`, `id_member`) VALUES
(1, '2020-04-07 03:48:35', 2),
(2, '2020-04-08 20:56:37', 1);
-- --------------------------------------------------------
--
-- Struktur dari tabel `tb_video`
--
CREATE TABLE `tb_video` (
`id_video` int(11) NOT NULL,
`judul_video` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
`deskripsi` varchar(256) COLLATE utf8_unicode_ci NOT NULL,
`id_kursus` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data untuk tabel `tb_video`
--
INSERT INTO `tb_video` (`id_video`, `judul_video`, `deskripsi`, `id_kursus`) VALUES
(1, '1.mp4', 'Blablabla', 1),
(2, '2.mp4', 'blablabla', 2);
--
-- Indexes for dumped tables
--
--
-- Indeks untuk tabel `admin`
--
ALTER TABLE `admin`
ADD PRIMARY KEY (`id_admin`);
--
-- Indeks untuk tabel `mainmenu`
--
ALTER TABLE `mainmenu`
ADD PRIMARY KEY (`seq`);
--
-- Indeks untuk tabel `meta_beranda`
--
ALTER TABLE `meta_beranda`
ADD PRIMARY KEY (`id_meta_beranda`);
--
-- Indeks untuk tabel `meta_kontak`
--
ALTER TABLE `meta_kontak`
ADD PRIMARY KEY (`id_meta_kontak`);
--
-- Indeks untuk tabel `meta_produk`
--
ALTER TABLE `meta_produk`
ADD PRIMARY KEY (`id_meta_produk`);
--
-- Indeks untuk tabel `meta_struktur`
--
ALTER TABLE `meta_struktur`
ADD PRIMARY KEY (`id_meta_struktur`);
--
-- Indeks untuk tabel `setting_ukuran`
--
ALTER TABLE `setting_ukuran`
ADD PRIMARY KEY (`id_setting_ukuran`);
--
-- Indeks untuk tabel `submenu`
--
ALTER TABLE `submenu`
ADD PRIMARY KEY (`id_sub`);
--
-- Indeks untuk tabel `tab_akses_mainmenu`
--
ALTER TABLE `tab_akses_mainmenu`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `tab_akses_submenu`
--
ALTER TABLE `tab_akses_submenu`
ADD PRIMARY KEY (`id`);
--
-- Indeks untuk tabel `tb_beranda`
--
ALTER TABLE `tb_beranda`
ADD PRIMARY KEY (`id_beranda`);
--
-- Indeks untuk tabel `tb_detail_paket_member`
--
ALTER TABLE `tb_detail_paket_member`
ADD PRIMARY KEY (`id_detail_paket`);
--
-- Indeks untuk tabel `tb_detail_ujian`
--
ALTER TABLE `tb_detail_ujian`
ADD PRIMARY KEY (`id_detail_ujian`);
--
-- Indeks untuk tabel `tb_kontak`
--
ALTER TABLE `tb_kontak`
ADD PRIMARY KEY (`id_kontak`);
--
-- Indeks untuk tabel `tb_kursus`
--
ALTER TABLE `tb_kursus`
ADD PRIMARY KEY (`id_kursus`);
--
-- Indeks untuk tabel `tb_member`
--
ALTER TABLE `tb_member`
ADD PRIMARY KEY (`id_member`);
--
-- Indeks untuk tabel `tb_pengajar`
--
ALTER TABLE `tb_pengajar`
ADD PRIMARY KEY (`id_pengajar`);
--
-- Indeks untuk tabel `tb_pertanyaan`
--
ALTER TABLE `tb_pertanyaan`
ADD PRIMARY KEY (`id_pertanyaan`);
--
-- Indeks untuk tabel `tb_slider`
--
ALTER TABLE `tb_slider`
ADD PRIMARY KEY (`id_slider`);
--
-- Indeks untuk tabel `tb_tentang`
--
ALTER TABLE `tb_tentang`
ADD PRIMARY KEY (`id_tentang`);
--
-- Indeks untuk tabel `tb_ujian`
--
ALTER TABLE `tb_ujian`
ADD PRIMARY KEY (`id_ujian`);
--
-- Indeks untuk tabel `tb_video`
--
ALTER TABLE `tb_video`
ADD PRIMARY KEY (`id_video`);
--
-- AUTO_INCREMENT untuk tabel yang dibuang
--
--
-- AUTO_INCREMENT untuk tabel `tb_detail_paket_member`
--
ALTER TABLE `tb_detail_paket_member`
MODIFY `id_detail_paket` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT untuk tabel `tb_detail_ujian`
--
ALTER TABLE `tb_detail_ujian`
MODIFY `id_detail_ujian` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT untuk tabel `tb_kursus`
--
ALTER TABLE `tb_kursus`
MODIFY `id_kursus` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT untuk tabel `tb_member`
--
ALTER TABLE `tb_member`
MODIFY `id_member` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT untuk tabel `tb_pengajar`
--
ALTER TABLE `tb_pengajar`
MODIFY `id_pengajar` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT untuk tabel `tb_pertanyaan`
--
ALTER TABLE `tb_pertanyaan`
MODIFY `id_pertanyaan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT untuk tabel `tb_slider`
--
ALTER TABLE `tb_slider`
MODIFY `id_slider` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT untuk tabel `tb_tentang`
--
ALTER TABLE `tb_tentang`
MODIFY `id_tentang` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT untuk tabel `tb_ujian`
--
ALTER TABLE `tb_ujian`
MODIFY `id_ujian` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT untuk tabel `tb_video`
--
ALTER TABLE `tb_video`
MODIFY `id_video` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 32.552 | 1,125 | 0.66167 |
2047ea8bcafc43be024bd3264c0530a7c29badde | 491 | swift | Swift | Sources/FaviconFinder/Classes/Types/Favicon.swift | francisfeng/FaviconFinder | 1b454ad7f69038b04d9f287ed78128324146ac8f | [
"MIT"
] | null | null | null | Sources/FaviconFinder/Classes/Types/Favicon.swift | francisfeng/FaviconFinder | 1b454ad7f69038b04d9f287ed78128324146ac8f | [
"MIT"
] | null | null | null | Sources/FaviconFinder/Classes/Types/Favicon.swift | francisfeng/FaviconFinder | 1b454ad7f69038b04d9f287ed78128324146ac8f | [
"MIT"
] | null | null | null | //
// Favicon.swift
// Pods
//
// Created by William Lumley on 26/5/21.
//
import Foundation
public struct Favicon {
/// The actual image
public let image: FaviconImage
public let data: Data
/// The url of the .ico or HTML page, of where the favicon was found
public let url: URL
/// The type of favicon we extracted
public let type: FaviconType
/// The download type of the favicon we extracted
public let downloadType: FaviconDownloadType
}
| 18.884615 | 72 | 0.672098 |
51bda34ce7657e9dc3963f7f8904134cc72194d2 | 2,417 | dart | Dart | lib/src/services/isochrones.dart | TheGreatRefrigerator/open_route_service | f42960f89c878d996d519af0a78e1b5e87413308 | [
"MIT"
] | null | null | null | lib/src/services/isochrones.dart | TheGreatRefrigerator/open_route_service | f42960f89c878d996d519af0a78e1b5e87413308 | [
"MIT"
] | null | null | null | lib/src/services/isochrones.dart | TheGreatRefrigerator/open_route_service | f42960f89c878d996d519af0a78e1b5e87413308 | [
"MIT"
] | null | null | null | part of 'package:open_route_service/src/open_route_service_base.dart';
extension ORServiceIsochrones on OpenRouteService {
static const String _isochronesEndpointURL =
'${OpenRouteService._baseURL}/v2/isochrones';
/// Obtain Isochrone (areas of reachability) Datas for the [locations] given
/// as a [List] of [Coordinate].
///
/// The Isochrone Service supports time and distance analysies for one single
/// or multiple locations.
///
/// You may also specify the isochrone interval or provide multiple exact
/// isochrone range values.
///
/// The isochrone service supports the following [attributes]: 'area',
/// 'reachfactor', 'total_pop'.
///
/// Information about the endpoint, parameters, response etc. can be found at:
/// https://openrouteservice.org/dev/#/api-docs/v2/isochrones/{profile}/post
Future<GeoJsonFeatureCollection> getIsochrones({
required List<Coordinate> locations,
required List<int> range,
List<String> attributes = const <String>[],
String? id,
bool intersections = false,
int? interval,
String locationType = 'start',
Map<String, dynamic>? options,
String rangeType = 'time',
int? smoothing,
String areaUnits = 'm',
String units = 'm',
ORSProfile? profileOverride,
}) async {
// If a path parameter override is provided, use it.
final ORSProfile chosenPathParam = profileOverride ?? _profile;
// Build the request URL.
final Uri uri = Uri.parse(
'$_isochronesEndpointURL/${OpenRouteService.getProfileString(chosenPathParam)}',
);
// Ready data to be sent.
final Map<String, dynamic> queryParameters = <String, dynamic>{
'locations': locations
.map<List<double>>(
(coordinate) => <double>[coordinate.longitude, coordinate.latitude],
)
.toList(),
'range': range,
'attributes': attributes,
'id': id,
'intersections': intersections,
'interval': interval,
'location_type': locationType,
'options': options,
'range_type': rangeType,
'smoothing': smoothing,
'area_units': areaUnits,
'units': units,
}..removeWhere((key, value) => value == null);
// Fetch and parse the data.
final Map<String, dynamic> data =
await _openRouteServicePost(uri: uri, data: queryParameters);
return GeoJsonFeatureCollection.fromJson(data);
}
}
| 34.528571 | 86 | 0.667356 |
e2e7afbd25e5cfa22e6611b125f12af3de1be88c | 8,422 | py | Python | tests/test_registration.py | berpress/shop_tests | c07329b93902a84f30043a38ec68f4e9d1576d94 | [
"Apache-2.0"
] | null | null | null | tests/test_registration.py | berpress/shop_tests | c07329b93902a84f30043a38ec68f4e9d1576d94 | [
"Apache-2.0"
] | 44 | 2021-02-03T18:19:31.000Z | 2021-02-10T15:20:54.000Z | tests/test_registration.py | berpress/shop_tests | c07329b93902a84f30043a38ec68f4e9d1576d94 | [
"Apache-2.0"
] | null | null | null | from models.fake_data import PersonalInformationData, Address
from common.constants import Users, Registration as reg, RandomData as rand
import allure
import pytest
from models.regdata import RegData
class TestRegistration:
@allure.story("Регистрация")
@allure.severity("critical")
@pytest.mark.skip(
reason="Не доделан переход на regdata"
)
def test_registration(self, app):
"""
Позитивный тест
1. Открыть главную страницу
2. Нажать на кнопку Sign in в хедере
3. Ввести e-mail
4. Нажать create an account
5. Заполнить все поля на форме
6. Нажать кнопку Register
"""
app.login.logout_button_click()
user = RegData.random()
email = user.login
addr = Address.random()
app.open_main_page()
app.registration.go_to_registration_form(email)
app.registration.fill_personal_information(
user.passwd, user.firstname, user.lastname, user.years
)
app.registration.fill_address(
user.firstname,
user.lastname,
addr.address,
addr.city,
addr.country,
addr.phone,
)
assert app.registration.account_header() == "MY ACCOUNT"
# @pytest.mark.parametrize(
# "email, expected_result",
# [
# pytest.param(Users.INVALID_EMAIL_2, reg.EMAIL_ERROR,
# id='Invalid email address'),
# pytest.param(Users.EMPTY_EMAIL, reg.EMAIL_ERROR,
# id='Empty email address'),
# pytest.param(Users.EMAIL, reg.EMAIL_EXISTS,
# id='Existing email'),
# ],
# )
# @allure.story("Регистрация")
# @allure.severity("minor")
# def test_registration_wrong_email(self, app, email, expected_result):
# """
# Негативные тесты для первого шага регистрации,
# где требуется только ввод email
# 1. Открыть главную страницу
# 2. Нажать на кнопку Sign In в правом верхнем углу
# 3. Ввести некорректный e-mail
# 4. Ожидается возникновение ошибок
# """
# app.open_main_page()
# app.registration.go_to_registration_form(email)
# error_message = str(app.registration.wrong_email_alert(expected_result))
#
# assert expected_result in error_message,
# f"Текст ошибки не соответствует ожидаемому.
# Текст ошибки:\n {error_message}\n, ожидаемый результат:\n {expected_result}"
#
# @pytest.mark.parametrize(
# "firstname, lastname, address1, city, expected_result",
# [
# pytest.param(rand.user.first_name, '', rand.addr.address,
# rand.addr.city,
# reg.LASTNAME_REQUIRED, id='Empty lastname'),
# pytest.param('', rand.user.last_name, rand.addr.address,
# rand.addr.city,
# reg.FIRSTNAME_REQUIRED, id='Empty firstname'),
# pytest.param(rand.user.first_name, rand.user.last_name, '',
# rand.addr.city,
# reg.ADDRESS_REQUIRED, id='Empty address'),
# pytest.param(rand.user.first_name, rand.user.last_name,
# rand.addr.address,
# '', reg.CITY_REQUIRED, id='Empty city')
# app.registration.go_to_registration_form(rand.email)
# app.registration.fill_personal_information(
# rand.user.password,
# rand.user.first_name,
# rand.user.last_name,
# rand.date.year,
# )
# app.registration.fill_address(
# rand.user.first_name,
# rand.user.last_name,
# rand.addr.address,
# rand.addr.city,
# rand.addr.country,
# rand.addr.phone,
# )
# assert app.registration.account_header() == "MY ACCOUNT"
# app.login.logout_button_click()
# @pytest.mark.parametrize(
# "email, expected_result",
# [
# pytest.param(
# Users.INVALID_EMAIL_2, reg.EMAIL_ERROR, id="Invalid email address"
# ),
# pytest.param(Users.EMPTY_EMAIL, reg.EMAIL_ERROR, id="Empty email address"),
# pytest.param(Users.EMAIL, reg.EMAIL_EXISTS, id="Existing email"),
# ],
# )
# @allure.story("Регистрация")
# @allure.severity("minor")
# def test_registration_wrong_email(self, app, email, expected_result):
# """
# Негативные тесты для первого шага регистрации,
# где требуется только ввод email
# 1. Открыть главную страницу
# 2. Нажать на кнопку Sign In в правом верхнем углу
# 3. Ввести некорректный e-mail
# 4. Ожидается возникновение ошибок
# """
# user = RegData.random()
# app.open_main_page()
# app.registration.go_to_registration_form(email)
# app.registration.fill_personal_information(user)
# error_message = str(app.registration.wrong_email_alert(expected_result))
# assert expected_result in error_message, (
# f"Текст ошибки не соответствует ожидаемому. Текст ошибки:\n "
# f"{error_message}\n, ожидаемый результат:\n {expected_result}"
# )
# @pytest.mark.parametrize(
# "firstname, lastname, address1, city, expected_result",
# [
# pytest.param(
# rand.user.first_name,
# "",
# rand.addr.address,
# rand.addr.city,
# reg.LASTNAME_REQUIRED,
# id="Empty lastname",
# ),
# pytest.param(
# "",
# rand.user.last_name,
# rand.addr.address,
# rand.addr.city,
# reg.FIRSTNAME_REQUIRED,
# id="Empty firstname",
# ),
# pytest.param(
# rand.user.first_name,
# rand.user.last_name,
# "",
# rand.addr.city,
# reg.ADDRESS_REQUIRED,
# id="Empty address",
# ),
# pytest.param(
# rand.user.first_name,
# rand.user.last_name,
# rand.addr.address,
# "",
# reg.CITY_REQUIRED,
# id="Empty city",
# ),
# ],
# )
# @allure.story("Регистрация")
# @allure.severity("minor")
# def test_registration_empty_fields(self, app, firstname,
# lastname, address1, city, expected_result):
# def test_registration_empty_fields(
# self, app, firstname, lastname, address1, city, expected_result
# ):
# """
# Негативный тест на возникновение ошибки при незаполненных обязательных полях.
# 1. Открыть главную страницу
# 2. Перейти на форму регистрации
# 3. Заполнить секцию личной информации, игнорируя обязательные поля
# 4. Заполнить секцию адреса, игнорируя обязательные поля
# 5. Ожидается возникновение ошибки
# """
# app.open_main_page()
# app.registration.go_to_registration_form(rand.addr.email)
# app.registration.fill_personal_information(
# rand.user.password, rand.user.first_name, rand.user.last_name,
# rand.date.year
# )
# app.registration.fill_address(
# rand.user.first_name,
# rand.user.last_name,
# rand.addr.address,
# rand.addr.city,
# rand.addr.country,
# rand.addr.phone,
# )
# assert app.registration.account_header() == MyAccount.MY_ACCOUNT,
# "Тест упал. Текст ошибки не совпадает с ожидаемым"
# app.login.logout_button_click()
# user = RegData.random()
# app.open_main_page()
# app.registration.go_to_registration_form(rand.addr.email)
# app.registration.fill_personal_information(
# user.password, user.firstname, user.lastname, user.years
# )
# app.registration.fill_address(
# user.firstname,
# user.lastname,
# addr.address,
# addr.city,
# addr.country,
# addr.phone,
# )
# assert (
# app.registration.account_header() == MyAccount.MY_ACCOUNT
# ), "Тест упал. Текст ошибки не совпадает с ожидаемым"
| 37.101322 | 89 | 0.56958 |
af54bd42d587209f4bc971b57f924918e09b2dac | 2,356 | py | Python | pkg/extractor.py | sveatlo/detektilo | d4a2f4abb90be5238ab537e648f35a2e4dc703a5 | [
"MIT"
] | null | null | null | pkg/extractor.py | sveatlo/detektilo | d4a2f4abb90be5238ab537e648f35a2e4dc703a5 | [
"MIT"
] | null | null | null | pkg/extractor.py | sveatlo/detektilo | d4a2f4abb90be5238ab537e648f35a2e4dc703a5 | [
"MIT"
] | null | null | null | import cv2
import imagehash
import xml.etree.ElementTree
import sys
from PIL import Image
from pathlib import Path
hashes = {}
class Extractor():
def __init__(self, root_path, video_file_path, images_dir, skipped_frames=1000, interactive=False):
self.video_file = str(video_file_path)
event_name = list(video_file_path.parts)[
len(list(root_path.parts)) - 1:-1]
self.images_path = Path(
"{}/{}".format(images_dir, "-".join(event_name)))
self.skipped_frames = skipped_frames
self.cap = None
self.frames_cnt = 0
self.interactive = interactive
def process(self):
self.cap = cv2.VideoCapture(self.video_file)
self.frames_cnt = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
self.images_path.mkdir(parents=True, exist_ok=True)
i = 0
while self.cap.isOpened():
# get image
ok, frame = self.cap.read()
if not ok:
break
# skip
i += self.skipped_frames
if i > self.frames_cnt:
i = self.frames_cnt
self.cap.set(cv2.CAP_PROP_POS_FRAMES, i)
# save the image
image = Image.fromarray(frame)
hash = str(imagehash.phash(image, hash_size=12))
if hash in hashes:
continue
hashes[hash] = True
# show image
if self.interactive:
cv2.imshow('frame', frame)
b = False
r = False
while True:
k = cv2.waitKey(0)
if k & 0xFF == ord('q'): # quit
b = True
break
elif k & 0xFF == ord('r'): # reject
r = True
break
elif k & 0xFF == ord('a'): # accept
break
if b:
break
elif r:
continue # skip to next frame
# save image
image_path = "{}/{}.jpg".format(str(self.images_path), i)
if not Path(image_path).exists():
cv2.imwrite(image_path, frame)
try:
self.images_path.rmdir()
except Exception as e:
pass
| 29.45 | 103 | 0.490662 |
e259d5ff4ebe225e42e3cbf53453ce418267529a | 467 | rb | Ruby | lib/crude_mutant/json_result_printer.rb | kellysutton/crude-mutant | 462bf718fd139fdb43c28ef60b21571a0a9a1e89 | [
"MIT"
] | 12 | 2018-12-27T03:03:42.000Z | 2021-03-02T17:55:56.000Z | lib/crude_mutant/json_result_printer.rb | kellysutton/crude-mutant | 462bf718fd139fdb43c28ef60b21571a0a9a1e89 | [
"MIT"
] | 3 | 2018-12-27T17:46:30.000Z | 2018-12-28T02:38:38.000Z | lib/crude_mutant/json_result_printer.rb | kellysutton/crude-mutant | 462bf718fd139fdb43c28ef60b21571a0a9a1e89 | [
"MIT"
] | null | null | null | # frozen_string_literal: true
require "json"
module CrudeMutant
class JsonResultPrinter
class << self
def call(result, stream = $stdout)
stream.print(
JSON.dump({
result.file_path => {
passed_lines: result.run_results.reject(&:success?).map(&:line_number),
failed_lines: result.run_results.select(&:success?).map(&:line_number),
}
}),
)
end
end
end
end
| 22.238095 | 85 | 0.571734 |
14a979d6438d02f9b253615d0c571d529352ffaa | 796 | dart | Dart | lib/parser/components/epitest/subResults.dart | EpitechUtils/EpiMobile | a64140f404835f9b0c544493fe27b97acf810ea7 | [
"MIT"
] | 2 | 2019-05-18T13:18:06.000Z | 2019-06-11T11:59:25.000Z | lib/parser/components/epitest/subResults.dart | EpitechUtils/IntraMobile_Flutter | a64140f404835f9b0c544493fe27b97acf810ea7 | [
"MIT"
] | null | null | null | lib/parser/components/epitest/subResults.dart | EpitechUtils/IntraMobile_Flutter | a64140f404835f9b0c544493fe27b97acf810ea7 | [
"MIT"
] | null | null | null | import 'package:json_annotation/json_annotation.dart';
import 'package:mobile_intranet/parser/components/epitest/resultsSkill.dart';
import 'package:mobile_intranet/parser/components/epitest/resultsExternalItems.dart';
part 'subResults.g.dart';
@JsonSerializable()
class SubResults
{
List<String> logins;
double prerequisites;
Map<String, ResultsSkill> skills;
double percentage;
String mark;
double mandatoryFailed;
List<ResultsExternalItems> externalItems;
int testRunId;
SubResults(this.logins, this.mandatoryFailed, this.mark, this.externalItems, this.prerequisites, this.skills, this.testRunId);
factory SubResults.fromJson(Map<String, dynamic> json) => _$SubResultsFromJson(json);
Map<String, dynamic> toJson() => _$SubResultsToJson(this);
} | 33.166667 | 130 | 0.768844 |
c9357bb53846e809a9beb9054e0a0ffa1dc3fd53 | 1,371 | ts | TypeScript | test/function.test.ts | nullabletypo/atomic | 6493d1e247d4674a2cc0ec5ad39443e370c334eb | [
"MIT"
] | null | null | null | test/function.test.ts | nullabletypo/atomic | 6493d1e247d4674a2cc0ec5ad39443e370c334eb | [
"MIT"
] | 8 | 2020-03-22T02:34:36.000Z | 2021-09-23T02:26:14.000Z | test/function.test.ts | nullabletypo/atomic | 6493d1e247d4674a2cc0ec5ad39443e370c334eb | [
"MIT"
] | null | null | null | import { after, before, compose, delayed, once } from '../src/function'
test('once', () => {
const origin = (a: number, b: number) => a + b
const mock = jest.fn(origin)
const fn = once(mock)
expect(fn(1, 1)).toBe(2)
expect(fn(1, 1)).toBe(2)
expect(mock).toBeCalledTimes(1)
})
test('before', () => {
const origin = (i: number) => i
const mock = jest.fn(origin)
const fn = before(2, mock)
expect(fn(1)).toBe(1)
expect(fn(1)).toBe(1)
expect(fn(1)).toBeUndefined()
expect(mock).toHaveBeenCalledTimes(2)
})
test('after', () => {
const origin = (n: number) => n
const mock = jest.fn(origin)
const fn = after(2, mock)
expect(fn(1)).toBeUndefined()
expect(fn(1)).toBe(1)
expect(fn(1)).toBe(1)
expect(mock).toHaveBeenCalledTimes(2)
})
test('delayed', async () => {
expect.assertions(1)
const fn = delayed(3, (i: number) => i)
expect(await fn(1)).toBe(1)
})
test('compose', () => {
const fn = compose(
(a: number, b: number) => a + b,
(n: number) => n * n,
(s: number) => String(s),
)
expect(fn(1, 2)).toBe('9')
})
test('compose.async', async () => {
expect.assertions(2)
const fn = compose.async(
(a: number, b: number) => a + b,
async (n: number) => n * n,
(s: number) => String(s),
)
const promise = fn(1, 2)
expect(promise).toBeInstanceOf(Promise)
expect(await promise).toBe('9')
})
| 23.637931 | 71 | 0.585704 |
54724d1938e51a0dfaf04b1e6b86ff8101b1a9c6 | 172 | css | CSS | HTML-CSS/aulas-web/box shadow/style.css | DavidRusyckiUnidavi/aula_css | 678f48eed11ffd05f0895e8a0e9d3639e4102b5b | [
"Apache-2.0"
] | null | null | null | HTML-CSS/aulas-web/box shadow/style.css | DavidRusyckiUnidavi/aula_css | 678f48eed11ffd05f0895e8a0e9d3639e4102b5b | [
"Apache-2.0"
] | null | null | null | HTML-CSS/aulas-web/box shadow/style.css | DavidRusyckiUnidavi/aula_css | 678f48eed11ffd05f0895e8a0e9d3639e4102b5b | [
"Apache-2.0"
] | null | null | null | .teste {
width: 200px;
height: 100px;
background-color: #f1efe6;
border: 1px solid #d3cdae;
position: relative;
box-shadow: 3px 3px 10px #aaa;
}
| 14.333333 | 34 | 0.610465 |
4d7b6d21da8d3a832937e2c4d8693f5a9192911c | 1,367 | cs | C# | XUCore.Template.Ddd/Content/XUCore.Template.Ddd/XUCore.Template.Ddd.Persistence/Mappings/User/UserLoginRecordMapping.cs | xuyiazl/XUCore.Template | d92a05349d03c8c8aea2b9b94875f79a51768aec | [
"MIT"
] | 2 | 2021-08-29T06:53:05.000Z | 2021-12-13T05:02:03.000Z | XUCore.Template.Ddd/Content/XUCore.Template.Ddd/XUCore.Template.Ddd.Persistence/Mappings/User/UserLoginRecordMapping.cs | xuyiazl/XUCore.Template | d92a05349d03c8c8aea2b9b94875f79a51768aec | [
"MIT"
] | null | null | null | XUCore.Template.Ddd/Content/XUCore.Template.Ddd/XUCore.Template.Ddd.Persistence/Mappings/User/UserLoginRecordMapping.cs | xuyiazl/XUCore.Template | d92a05349d03c8c8aea2b9b94875f79a51768aec | [
"MIT"
] | null | null | null | using XUCore.Template.Ddd.Domain.Core.Entities.User;
namespace XUCore.Template.Ddd.Persistence.Mappings.User
{
public class UserLoginRecordMapping : BaseKeyMapping<UserLoginRecordEntity>
{
public UserLoginRecordMapping() : base("t_user_loginrecord", t => t.Id)
{
}
public override void Configure(EntityTypeBuilder<UserLoginRecordEntity> builder)
{
base.Configure(builder);
builder.Property(e => e.UserId)
.IsRequired()
.HasColumnType("varchar(50)");
builder.Property(e => e.LoginIp)
.IsRequired()
.HasColumnType("varchar(50)")
.HasCharSet("utf8");
builder.Property(e => e.LoginTime)
.IsRequired()
.HasColumnType("datetime")
.ValueGeneratedOnAddOrUpdate()
.HasDefaultValueSql("CURRENT_TIMESTAMP");
builder.Property(e => e.LoginWay)
.IsRequired()
.HasColumnType("varchar(30)")
.HasCharSet("utf8");
builder.HasOne(d => d.User)
.WithMany(p => p.LoginRecords)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_User_UserLoginRecord");
}
}
}
| 31.068182 | 88 | 0.55523 |
cd3e9a309bfa00b2e94e41919641e5a988fce461 | 367 | cs | C# | Hyperion.SiteManagement/ISiteManager.cs | n3rd/Hyperion | 03d83e3c618b186e86b50d6ba56dae2c05d91204 | [
"MIT"
] | null | null | null | Hyperion.SiteManagement/ISiteManager.cs | n3rd/Hyperion | 03d83e3c618b186e86b50d6ba56dae2c05d91204 | [
"MIT"
] | null | null | null | Hyperion.SiteManagement/ISiteManager.cs | n3rd/Hyperion | 03d83e3c618b186e86b50d6ba56dae2c05d91204 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hyperion.SiteManagement
{
public interface ISiteManager
{
IEnumerable<Site> GetSites();
Task StartAsync(string siteName);
Task StopAsync(string siteName);
Task RestartAsync(string siteName);
}
}
| 21.588235 | 43 | 0.711172 |
5f198fca151cc9a9cd709aaf8ded9e8ba31cda86 | 1,668 | css | CSS | style/main/tablet.css | augustobor/myWebsite | d266465a20bd8d5a54d42271aa36ba3ea3fe4f61 | [
"Apache-2.0"
] | 1 | 2022-03-03T00:43:14.000Z | 2022-03-03T00:43:14.000Z | style/main/tablet.css | augustobor/myWebsite | d266465a20bd8d5a54d42271aa36ba3ea3fe4f61 | [
"Apache-2.0"
] | null | null | null | style/main/tablet.css | augustobor/myWebsite | d266465a20bd8d5a54d42271aa36ba3ea3fe4f61 | [
"Apache-2.0"
] | null | null | null | @import url('../config/menu-desktop.css');
/*Menu*/
.menu-mobile {
display: none;
}
.menu-desktop {
display: block;
background-color: var(--black);
}
/*Profile*/
.website-profile--mobile {
transform: scale(1.3);
}
.website-profile > div .website-profile--article p, .website-portfolio p {
font-size: 3rem;
}
/*Portfolio*/
.website-portfolio > article:nth-child(1), .website-portfolio > article:nth-child(2) {
margin-top: 1rem;
margin-bottom: 15rem;
}
.website-portfolio > article:nth-child(1) hr, .website-portfolio > article:nth-child(2) hr {
margin-top: 2rem;
border-width: 0.4rem;
}
.website-portfolio--high {
flex-direction: row;
margin: 3rem;
}
.website-portfolio--high p {
font-size: xx-large;
}
.website-portfolio > article:nth-last-child(3) {
margin: 2rem 10%;
}
.website-portfolio > article:nth-last-child(3) p {
font-size: 2.5rem;
}
.website-portfolio > article:nth-last-child(3) hr {
margin-top: 1.5rem;
border-width: 0.4rem;
}
.website-portfolio > p {
margin-top: 10rem;
font-size: xx-large;
margin-bottom: 5rem;
}
.website-portfolio--high--button {
font-size: xx-large;
}
.website-portfolio--button, .website-contact--button {
font-size: xx-large;
border-width: 0.3rem;
}
.website-posts--description p {
font-size: x-large;
}
/*Contact*/
.github-image {
transform: scale(0.4);
width: 90%;
}
.website-contact--logos article a .github-image:hover {
transform: scale(0.5);
}
.website-contact > p {
font-size: 5rem;
padding-top: 10rem;
margin-bottom: 1rem;
}
.website-contact--logos {
margin-top: 3rem;
}
| 16.352941 | 92 | 0.63729 |
b8836e564dad9d15c1875b2df875b8a69f8052db | 350 | h | C | UdpProcessor.h | zulhilmizainuddin/nettomon | da5b6c6a99edea0315c19e4c88a7548a16d108ac | [
"MIT"
] | 2 | 2016-01-30T23:45:49.000Z | 2019-03-25T01:04:29.000Z | UdpProcessor.h | zulhilmizainuddin/nettomon | da5b6c6a99edea0315c19e4c88a7548a16d108ac | [
"MIT"
] | null | null | null | UdpProcessor.h | zulhilmizainuddin/nettomon | da5b6c6a99edea0315c19e4c88a7548a16d108ac | [
"MIT"
] | null | null | null | #ifndef NETTOMON_UDPPROCESSOR_H
#define NETTOMON_UDPPROCESSOR_H
#include <netinet/udp.h>
#include "TransportLayerProcessor.h"
class UdpProcessor : public TransportLayerProcessor {
public:
virtual uint16_t getSourcePort(const u_char *header);
virtual uint16_t getDestinationPort(const u_char *header);
};
#endif //NETTOMON_UDPPROCESSOR_H
| 21.875 | 62 | 0.805714 |
cc5fa243a5534b8c432ec36f3e65b3fc750aa87a | 1,849 | dart | Dart | test/iron_behavior_disabled_state_test.dart | bwu-dart-playground/polymer_elements_parent | ac9a5c9198561022455e8b7160fdd0b40489bca9 | [
"BSD-3-Clause"
] | null | null | null | test/iron_behavior_disabled_state_test.dart | bwu-dart-playground/polymer_elements_parent | ac9a5c9198561022455e8b7160fdd0b40489bca9 | [
"BSD-3-Clause"
] | null | null | null | test/iron_behavior_disabled_state_test.dart | bwu-dart-playground/polymer_elements_parent | ac9a5c9198561022455e8b7160fdd0b40489bca9 | [
"BSD-3-Clause"
] | null | null | null | @TestOn('browser')
library polymer_elements.test.iron_behavior_disabled_state_test;
import 'dart:async';
import 'dart:convert';
import 'dart:html';
import 'dart:js';
import 'package:polymer_interop/polymer_interop.dart';
import 'package:test/test.dart';
import 'package:web_components/web_components.dart';
import 'fixtures/iron_behavior_elements.dart';
import 'common.dart';
main() async {
await initWebComponents();
group('disabled-state', () {
TestControl disableTarget;
group('a trivial disabled state', () {
setUp(() {
disableTarget = fixture('TrivialDisabledState');
});
group('when disabled is true', () {
test('receives a disabled attribute', () {
disableTarget.disabled = true;
expect(disableTarget.getAttribute('disabled'), isNotNull);
});
test('receives an appropriate aria attribute', () {
disableTarget.disabled = true;
expect(disableTarget.getAttribute('aria-disabled'), 'true');
});
});
group('when disabled is false', () {
test('loses the disabled attribute', () {
disableTarget.disabled = true;
expect(disableTarget.getAttribute('disabled'), isNotNull);
disableTarget.disabled = false;
expect(disableTarget.getAttribute('disabled'), isNull);
});
});
});
group('a state with an initially disabled target', () {
setUp(() {
disableTarget = fixture('InitiallyDisabledState');
});
test('preserves the disabled attribute on target', () {
expect(disableTarget.getAttribute('disabled'), isNotNull);
expect(disableTarget.disabled, true);
});
test('adds `aria-disabled` to the target', () {
expect(disableTarget.getAttribute('aria-disabled'), 'true');
});
});
});
}
| 29.349206 | 70 | 0.630611 |
dbbb80a1984ff48cf7bdb2d46f750340d13a7985 | 330 | php | PHP | app/Models/Tank.php | mubahood/nawec | 108c8f942d93c28db1573a62246eab4a57a51348 | [
"MIT"
] | null | null | null | app/Models/Tank.php | mubahood/nawec | 108c8f942d93c28db1573a62246eab4a57a51348 | [
"MIT"
] | null | null | null | app/Models/Tank.php | mubahood/nawec | 108c8f942d93c28db1573a62246eab4a57a51348 | [
"MIT"
] | null | null | null | <?php
namespace App\Models;
use Encore\Admin\Form\Field\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tank extends Model
{
use HasFactory;
public function power_station(){
return $this->belongsTo(PowerStation::class,'power_station_id');
}
}
| 20.625 | 72 | 0.751515 |
a468196994949ae8598fe215461dbce80248af7b | 767 | php | PHP | src/vendor/magento/framework/Event/Config.php | tuliodemelo/fulcrum | eae18d5d449d257ab9d9f1a2c1cd0901ee659229 | [
"MIT"
] | 1 | 2018-11-28T08:11:17.000Z | 2018-11-28T08:11:17.000Z | src/vendor/magento/framework/Event/Config.php | tuliodemelo/fulcrum | eae18d5d449d257ab9d9f1a2c1cd0901ee659229 | [
"MIT"
] | 12 | 2018-11-22T05:03:24.000Z | 2018-11-27T06:30:53.000Z | src/vendor/magento/framework/Event/Config.php | tuliodemelo/fulcrum | eae18d5d449d257ab9d9f1a2c1cd0901ee659229 | [
"MIT"
] | 5 | 2018-11-29T00:36:49.000Z | 2020-11-06T07:37:19.000Z | <?php
/**
* Event configuration model
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\Framework\Event;
use Magento\Framework\Event\Config\Data;
class Config implements ConfigInterface
{
/**
* Modules configuration model
*
* @var Data
*/
protected $_dataContainer;
/**
* @param Data $dataContainer
*/
public function __construct(Data $dataContainer)
{
$this->_dataContainer = $dataContainer;
}
/**
* Get observers by event name
*
* @param string $eventName
* @return null|array|mixed
*/
public function getObservers($eventName)
{
return $this->_dataContainer->get($eventName, []);
}
}
| 19.175 | 58 | 0.6206 |
55f9a6c215b3346244cc13eeafbf040dab0ee9ef | 1,281 | sql | SQL | SistemaUniversidad.BackEnd.BD/Stored Procedures/SP_CursosEnMatricula_Actualizar.sql | estibent10/SistemaUniversidad.BackEnd | bf80b401bd40178383c7c033f8cc8fb4ea418ce7 | [
"MIT"
] | null | null | null | SistemaUniversidad.BackEnd.BD/Stored Procedures/SP_CursosEnMatricula_Actualizar.sql | estibent10/SistemaUniversidad.BackEnd | bf80b401bd40178383c7c033f8cc8fb4ea418ce7 | [
"MIT"
] | null | null | null | SistemaUniversidad.BackEnd.BD/Stored Procedures/SP_CursosEnMatricula_Actualizar.sql | estibent10/SistemaUniversidad.BackEnd | bf80b401bd40178383c7c033f8cc8fb4ea418ce7 | [
"MIT"
] | 1 | 2021-12-20T07:03:59.000Z | 2021-12-20T07:03:59.000Z | CREATE PROCEDURE SP_CursosEnMatricula_Actualizar
@CodigoMatricula INT,
@CodigoCurso INT,
@FechaModificacion DATE= GETDATE,
@ModificadoPor VARCHAR (60),
@ExisteError BIT OUTPUT,
@DetalleError VARCHAR(60) OUTPUT
AS
BEGIN TRY
BEGIN TRANSACTION
DECLARE @ExisteCursoEnMatricula BIT
SET @ExisteCursoEnMatricula = dbo.FN_CursosEnMatricula_VerificaExistenciaPorId(@CodigoMatricula,@CodigoCurso)
IF(@ExisteCursoEnMatricula = 1)
BEGIN
UPDATE CursosEnMatricula
SET
CodigoMatricula = @CodigoMatricula,
CodigoCurso = @CodigoCurso,
FechaModificacion = @FechaModificacion,
ModificadoPor = @ModificadoPor
WHERE
CodigoMatricula = @CodigoMatricula AND CodigoCurso = @CodigoCurso
SET @ExisteError = 0
END
ELSE
BEGIN
SET @ExisteError = 1
SET @DetalleError = 'El Curso en Matricula: '+ @CodigoMatricula + ' , '+ @CodigoCurso +', No Existe'
END
COMMIT TRANSACTION
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION
DECLARE @NumeroDeError INT
EXEC @NumeroDeError = SP_ErroresBD_Insertar @ModificadoPor
SET @ExisteError = 1
SET @DetalleError = 'Error actualizando el Curso en Matricula: '+ @CodigoMatricula + ' , '+ @CodigoCurso + '. Número de Error: ' + @NumeroDeError
END CATCH | 28.466667 | 149 | 0.71975 |
751aa1a48e95c7af450e4d74c1bb9bb7a5eab240 | 540 | swift | Swift | HeroesNet/EamCoreUtils/EamCoreUtils/Source/String/StringExtension.swift | Genar/HeroesNet | 7613237cda0ca162bc2560d76a102cd0aef1a402 | [
"MIT"
] | null | null | null | HeroesNet/EamCoreUtils/EamCoreUtils/Source/String/StringExtension.swift | Genar/HeroesNet | 7613237cda0ca162bc2560d76a102cd0aef1a402 | [
"MIT"
] | null | null | null | HeroesNet/EamCoreUtils/EamCoreUtils/Source/String/StringExtension.swift | Genar/HeroesNet | 7613237cda0ca162bc2560d76a102cd0aef1a402 | [
"MIT"
] | 1 | 2021-11-19T10:32:01.000Z | 2021-11-19T10:32:01.000Z | //
// StringExtension.swift
// EamCoreUtils
//
// Created by Genar Codina on 11/11/21.
//
import Foundation
extension String {
public var localized: String {
return NSLocalizedString(self, comment: "\(self)_comment")
}
public func localized(_ args: CVarArg...) -> String {
return String(format: localized, args)
}
}
extension String {
public func numberOfOccurrencesOf(string: String) -> Int {
return self.components(separatedBy: string).count - 1
}
}
| 18 | 66 | 0.616667 |
40aa36175547927e0e42858621c63cf39bf37ebe | 918 | ts | TypeScript | src/helpers/error.ts | YGT-cxy/ts-axios | 2785d934b25122908cb5a0a2cbcf67d5afa1357c | [
"MIT"
] | null | null | null | src/helpers/error.ts | YGT-cxy/ts-axios | 2785d934b25122908cb5a0a2cbcf67d5afa1357c | [
"MIT"
] | null | null | null | src/helpers/error.ts | YGT-cxy/ts-axios | 2785d934b25122908cb5a0a2cbcf67d5afa1357c | [
"MIT"
] | null | null | null | import { AxiosRequestConfig, AxiosResponse } from './../types'
// AxiosError参数集合接口
interface AxiosErrorArgs {
message: string // Error的报错信息
config: AxiosRequestConfig // request的config配置项
code?: string | null // 状态码
request?: any // request实例本身
response?: AxiosResponse // 响应体
}
// request请求响应出错类
class AxiosError extends Error {
isAxiosError: boolean
config: AxiosRequestConfig
code?: string | number | null
request?: any
response?: AxiosResponse
constructor(args: AxiosErrorArgs) {
const { message, config, code, request, response } = args
super(message)
this.isAxiosError = true
this.config = config
this.code = code
this.request = request
this.response = response
Object.setPrototypeOf(this, AxiosError.prototype)
}
}
/**
* 创建axios请求错误的信息
* @param args 参数集合
*/
export function createError(args: AxiosErrorArgs): any {
return new AxiosError(args)
}
| 22.95 | 62 | 0.711329 |
9e8ed98e2ce92f1d1df99c1601cafa956112fdec | 3,027 | kts | Kotlin | build.gradle.kts | cobaltinc/vortex | 5ea999530372814ff0429dfe99805d6260c524ac | [
"MIT"
] | null | null | null | build.gradle.kts | cobaltinc/vortex | 5ea999530372814ff0429dfe99805d6260c524ac | [
"MIT"
] | null | null | null | build.gradle.kts | cobaltinc/vortex | 5ea999530372814ff0429dfe99805d6260c524ac | [
"MIT"
] | null | null | null | plugins {
kotlin("jvm") version "1.6.0"
id("io.spring.dependency-management") version "1.0.11.RELEASE"
`maven-publish`
signing
}
group = "run.cobalt"
version = "0.0.2"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
maven(url = "https://plugins.gradle.org/m2/")
mavenCentral()
}
tasks {
compileKotlin {
kotlinOptions {
jvmTarget = "11"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "11"
}
}
val sourcesJar by creating(Jar::class) {
archiveClassifier.set("sources")
from(sourceSets.main.get().allSource)
}
val javadocJar by creating(Jar::class) {
dependsOn.add(javadoc)
archiveClassifier.set("javadoc")
from(javadoc)
}
artifacts {
archives(sourcesJar)
archives(javadocJar)
archives(jar)
}
}
publishing {
repositories {
maven {
credentials {
username = project.property("ossrhUsername").toString()
password = project.property("ossrhPassword").toString()
}
val releasesRepoUrl = uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/")
val snapshotsRepoUrl = uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")
url = if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl
}
}
publications {
create<MavenPublication>("vortex") {
groupId = "$group"
artifactId = rootProject.name
version = version
from(components["java"])
artifact(tasks["sourcesJar"])
artifact(tasks["javadocJar"])
pom {
name.set("vortex")
packaging = "jar"
description.set("Kotlin functional extensions for Spring Webflux")
url.set("https://github.com/cobaltinc/vortex")
licenses {
license {
name.set("The MIT License")
url.set("https://opensource.org/licenses/MIT")
}
}
developers {
developer {
id.set("kciter")
name.set("Lee Sun-Hyoup")
email.set("[email protected]")
url.set("https://github.com/kciter")
roles.addAll("developer")
timezone.set("Asia/Seoul")
}
}
scm {
connection.set("scm:git:git://github.com/cobaltinc/vortex.git")
developerConnection.set("scm:git:ssh://github.com:cobaltinc/vortex.git")
url.set("https://github.com/cobaltinc/vortex")
}
}
}
}
}
signing {
sign(configurations.archives.get())
sign(publishing.publications["vortex"])
}
dependencyManagement {
imports {
mavenBom("org.springframework.boot:spring-boot-dependencies:2.5.6")
}
}
dependencies {
compileOnly(kotlin("stdlib-jdk8"))
compileOnly(kotlin("reflect"))
compileOnly("org.springframework.boot:spring-boot-starter-webflux")
testImplementation("io.kotest:kotest-runner-junit5:4.6.3")
testImplementation("io.kotest:kotest-framework-engine:4.6.3")
testImplementation("io.projectreactor:reactor-test")
}
| 23.834646 | 100 | 0.631318 |
72e96b69c37b3b53666a8fc1d0efa40c6146bf7e | 6,941 | cs | C# | SecureFolderFS.WinUI/Dialogs/VaultWizardDialog.xaml.cs | securefolderfs-community/SecureFolderFS | f1e7411dcc50c742478ffb04759edc2d7e54c763 | [
"MIT"
] | 17 | 2022-02-08T09:26:20.000Z | 2022-03-30T18:42:28.000Z | SecureFolderFS.WinUI/Dialogs/VaultWizardDialog.xaml.cs | securefolderfs-community/SecureFolderFS | f1e7411dcc50c742478ffb04759edc2d7e54c763 | [
"MIT"
] | null | null | null | SecureFolderFS.WinUI/Dialogs/VaultWizardDialog.xaml.cs | securefolderfs-community/SecureFolderFS | f1e7411dcc50c742478ffb04759edc2d7e54c763 | [
"MIT"
] | null | null | null | using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.WinUI.UI.Animations;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Animation;
using SecureFolderFS.Backend.Dialogs;
using SecureFolderFS.Backend.Enums;
using SecureFolderFS.Backend.Messages;
using SecureFolderFS.Backend.Utils;
using SecureFolderFS.Backend.ViewModels.Dialogs;
using SecureFolderFS.Backend.ViewModels.Pages.VaultWizard;
using SecureFolderFS.WinUI.Helpers;
using SecureFolderFS.WinUI.Views.VaultWizard;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace SecureFolderFS.WinUI.Dialogs
{
public sealed partial class VaultWizardDialog : ContentDialog, IDialog<VaultWizardDialogViewModel>, IRecipient<VaultWizardNavigationRequestedMessage>
{
private bool _hasNavigationAnimatedOnLoaded;
private bool _isBackAnimationState;
public VaultWizardDialogViewModel ViewModel
{
get => (VaultWizardDialogViewModel)DataContext;
set => DataContext = value;
}
public VaultWizardDialog()
{
this.InitializeComponent();
}
public new async Task<DialogResult> ShowAsync() => (DialogResult)await base.ShowAsync();
public async void Receive(VaultWizardNavigationRequestedMessage message)
{
if (message.Value is VaultWizardMainPageViewModel)
{
await NavigateAsync(message.Value, new SuppressNavigationTransitionInfo());
}
else
{
await NavigateAsync(message.Value, new SlideNavigationTransitionInfo() { Effect = SlideNavigationTransitionEffect.FromRight });
}
}
private async Task NavigateAsync(BaseVaultWizardPageViewModel viewModel, NavigationTransitionInfo transition)
{
switch (viewModel)
{
case VaultWizardMainPageViewModel:
ContentFrame.Navigate(typeof(VaultWizardMainPage), viewModel, transition);
break;
case AddExistingVaultPageViewModel:
ContentFrame.Navigate(typeof(AddExistingVaultPage), viewModel, transition);
break;
case ChooseVaultCreationPathPageViewModel:
ContentFrame.Navigate(typeof(ChooseVaultCreationPathPage), viewModel, transition);
break;
case SetPasswordPageViewModel:
ContentFrame.Navigate(typeof(SetPasswordPage), viewModel, transition);
break;
case ChooseEncryptionPageViewModel:
ContentFrame.Navigate(typeof(ChooseEncryptionPage), viewModel, transition);
break;
case VaultWizardFinishPageViewModel:
ContentFrame.Navigate(typeof(VaultWizardFinishPage), viewModel, transition);
break;
}
await FinalizeNavigationAnimationAsync(viewModel);
}
private async Task FinalizeNavigationAnimationAsync(BaseVaultWizardPageViewModel viewModel)
{
switch (viewModel)
{
case VaultWizardMainPageViewModel:
TitleText.Text = "Add new vault";
PrimaryButtonText = string.Empty;
break;
case AddExistingVaultPageViewModel:
TitleText.Text = "Add existing vault";
PrimaryButtonText = "Continue";
break;
case ChooseVaultCreationPathPageViewModel:
TitleText.Text = "Create new vault";
PrimaryButtonText = "Continue";
break;
case SetPasswordPageViewModel:
TitleText.Text = "Set password";
PrimaryButtonText = "Continue";
break;
case ChooseEncryptionPageViewModel:
TitleText.Text = "Choose encryption";
PrimaryButtonText = "Continue";
break;
case VaultWizardFinishPageViewModel:
TitleText.Text = "Summary";
PrimaryButtonText = "Close";
SecondaryButtonText = string.Empty;
break;
}
if (!_hasNavigationAnimatedOnLoaded)
{
_hasNavigationAnimatedOnLoaded = true;
GoBack.Visibility = Visibility.Collapsed;
return;
}
if (!_isBackAnimationState && viewModel.CanGoBack && ContentFrame.CanGoBack)
{
_isBackAnimationState = true;
GoBack.Visibility = Visibility.Visible;
await ShowBackButtonStoryboard.BeginAsync();
ShowBackButtonStoryboard.Stop();
}
else if (_isBackAnimationState && !(viewModel.CanGoBack && ContentFrame.CanGoBack))
{
_isBackAnimationState = false;
await HideBackButtonStoryboard.BeginAsync();
HideBackButtonStoryboard.Stop();
GoBack.Visibility = Visibility.Collapsed;
}
GoBack.Visibility = viewModel.CanGoBack && ContentFrame.CanGoBack ? Visibility.Visible : Visibility.Collapsed;
}
private void VaultWizardDialog_Loaded(object sender, RoutedEventArgs e)
{
ViewModel.Messenger.Register<VaultWizardNavigationRequestedMessage>(this);
ViewModel.StartNavigation();
}
private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
var handledCallback = new HandledOrCanceledFlag(value => args.Cancel = value);
ViewModel.PrimaryButtonClickCommand?.Execute(handledCallback);
}
private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
var handledCallback = new HandledOrCanceledFlag(value => args.Cancel = value);
ViewModel.SecondaryButtonClickCommand?.Execute(handledCallback);
}
private async void GoBack_Click(object sender, RoutedEventArgs e)
{
ContentFrame.GoBack();
if ((ContentFrame.Content as Page)?.DataContext is BaseVaultWizardPageViewModel viewModel)
{
viewModel.ReattachCommands();
await FinalizeNavigationAnimationAsync(viewModel);
}
}
private void ContentDialog_Closing(ContentDialog sender, ContentDialogClosingEventArgs args)
{
(ContentFrame.Content as IDisposable)?.Dispose();
}
}
}
| 38.137363 | 153 | 0.618787 |
48836c4594633244cd497ef4dc7af5d44574060c | 533 | lua | Lua | killfeed/server/killfeed.lua | Jokler/JC2MP-Scripts | d6a2a2534851142b08fa244294367c93bcfca977 | [
"MIT"
] | 1 | 2015-02-19T14:56:50.000Z | 2015-02-19T14:56:50.000Z | killfeed/server/killfeed.lua | Jokler/JC2MP-Scripts | d6a2a2534851142b08fa244294367c93bcfca977 | [
"MIT"
] | null | null | null | killfeed/server/killfeed.lua | Jokler/JC2MP-Scripts | d6a2a2534851142b08fa244294367c93bcfca977 | [
"MIT"
] | 2 | 2015-04-17T22:17:20.000Z | 2021-12-08T16:06:55.000Z | class 'Killfeed'
function Killfeed:__init()
Events:Subscribe("PlayerDeath", self, self.PlayerDeath)
end
function Killfeed:PlayerDeath(args)
t = {["player"] = args.player,
["reason"] = args.reason}
if args.killer and args.killer:GetName() ~= args.player:GetName() then
t.killer = args.killer
args.killer:SetMoney(args.killer:GetMoney() + 100)
end
t.id = math.floor(math.random(1, 3) + 0.5)
Network:Broadcast("PlayerDeath", t)
end
local killfeed = Killfeed() | 24.227273 | 74 | 0.63227 |
377ad4d231bebca342a7f26e0b631a5a8e63be66 | 135 | sh | Shell | rootdir/enableswap.sh | mhdzumair/android_device_e4 | 86c80b9f766520ea522ce75cd637ab4b729b5550 | [
"FTL"
] | null | null | null | rootdir/enableswap.sh | mhdzumair/android_device_e4 | 86c80b9f766520ea522ce75cd637ab4b729b5550 | [
"FTL"
] | null | null | null | rootdir/enableswap.sh | mhdzumair/android_device_e4 | 86c80b9f766520ea522ce75cd637ab4b729b5550 | [
"FTL"
] | null | null | null | #!/bin/sh
echo 536870912 > /sys/block/zram0/disksize
/system/bin/tiny_mkswap /dev/block/zram0
/system/bin/tiny_swapon /dev/block/zram0
| 27 | 42 | 0.777778 |
f446875680da34f8b609887249d68d7af32d29d7 | 2,360 | ts | TypeScript | src/range.ts | zangfenziang/vscode-open | ecfbe085b7aea4e23bf06b9280b0e6b701c5b53f | [
"MIT"
] | null | null | null | src/range.ts | zangfenziang/vscode-open | ecfbe085b7aea4e23bf06b9280b0e6b701c5b53f | [
"MIT"
] | null | null | null | src/range.ts | zangfenziang/vscode-open | ecfbe085b7aea4e23bf06b9280b0e6b701c5b53f | [
"MIT"
] | null | null | null | import * as regex from './regex';
// TODO (ayu): docstrings
class RangeRegex {
lineRegex: string;
linePrefix: string;
constructor(lineRegex: string, linePrefix: string) {
this.lineRegex = lineRegex;
this.linePrefix = linePrefix || '';
}
toRegex(lineSeparator: string, captureGroups: boolean = false): string {
if (captureGroups) {
return (
`${escapeRegex(lineSeparator)}` +
`${this.linePrefix}(?<start>${this.lineRegex})` +
`(?:-${this.linePrefix}(?<end>${this.lineRegex}))?$`
);
}
return (
`${escapeRegex(lineSeparator)}` +
`${this.linePrefix}${this.lineRegex}` +
`(?:-${this.linePrefix}${this.lineRegex})?`
);
}
}
function escapeRegex(value: string): string {
return value.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
export const REGEXES : RangeRegex[] = [
new RangeRegex('[0-9]+', ''),
// e.g. for GitHub, where line numbers are of the form L123-L124 instead of 123-124; hard-code this
// since it's a relatively common line format
new RangeRegex('[0-9]+', 'L'),
];
export class Range {
start: number;
end: number;
constructor(start: number, end: number) {
this.start = start;
this.end = end;
}
toFragment(lineSeparator: string, linePrefix: string): string {
if (this.start === this.end) {
return `${lineSeparator}${linePrefix}${this.start.toString()}`;
}
return `${lineSeparator}${linePrefix}${this.start.toString()}-${linePrefix}${this.end.toString()}`;
}
}
export function extractRangeFromURI(lineSeparator: string, uri: string): [string, Range | null] {
let range: Range | null = null;
let match: RegExpExecArray | null = null;
for (const regex of REGEXES) {
match = RegExp(regex.toRegex(lineSeparator, true)).exec(uri);
if (match) {
break;
}
}
if (match && match.groups) {
const start = match.groups['start'];
const end = match.groups['end'] || start;
range = new Range(
parseInt(start, 10),
parseInt(end, 10),
);
}
if (match) {
uri = uri.slice(0, match.index);
}
return [uri, range];
}
| 27.764706 | 107 | 0.555508 |
d30693d1f98b82ed05e0f5a3e812119d62227c06 | 31 | lua | Lua | resources/words/aty.lua | terrabythia/alfabeter | da422481ba223ebc6c4ded63fed8f75605193d44 | [
"MIT"
] | null | null | null | resources/words/aty.lua | terrabythia/alfabeter | da422481ba223ebc6c4ded63fed8f75605193d44 | [
"MIT"
] | null | null | null | resources/words/aty.lua | terrabythia/alfabeter | da422481ba223ebc6c4ded63fed8f75605193d44 | [
"MIT"
] | null | null | null | return {'atypisch','atypische'} | 31 | 31 | 0.741935 |
4704a75ddd875239d096bc6ef2677edd7e5bded7 | 48,711 | rb | Ruby | lib/adwords_api/v201101/DataServiceMappingRegistry.rb | Luckyplanet/google-adwords-api | 64c8df1c7fca9c0933945d7657981dec78463075 | [
"Apache-2.0"
] | 2 | 2015-10-20T18:18:14.000Z | 2017-02-16T01:39:57.000Z | lib/adwords_api/v201101/DataServiceMappingRegistry.rb | chromeragnarok/adwords_api | b9563ad2729ec98c814b294cf5bcb38c8ce22751 | [
"Apache-2.0"
] | null | null | null | lib/adwords_api/v201101/DataServiceMappingRegistry.rb | chromeragnarok/adwords_api | b9563ad2729ec98c814b294cf5bcb38c8ce22751 | [
"Apache-2.0"
] | 1 | 2020-09-30T21:13:51.000Z | 2020-09-30T21:13:51.000Z | require 'adwords_api/v201101/DataService'
require 'soap/mapping'
module AdwordsApi; module V201101; module DataService
module DefaultMappingRegistry
EncodedRegistry = ::SOAP::Mapping::EncodedRegistry.new
LiteralRegistry = ::SOAP::Mapping::LiteralRegistry.new
NsV201101 = "https://adwords.google.com/api/adwords/cm/v201101"
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::AdGroupBidLandscape,
:schema_type => XSD::QName.new(NsV201101, "AdGroupBidLandscape"),
:schema_basetype => XSD::QName.new(NsV201101, "BidLandscape"),
:schema_element => [
["dataEntry_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "DataEntry.Type")], [0, 1]],
["campaignId", "SOAP::SOAPLong", [0, 1]],
["adGroupId", "SOAP::SOAPLong", [0, 1]],
["startDate", "SOAP::SOAPString", [0, 1]],
["endDate", "SOAP::SOAPString", [0, 1]],
["landscapePoints", "AdwordsApi::V201101::DataService::BidLandscapeLandscapePoint[]", [0, nil]],
["type", "AdwordsApi::V201101::DataService::AdGroupBidLandscapeType", [0, 1]],
["landscapeCurrent", "SOAP::SOAPBoolean", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::AuthenticationError,
:schema_type => XSD::QName.new(NsV201101, "AuthenticationError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::AuthenticationErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::AuthorizationError,
:schema_type => XSD::QName.new(NsV201101, "AuthorizationError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::AuthorizationErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::ClientTermsError,
:schema_type => XSD::QName.new(NsV201101, "ClientTermsError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::ClientTermsErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::CriterionBidLandscape,
:schema_type => XSD::QName.new(NsV201101, "CriterionBidLandscape"),
:schema_basetype => XSD::QName.new(NsV201101, "BidLandscape"),
:schema_element => [
["dataEntry_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "DataEntry.Type")], [0, 1]],
["campaignId", "SOAP::SOAPLong", [0, 1]],
["adGroupId", "SOAP::SOAPLong", [0, 1]],
["startDate", "SOAP::SOAPString", [0, 1]],
["endDate", "SOAP::SOAPString", [0, 1]],
["landscapePoints", "AdwordsApi::V201101::DataService::BidLandscapeLandscapePoint[]", [0, nil]],
["criterionId", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DateError,
:schema_type => XSD::QName.new(NsV201101, "DateError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::DateErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DateRange,
:schema_type => XSD::QName.new(NsV201101, "DateRange"),
:schema_element => [
["min", "SOAP::SOAPString", [0, 1]],
["max", "SOAP::SOAPString", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DistinctError,
:schema_type => XSD::QName.new(NsV201101, "DistinctError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::DistinctErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DoubleValue,
:schema_type => XSD::QName.new(NsV201101, "DoubleValue"),
:schema_basetype => XSD::QName.new(NsV201101, "NumberValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ComparableValue.Type")], [0, 1]],
["number", "SOAP::SOAPDouble", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::InternalApiError,
:schema_type => XSD::QName.new(NsV201101, "InternalApiError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::InternalApiErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::LongValue,
:schema_type => XSD::QName.new(NsV201101, "LongValue"),
:schema_basetype => XSD::QName.new(NsV201101, "NumberValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ComparableValue.Type")], [0, 1]],
["number", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::Money,
:schema_type => XSD::QName.new(NsV201101, "Money"),
:schema_basetype => XSD::QName.new(NsV201101, "ComparableValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ComparableValue.Type")], [0, 1]],
["microAmount", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::NotEmptyError,
:schema_type => XSD::QName.new(NsV201101, "NotEmptyError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::NotEmptyErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::NotWhitelistedError,
:schema_type => XSD::QName.new(NsV201101, "NotWhitelistedError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::NotWhitelistedErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::NullError,
:schema_type => XSD::QName.new(NsV201101, "NullError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::NullErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::OrderBy,
:schema_type => XSD::QName.new(NsV201101, "OrderBy"),
:schema_element => [
["field", "SOAP::SOAPString", [0, 1]],
["sortOrder", "AdwordsApi::V201101::DataService::SortOrder", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::Paging,
:schema_type => XSD::QName.new(NsV201101, "Paging"),
:schema_element => [
["startIndex", "SOAP::SOAPInt", [0, 1]],
["numberResults", "SOAP::SOAPInt", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::Predicate,
:schema_type => XSD::QName.new(NsV201101, "Predicate"),
:schema_element => [
["field", "SOAP::SOAPString", [0, 1]],
["operator", "AdwordsApi::V201101::DataService::PredicateOperator", [0, 1]],
["values", "SOAP::SOAPString[]", [0, nil]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::QuotaCheckError,
:schema_type => XSD::QName.new(NsV201101, "QuotaCheckError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::QuotaCheckErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::C_RangeError,
:schema_type => XSD::QName.new(NsV201101, "RangeError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RangeErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::RateExceededError,
:schema_type => XSD::QName.new(NsV201101, "RateExceededError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RateExceededErrorReason", [0, 1]],
["rateName", "SOAP::SOAPString", [0, 1]],
["rateScope", "SOAP::SOAPString", [0, 1]],
["retryAfterSeconds", "SOAP::SOAPInt", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::RejectedError,
:schema_type => XSD::QName.new(NsV201101, "RejectedError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RejectedErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::RequestError,
:schema_type => XSD::QName.new(NsV201101, "RequestError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RequestErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::RequiredError,
:schema_type => XSD::QName.new(NsV201101, "RequiredError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RequiredErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::SelectorError,
:schema_type => XSD::QName.new(NsV201101, "SelectorError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::SelectorErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::SizeLimitError,
:schema_type => XSD::QName.new(NsV201101, "SizeLimitError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::SizeLimitErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::SoapHeader,
:schema_type => XSD::QName.new(NsV201101, "SoapHeader"),
:schema_element => [
["authToken", "SOAP::SOAPString", [0, 1]],
["clientCustomerId", "SOAP::SOAPString", [0, 1]],
["clientEmail", "SOAP::SOAPString", [0, 1]],
["developerToken", "SOAP::SOAPString", [0, 1]],
["userAgent", "SOAP::SOAPString", [0, 1]],
["validateOnly", "SOAP::SOAPBoolean", [0, 1]],
["partialFailure", "SOAP::SOAPBoolean", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::SoapResponseHeader,
:schema_type => XSD::QName.new(NsV201101, "SoapResponseHeader"),
:schema_element => [
["requestId", "SOAP::SOAPString", [0, 1]],
["operations", "SOAP::SOAPLong", [0, 1]],
["responseTime", "SOAP::SOAPLong", [0, 1]],
["units", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DataError,
:schema_type => XSD::QName.new(NsV201101, "DataError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::DataErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DatabaseError,
:schema_type => XSD::QName.new(NsV201101, "DatabaseError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::DatabaseErrorReason", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::Selector,
:schema_type => XSD::QName.new(NsV201101, "Selector"),
:schema_element => [
["fields", "SOAP::SOAPString[]", [0, nil]],
["predicates", "AdwordsApi::V201101::DataService::Predicate[]", [0, nil]],
["dateRange", "AdwordsApi::V201101::DataService::DateRange", [0, 1]],
["ordering", "AdwordsApi::V201101::DataService::OrderBy[]", [0, nil]],
["paging", "AdwordsApi::V201101::DataService::Paging", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::ApiException,
:schema_type => XSD::QName.new(NsV201101, "ApiException"),
:schema_basetype => XSD::QName.new(NsV201101, "ApplicationException"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApplicationException.Type")], [0, 1]],
["errors", "AdwordsApi::V201101::DataService::ApiError[]", [0, nil]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::ApplicationException,
:schema_type => XSD::QName.new(NsV201101, "ApplicationException"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApplicationException.Type")], [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::BidLandscapeLandscapePoint,
:schema_type => XSD::QName.new(NsV201101, "BidLandscape.LandscapePoint"),
:schema_element => [
["bid", "AdwordsApi::V201101::DataService::Money", [0, 1]],
["clicks", "SOAP::SOAPLong", [0, 1]],
["cost", "AdwordsApi::V201101::DataService::Money", [0, 1]],
["marginalCpc", "AdwordsApi::V201101::DataService::Money", [0, 1]],
["impressions", "SOAP::SOAPLong", [0, 1]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::AdGroupBidLandscapePage,
:schema_type => XSD::QName.new(NsV201101, "AdGroupBidLandscapePage"),
:schema_basetype => XSD::QName.new(NsV201101, "NoStatsPage"),
:schema_element => [
["totalNumEntries", "SOAP::SOAPInt", [0, 1]],
["page_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "Page.Type")], [0, 1]],
["entries", "AdwordsApi::V201101::DataService::AdGroupBidLandscape[]", [0, nil]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::CriterionBidLandscapePage,
:schema_type => XSD::QName.new(NsV201101, "CriterionBidLandscapePage"),
:schema_basetype => XSD::QName.new(NsV201101, "NoStatsPage"),
:schema_element => [
["totalNumEntries", "SOAP::SOAPInt", [0, 1]],
["page_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "Page.Type")], [0, 1]],
["entries", "AdwordsApi::V201101::DataService::CriterionBidLandscape[]", [0, nil]]
]
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::AdGroupBidLandscapeType,
:schema_type => XSD::QName.new(NsV201101, "AdGroupBidLandscape.Type")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::AuthenticationErrorReason,
:schema_type => XSD::QName.new(NsV201101, "AuthenticationError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::AuthorizationErrorReason,
:schema_type => XSD::QName.new(NsV201101, "AuthorizationError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::ClientTermsErrorReason,
:schema_type => XSD::QName.new(NsV201101, "ClientTermsError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DatabaseErrorReason,
:schema_type => XSD::QName.new(NsV201101, "DatabaseError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DateErrorReason,
:schema_type => XSD::QName.new(NsV201101, "DateError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DistinctErrorReason,
:schema_type => XSD::QName.new(NsV201101, "DistinctError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::InternalApiErrorReason,
:schema_type => XSD::QName.new(NsV201101, "InternalApiError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::NotEmptyErrorReason,
:schema_type => XSD::QName.new(NsV201101, "NotEmptyError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::NotWhitelistedErrorReason,
:schema_type => XSD::QName.new(NsV201101, "NotWhitelistedError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::NullErrorReason,
:schema_type => XSD::QName.new(NsV201101, "NullError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::PredicateOperator,
:schema_type => XSD::QName.new(NsV201101, "Predicate.Operator")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::QuotaCheckErrorReason,
:schema_type => XSD::QName.new(NsV201101, "QuotaCheckError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::RangeErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RangeError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::RateExceededErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RateExceededError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::RejectedErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RejectedError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::RequestErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RequestError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::RequiredErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RequiredError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::SelectorErrorReason,
:schema_type => XSD::QName.new(NsV201101, "SelectorError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::SizeLimitErrorReason,
:schema_type => XSD::QName.new(NsV201101, "SizeLimitError.Reason")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::SortOrder,
:schema_type => XSD::QName.new(NsV201101, "SortOrder")
)
EncodedRegistry.register(
:class => AdwordsApi::V201101::DataService::DataErrorReason,
:schema_type => XSD::QName.new(NsV201101, "DataError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::AdGroupBidLandscape,
:schema_type => XSD::QName.new(NsV201101, "AdGroupBidLandscape"),
:schema_basetype => XSD::QName.new(NsV201101, "BidLandscape"),
:schema_element => [
["dataEntry_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "DataEntry.Type")], [0, 1]],
["campaignId", "SOAP::SOAPLong", [0, 1]],
["adGroupId", "SOAP::SOAPLong", [0, 1]],
["startDate", "SOAP::SOAPString", [0, 1]],
["endDate", "SOAP::SOAPString", [0, 1]],
["landscapePoints", "AdwordsApi::V201101::DataService::BidLandscapeLandscapePoint[]", [0, nil]],
["type", "AdwordsApi::V201101::DataService::AdGroupBidLandscapeType", [0, 1]],
["landscapeCurrent", "SOAP::SOAPBoolean", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::AuthenticationError,
:schema_type => XSD::QName.new(NsV201101, "AuthenticationError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::AuthenticationErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::AuthorizationError,
:schema_type => XSD::QName.new(NsV201101, "AuthorizationError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::AuthorizationErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::ClientTermsError,
:schema_type => XSD::QName.new(NsV201101, "ClientTermsError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::ClientTermsErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::CriterionBidLandscape,
:schema_type => XSD::QName.new(NsV201101, "CriterionBidLandscape"),
:schema_basetype => XSD::QName.new(NsV201101, "BidLandscape"),
:schema_element => [
["dataEntry_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "DataEntry.Type")], [0, 1]],
["campaignId", "SOAP::SOAPLong", [0, 1]],
["adGroupId", "SOAP::SOAPLong", [0, 1]],
["startDate", "SOAP::SOAPString", [0, 1]],
["endDate", "SOAP::SOAPString", [0, 1]],
["landscapePoints", "AdwordsApi::V201101::DataService::BidLandscapeLandscapePoint[]", [0, nil]],
["criterionId", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DateError,
:schema_type => XSD::QName.new(NsV201101, "DateError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::DateErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DateRange,
:schema_type => XSD::QName.new(NsV201101, "DateRange"),
:schema_element => [
["min", "SOAP::SOAPString", [0, 1]],
["max", "SOAP::SOAPString", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DistinctError,
:schema_type => XSD::QName.new(NsV201101, "DistinctError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::DistinctErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DoubleValue,
:schema_type => XSD::QName.new(NsV201101, "DoubleValue"),
:schema_basetype => XSD::QName.new(NsV201101, "NumberValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ComparableValue.Type")], [0, 1]],
["number", "SOAP::SOAPDouble", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::InternalApiError,
:schema_type => XSD::QName.new(NsV201101, "InternalApiError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::InternalApiErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::LongValue,
:schema_type => XSD::QName.new(NsV201101, "LongValue"),
:schema_basetype => XSD::QName.new(NsV201101, "NumberValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ComparableValue.Type")], [0, 1]],
["number", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::Money,
:schema_type => XSD::QName.new(NsV201101, "Money"),
:schema_basetype => XSD::QName.new(NsV201101, "ComparableValue"),
:schema_element => [
["comparableValue_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ComparableValue.Type")], [0, 1]],
["microAmount", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::NotEmptyError,
:schema_type => XSD::QName.new(NsV201101, "NotEmptyError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::NotEmptyErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::NotWhitelistedError,
:schema_type => XSD::QName.new(NsV201101, "NotWhitelistedError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::NotWhitelistedErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::NullError,
:schema_type => XSD::QName.new(NsV201101, "NullError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::NullErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::OrderBy,
:schema_type => XSD::QName.new(NsV201101, "OrderBy"),
:schema_element => [
["field", "SOAP::SOAPString", [0, 1]],
["sortOrder", "AdwordsApi::V201101::DataService::SortOrder", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::Paging,
:schema_type => XSD::QName.new(NsV201101, "Paging"),
:schema_element => [
["startIndex", "SOAP::SOAPInt", [0, 1]],
["numberResults", "SOAP::SOAPInt", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::Predicate,
:schema_type => XSD::QName.new(NsV201101, "Predicate"),
:schema_element => [
["field", "SOAP::SOAPString", [0, 1]],
["operator", "AdwordsApi::V201101::DataService::PredicateOperator", [0, 1]],
["values", "SOAP::SOAPString[]", [0, nil]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::QuotaCheckError,
:schema_type => XSD::QName.new(NsV201101, "QuotaCheckError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::QuotaCheckErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::C_RangeError,
:schema_type => XSD::QName.new(NsV201101, "RangeError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RangeErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::RateExceededError,
:schema_type => XSD::QName.new(NsV201101, "RateExceededError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RateExceededErrorReason", [0, 1]],
["rateName", "SOAP::SOAPString", [0, 1]],
["rateScope", "SOAP::SOAPString", [0, 1]],
["retryAfterSeconds", "SOAP::SOAPInt", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::RejectedError,
:schema_type => XSD::QName.new(NsV201101, "RejectedError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RejectedErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::RequestError,
:schema_type => XSD::QName.new(NsV201101, "RequestError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RequestErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::RequiredError,
:schema_type => XSD::QName.new(NsV201101, "RequiredError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::RequiredErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::SelectorError,
:schema_type => XSD::QName.new(NsV201101, "SelectorError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::SelectorErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::SizeLimitError,
:schema_type => XSD::QName.new(NsV201101, "SizeLimitError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::SizeLimitErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::SoapHeader,
:schema_type => XSD::QName.new(NsV201101, "SoapHeader"),
:schema_element => [
["authToken", "SOAP::SOAPString", [0, 1]],
["clientCustomerId", "SOAP::SOAPString", [0, 1]],
["clientEmail", "SOAP::SOAPString", [0, 1]],
["developerToken", "SOAP::SOAPString", [0, 1]],
["userAgent", "SOAP::SOAPString", [0, 1]],
["validateOnly", "SOAP::SOAPBoolean", [0, 1]],
["partialFailure", "SOAP::SOAPBoolean", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::SoapResponseHeader,
:schema_type => XSD::QName.new(NsV201101, "SoapResponseHeader"),
:schema_element => [
["requestId", "SOAP::SOAPString", [0, 1]],
["operations", "SOAP::SOAPLong", [0, 1]],
["responseTime", "SOAP::SOAPLong", [0, 1]],
["units", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DataError,
:schema_type => XSD::QName.new(NsV201101, "DataError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::DataErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DatabaseError,
:schema_type => XSD::QName.new(NsV201101, "DatabaseError"),
:schema_basetype => XSD::QName.new(NsV201101, "ApiError"),
:schema_element => [
["fieldPath", "SOAP::SOAPString", [0, 1]],
["trigger", "SOAP::SOAPString", [0, 1]],
["errorString", "SOAP::SOAPString", [0, 1]],
["apiError_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApiError.Type")], [0, 1]],
["reason", "AdwordsApi::V201101::DataService::DatabaseErrorReason", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::Selector,
:schema_type => XSD::QName.new(NsV201101, "Selector"),
:schema_element => [
["fields", "SOAP::SOAPString[]", [0, nil]],
["predicates", "AdwordsApi::V201101::DataService::Predicate[]", [0, nil]],
["dateRange", "AdwordsApi::V201101::DataService::DateRange", [0, 1]],
["ordering", "AdwordsApi::V201101::DataService::OrderBy[]", [0, nil]],
["paging", "AdwordsApi::V201101::DataService::Paging", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::ApiException,
:schema_type => XSD::QName.new(NsV201101, "ApiException"),
:schema_basetype => XSD::QName.new(NsV201101, "ApplicationException"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApplicationException.Type")], [0, 1]],
["errors", "AdwordsApi::V201101::DataService::ApiError[]", [0, nil]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::ApplicationException,
:schema_type => XSD::QName.new(NsV201101, "ApplicationException"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApplicationException.Type")], [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::BidLandscapeLandscapePoint,
:schema_type => XSD::QName.new(NsV201101, "BidLandscape.LandscapePoint"),
:schema_element => [
["bid", "AdwordsApi::V201101::DataService::Money", [0, 1]],
["clicks", "SOAP::SOAPLong", [0, 1]],
["cost", "AdwordsApi::V201101::DataService::Money", [0, 1]],
["marginalCpc", "AdwordsApi::V201101::DataService::Money", [0, 1]],
["impressions", "SOAP::SOAPLong", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::AdGroupBidLandscapePage,
:schema_type => XSD::QName.new(NsV201101, "AdGroupBidLandscapePage"),
:schema_basetype => XSD::QName.new(NsV201101, "NoStatsPage"),
:schema_element => [
["totalNumEntries", "SOAP::SOAPInt", [0, 1]],
["page_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "Page.Type")], [0, 1]],
["entries", "AdwordsApi::V201101::DataService::AdGroupBidLandscape[]", [0, nil]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::CriterionBidLandscapePage,
:schema_type => XSD::QName.new(NsV201101, "CriterionBidLandscapePage"),
:schema_basetype => XSD::QName.new(NsV201101, "NoStatsPage"),
:schema_element => [
["totalNumEntries", "SOAP::SOAPInt", [0, 1]],
["page_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "Page.Type")], [0, 1]],
["entries", "AdwordsApi::V201101::DataService::CriterionBidLandscape[]", [0, nil]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::AdGroupBidLandscapeType,
:schema_type => XSD::QName.new(NsV201101, "AdGroupBidLandscape.Type")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::AuthenticationErrorReason,
:schema_type => XSD::QName.new(NsV201101, "AuthenticationError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::AuthorizationErrorReason,
:schema_type => XSD::QName.new(NsV201101, "AuthorizationError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::ClientTermsErrorReason,
:schema_type => XSD::QName.new(NsV201101, "ClientTermsError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DatabaseErrorReason,
:schema_type => XSD::QName.new(NsV201101, "DatabaseError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DateErrorReason,
:schema_type => XSD::QName.new(NsV201101, "DateError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DistinctErrorReason,
:schema_type => XSD::QName.new(NsV201101, "DistinctError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::InternalApiErrorReason,
:schema_type => XSD::QName.new(NsV201101, "InternalApiError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::NotEmptyErrorReason,
:schema_type => XSD::QName.new(NsV201101, "NotEmptyError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::NotWhitelistedErrorReason,
:schema_type => XSD::QName.new(NsV201101, "NotWhitelistedError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::NullErrorReason,
:schema_type => XSD::QName.new(NsV201101, "NullError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::PredicateOperator,
:schema_type => XSD::QName.new(NsV201101, "Predicate.Operator")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::QuotaCheckErrorReason,
:schema_type => XSD::QName.new(NsV201101, "QuotaCheckError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::RangeErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RangeError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::RateExceededErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RateExceededError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::RejectedErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RejectedError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::RequestErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RequestError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::RequiredErrorReason,
:schema_type => XSD::QName.new(NsV201101, "RequiredError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::SelectorErrorReason,
:schema_type => XSD::QName.new(NsV201101, "SelectorError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::SizeLimitErrorReason,
:schema_type => XSD::QName.new(NsV201101, "SizeLimitError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::SortOrder,
:schema_type => XSD::QName.new(NsV201101, "SortOrder")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::DataErrorReason,
:schema_type => XSD::QName.new(NsV201101, "DataError.Reason")
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::GetAdGroupBidLandscape,
:schema_name => XSD::QName.new(NsV201101, "getAdGroupBidLandscape"),
:schema_element => [
["serviceSelector", "AdwordsApi::V201101::DataService::Selector", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::GetAdGroupBidLandscapeResponse,
:schema_name => XSD::QName.new(NsV201101, "getAdGroupBidLandscapeResponse"),
:schema_element => [
["rval", "AdwordsApi::V201101::DataService::AdGroupBidLandscapePage", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::ApiException,
:schema_name => XSD::QName.new(NsV201101, "ApiExceptionFault"),
:schema_element => [
["message", "SOAP::SOAPString", [0, 1]],
["applicationException_Type", ["SOAP::SOAPString", XSD::QName.new(NsV201101, "ApplicationException.Type")], [0, 1]],
["errors", "AdwordsApi::V201101::DataService::ApiError[]", [0, nil]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::GetCriterionBidLandscape,
:schema_name => XSD::QName.new(NsV201101, "getCriterionBidLandscape"),
:schema_element => [
["serviceSelector", "AdwordsApi::V201101::DataService::Selector", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::GetCriterionBidLandscapeResponse,
:schema_name => XSD::QName.new(NsV201101, "getCriterionBidLandscapeResponse"),
:schema_element => [
["rval", "AdwordsApi::V201101::DataService::CriterionBidLandscapePage", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::SoapHeader,
:schema_name => XSD::QName.new(NsV201101, "RequestHeader"),
:schema_element => [
["authToken", "SOAP::SOAPString", [0, 1]],
["clientCustomerId", "SOAP::SOAPString", [0, 1]],
["clientEmail", "SOAP::SOAPString", [0, 1]],
["developerToken", "SOAP::SOAPString", [0, 1]],
["userAgent", "SOAP::SOAPString", [0, 1]],
["validateOnly", "SOAP::SOAPBoolean", [0, 1]],
["partialFailure", "SOAP::SOAPBoolean", [0, 1]]
]
)
LiteralRegistry.register(
:class => AdwordsApi::V201101::DataService::SoapResponseHeader,
:schema_name => XSD::QName.new(NsV201101, "ResponseHeader"),
:schema_element => [
["requestId", "SOAP::SOAPString", [0, 1]],
["operations", "SOAP::SOAPLong", [0, 1]],
["responseTime", "SOAP::SOAPLong", [0, 1]],
["units", "SOAP::SOAPLong", [0, 1]]
]
)
end
end; end; end
| 41.350594 | 122 | 0.642011 |
a469c217cb2965333cb4a18d108a5d813b205666 | 2,421 | php | PHP | app/Http/Controllers/API/BookController.php | ThuHtetDev/Rentook_02 | 7e5f09bc3ada3020a1be17102cdc9a4484f89058 | [
"MIT"
] | null | null | null | app/Http/Controllers/API/BookController.php | ThuHtetDev/Rentook_02 | 7e5f09bc3ada3020a1be17102cdc9a4484f89058 | [
"MIT"
] | null | null | null | app/Http/Controllers/API/BookController.php | ThuHtetDev/Rentook_02 | 7e5f09bc3ada3020a1be17102cdc9a4484f89058 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Http\Resources\BookResource;
use App\Http\Resources\BookResourceCollection;
use App\Book;
use Validator;
class BookController extends BaseController
{
public function index()
{
$book = Book::all();
return $this->sendRequest(new BookResourceCollection($book),"All books are in view");
}
public function create()
{
//
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'description' => 'required'
]);
if($validator->fails()){
return $this->errorRequest('Validation Error.', $validator->errors());
}
// $validation = $this->apiValidation($request->all(),[
// 'name' => 'required',
// 'description' => 'required'
// ]);
// if($validation instanceof Response){
// return $validation;
// }
$bookStore = Book::create($request->all());
return $this->sendRequest($bookStore,"New Book is successfully added in view");
}
public function show($id)
{
$bookDetail = Book::find($id);
if(is_null( $bookDetail)){
return $this->notFoundError();
}
return $this->sendRequest(new BookResource($bookDetail),"Detail Book is in view");
}
public function update(Request $request, $id)
{
$bookEdit = Book::find($id);
if(is_null( $bookEdit)){
return $this->notFoundError();
}
$validator = Validator::make($request->all(), [
'name' => 'required',
'description' => 'required'
]);
if($validator->fails()){
return $this->errorRequest('Validation Error.', $validator->errors());
}
$bookEdit->name = $request['name'];
$bookEdit->description = $request['description'];
$bookEdit->save();
return $this->sendRequest($bookEdit,"Book is successfully edited in view");
}
public function destroy($id)
{
$bookDelete = Book::find($id);
$bookDelete->delete();
return $this->giveMsg("Selected Book is successfully deleted in view",202);
}
public function validated(){
}
}
| 29.168675 | 93 | 0.567534 |
71a7eb306ae3a8fe7053737ba8c9f7115ebbb2d3 | 1,462 | rs | Rust | src/main.rs | marti1125/terminal_utils | b685a43aa93368d27c89ed98fca9021584b7801c | [
"MIT"
] | null | null | null | src/main.rs | marti1125/terminal_utils | b685a43aa93368d27c89ed98fca9021584b7801c | [
"MIT"
] | null | null | null | src/main.rs | marti1125/terminal_utils | b685a43aa93368d27c89ed98fca9021584b7801c | [
"MIT"
] | null | null | null | use std::env;
use std::process::Command;
fn main() {
for argument in env::args() {
if argument.len() >= 10 {
// To list any process listening to the port
let open_port = &argument[..10];
if open_port == "open_port=" {
let port = &argument[10..argument.len()];
let cmd = "-i:";
Command::new("lsof")
.args(&[cmd.to_owned() + port])
.spawn()
.expect("failed to execute process");
}
}
if argument.len() >= 15 {
// Kill process in the port
let open_port_kill = &argument[..15];
if open_port_kill == "open_port_kill=" {
let port = &argument[15..argument.len()];
let output = Command::new("lsof")
.args(&["-t", &format!("-i:{port}", port=port), "-sTCP:LISTEN"])
.output()
.expect("failed to execute process");
let mut pid = String::from_utf8_lossy(&output.stdout);
println!("{:?}", &pid[0..5]);
let mut lines = pid.lines();
println!("{:?}", lines.next());
Command::new("kill")
.args(&["-9", &pid[0..5]])
.spawn()
.expect("failed to execute process");
}
}
}
}
| 24.366667 | 84 | 0.413133 |
e221e4cf1a1a49eecc5cd539c9206bec02d704c1 | 1,976 | py | Python | network.py | xaggi/OGNet | bb9741c6ef698366544d01b849f329cc1187c917 | [
"MIT"
] | 64 | 2020-06-19T00:02:00.000Z | 2022-03-27T07:39:24.000Z | network.py | xaggi/OGNet | bb9741c6ef698366544d01b849f329cc1187c917 | [
"MIT"
] | 8 | 2020-07-09T01:54:09.000Z | 2022-01-05T23:16:54.000Z | network.py | xaggi/OGNet | bb9741c6ef698366544d01b849f329cc1187c917 | [
"MIT"
] | 19 | 2020-08-03T07:45:53.000Z | 2022-02-12T02:52:22.000Z |
from torch import nn
class g_net(nn.Module):
def __init__(self):
super(g_net, self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(1, 64, 5, stride=1),
nn.BatchNorm2d(64),
nn.ReLU(True),
nn.Conv2d(64, 128, 5, stride=1),
nn.BatchNorm2d(128),
nn.ReLU(True),
nn.Conv2d(128, 256, 5, stride=1),
nn.ReLU(True),
nn.BatchNorm2d(256),
nn.Conv2d(256, 512, 5, stride=1),
nn.ReLU(True),
nn.BatchNorm2d(512),
)
self.decoder = nn.Sequential(
nn.ConvTranspose2d(512, 256, 5, stride=1),
nn.BatchNorm2d(256),
nn.ReLU(True),
nn.ConvTranspose2d(256, 128, 5, stride=1),
nn.BatchNorm2d(128),
nn.ReLU(True),
nn.ConvTranspose2d(128, 64, 5, stride=1),
nn.BatchNorm2d(64),
nn.ReLU(True),
nn.ConvTranspose2d(64, 1, 5, stride=1),
nn.Tanh()
)
def forward(self, x):
x = self.encoder(x)
x = self.decoder(x)
return x
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class d_net(nn.Module):
def __init__(self):
super(d_net, self).__init__()
self.discriminator = nn.Sequential(
nn.Conv2d(1, 64, 5, stride=2, padding=2),
nn.BatchNorm2d(64),
nn.ReLU(True),
nn.Conv2d(64, 128, 5, stride=2, padding=2),
nn.BatchNorm2d(128),
nn.ReLU(True),
nn.Conv2d(128, 256, 5, stride=2, padding=2),
nn.BatchNorm2d(256),
nn.ReLU(True),
nn.Conv2d(256, 512, 5, stride=2, padding=2),
nn.ReLU(True),
Flatten(),
nn.Linear(4608, 1),
nn.Sigmoid()
)
def forward(self, x):
x = self.discriminator(x)
return x
| 27.830986 | 56 | 0.494939 |
7d646405c05e09a23443942682d89e5d469ab6a9 | 381 | rs | Rust | cli/src/code_generate/project/gitignore_file.rs | Tak-Iwamoto/rusty-gql | 8244d844f827a524cd91ba815fe5d113f3499927 | [
"MIT"
] | 53 | 2022-01-30T23:34:36.000Z | 2022-03-22T08:24:24.000Z | cli/src/code_generate/project/gitignore_file.rs | Tak-Iwamoto/rusty-gql | 8244d844f827a524cd91ba815fe5d113f3499927 | [
"MIT"
] | 1 | 2022-02-15T02:58:56.000Z | 2022-02-19T06:58:50.000Z | cli/src/code_generate/project/gitignore_file.rs | Tak-Iwamoto/rusty-gql | 8244d844f827a524cd91ba815fe5d113f3499927 | [
"MIT"
] | null | null | null | use crate::code_generate::FileDefinition;
pub struct GitignoreFile<'a> {
pub app_name: &'a str,
}
impl<'a> FileDefinition for GitignoreFile<'a> {
fn name(&self) -> String {
".gitignore".to_string()
}
fn path(&self) -> String {
format!("{}/.gitignore", self.app_name)
}
fn content(&self) -> String {
"/target".to_string()
}
}
| 19.05 | 47 | 0.577428 |
2e19df720889ecb59071f601964d50a4f5c21e9b | 3,381 | lua | Lua | swsfawse_ai/data/Scripts/Ai/Landmode/Buildstructureland.lua | Silvakilla/sci-fi-at-war | cdf9b834b4af365878416a7adc17585cf37a7508 | [
"Apache-2.0"
] | null | null | null | swsfawse_ai/data/Scripts/Ai/Landmode/Buildstructureland.lua | Silvakilla/sci-fi-at-war | cdf9b834b4af365878416a7adc17585cf37a7508 | [
"Apache-2.0"
] | null | null | null | swsfawse_ai/data/Scripts/Ai/Landmode/Buildstructureland.lua | Silvakilla/sci-fi-at-war | cdf9b834b4af365878416a7adc17585cf37a7508 | [
"Apache-2.0"
] | null | null | null | -- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/LandMode/BuildStructureLand.lua#4 $
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- (C) Petroglyph Games, Inc.
--
--
-- ***** ** * *
-- * ** * * *
-- * * * * *
-- * * * * * * * *
-- * * *** ****** * ** **** *** * * * ***** * ***
-- * ** * * * ** * ** ** * * * * ** ** ** *
-- *** ***** * * * * * * * * ** * * * *
-- * * * * * * * * * * * * * * *
-- * * * * * * * * * * ** * * * *
-- * ** * * ** * ** * * ** * * * *
-- ** **** ** * **** ***** * ** *** * *
-- * * *
-- * * *
-- * * *
-- * * * *
-- **** * *
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
-- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/LandMode/BuildStructureLand.lua $
--
-- Original Author: Steve Copeland
--
-- $Author: James_Yarrow $
--
-- $Change: 54633 $
--
-- $DateTime: 2006/09/14 17:46:53 $
--
-- $Revision: #4 $
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
require("pgevents")
function Definitions()
Category = "Tactical_Multiplayer_Build_Basic_Structure"
IgnoreTarget = true
TaskForce = {
{
"MainForce"
,"UC_Power_Generator_R | UC_R_Ground_Base_Shield | UC_R_Small_Ground_Base_Shield | UC_Rebel_Mineral_Processor | UC_Rebel_Ground_Mining_Facility | UC_R_Ground_Turbolaser_Tower | UC_R_Ground_Light_Vehicle_Factory | UC_R_Ground_Heavy_Vehicle_Factory | UC_R_Ground_Research_Facility | UC_Communications_Array_R | UC_Ground_Hutt_Palace_R | UC_R_Uplink_Station = 0,1"
,"UC_Power_Generator_E | UC_E_Ground_Base_Shield | UC_E_Small_Ground_Base_Shield | UC_Empire_Mineral_Processor | UC_Empire_Ground_Mining_Facility | UC_E_Ground_Turbolaser_Tower | UC_E_Ground_Light_Vehicle_Factory | UC_E_Ground_Heavy_Vehicle_Factory | UC_E_Ground_Research_Facility | UC_Communications_Array_E | UC_Ground_Hutt_Palace_E | UC_Ground_Magnepulse_Cannon_E = 0,1"
,"UC_U_Ground_Merc_Outpost | UC_U_Ground_Droid_Works | UC_Underworld_Palace | UC_U_Ground_Arms_Depot | UC_Underworld_Mineral_Processor | UC_U_Ground_Turbolaser_Tower | UC_Ground_Hutt_Palace_U | UC_U_Ground_Gravity_Generator = 0,1"
}
}
RequiredCategories = {"Structure"}
AllowFreeStoreUnits = false
end
function MainForce_Thread()
BlockOnCommand(MainForce.Build_All())
MainForce.Set_Plan_Result(true)
ScriptExit()
end
| 47.619718 | 375 | 0.422064 |
516f8e78cfa9ea7faffecccae203142338540438 | 592 | lua | Lua | lib/trace.lua | poga/docker-microservice-dep | 9812a50a8d01e02305cfd796fd79f235d4caadd6 | [
"MIT"
] | 55 | 2015-09-18T05:38:32.000Z | 2021-03-11T04:55:12.000Z | lib/trace.lua | poga/docker-microservice-dep | 9812a50a8d01e02305cfd796fd79f235d4caadd6 | [
"MIT"
] | 2 | 2017-12-02T21:31:43.000Z | 2018-04-15T21:33:18.000Z | lib/trace.lua | poga/docker-microservice-dep | 9812a50a8d01e02305cfd796fd79f235d4caadd6 | [
"MIT"
] | 3 | 2018-04-15T16:17:45.000Z | 2021-01-21T22:33:35.000Z | -- generate trace ID if there's none
-- trace-id == root-span-id
if not ngx.var.HTTP_X_SPACER_TRACE_ID then
-- use request_id so we don't have to generate unique id by ourself
ngx.req.set_header('X-SPACER-TRACE-ID', ngx.var.request_id)
end
-- We are a child span if there's already a SPAN_ID
-- in this case, move the original SPAN_ID to PARENT_SPAN_ID and generate a new SPAN_ID
if ngx.var.HTTP_X_SPACER_SPAN_ID then
ngx.req.set_header('X-SPACER-PARENT-SPAN-ID', ngx.var.HTTP_X_SPACER_SPAN_ID)
end
-- generate SPAN_ID
ngx.req.set_header('X-SPACER-SPAN-ID', ngx.var.request_id)
| 37 | 87 | 0.756757 |
1dfdb976f14f223165e9d55e08398025ec34d1e1 | 636 | kt | Kotlin | android_app/app/src/main/java/com/pwr/sailapp/ui/generic/ScopedActivity.kt | PGliw/SailApp | 8d87679ef94f44071f12a2ea3fa9b84834ea60b2 | [
"MIT"
] | null | null | null | android_app/app/src/main/java/com/pwr/sailapp/ui/generic/ScopedActivity.kt | PGliw/SailApp | 8d87679ef94f44071f12a2ea3fa9b84834ea60b2 | [
"MIT"
] | 42 | 2019-04-01T13:35:45.000Z | 2022-02-26T10:32:51.000Z | android_app/app/src/main/java/com/pwr/sailapp/ui/generic/ScopedActivity.kt | PGliw/SailApp | 8d87679ef94f44071f12a2ea3fa9b84834ea60b2 | [
"MIT"
] | 3 | 2019-05-12T00:32:46.000Z | 2019-11-25T20:11:17.000Z | package com.pwr.sailapp.ui.generic
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlin.coroutines.CoroutineContext
abstract class ScopedActivity : AppCompatActivity(), CoroutineScope {
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
override fun onDestroy() {
super.onDestroy()
job.cancel()
}
protected fun toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
} | 27.652174 | 93 | 0.756289 |
42f67bb8ada877e33dda59c127a0cf639ae96f0e | 307 | sql | SQL | DB-with-C#/Labs-And-Homeworks/Databases Basics - MS SQL Server/06. Built-in functions - Exercise/10RankEmployeesBySalary.sql | veloman86/SoftUni-Software-Engineering | 20348f2335dc4256a5fe5622569104eaa28b2131 | [
"MIT"
] | 1 | 2020-02-05T23:22:02.000Z | 2020-02-05T23:22:02.000Z | DB-with-C#/Labs-And-Homeworks/Databases Basics - MS SQL Server/06. Built-in functions - Exercise/10RankEmployeesBySalary.sql | veloman86/SoftUni-Software-Engineering | 20348f2335dc4256a5fe5622569104eaa28b2131 | [
"MIT"
] | null | null | null | DB-with-C#/Labs-And-Homeworks/Databases Basics - MS SQL Server/06. Built-in functions - Exercise/10RankEmployeesBySalary.sql | veloman86/SoftUni-Software-Engineering | 20348f2335dc4256a5fe5622569104eaa28b2131 | [
"MIT"
] | 7 | 2019-07-09T12:53:25.000Z | 2021-01-05T16:07:54.000Z | SELECT EmployeeID,
FirstName,
LastName,
Salary,
DENSE_RANK() OVER (
PARTITION BY Salary
ORDER BY EmployeeID
)
[Rank]
FROM Employees
WHERE Salary BETWEEN 10000 AND 50000
ORDER BY Salary
DESC | 23.615385 | 39 | 0.495114 |
a18de011cbec759e513c042fe3df579d5d494d39 | 592 | ts | TypeScript | front/src/app/models/UserPublic.model.ts | jdakata/concours-photo | 568f00ac8e989c86d943211155ea32a73fc1b9f3 | [
"MIT"
] | null | null | null | front/src/app/models/UserPublic.model.ts | jdakata/concours-photo | 568f00ac8e989c86d943211155ea32a73fc1b9f3 | [
"MIT"
] | null | null | null | front/src/app/models/UserPublic.model.ts | jdakata/concours-photo | 568f00ac8e989c86d943211155ea32a73fc1b9f3 | [
"MIT"
] | null | null | null | import {User} from './User.model';
export class UserPublic {
constructor(
public id,
public username,
public victories,
public score,
public theme_score,
public participations,
public rank,
public photo
) {
}
static fromUser(user: User): UserPublic {
return new UserPublic(
user.id,
user.username,
user.victories,
user.theme_score,
user.score,
user.participations,
user.rank,
user.photo
);
}
}
| 20.413793 | 45 | 0.510135 |
46d24ac092cabd253e49c905af0cfa7be6439b99 | 174 | py | Python | web/settings/production.py | beniaminonobile/www.albertifra.it | 721b6125bbe56e806cf3abd5270d9c5cd85034be | [
"MIT"
] | null | null | null | web/settings/production.py | beniaminonobile/www.albertifra.it | 721b6125bbe56e806cf3abd5270d9c5cd85034be | [
"MIT"
] | null | null | null | web/settings/production.py | beniaminonobile/www.albertifra.it | 721b6125bbe56e806cf3abd5270d9c5cd85034be | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Put here your production specific settings
ADMINS = [
('Francesca Alberti', '[email protected]'),
]
EMAIL_SUBJECT_PREFIX = '[ALBERTIFRA]' | 21.75 | 52 | 0.683908 |
eb3bd839caf81564045ef2b7c8902380ec1554ab | 1,007 | css | CSS | static/style.css | gbv/coli-rich | 94393d40329d038cdf69a1ab0466aed82961c974 | [
"MIT"
] | 1 | 2021-09-30T07:07:51.000Z | 2021-09-30T07:07:51.000Z | static/style.css | gbv/coli-rich | 94393d40329d038cdf69a1ab0466aed82961c974 | [
"MIT"
] | 22 | 2020-08-14T09:02:33.000Z | 2021-08-23T07:45:33.000Z | static/style.css | gbv/coli-rich | 94393d40329d038cdf69a1ab0466aed82961c974 | [
"MIT"
] | null | null | null | body {
font-family: Sans-Serif;
}
main {
margin: 1em;
}
h2 {
font-size: large;
}
.table {
border-collapse: collapse;
}
.table thead, tfoot {
background: #eee;
}
.table th {
text-align: left;
}
.table > tbody > tr > td, th {
padding: 0.2em 0.5em;
border: 1px solid #ddd;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
ul.inline {
display: inline;
padding: 0px;
}
ul.inline li {
display: inline;
list-style: none;
}
ul.inline li:after {
content: ", ";
}
ul.inline li:last-child:after {
content: "";
}
header ul.navbar {
padding-bottom: 1em;
border-bottom: 1px solid #ddd;
}
footer {
margin-top: 1em;
border-top: 1px solid #ddd;
}
ul.navbar {
padding: 0 1em;
}
ul.navbar li {
display: inline;
list-style-type: none;
}
ul.navbar li + li::before {
content: "\A0\A0|\A0\A0";
}
li.selected {
font-weight: bold;
}
dl.params dt {
font-family: monospace;
}
dl.params dd {
padding: 0.5em 0;
}
dl.params dl {
margin: 0;
}
| 13.794521 | 32 | 0.612711 |
4561ec0c7487642899455ccc3ff726120ddf3e2e | 4,761 | py | Python | tests/test_adb.py | RakhithJK/andriller | be94bc5aff84069395c333bdf472f39b550bdba7 | [
"MIT"
] | 883 | 2019-12-14T10:47:48.000Z | 2022-03-30T12:35:19.000Z | tests/test_adb.py | RakhithJK/andriller | be94bc5aff84069395c333bdf472f39b550bdba7 | [
"MIT"
] | 40 | 2019-12-18T03:04:28.000Z | 2022-03-30T03:07:05.000Z | tests/test_adb.py | RakhithJK/andriller | be94bc5aff84069395c333bdf472f39b550bdba7 | [
"MIT"
] | 169 | 2019-12-15T17:08:41.000Z | 2022-03-25T12:52:12.000Z | import sys
import pytest
import tempfile
import subprocess
from unittest import mock
from andriller import adb_conn
fake_adb = tempfile.NamedTemporaryFile()
@pytest.fixture
def ADB(mocker):
mocker.patch('andriller.adb_conn.ADBConn.kill')
mocker.patch('andriller.adb_conn.ADBConn._opt_use_capture', return_value=True)
with mock.patch('andriller.adb_conn.ADBConn._get_adb_bin', return_value=fake_adb.name):
with mock.patch('andriller.adb_conn.ADBConn._adb_has_exec', return_value=True):
adb = adb_conn.ADBConn()
adb_cmd = adb.adb.__func__
setattr(adb, 'adb', lambda *args, **kwargs: adb_cmd(adb, *args, **kwargs))
return adb
@pytest.fixture
def ADB_alt(mocker):
mocker.patch('andriller.adb_conn.ADBConn.kill')
mocker.patch('andriller.adb_conn.ADBConn._opt_use_capture', return_value=False)
with mock.patch('andriller.adb_conn.ADBConn._get_adb_bin', return_value=fake_adb.name):
with mock.patch('andriller.adb_conn.ADBConn._adb_has_exec', return_value=False):
adb = adb_conn.ADBConn()
adb_cmd = adb.adb.__func__
setattr(adb, 'adb', lambda *args, **kwargs: adb_cmd(adb, *args, **kwargs))
return adb
@pytest.fixture
def ADB_win(mocker):
mock_sub = mocker.patch('andriller.adb_conn.subprocess', autospec=True)
mock_sub.STARTUPINFO = mock.MagicMock()
mock_sub.STARTF_USESHOWWINDOW = mock.MagicMock()
mocker.patch('andriller.adb_conn.ADBConn.kill')
mocker.patch('andriller.adb_conn.ADBConn._opt_use_capture', return_value=True)
with mock.patch('sys.platform', return_value='win32'):
with mock.patch('andriller.adb_conn.ADBConn._get_adb_bin', return_value=fake_adb.name):
with mock.patch('andriller.adb_conn.ADBConn._adb_has_exec', return_value=True):
adb = adb_conn.ADBConn()
return adb
def test_init_windows(ADB_win):
assert ADB_win.startupinfo is not None
assert ADB_win.rmr == b'\r\r\n'
@pytest.mark.parametrize('file_path, result', [
('/some/file.txt', '/some/file.txt\n'),
('/some/my file.txt', '/some/my file.txt\n'),
('some/file.txt', 'some/file.txt\n'),
])
def test_file_regex(file_path, result):
assert adb_conn.ADBConn._file_regex(file_path).match(result)
def test_adb_simple(ADB, mocker):
output = mock.Mock(stdout=b'lala', returncode=0)
mock_run = mocker.patch('andriller.adb_conn.subprocess.run', return_value=output)
res = ADB('hello')
assert res == 'lala'
mock_run.assert_called_with([fake_adb.name, 'hello'],
capture_output=True, shell=False, startupinfo=None)
def test_adb_simple_su(ADB, mocker):
output = mock.Mock(stdout=b'lala', returncode=0)
mock_run = mocker.patch('andriller.adb_conn.subprocess.run', return_value=output)
res = ADB('hello', su=True)
assert res == 'lala'
mock_run.assert_called_with([fake_adb.name, 'su -c', 'hello'],
capture_output=True, shell=False, startupinfo=None)
def test_adb_binary(ADB, mocker):
output = mock.Mock(stdout=b'lala', returncode=0)
mock_run = mocker.patch('andriller.adb_conn.subprocess.run', return_value=output)
res = ADB('hello', binary=True)
assert res == b'lala'
mock_run.assert_called_with([fake_adb.name, 'hello'],
capture_output=True, shell=False, startupinfo=None)
def test_adb_out(ADB, mocker):
output = mock.Mock(stdout=b'uid(1000)', returncode=0)
mock_run = mocker.patch('andriller.adb_conn.subprocess.run', return_value=output)
res = ADB.adb_out('id', binary=False)
assert res == 'uid(1000)'
mock_run.assert_called_with([fake_adb.name, 'shell', 'id'],
capture_output=True, shell=False, startupinfo=None)
def test_adb_out_alt(ADB_alt, mocker):
output = mock.Mock(stdout=b'uid(1000)', returncode=0)
mock_run = mocker.patch('andriller.adb_conn.subprocess.run', return_value=output)
res = ADB_alt.adb_out('id', binary=True)
assert res == b'uid(1000)'
mock_run.assert_called_with([fake_adb.name, 'shell', 'id'],
stdout=subprocess.PIPE, shell=False, startupinfo=None)
def test_adb_out_win(ADB_win, mocker):
output = mock.Mock(stdout=b'uid(1000)\r\r\n', returncode=0)
mock_run = mocker.patch('andriller.adb_conn.subprocess.run', return_value=output)
res = ADB_win.adb_out('id', binary=True)
assert res == b'uid(1000)\n'
def test_adb_out_uses_exec(ADB, mocker):
ADB._is_adb_out_post_v5 = True
output = mock.Mock(stdout=b'uid(1000)', returncode=0)
mock_run = mocker.patch('andriller.adb_conn.subprocess.run', return_value=output)
res = ADB.adb_out('id', binary=False)
assert res == 'uid(1000)'
mock_run.assert_called_with([fake_adb.name, 'exec-out', 'id'],
capture_output=True, shell=False, startupinfo=None)
| 36.623077 | 95 | 0.710775 |
06d17e1327456ea7fc2376a7520afea4aafbb72d | 740 | py | Python | src/zumanji/admin.py | disqus/zumanji | c68bbae5381f6ab4733256ab0af0ca21af34abcf | [
"Apache-2.0"
] | 8 | 2015-07-14T16:07:22.000Z | 2021-07-05T02:06:31.000Z | src/zumanji/admin.py | disqus/zumanji | c68bbae5381f6ab4733256ab0af0ca21af34abcf | [
"Apache-2.0"
] | null | null | null | src/zumanji/admin.py | disqus/zumanji | c68bbae5381f6ab4733256ab0af0ca21af34abcf | [
"Apache-2.0"
] | null | null | null | from django.contrib import admin
from zumanji.models import Project, Revision, Build
class ProjectAdmin(admin.ModelAdmin):
list_display = ('label',)
search_fields = ('label',)
admin.site.register(Project, ProjectAdmin)
class RevisionAdmin(admin.ModelAdmin):
list_display = ('label', 'project')
list_filter = ('project',)
search_fields = ('label', 'project__label')
admin.site.register(Revision, RevisionAdmin)
class BuildAdmin(admin.ModelAdmin):
list_display = ('id', 'revision', 'num_tests', 'result', 'datetime')
list_filter = ('datetime', 'project', 'result')
search_fields = ('label', 'project__label', 'revision__label')
raw_id_fields = ('revision',)
admin.site.register(Build, BuildAdmin)
| 27.407407 | 72 | 0.710811 |
39308b78fd66d3b216155fa729174e751b15f79d | 3,038 | py | Python | SnP500/ARMA.py | tillaczel/LSTM-GRU-RF-predicting-SP500 | 165bda67dbd613181a52e73d014996a6035762fc | [
"MIT"
] | null | null | null | SnP500/ARMA.py | tillaczel/LSTM-GRU-RF-predicting-SP500 | 165bda67dbd613181a52e73d014996a6035762fc | [
"MIT"
] | null | null | null | SnP500/ARMA.py | tillaczel/LSTM-GRU-RF-predicting-SP500 | 165bda67dbd613181a52e73d014996a6035762fc | [
"MIT"
] | null | null | null | from pandas import read_csv
from pandas import datetime
from pandas import DataFrame
from pmdarima.arima import auto_arima
import matplotlib.pyplot as plt
import numpy as np
import time
import pandas as pd
from manipulate_data import *
def predict(coef, history):
yhat = 0.0
for i in range(1, len(coef)+1):
yhat += coef[i-1] * history[-i]
return yhat
def train_ARMA(number_of_study_periods, study_periods, frequency_index, frequencies, frequencies_number_of_samples):
ARMA_start_time = time.time()
model_results = np.ones((number_of_study_periods,2))*np.Inf
model_names = [None]*number_of_study_periods
train_size, valid_size, test_size = data_split(study_periods)
mse = np.zeros((number_of_study_periods,2))
parameters = np.zeros((number_of_study_periods,2))
predictions = np.zeros((number_of_study_periods,study_periods.shape[2]))
predictions[:] = np.nan
for period in range(number_of_study_periods):
X = study_periods[0,period]
train, test = X[:train_size+valid_size], X[train_size+valid_size:]
mean = np.mean(train)
std = np.std(train)
train_norm, test_norm = (train-mean)/std, (test-mean)/std
# fit model
model = auto_arima(train_norm, exogenous=None, start_p=0, start_q=0, max_p=5, max_q=5, max_order=10, seasonal=False,\
stationary=True, information_criterion='bic', alpha=0.05, test='kpss', stepwise=True, n_jobs=1,\
solver='nm', maxiter=1000, disp=0, suppress_warnings=True, error_action='ignore',\
return_valid_fits=False, out_of_sample_size=0, scoring='mse')
mse[period,0] = np.mean(np.square(train-(model.predict_in_sample()*std+mean)))
forecast = list()
for t in range(len(test_norm)):
yhat = model.predict(n_periods=1)[0]
model.arima_res_.model.endog = np.append(model.arima_res_.model.endog, [test_norm[t]])
forecast.append(yhat)
forecast = np.array(forecast)*std+mean
mse[period,1] = np.mean(np.square(forecast-test))
predictions[period,-len(forecast):] = forecast
parameters[period] = [int(model.order[0]), int(model.order[2])]
print(f'Period: {period}, order: {parameters[period]}, mse: {mse[period]}')
pd.DataFrame(parameters).to_csv('results/ARMA_names_frequency_'+str(frequencies[frequency_index])+'.csv',\
index=False, header=False)
pd.DataFrame(mse).to_csv('results/ARMA_mse_frequency_'+str(frequencies[frequency_index])+'.csv',\
index=False, header=False)
pd.DataFrame(predictions).to_csv('results/ARMA_predictions_frequency_'+str(frequencies[frequency_index])+'.csv',\
index=False, header=False)
print(f'ARMA training time: {np.round((time.time()-ARMA_start_time)/60,2)} minutes')
return parameters, mse, predictions | 46.738462 | 125 | 0.64944 |
2d62b6a963638ceafe8d682fc0ace60546709d3b | 385 | css | CSS | kxEditor/wvbrowser_ui/content_ui/styles.css | kxkx5150/KXEditor | d131cc6312b5cbff0c297bd269a253c0c7c6380a | [
"MIT"
] | 61 | 2019-12-17T15:22:47.000Z | 2022-01-17T08:51:02.000Z | kxEditor/wvbrowser_ui/content_ui/styles.css | kxkx5150/KXEditor | d131cc6312b5cbff0c297bd269a253c0c7c6380a | [
"MIT"
] | 16 | 2019-11-16T00:21:53.000Z | 2021-06-22T18:10:54.000Z | kxEditor/wvbrowser_ui/content_ui/styles.css | kxkx5150/KXEditor | d131cc6312b5cbff0c297bd269a253c0c7c6380a | [
"MIT"
] | 16 | 2019-12-17T15:41:19.000Z | 2022-03-29T12:54:22.000Z | html, body {
margin: 0;
border: none;
padding: 0;
font-family: Arial, Helvetica, sans-serif;
background-color: rgb(240, 240, 242);
}
p {
margin: 0;
}
body {
padding: 32px 50px;
font-family: 'system-ui', sans-serif;
}
.main-title {
display: block;
margin-bottom: 18px;
font-size: 24px;
font-weight: 600;
color: rgb(16, 16, 16);
}
| 14.807692 | 46 | 0.579221 |
af281b71d5dc8b4b89c8f774c158725a97dff5f4 | 1,072 | py | Python | setup.py | mverleg/django_tex_response | fbc3c260ddb9409909c0324759bbd16e037d1a8b | [
"BSD-3-Clause"
] | null | null | null | setup.py | mverleg/django_tex_response | fbc3c260ddb9409909c0324759bbd16e037d1a8b | [
"BSD-3-Clause"
] | 1 | 2019-09-11T06:48:59.000Z | 2019-09-11T06:48:59.000Z | setup.py | mverleg/django_tex_response | fbc3c260ddb9409909c0324759bbd16e037d1a8b | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""
For installing with pip
"""
from distutils.core import setup
import setuptools # keep!
setup(
name='tex-response',
version='1.2.2',
author=u'Mark V',
author_email='[email protected]',
packages=['tex_response'],
include_package_data=True,
url='https://github.com/mverleg/django_tex_response',
license='revised BSD license; see LICENSE.txt',
description='Simple Django code that lets you use your installed luatex compiler to render a .tex template to a pdf-file response.',
zip_safe=True,
classifiers=[
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Software Development :: Libraries :: Python Modules',
# 'Topic :: Utilities',
],
install_requires=[
'django',
],
)
| 29.777778 | 136 | 0.627799 |
387ff08929c80865ea0e20557106a86b46e21256 | 1,529 | php | PHP | app/Exports/StudentsCourseExport.php | mvdcreativo/on_api_v1 | 976686de5a4e81c2138332e01a2cc40b2b8e9243 | [
"MIT"
] | null | null | null | app/Exports/StudentsCourseExport.php | mvdcreativo/on_api_v1 | 976686de5a4e81c2138332e01a2cc40b2b8e9243 | [
"MIT"
] | null | null | null | app/Exports/StudentsCourseExport.php | mvdcreativo/on_api_v1 | 976686de5a4e81c2138332e01a2cc40b2b8e9243 | [
"MIT"
] | null | null | null | <?php
namespace App\Exports;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
class StudentsCourseExport implements FromQuery , WithMapping, WithHeadings
{
use Exportable;
public function __construct(int $course_id)
{
$this->course_id = $course_id;
}
public function query()
{
$course_id = $this->course_id;
$listStudents = Order::query()->with('user')->whereHas('courses', function (Builder $q) use ($course_id){
$q->where('course_id', $course_id);
});
return $listStudents;
}
public function map($list): array
{
return [
$list->id,
trim($list->user->name),
trim($list->user->last_name),
$list->user->email,
trim($list->user->account->type_doc_iden." ".$list->user->account->n_doc_iden),
trim($list->user->account->phone_one." ".$list->user->account->phone_two),
Carbon::parse($list->user->account->birth)->format('d/m/Y'),
];
}
// Headers columnas
public function headings(): array
{
return [
'ID',
'Nombre',
'Apellido',
'Email',
'Documento',
'Teléfonos',
'F.Nac.'
];
}
}
| 20.662162 | 113 | 0.564421 |
aff9e119ceb4f243b5b223b3904876dce1405cd0 | 9,697 | py | Python | misc/migrate_signoffs/migrate_signoffs.py | nova-labs/wild_apricot_python_flask_utils | f3f79dff8a23b4d82385fe6453803fe3d994b93c | [
"MIT"
] | 1 | 2021-07-30T13:09:28.000Z | 2021-07-30T13:09:28.000Z | misc/migrate_signoffs/migrate_signoffs.py | nova-labs/wild_apricot_python_flask_utils | f3f79dff8a23b4d82385fe6453803fe3d994b93c | [
"MIT"
] | 8 | 2021-04-03T12:38:50.000Z | 2021-06-17T22:52:00.000Z | misc/migrate_signoffs/migrate_signoffs.py | nova-labs/wild_apricot_python_flask_utils | f3f79dff8a23b4d82385fe6453803fe3d994b93c | [
"MIT"
] | 1 | 2021-04-07T21:00:12.000Z | 2021-04-07T21:00:12.000Z | #!/usr/bin/env python3
"""
migrate_signoffs.py
Copies nova-labs signoffs from spaceman to wild apricot
adapted from spaceman2apricot.py by https://github.com/azagh
"""
import argparse
import datetime
import pandas as pd
import numpy as np
import os
import sys
import traceback
import urllib.parse
import signoffs
from dotenv import load_dotenv
from WaApi import WaApiClient
import pprint
pp = pprint.PrettyPrinter(stream=sys.stdout,indent=4)
import time
load_dotenv(override=True)
# Connect to WA and get all the contacts from WA
api = WaApiClient(os.getenv("CLIENT_ID"), os.getenv("CLIENT_SECRET"))
api.authenticate_with_apikey(os.getenv("API_KEY"))
accounts = api.execute_request("/accounts")
account = accounts[0]
contactsUrl = account.Url + '/Contacts'
contactfieldsUrl = account.Url + '/contactfields'
contactsignoffsUrl = contactfieldsUrl + '/12472413'
def update_signoffs(contact_id,signoffs,signoffs_ids_by_name):
#pp.pprint(get_contacts_signoffs_by_email('[email protected]'))
"""
how we do it in js
wa_put_data =
{
'Id' : this_contact_id ,
'FieldValues' :
[{
'FieldName' : 'EquipmentSignoffs',
'SystemCode' : window.wautils_equipment_signoff_systemcode,
'Value' :
indiv_signoff_ids
}]
}
What it a they look like in a get
{ 'FieldName': 'NL Signoffs and Categories',
'SystemCode': 'custom-12472413',
'Value': [ {"Id": 13925244, "Label": "[equipment] *GREEN"},
{"Id": 13925245, "Label": "[equipment] *Minor or Supervised Access Only"}]}
"""
# build individual list of signoffs
soc = []
for sos in signoffs:
soc.append({'Id': int(signoffs_ids_by_name[sos]),
'Label': sos})
"""
soc should look something like this now:
[{'Id': 13948202, 'Label': '[equipment] WW_Rikon_Bandsaw Red'},
{'Id': 13948213, 'Label': '[equipment] WWR_SawStop_Table Saw'},
{'Id': 13948153, 'Label': '[signoff] GREEN ORIENTATION'},
{'Id': 13948228, 'Label': '[novapass] WWR_SawStop_Table Saw'},
{'Id': 13948200, 'Label': '[equipment] WW_General_Bandsaw Red'},
{'Id': 13948238, 'Label': '[category] members'}]
"""
# fill in the rest of the request
data = {}
data['Id'] = str(contact_id)
data['FieldValues'] = []
data['FieldValues'].append({'FieldName':'NL Signoffs and Categories',
'SystemCode':'custom-12472413',
'Value': soc
})
"""
The completed request:
{ 'FieldValues': [ { 'FieldName': 'NL Signoffs and Categories',
'SystemCode': 'custom-12472413',
'Value': [ { 'Id': 13948202,
'Label': '[equipment] '
'WW_Rikon_Bandsaw Red'},
{ 'Id': 13948213,
'Label': '[equipment] '
'WWR_SawStop_Table Saw'},
{ 'Id': 13948153,
'Label': '[signoff] GREEN '
'ORIENTATION'},
{ 'Id': 13948228,
'Label': '[novapass] '
'WWR_SawStop_Table Saw'},
{ 'Id': 13948200,
'Label': '[equipment] '
'WW_General_Bandsaw Red'},
{ 'Id': 13948238,
'Label': '[category] members'}]}],
'Id': '56825441'}
"""
#pp.pprint("---------")
#pp.pprint(data)
#pp.pprint("---------")
result = api.execute_request_raw(contactsUrl + "/" + str(contact_id), api_request_object=data, method='PUT')
#import pdb;pdb.set_trace() # stop and debug
return result
def get_contacts_signoffs_by_email(email):
#wa_contact = get_contactfields_by_email('[email protected]')
wa_contact = get_contact_by_email(email)
wa_contact = vars(wa_contact[0])
for f in wa_contact['FieldValues']:
#import pdb;pdb.set_trace() # stop and debug
f = vars(f) # convert from object to dict
if f['FieldName'] == "NL Signoffs and Categories":
#pp.pprint(f)
return(f)
def get_contactfields_by_email(emailAddress):
params = {'$filter': 'Email eq ' + emailAddress,
'$async': 'false'}
request_url = contactsignoffsUrl + '?' + urllib.parse.urlencode(params)
print(request_url)
response = api.execute_request(request_url)
return response
def get_all_contacts():
params = {'$async': 'false'}
request_url = contactsUrl + '?' + urllib.parse.urlencode(params)
#print(request_url)
return api.execute_request(request_url).Contacts
def get_contact_by_email(emailAddress):
params = {'$filter': 'Email eq ' + emailAddress,
'$async': 'false'}
request_url = contactsUrl + '?' + urllib.parse.urlencode(params)
print(request_url)
response = api.execute_request(request_url)
return response.Contacts
def create_member(email, fname, lname, phone, spaceman_id, badge_number):
data = {
'Email': email,
'FirstName': fname,
'LastName': lname,
'FieldValues': [
{
'FieldName': 'Phone',
'Value': phone},
{
'FieldName': 'Spaceman ID',
'Value': '' + str(spaceman_id) + ''},
{
'FieldName': 'Badge Number',
'Value': '' + str(badge_number) + ''},
],
'MembershipEnabled': 'true',
'Status': 'Active',
"MembershipLevel": {
"Id": 1207614
}
}
return api.execute_request(contactsUrl, api_request_object=data, method='POST')
def update_member(contact_id, spaceman_id, badge_number,signoffs):
data = {
'Id': str(contact_id),
'FieldValues': [
{
'FieldName': 'Spaceman ID',
'Value': '' + str(spaceman_id) + ''
},
{
'FieldName': 'Badge Number',
'Value': '' + str(badge_number) + ''
},
],
'MembershipEnabled': 'true',
'Status': 'Active',
"MembershipLevel": {
"Id": 1207614
}
}
return api.execute_request(contactsUrl + "/" + str(contact_id), api_request_object=data, method='PUT')
def parse_fullname(name_string):
names = name_string.split(" ", 1)
firstName = names[0]
if len(names) > 1:
lastName = names[1]
else:
lastName = ''
return firstName, lastName
if __name__ == '__main__':
# Make a dictionary of WA contacts using the spaceman person record id as the key
# Use this key to sync the two databases
wa_id_dictionary = {}
wa_email_dictionary = {}
contacts = get_all_contacts()
for contact in contacts:
wa_email_dictionary[contact.Email] = contact
for value in contact.FieldValues:
if value.FieldName == "Spaceman ID":
wa_id_dictionary[value.Value] = contact
# Make sure we got a list of contacts from WA. If the length is zero
# something bad happened and we shouldn't try to repopulate the entire db
if(len(contacts) < 1):
print("No WA contacts found; exiting")
sys.exit()
# Read in all the users from the legacy system Spaceman
spacemanDump = pd.read_csv(os.getenv("SPACEMAN_URL"))
# loop through the spaceman rows
for sm_row in spacemanDump.itertuples(index = True, name ='Pandas'):
# Skip Attendees for now
if getattr(sm_row, "member_type") == "Attendee":
continue
# determine this user's signoffs
found_signoffs = signoffs.process(getattr(sm_row,"auths"))
# get their spaceman record
sm_record_id = str(getattr(sm_row, "person_record_id"))
# if they have an entry wa..
if sm_record_id in wa_id_dictionary:
spacemanId = getattr(sm_row, "person_record_id")
emailAddress = getattr(sm_row, "email_address").lower().rstrip('.').strip()
badgeNumber = getattr(sm_row, "card_id")
get_contacts_signoffs_by_email(emailAddress)
# get all possible contact fields and their ID
contactfields = get_contactfields_by_email(emailAddress)
signoffs_ids_by_name = {}
for cf in contactfields.AllowedValues:
cfs = vars(cf)
signoffs_ids_by_name[ cfs['Label'] ] = cfs['Value']
sys.stdout.write(datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S"))
sys.stdout.write(f' Updating member: email:[{emailAddress}] spaceman_id:[{spacemanId}] badge_number:[{badgeNumber}] ')
sys.stdout.write('signoffs:(')
for s in found_signoffs:
sys.stdout.write(s)
sys.stdout.write(')\n')
updated_member = update_signoffs(wa_email_dictionary[emailAddress].Id,found_signoffs,signoffs_ids_by_name)
time.sleep(.25) # make sure we don't step over the max rate limit
| 34.265018 | 130 | 0.54883 |
3f0aed5ee7011888708962a16c1b8c2294b6fc21 | 338 | lua | Lua | DxP - Server-V3/data/talkactions/scripts/correr.lua | Renanziinz/Otziinz | 64c5594592e5e44f5d939d95ecdd4c63fcc4281a | [
"MIT"
] | null | null | null | DxP - Server-V3/data/talkactions/scripts/correr.lua | Renanziinz/Otziinz | 64c5594592e5e44f5d939d95ecdd4c63fcc4281a | [
"MIT"
] | 4 | 2018-12-17T22:47:53.000Z | 2018-12-19T05:18:48.000Z | DxP - Server-V3/data/talkactions/scripts/correr.lua | Renanziinz/Otziinz | 64c5594592e5e44f5d939d95ecdd4c63fcc4281a | [
"MIT"
] | null | null | null | function onSay(cid, words, param)
if exhaustion.get(cid, 500) then
doPlayerSendCancel(cid, 'You can use this command only once per 10 seconds.')
return true
end
doCreatureSay(cid, "correr", TALKTYPE_ORANGE_1)
doChangeSpeed(cid, 1 * 500)
doSendMagicEffect(getPlayerPosition(cid), 40)
exhaustion.set(cid, 501, 10)
return true
end | 30.727273 | 78 | 0.760355 |
38cae50c5a4758c285bf70cfc0d296b3686e0fbd | 1,532 | php | PHP | src/ChatSDK/Channels/Product/Builder/Options.php | jawabapp/chat-sdk | 9f251bccec4d081f3f9a065d249f33582e0920de | [
"Apache-2.0"
] | null | null | null | src/ChatSDK/Channels/Product/Builder/Options.php | jawabapp/chat-sdk | 9f251bccec4d081f3f9a065d249f33582e0920de | [
"Apache-2.0"
] | null | null | null | src/ChatSDK/Channels/Product/Builder/Options.php | jawabapp/chat-sdk | 9f251bccec4d081f3f9a065d249f33582e0920de | [
"Apache-2.0"
] | 4 | 2018-11-26T09:52:34.000Z | 2019-03-25T13:08:22.000Z | <?php
/**
* Created by PhpStorm.
* User: ibraheemqanah
* Date: 2019-03-26
* Time: 17:58
*/
namespace ChatSDK\Channels\Product\Builder;
class Options
{
private $options = array();
private $orders = array();
private function add($value, $label, $order) {
$this->options[$value] = $label;
$this->orders[$value] = $order;
return $this;
}
public function getOptions($lang = null) {
if(is_null($lang)) {
return $this->options;
}
$options = array();
foreach ($this->options as $option => $option_label) {
if($option_label instanceof Label) {
array_push($options,[
'value' => $option,
'label' => $option_label->getLabel($lang),
]);
}
if ($option_label instanceof Option) {
array_push($options,[
'value' => $option,
'label' => $option_label->getOption($lang),
]);
}
}
return $options;
}
public static function make(array $options) {
$obj = new self();
if($options) {
$order = 0;
foreach ($options as $value => $option_label) {
$order++;
$obj->add($value, $option_label, $order);
}
}
return $obj;
}
/**
* @return array
*/
public function getOrders()
{
return $this->orders;
}
}
| 20.426667 | 63 | 0.465405 |
d151f0476d53c348586d7e577e7e90068b0afc6a | 2,767 | cs | C# | runtime/CSharp/Antlr4.Tool/Codegen/OutputModelFactory.cs | kaby76/antlr4cs | bc7fb74f3cf64f656cf2c9c1e05d71386e580a41 | [
"BSD-3-Clause"
] | 321 | 2015-01-01T02:40:35.000Z | 2022-03-15T20:55:47.000Z | runtime/CSharp/Antlr4.Tool/Codegen/OutputModelFactory.cs | kaby76/antlr4cs | bc7fb74f3cf64f656cf2c9c1e05d71386e580a41 | [
"BSD-3-Clause"
] | 192 | 2015-01-01T00:49:58.000Z | 2022-02-25T17:14:53.000Z | runtime/CSharp/Antlr4.Tool/Codegen/OutputModelFactory.cs | kaby76/antlr4cs | bc7fb74f3cf64f656cf2c9c1e05d71386e580a41 | [
"BSD-3-Clause"
] | 83 | 2015-01-03T04:12:29.000Z | 2022-02-17T04:09:58.000Z | // Copyright (c) Terence Parr, Sam Harwell. All Rights Reserved.
// Licensed under the BSD License. See LICENSE.txt in the project root for license information.
namespace Antlr4.Codegen
{
using System.Collections.Generic;
using Antlr4.Codegen.Model;
using Antlr4.Codegen.Model.Decl;
using Antlr4.Tool;
using Antlr4.Tool.Ast;
using IntervalSet = Antlr4.Runtime.Misc.IntervalSet;
using NotNullAttribute = Antlr4.Runtime.Misc.NotNullAttribute;
public interface OutputModelFactory
{
Grammar GetGrammar();
[return: NotNull]
CodeGenerator GetGenerator();
[return: NotNull]
AbstractTarget GetTarget();
void SetController(OutputModelController controller);
OutputModelController GetController();
ParserFile ParserFile(string fileName);
Parser Parser(ParserFile file);
LexerFile LexerFile(string fileName);
Lexer Lexer(LexerFile file);
RuleFunction Rule(Rule r);
IList<SrcOp> RulePostamble(RuleFunction function, Rule r);
// ELEMENT TRIGGERS
CodeBlockForAlt Alternative(Alternative alt, bool outerMost);
CodeBlockForAlt FinishAlternative(CodeBlockForAlt blk, IList<SrcOp> ops);
CodeBlockForAlt Epsilon(Alternative alt, bool outerMost);
IList<SrcOp> RuleRef(GrammarAST ID, GrammarAST label, GrammarAST args);
IList<SrcOp> TokenRef(GrammarAST ID, GrammarAST label, GrammarAST args);
IList<SrcOp> StringRef(GrammarAST ID, GrammarAST label);
IList<SrcOp> Set(GrammarAST setAST, GrammarAST label, bool invert);
IList<SrcOp> Wildcard(GrammarAST ast, GrammarAST labelAST);
IList<SrcOp> Action(ActionAST ast);
IList<SrcOp> Sempred(ActionAST ast);
Choice GetChoiceBlock(BlockAST blkAST, IList<CodeBlockForAlt> alts, GrammarAST label);
Choice GetEBNFBlock(GrammarAST ebnfRoot, IList<CodeBlockForAlt> alts);
Choice GetLL1ChoiceBlock(BlockAST blkAST, IList<CodeBlockForAlt> alts);
Choice GetComplexChoiceBlock(BlockAST blkAST, IList<CodeBlockForAlt> alts);
Choice GetLL1EBNFBlock(GrammarAST ebnfRoot, IList<CodeBlockForAlt> alts);
Choice GetComplexEBNFBlock(GrammarAST ebnfRoot, IList<CodeBlockForAlt> alts);
IList<SrcOp> GetLL1Test(IntervalSet look, GrammarAST blkAST);
bool NeedsImplicitLabel(GrammarAST ID, LabeledOp op);
// CONTEXT INFO
OutputModelObject GetRoot();
RuleFunction GetCurrentRuleFunction();
Alternative GetCurrentOuterMostAlt();
CodeBlock GetCurrentBlock();
CodeBlockForOuterMostAlt GetCurrentOuterMostAlternativeBlock();
int GetCodeBlockLevel();
int GetTreeLevel();
}
}
| 29.126316 | 95 | 0.70618 |
06d1b64a7b0d99a72bcf178d62a14abc124266de | 1,075 | py | Python | Basic_Python_Programs/march27.py | Techme2911/HacktoberFest19-Algo | 1ca4007cc014b9d9131be92f362f4d2f846cdbc4 | [
"MIT"
] | null | null | null | Basic_Python_Programs/march27.py | Techme2911/HacktoberFest19-Algo | 1ca4007cc014b9d9131be92f362f4d2f846cdbc4 | [
"MIT"
] | null | null | null | Basic_Python_Programs/march27.py | Techme2911/HacktoberFest19-Algo | 1ca4007cc014b9d9131be92f362f4d2f846cdbc4 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 27 09:09:36 2019
@author: Dell
"""
import math as m
m.pow(2,6)#returns 2^6
m.factorial(6)#returns 6!
m.floor(23.4)#returns an integer lower than the real number
#in this case 23
m.floor(23)#here also 23
m.fmod(6,4)#returns remainder when first arg divided by second arg.
m.modf(23.4)#returs integral and fractional part of the arg.
#here it returns (0.3999999999999986,23.0)
#here it returns an imprecise value of fractional part to 16 decimal digits.
area_of_a_circle=m.pi*(m.pow(5,2))#gives u area of a circle of radius 5
circumference_of_circle=m.tau*(5)#gives circumference of a circle of radius 5
import random as r
r.random()#returns a random floating number btw 0.0 and 1.0
r.choice([1,2,3,4,5,6])#returns random value from a sequence
"""
The sequence can be a list tupple dictionary etc.
"""
r.randint(1,9)#include last item
r.randrange(1,20,2)#don't include last item
l=[1,3,5,7,9]
r.shuffle(l)
print(l)
import tensorflow as tf
tf.__version__
| 19.907407 | 78 | 0.687442 |
ff64bb59b460b0cdf0f109dac57e797cdbbace77 | 10,038 | py | Python | physipy/quantity/dimension.py | mocquin/physipy | a44805dbf4e68544c987e07564dd4a8d50be8b4c | [
"MIT"
] | 5 | 2021-01-23T11:23:07.000Z | 2022-02-28T15:38:58.000Z | physipy/quantity/dimension.py | mocquin/physipy | a44805dbf4e68544c987e07564dd4a8d50be8b4c | [
"MIT"
] | null | null | null | physipy/quantity/dimension.py | mocquin/physipy | a44805dbf4e68544c987e07564dd4a8d50be8b4c | [
"MIT"
] | 2 | 2020-11-07T20:08:08.000Z | 2021-06-09T02:58:04.000Z | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""allows manipulating physical Dimension objects.
PROPOSITIONS:
* method to return a latex-formated str ?
* change the str/repr style to a table-view of the dimension content ?
* should sr be just a unit with dimension rad**2 ?
* add a full-named repr ? (ex: "length/time")
* should Dimension implement add/sub operation (allowed when dims are equal) ?
* change the dimension representation from dict to array (faster) ?
* allow construction with strings (Dimension("m**2") or Dimension ("L**2")) ?
* could define a contains method to check if a dimension is not 0
* try to not relie on numpy/sympy
* should allow complex exponent ?
* move has_integer_dimension from Quantity to Dimension ?
* allow None definition with Dimension() ?
* implementation should not rely on the dimension system choosen
PLEASE NOTE :
- rad and sr are not base SI-units, but were added for convenience. They can be
deleted if not needed, but update tests in consequence.
- this modules relies on :
- sympy to compute the concatenated representation of the Dimension object
- numpy to check if the dimension powers are scalars
"""
import json
import os
import sympy as sp
import numpy as np
from sympy.parsing.sympy_parser import parse_expr
import sympy.printing.latex as latex
dirname = os.path.dirname(__file__)
with open(os.path.join(dirname, "dimension.txt")) as file:
SI_UNIT_SYMBOL = json.load(file)
SI_SYMBOL_LIST = list(SI_UNIT_SYMBOL.keys())
NO_DIMENSION_STR = "no-dimension"
NULL_SI_DICT = {dim: 0 for dim in SI_SYMBOL_LIST}
def parse_str_to_dic(exp_str):
parsed = parse_expr(exp_str)
exp_dic = {str(key):value for key,value in parsed.as_powers_dict().items()}
return exp_dic
def check_pattern(exp_str, symbol_list):
exp_dic = parse_str_to_dic(exp_str)
return set(exp_dic.keys()).issubset(set(symbol_list))
class DimensionError(Exception):
"""Exception class for dimension errors."""
def __init__(self, dim_1, dim_2, binary=True):
"""Init method of DimensionError class."""
if binary:
self.message = ("Dimension error : dimensions of "
"operands are {} and {}, and are "
"differents.").format(str(dim_1), str(dim_2))
else:
self.message = ("Dimension error : dimension is {} "
"but should be {}").format(str(dim_1), str(dim_2))
def __str__(self):
"""Str method of DimensionError class."""
return self.message
class Dimension(object):
"""Allows to manipulate physical dimensions."""
# DEFAULT REPR LATEX can be used to change the way a Dimension
# object is displayed in JLab
DEFAULT_REPR_LATEX = "dim_dict" # "SI_unit"
def __init__(self, definition):
"""Allow the creation of Dimension object with 3 possibile ways."""
self.dim_dict = NULL_SI_DICT.copy()
if definition is None:
pass # dim_dict already initialized
# example : {"L":1, "T":-2}
elif (isinstance(definition, dict) and
set(list(definition.keys())).issubset(SI_SYMBOL_LIST)): #and
#all([np.isscalar(v) for v in definition.values()])):
for dim_symbol, dim_power in definition.items():
self.dim_dict[dim_symbol] = dim_power
# example : "L"
elif definition in list(self.dim_dict.keys()):
self.dim_dict[definition] = 1
# example : "L**2/T**3"
elif (isinstance(definition, str) and check_pattern(definition, SI_UNIT_SYMBOL.keys())):
definition = parse_str_to_dic(definition)
for dim_symbol, dim_power in definition.items():
if dim_power == int(dim_power):
dim_power = int(dim_power)
self.dim_dict[dim_symbol] = dim_power
# example : "m"
elif (isinstance(definition, str) and check_pattern(definition, SI_UNIT_SYMBOL.values())):
definition = parse_str_to_dic(definition)
for my_si_symbol, dim_power in definition.items():
if dim_power == int(dim_power):
dim_power = int(dim_power)
dim_symbol = [dim_symbol for dim_symbol, si_symbol in SI_UNIT_SYMBOL.items() if my_si_symbol == si_symbol][0]
self.dim_dict[dim_symbol] = dim_power
else:
raise TypeError(("Dimension can be constructed with either a "
"string among {}, either None, either a "
"dictionnary with keys included in {}, "
"either a string of sympy expression with "
"those same keys "
"but not {}.").format(SI_SYMBOL_LIST,
SI_SYMBOL_LIST,
definition))
def __str__(self):
"""Concatenate symbol-wise the content of the dim_dict attribute."""
return compute_str(self.dim_dict, NO_DIMENSION_STR)
def __format__(self, format_spec):
raw = self.__str__()
return format(raw, format_spec)
def __repr__(self):
"""Return the dim_dict into a <Dimension : ...> tag."""
return "<Dimension : " + str(self.dim_dict) + ">"
def _repr_latex_(self):
"""Latex repr hook for IPython."""
if self.DEFAULT_REPR_LATEX == "dim_dict":
expr_dim = expand_dict_to_expr(self.dim_dict)
return "$" + latex(expr_dim) + "$"
else:# self.DEFAULT_REPR_LATEX == "SI_unit":
return self.latex_SI_unit()
def __mul__(self, y):
"""Allow the multiplication of Dimension objects."""
if isinstance(y, Dimension):
new_dim_dict = {d: self.dim_dict[d] + y.dim_dict[d] for d in self.dim_dict.keys()}
return Dimension(new_dim_dict)
else:
raise TypeError(("A dimension can only be multiplied "
"by another dimension, not {}.").format(y))
__rmul__ = __mul__
def __truediv__(self, y):
"""Allow the division of Dimension objects."""
if isinstance(y, Dimension):
new_dim_dict = {d: self.dim_dict[d] - y.dim_dict[d] for d in self.dim_dict.keys()}
return Dimension(new_dim_dict)
#elif y == 1: # allowing division by one
# return self
else:
raise TypeError(("A dimension can only be divided "
"by another dimension, not {}.").format(y))
def __rtruediv__(self, x):
"""Only used to raise a TypeError."""
if x == 1: # allowing one-divion
#return self.inverse()
return self**-1
else:
raise TypeError("A Dimension can only divide 1 to be inverted.")
def __pow__(self, y):
"""Allow the elevation of Dimension objects to a real power."""
if np.isscalar(y):
new_dim_dict = {d: self.dim_dict[d] * y for d in self.dim_dict.keys()}
return Dimension(new_dim_dict)
else:
raise TypeError(("The power of a dimension must be a scalar,"
"not {}").format(type(y)))
def __eq__(self, y):
"""Dimensions are equal if their dim_dict are equal."""
return self.dim_dict == y.dim_dict
#def __ne__(self, y):
# """Return not (self == y)."""
# return not self.__eq__(y)
#def inverse(self):
# """Inverse the dimension by taking the negative of the powers."""
# inv_dict = {key: -value for key, value in self.dim_dict.items()}
# return Dimension(inv_dict)
def siunit_dict(self):
"""Return a dict where keys are SI unit
string, and value are powers."""
return {SI_UNIT_SYMBOL[key]: value for key, value in self.dim_dict.items()}
def str_SI_unit(self):
"""Compute the symbol-wise SI unit."""
str_dict = self.siunit_dict()
return compute_str(str_dict, "")
def latex_SI_unit(self):
"""Latex repr of SI unit form."""
expr_SI = expand_dict_to_expr(self.siunit_dict())
return "$" + latex(expr_SI) + "$"
@property
def dimensionality(self):
"""Return the first dimensionality with same
dimension found in DIMENSIONALITY"""
return [dimensionality for dimensionality, dimension in DIMENSIONALITY.items() if dimension == self][0]
def compute_str(dic, default_str, output_init=1):
"""Compute the product-concatenation of the
dict as key**value."""
output = expand_dict_to_expr(dic, output_init)
if output == output_init:
return default_str
else:
return str(output)
def expand_dict_to_expr(dic, output_init=1):
"""Compute the sympy expression from exponent dict,
starting the product with ouptput=1."""
output = output_init
for key, value in dic.items():
output *= sp.Symbol(key)**value
return output
DIMENSIONALITY = {
# Base dimension
"length": Dimension("L"),
"mass": Dimension("M"),
"time": Dimension("T"),
"electric_current": Dimension("I"),
"temperature": Dimension("theta"),
"amount_of_substance":Dimension("N"),
"luminous_intensity": Dimension("J"),
"plane_angle": Dimension("RAD"),
"solid_angle": Dimension("SR"),
#
"area": Dimension({"L":2}),
"volume": Dimension({"L":3}),
"speed": Dimension({"L":1, "T":-1}),
"acceleration": Dimension({"L":1, "T":-2}),
"force": Dimension({"M":1, "L":1, "T":-2}),
"energy": Dimension({"M":1, "L":2, "T":-2}),
"power": Dimension({"M":1, "L":2, "T":-3}),
"capacitance": Dimension({"M":-1, "L":-2, "T":4, "I":2}),
"voltage": Dimension({"M":1, "L":2, "T":-3, "I":-1}),
} | 38.45977 | 125 | 0.595138 |
df2951e9be3b89be0802af9122bf4ca5c3f206b0 | 789 | swift | Swift | CoreTesting/Classes/Extensions/UIStackView+Testing.swift | gsoti/core-testing | 61b51113b9e46ea9c668a3cba2dfdf83f5765e91 | [
"MIT"
] | null | null | null | CoreTesting/Classes/Extensions/UIStackView+Testing.swift | gsoti/core-testing | 61b51113b9e46ea9c668a3cba2dfdf83f5765e91 | [
"MIT"
] | null | null | null | CoreTesting/Classes/Extensions/UIStackView+Testing.swift | gsoti/core-testing | 61b51113b9e46ea9c668a3cba2dfdf83f5765e91 | [
"MIT"
] | 1 | 2020-11-25T12:18:02.000Z | 2020-11-25T12:18:02.000Z | import UIKit
extension UIStackView {
func setBackgroundColor(_ color: UIColor) {
let backgroundView = UIView()
backgroundView.backgroundColor = color
backgroundView.translatesAutoresizingMaskIntoConstraints = false
// put background view as the most background subviews of stack view
insertSubview(backgroundView, at: 0)
// pin the background view edge to the stack view edge
NSLayoutConstraint.activate([
backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor),
backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor),
backgroundView.topAnchor.constraint(equalTo: topAnchor),
backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor),
])
}
}
| 35.863636 | 78 | 0.704689 |
6da79188b6b686f0ae849b8ffb97fe3b02299f0f | 437 | ts | TypeScript | crates/swc_bundler/tests/.cache/deno/f82565dd05871e7fa0d0a36120ce2822e4470f74.ts | mengxy/swc | bcc3ae86ae0732979f9fbfef370ae729ba9af080 | [
"Apache-2.0"
] | 21,008 | 2017-04-01T04:06:55.000Z | 2022-03-31T23:11:05.000Z | bundler/tests/.cache/deno/f82565dd05871e7fa0d0a36120ce2822e4470f74.ts | sventschui/swc | cd2a2777d9459ba0f67774ed8a37e2b070b51e81 | [
"Apache-2.0",
"MIT"
] | 2,309 | 2018-01-14T05:54:44.000Z | 2022-03-31T15:48:40.000Z | bundler/tests/.cache/deno/f82565dd05871e7fa0d0a36120ce2822e4470f74.ts | sventschui/swc | cd2a2777d9459ba0f67774ed8a37e2b070b51e81 | [
"Apache-2.0",
"MIT"
] | 768 | 2018-01-14T05:15:43.000Z | 2022-03-30T11:29:42.000Z | // Loaded from https://deno.land/x/[email protected]/packages/command/types/number.ts
import { IFlagArgument, IFlagOptions } from '../../flags/lib/types.ts';
import { number } from '../../flags/lib/types/number.ts';
import { Type } from './type.ts';
export class NumberType extends Type<number> {
public parse( option: IFlagOptions, arg: IFlagArgument, value: string ): number {
return number( option, arg, value );
}
}
| 31.214286 | 85 | 0.677346 |
0c50c17c3c2d76d2398654f4bf028e54723a64e1 | 204 | rb | Ruby | db/migrate/20141018001557_create_topic.rb | kamilbielawski/knowledge_base | acf7f3b0b36211d779f477af8b5f3e1597d57a7a | [
"MIT"
] | null | null | null | db/migrate/20141018001557_create_topic.rb | kamilbielawski/knowledge_base | acf7f3b0b36211d779f477af8b5f3e1597d57a7a | [
"MIT"
] | null | null | null | db/migrate/20141018001557_create_topic.rb | kamilbielawski/knowledge_base | acf7f3b0b36211d779f477af8b5f3e1597d57a7a | [
"MIT"
] | null | null | null | class CreateTopic < ActiveRecord::Migration
def change
create_table :topics do |t|
t.string :name, nil: false
t.timestamps
end
add_index :topics, :name, unique: true
end
end
| 17 | 43 | 0.661765 |
18cf94884b52017af80f19ef29ae0308eb1c73c4 | 1,164 | ps1 | PowerShell | SecretManagement.PasswordState/SecretManagement.PasswordState.Extension/Public/Remove-Secret.ps1 | taalmahret/SecretManagement.PasswordState | 24fa1d1f800351416e52c1aafb0b961cf2021eed | [
"Apache-2.0"
] | null | null | null | SecretManagement.PasswordState/SecretManagement.PasswordState.Extension/Public/Remove-Secret.ps1 | taalmahret/SecretManagement.PasswordState | 24fa1d1f800351416e52c1aafb0b961cf2021eed | [
"Apache-2.0"
] | 2 | 2021-08-05T22:36:26.000Z | 2021-08-15T23:09:35.000Z | SecretManagement.PasswordState/SecretManagement.PasswordState.Extension/Public/Remove-Secret.ps1 | taalmahret/SecretManagement.PasswordState | 24fa1d1f800351416e52c1aafb0b961cf2021eed | [
"Apache-2.0"
] | null | null | null | function Remove-Secret {
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()][string]$Name,
[Alias('Vault')][string]$VaultName,
[Alias('VaultParameters')][hashtable]$AdditionalParameters = (Get-SecretVault -Name $VaultName).VaultParameters
)
trap {
VaultError $PSItem
throw $PSItem
}
if ($AdditionalParameters.Verbose) {$VerbosePreference = 'continue'}
if (-not (Test-SecretVault -VaultName $vaultName)) {
throw 'There appears to be an issue with the vault (Test-SecretVault returned false)'
}
$KeepassParams = GetKeepassParams $VaultName $AdditionalParameters
$GetKeePassResult = Get-SecretInfo -VaultName $VaultName -Name $Name -AsKPPSObject
if ($GetKeePassResult.count -gt 1) {
VaultError "There are multiple entries with the name $Name and Remove-Secret will not proceed for safety."
return $false
}
if (-not $GetKeePassResult) {
VaultError "No Keepass Entry named $Name found"
return $false
}
Remove-KPEntry @KeepassParams -KeePassEntry $GetKeePassResult.KPEntry -ErrorAction stop -Confirm:$false
return $true
} | 37.548387 | 119 | 0.681271 |
7043abc1a4cce86a5309ef82c416f026b6adfc85 | 4,297 | dart | Dart | lib/screens/Login/login_screen.dart | LacErnest/just_audio | eea277caa084415d1ed60415660508ddacda1724 | [
"Apache-2.0"
] | null | null | null | lib/screens/Login/login_screen.dart | LacErnest/just_audio | eea277caa084415d1ed60415660508ddacda1724 | [
"Apache-2.0"
] | null | null | null | lib/screens/Login/login_screen.dart | LacErnest/just_audio | eea277caa084415d1ed60415660508ddacda1724 | [
"Apache-2.0"
] | null | null | null | import 'package:flutter/material.dart';
import 'package:filex/screens/Signup/signup_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:filex/api/databasehelper.dart';
import 'package:filex/screens/Login/components/background.dart';
import 'package:filex/components/already_have_an_account_acheck.dart';
import 'package:filex/components/rounded_button.dart';
import 'package:filex/components/rounded_input_field.dart';
import 'package:filex/components/rounded_password_field.dart';
import 'package:filex/screens/main_screen.dart';
import 'package:page_transition/page_transition.dart';
import 'package:flutter_svg/svg.dart';
class LoginScreen extends StatefulWidget {
LoginScreen({Key key , this.title}) : super(key : key);
final String title;
@override
LoginScreenState createState() => LoginScreenState();
}
class LoginScreenState extends State<LoginScreen> {
DatabaseHelper databaseHelper = new DatabaseHelper();
String msgStatus = '';
final TextEditingController _usernameController = new TextEditingController();
final TextEditingController _passwordController = new TextEditingController();
_onPressed(){
setState(() {
if(_usernameController.text.trim().isNotEmpty &&
_passwordController.text.trim().isNotEmpty ){
databaseHelper.loginData(_usernameController.text.trim(),
_passwordController.text.trim()).whenComplete((){
if(databaseHelper.status){
_showDialog();
msgStatus = 'Check username or password';
}else{
Navigator.pushReplacement(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: MainScreen(),
),
);
}
});
}
});
}
read() async {
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key ) ?? 0;
print('Value : $value');
if(value != 0){
print('dive into');
Navigator.pushReplacement(
context,
PageTransition(
type: PageTransitionType.rightToLeft,
child: MainScreen(),
),
);
}
}
@override
initState(){
read();
}
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Scaffold(
body: Background(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
"LOGIN",
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(height: size.height * 0.03),
SvgPicture.asset(
"assets/icons/login.svg",
height: size.height * 0.35,
),
SizedBox(height: size.height * 0.03),
RoundedInputField(
hintText: "Your Username",
controller: _usernameController,
onChanged: (value) {},
),
RoundedPasswordField(
controller: _passwordController,
onChanged: (value) {},
),
RoundedButton(
text: "LOGIN",
press: () { _onPressed(); },
),
SizedBox(height: size.height * 0.03),
AlreadyHaveAnAccountCheck(
press: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return SignUpScreen();
},
),
);
},
),
],
),
),
)
);
}
void _showDialog(){
showDialog(
context:context ,
builder:(BuildContext context){
return AlertDialog(
title: new Text('Failed'),
content: new Text('Check your email or password'),
actions: <Widget>[
new RaisedButton(
child: new Text(
'Close',
),
onPressed: (){
Navigator.of(context).pop();
},
),
],
);
}
);
}
}
| 28.646667 | 80 | 0.554573 |
c57664a5ec151935a07af34ef2834ba343892d6f | 2,650 | css | CSS | wcms-admin.min.css | StephanStanisic/wondercms-cdn-files | 5fa5a7b8fa4d7e181490a9d142fd3bdae73770ff | [
"MIT"
] | null | null | null | wcms-admin.min.css | StephanStanisic/wondercms-cdn-files | 5fa5a7b8fa4d7e181490a9d142fd3bdae73770ff | [
"MIT"
] | null | null | null | wcms-admin.min.css | StephanStanisic/wondercms-cdn-files | 5fa5a7b8fa4d7e181490a9d142fd3bdae73770ff | [
"MIT"
] | null | null | null | .alert{margin-bottom:0}div.editText{word-wrap:break-word;border:2px dashed #ccc;display:block}div.editText textarea{outline:0;border:none;width:100%;resize:none;color:inherit;font-size:inherit;font-family:inherit;background-color:transparent;overflow:hidden;box-sizing:content-box}div.editText:empty{min-height:20px}#save{color:#ccc;left:0;width:100%;height:100%;display:none;position:fixed;text-align:center;padding-top:100px;background:rgba(51,51,51,.8);z-index:2448}.change{padding-left:15px}.marginTop5{margin-top:5px}.marginTop20{margin-top:20px}.marginLeft5{margin-left:5px}.padding20{padding:20px}.subTitle{color:#aaa;font-size:24px;margin:20px 0 5px;font-variant:all-small-caps}.menu-item-hide{color:#5bc0de}.menu-item-delete,.menu-item-hide,.menu-item-show{padding:0 10%}.tab-content{padding:20px}#adminPanel{background:#e5e5e5;color:#aaa;font-family:"Lucida Sans Unicode",Verdana;font-size:14px;text-align:left;font-variant:small-caps}#adminPanel .fas,.cursorPointer,div.editText{cursor:pointer}#adminPanel .btn{overflow:hidden;white-space:nowrap;display:inline-block;text-overflow:ellipsis}#adminPanel .fontSize21{font-size:21px}#adminPanel a{color:#aaa;outline:0;border:0;text-decoration:none}#adminPanel a.btn,#adminpanel .alert a{color:#fff}#adminPanel div.editText{color:#555;font-variant:normal}#adminPanel .normalFont{font-variant:normal;word-wrap:break-word}#adminPanel .nav-tabs{border-bottom:2px solid #ddd}#adminPanel .nav-tabs>li>a:after{content:"";background:#1ab;height:2px;position:absolute;width:100%;left:0;bottom:-2px;transition:all 250ms ease 0s;transform:scale(0)}#adminPanel .nav-tabs>li.active>a:after,#adminPanel .nav-tabs>li:hover>a,#adminPanel .nav-tabs>li:hover>a:after,#adminPanel .nav-tabs>li>a{transform:scale(1)}#adminPanel .nav-tabs>li>a.active{border-bottom:2px solid #1ab!important}#adminPanel .modal-content{background-color:#eee}#adminPanel .modal-header{border:0}#adminPanel .nav li{font-size:30px;float:none;display:inline-block},#adminPanel .tab-pane.active a.btn{color:#fff}#adminPanel .btn-info{background-color:#5bc0de;border-color:#5bc0de}#adminPanel .nav-link.active,#adminPanel .nav-tabs>li.active a,#adminPanel .tab-pane.active{background:0!important;border:0!important;color:#aaa!important}#adminPanel .clear{clear:both}#adminPanel .custom-cards>div{margin:15px 0}#adminPanel .custom-cards>div>div{box-shadow:-1px -1px 6px 0 rgba(0,0,0,.1);padding:.5em}#adminPanel .custom-cards>div>div h4{font-weight:700;margin-bottom:.2em;line-height:1em;min-height:40px}#adminPanel .custom-cards .col-sm-4:nth-child(3n+1){clear:left}@media(min-width:768px){#adminPanel .modal-xl{width:90%;max-width:1200px}} | 2,650 | 2,650 | 0.796981 |
b30fe42f8cca7219a213d2592238401b41e2044f | 2,184 | py | Python | pysal/contrib/network/weights.py | cubensys/pysal | 8d50990f6e6603ba79ae1a887a20a1e3a0734e51 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | pysal/contrib/network/weights.py | cubensys/pysal | 8d50990f6e6603ba79ae1a887a20a1e3a0734e51 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | pysal/contrib/network/weights.py | cubensys/pysal | 8d50990f6e6603ba79ae1a887a20a1e3a0734e51 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2021-07-19T01:46:17.000Z | 2021-07-19T01:46:17.000Z | """
A library of spatial network functions.
Not to be used without permission.
Contact:
Andrew Winslow
GeoDa Center for Geospatial Analysis
Arizona State University
Tempe, AZ
[email protected]
"""
import csv
import numpy as np
from pysal import W
import unittest
import test
def dist_weights(distfile, weight_type, ids, cutoff, inverse=False):
"""
Returns a distance-based weights object using user-defined options
Parameters
----------
distfile: string, a path to distance csv file
weighttype: string, either 'threshold' or 'knn'
ids: a numpy array of id values
cutoff: float or integer; float for 'threshold' weight type and integer for knn type
inverse: boolean; true if inversed weights required
"""
try:
data_csv = csv.reader(open(distfile))
if csv.Sniffer().has_header(distfile):
data_csv.next()
except:
data_csv = None
if weight_type == 'threshold':
def neighbor_func(dists, threshold):
dists = filter(lambda x: x[0] <= threshold, dists)
return dists
else:
def neighbor_func(dists, k):
dists.sort()
return dists[:k]
if inverse:
def weight_func(dists, alpha=-1.0):
return list((np.array(dists)**alpha).round(decimals=6))
else:
def weight_func(dists, binary=False):
return [1]*len(dists)
dist_src = {}
for row in data_csv:
des = dist_src.setdefault(row[0], {})
if row[0] != row[1]:
des[row[1]] = float(row[2])
neighbors, weights = {}, {}
for id_val in ids:
if id_val not in dist_src:
raise ValueError, 'An ID value doest not exist in distance file'
else:
dists = zip(dist_src[id_val].values(), dist_src[id_val].keys())
ngh, wgt = [], []
if len(dists) > 0:
nghs = neighbor_func(dists, cutoff)
for d, i in nghs:
ngh.append(i)
wgt.append(d)
neighbors[id_val] = ngh
weights[id_val] = weight_func(wgt)
w = W(neighbors, weights)
w.id_order = ids
return w
| 26.962963 | 88 | 0.59478 |
2fae7e4116b3e891f16aa1005ab88792f91968dc | 3,033 | py | Python | crichtonweb/core/httpshelpers.py | bpluly/crichton | a2fa09c181ba1e44ee1aae7a57769e1778de7f3a | [
"Apache-2.0"
] | null | null | null | crichtonweb/core/httpshelpers.py | bpluly/crichton | a2fa09c181ba1e44ee1aae7a57769e1778de7f3a | [
"Apache-2.0"
] | null | null | null | crichtonweb/core/httpshelpers.py | bpluly/crichton | a2fa09c181ba1e44ee1aae7a57769e1778de7f3a | [
"Apache-2.0"
] | null | null | null | # Crichton, Admirable Source Configuration Management
# Copyright 2012 British Broadcasting Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
import httplib2
from urlparse import urlparse
CONTENT_TYPES = {
"xml" : "application/xml",
"textxml" : "text/xml",
"json" : "application/json",
"javascript" : "application/javascript"
}
def makeHttps(url, cert_file=None, key_file=None, ca_file=None, **options):
""" Use cert_file and key_file
to locate the cert files and make the https requests
httplib2 uses its authority list to store certificates by domain
By default, cache dir location is controlled in the settings file.
This can be overridden by passing in a 'cache' parameter.
"""
scheme, netloc, path, parameters, query, fragment = urlparse(url)
if options.has_key('cache'):
cache = options['cache']
else:
cache = None
https = httplib2.Http(cache=cache, timeout=1000)
if scheme == "https" and cert_file and key_file:
https.add_certificate(key_file, cert_file, netloc)
if ca_file:
https.set_ca_file(ca_file)
return https
class HttpError(Exception):
def __init__(self, desc, response, content):
self.response = response
self.content = content
data = "HttpError-Status_" + str(self.response.status) + "\n"
data += "Description: " + desc + "\n"
data += "Details:" + "\n"
for line in self.content.split("\n"):
data += " " + line + "\n"
Exception.__init__(self, data)
def ok(resp):
return resp.status >= 200 and resp.status < 400
def is_of_type(resp, content_type):
content_type = CONTENT_TYPES.get(content_type, content_type)
return resp.get("content-type", content_type).find(content_type) != -1
def is_json(resp):
# jenkins spits out application/javascript if you ask for json. Yes, really.
return is_of_type(resp, "json") or is_of_type(resp, "javascript")
def is_xml(resp):
return is_of_type(resp, "xml") or is_of_type(resp, "textxml")
def expect_ok(resp, content):
if not ok(resp):
raise HttpError("Status %s" % (resp.status,), resp, content)
def expect_json(resp, content):
if not is_json(resp):
raise HttpError("Expected json, got %s" % (resp.get("content-type", "")), resp, content)
def expect_xml(resp, content):
if not is_xml(resp):
raise HttpError("Expected xml, got %s" % (resp.get("content-type", "")), resp, content)
| 34.465909 | 96 | 0.672931 |
386bf15a496f8ca5264012ff4b83264c30392b06 | 4,352 | php | PHP | resources/views/admin/categories/index.blade.php | jndantas/cms | 660d6d314886a5665be4eb019e6c835d7b083d88 | [
"MIT"
] | 1 | 2021-07-30T22:28:41.000Z | 2021-07-30T22:28:41.000Z | resources/views/admin/categories/index.blade.php | jndantas/cms | 660d6d314886a5665be4eb019e6c835d7b083d88 | [
"MIT"
] | 3 | 2021-05-11T02:08:52.000Z | 2022-02-26T23:09:17.000Z | resources/views/admin/categories/index.blade.php | jndantas/cms | 660d6d314886a5665be4eb019e6c835d7b083d88 | [
"MIT"
] | null | null | null | @extends('layouts.admin.master')
@section('title')
Categorias
@endsection
@section('content')
<!-- Content Header (Page header) -->
<section class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0 text-dark">Categorias</h1>
</div><!-- /.col -->
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="#">Home</a></li>
<li class="breadcrumb-item active">Categorias</li>
</ol>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</section>
<!-- /.content-header -->
<section class="content">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
<h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-2x fa-boxes"></i>
<a href="{{ route('category.create') }}" class="btn btn-primary btn-circle float-right"><i class="fas fa-plus"></i></a>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered dataTable">
<thead>
<tr>
<th>Nome</th>
<th>Quantidade de Posts</th>
<th>Editar</th>
<th>Apagar</th>
</tr>
</thead>
<tbody>
@if ($categories->count() > 0)
@foreach ($categories as $c)
<tr>
<td>{{ $c->name }}</td>
<td> {{ $c->posts->count() }}</td>
<th scope="row">
<a href="{{ route('category.edit', $c->id ) }}" class="btn btn-info btn-circle btn-lg"><i class="fas fa-pen-alt"></i>
</a>
</th>
<th>
<button class="btn btn-danger btn-circle btn-lg" onclick="handleDelete({{ $c->id }})"><i class="fas fa-trash-alt"></i> </button>
</th>
</tr>
@endforeach
@else
<th colspan="5" class="text-center">Sem categorias cadastradas</th>
@endif
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<form action="" method="POST" id="deleteCategoryForm">
@csrf
@method('DELETE')
<!-- Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deleteModalLabel">Apagar Categoria</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p class="text-center text-bold">
Você realmente quer apagar essa categoria?
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Não, Volte!</button>
<button type="submit" class="btn btn-danger">Sim, Apague!</button>
</div>
</div>
</div>
</div>
</form>
@endsection
@section('js')
<script>
function handleDelete(id){
var form = document.getElementById('deleteCategoryForm')
form.action = '/admin/category/' + id
$('#deleteModal').modal('show')
}
</script>
@endsection
| 37.843478 | 168 | 0.417739 |
fc3d8d768f3edfcd5fc8993494a32b6d927f9546 | 2,420 | asm | Assembly | src/app/midi.asm | neri/osz | d1766e2f5daabd5914a80b838c0219f330a0d0af | [
"MIT"
] | 7 | 2017-01-11T17:13:10.000Z | 2022-02-17T06:40:50.000Z | src/app/midi.asm | neri/osz | d1766e2f5daabd5914a80b838c0219f330a0d0af | [
"MIT"
] | null | null | null | src/app/midi.asm | neri/osz | d1766e2f5daabd5914a80b838c0219f330a0d0af | [
"MIT"
] | 1 | 2019-06-24T09:49:43.000Z | 2019-06-24T09:49:43.000Z | ;; MIDI Sample Application for OSZ
;; Copyright (c) 2019 MEG-OS project All rights reserved.
%include "osz.inc"
%define PORT_MPU 0x0330
[BITS 16]
[ORG 0x0100]
xor bp, bp
jmp _init
alignb 2
__bdos resw 1
_call_bdos:
jmp word [cs:__bdos]
; ---------------------------------------------------------------------
_init:
mov [__bdos], bp
mov cl, 0x40
mov dx, 100
call _mpu_wait_status
or ax, ax
jnz _no_mpu
mov dx, PORT_MPU + 1
mov al, 0xFF
out dx, al
mov cl, 0x80
mov dx, 100
call _mpu_wait_status
or ax, ax
jnz _no_mpu
mov dx, PORT_MPU
in al, dx
cmp al, 0xFE
jnz _no_mpu
mov cl, 0x40
mov dx, 100
call _mpu_wait_status
or ax, ax
jnz _no_mpu
mov dx, PORT_MPU + 1
mov al, 0x3F
out dx, al
jmp _init_ok
_no_mpu:
mov dx, _no_mpu_msg
mov ah, 9
int 0x21
int 0x20
_init_ok:
mov dx, _mpu_found_msg
mov ah, 9
int 0x21
mov si, _midi_data
call _play_midi
int 0x20
_mpu_wait_status:
push bp
mov bp, sp
sub sp, 16
mov [bp - 2], cl
mov [bp - 4], dx
mov ah, OSZ_GET_TICK
call _call_bdos
mov [bp - 6], dx
mov [bp - 8], ax
.loop:
mov dx, PORT_MPU + 1
in al, dx
and al, [bp - 2]
jz .ok
mov ah, OSZ_SLEEP
mov cx, 1
call _call_bdos
sub ax, [bp - 6]
sbb dx, [bp - 8]
or dx, dx
jnz .failure
mul cx
or dx, dx
jnz .failure
cmp ax, [bp - 4]
jb .loop
.failure:
mov ax, -1
jmp .end
.ok:
xor ax, ax
.end:
mov sp, bp
pop bp
ret
_play_midi:
.loop:
lodsb
or al, al
jz .end
mov dx, 0x0330
cmp al, 0xF0
jz .sysex
out dx, al
lodsb
out dx, al
lodsb
out dx, al
.end_common:
lodsb
or al, al
jz .loop
xor ah, ah
mov cl, 25
mul cl
xchg ax, cx
call _bios_wait
jmp .loop
.sysex:
out dx, al
.loop_sysex:
lodsb
out dx, al
cmp al, 0xF7
jnz .loop_sysex
jmp .end_common
.end:
ret
_bios_wait:
mov ah, OSZ_SLEEP
jmp _call_bdos
_no_mpu_msg:
db "NO MPU Found", 13, 10, "$"
_mpu_found_msg:
db "Now playing testing MIDI...", 13, 10, "$"
_midi_data:
db 0xF0, 0x7E, 0x7F, 0x09, 0x01, 0xF7, 20
db 0x90, 60, 100, 1
db 0x90, 62, 100, 1
db 0x90, 64, 100, 1
db 0x90, 67, 100, 17
db 0xB0, 123, 0, 0
db 0
_END:
| 14.069767 | 71 | 0.540909 |
72c8154d936593da1dea593e6a3c592564c73b83 | 2,297 | cs | C# | src/Tests/Nest.Tests.Integration/Search/Filter/RangeFilterTests.cs | rlugojr/elasticsearch-net | 3f4dbaa050fc007e4544da6c3afeee6b52b45705 | [
"Apache-2.0"
] | 2 | 2019-05-01T01:42:54.000Z | 2019-11-23T03:36:13.000Z | src/Tests/Nest.Tests.Integration/Search/Filter/RangeFilterTests.cs | funnelfire/elasticsearch-net | 49940f04ef8014b01fb15e1697beae316797bb56 | [
"Apache-2.0"
] | null | null | null | src/Tests/Nest.Tests.Integration/Search/Filter/RangeFilterTests.cs | funnelfire/elasticsearch-net | 49940f04ef8014b01fb15e1697beae316797bb56 | [
"Apache-2.0"
] | 12 | 2016-10-09T11:52:34.000Z | 2021-09-13T08:59:51.000Z | using System.Linq;
using Elasticsearch.Net;
using NUnit.Framework;
using Nest.Tests.MockData;
using Nest.Tests.MockData.Domain;
namespace Nest.Tests.Integration.Search.Filter
{
/// <summary>
/// Integrated tests of RangeFilter with elasticsearch.
/// </summary>
[TestFixture]
public class RangeFilterTests : IntegrationTests
{
/// <summary>
/// Document used in test.
/// </summary>
private ElasticsearchProject _LookFor;
[TestFixtureSetUp]
public void Initialize()
{
_LookFor = NestTestData.Session.Single<ElasticsearchProject>().Get();
_LookFor.Name = "mmm";
var status = this.Client.Index(_LookFor, i=>i.Refresh()).ConnectionStatus;
Assert.True(status.Success, status.ResponseRaw.Utf8String());
}
/// <summary>
/// Set of filters that should not filter de documento _LookFor.
/// </summary>
[Test]
public void TestNotFiltered()
{
var name = _LookFor.Name;
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Name).GreaterOrEquals(name).LowerOrEquals(name)), _LookFor, true);
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Name).GreaterOrEquals("aaa").LowerOrEquals("zzz")), _LookFor, true);
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Name).GreaterOrEquals(name)), _LookFor, true);
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Name).LowerOrEquals(name)), _LookFor, true);
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Id).GreaterOrEquals(1), RangeExecution.FieldData), _LookFor, true);
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Name).LowerOrEquals(name), RangeExecution.Index), _LookFor, true);
}
/// <summary>
/// Set of filters that should filter de documento _LookFor.
/// </summary>
[Test]
public void TestFiltered()
{
var name = _LookFor.Name;
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Name).GreaterOrEquals("zzz")), _LookFor, false);
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Name).LowerOrEquals("aaa")), _LookFor, false);
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Name).GreaterOrEquals(name)), _LookFor, true);
this.DoFilterTest(f => f.Range(range => range.OnField(e => e.Name).LowerOrEquals(name)), _LookFor, true);
}
}
}
| 32.352113 | 132 | 0.691772 |
daa8fbe2f95969c18f05ed9f293d48d9b0e4da84 | 1,201 | tsx | TypeScript | src/component/reply-input.component.tsx | Laterality/primitive-renew-web | 5329c3d0813b9d4b32f08a39c64340e971f60873 | [
"MIT"
] | null | null | null | src/component/reply-input.component.tsx | Laterality/primitive-renew-web | 5329c3d0813b9d4b32f08a39c64340e971f60873 | [
"MIT"
] | null | null | null | src/component/reply-input.component.tsx | Laterality/primitive-renew-web | 5329c3d0813b9d4b32f08a39c64340e971f60873 | [
"MIT"
] | null | null | null | /**
* Reply input box component
*
* author: Jinwoo Shin
* date: 2018-05-14
*/
import * as jquery from "jquery";
import * as React from "react";
import TextField from "@material-ui/core/TextField";
import { withStyles, WithStyles } from "@material-ui/core";
import { MyButton as Button } from "./button.component";
export interface IReplyInputProps {
onInputClick: (input: string) => void;
}
const styles = {
root: {
marginBottom: "24px",
},
submitButton: {
marginTop: "16px",
},
};
type ReplyInputProps = IReplyInputProps & WithStyles<"root" | "submitButton">;
class ReplyInput extends React.Component<ReplyInputProps> {
public render() {
const { classes } = this.props;
return (
<div className={classes.root}>
<TextField className="form-control" id="reply-input" multiline rows={5} label="댓글" placeholder="댓글 입력"/>
<Button className={classes.submitButton}
onClick={ () => this.onInputClick() } text="댓글 달기" />
</div>);
}
public onInputClick() {
const elmInput = jquery("#reply-input");
const input = elmInput.val();
elmInput.val("");
this.props.onInputClick(input as string);
}
}
export default withStyles(styles)<IReplyInputProps>(ReplyInput);
| 22.660377 | 107 | 0.686095 |
f168a25f8e78ca7c202d2c16178ab5698d8a88b6 | 8,392 | rb | Ruby | spp-master/app/mailers/user_mailer.rb | Room-to-read/StoryWeaver | 68b451c797cedd2771a366011bf2a54b69b6511c | [
"Apache-2.0"
] | null | null | null | spp-master/app/mailers/user_mailer.rb | Room-to-read/StoryWeaver | 68b451c797cedd2771a366011bf2a54b69b6511c | [
"Apache-2.0"
] | null | null | null | spp-master/app/mailers/user_mailer.rb | Room-to-read/StoryWeaver | 68b451c797cedd2771a366011bf2a54b69b6511c | [
"Apache-2.0"
] | null | null | null | class UserMailer < ActionMailer::Base
default from: "[email protected]"
def pulled_down_story_mail(user,story,reasons)
@reasons = reasons
@user = user
@story = story
mail(:to => @user.email, :subject => "StoryWeaver: your story has been pulled down") do |format|
format.html { render :partial => "/user_mailer/pulled_down_story_mail", :layout=>"email/layout" }
end
end
def pulled_down_illustration_mail(illustrator,illustration,reasons)
@reasons = reasons
@illustrator = illustrator
@illustration = illustration
mail(:to => @illustrator.email, :subject => "StoryWeaver: your illustration has been pulled down") do |format|
format.html { render :partial => "/user_mailer/pulled_down_illustration_mail", :layout=>"email/layout" }
end
end
def pulled_down_story_by_illustration_mail(author,illustration,story,pages)
@author = author
@story = story
@illustration = illustration
@pages = pages
mail(:to => @author.email, :subject => "StoryWeaver: your story has been pulled down") do |format|
format.html { render :partial => "/user_mailer/pulled_down_story_by_illustration_mail", :layout=>"email/layout" }
end
end
def flagged_story(content_manager,story,user,reason,path)
@story = story
@user = user
@reason = reason
@path = path
mail(:to => content_manager, :subject => "StoryWeaver: A story has been flagged #{@path.present? ? 'by reviewer' : ''} ") do |format|
format.html { render :partial => "/user_mailer/flagged_story", :layout=>"email/layout" }
end
end
def flagged_illustration(content_manager,illustration,user,reason)
@illustration = illustration
@user = user
@reason = reason
mail(:to => content_manager, :subject => "StoryWeaver: An illustration has been flagged") do |format|
format.html { render :partial => "/user_mailer/flagged_illustration", :layout=>"email/layout" }
end
end
def published_story(content_managers, story)
@story = story
mail(:to => content_managers, :subject => "StoryWeaver: Story got published") do |format|
format.html {render :partial => "/user_mailer/published_story", :layout => "email/layout"}
end
end
def re_publish_story(content_managers, story, user)
@story = story
@user = user
mail(:to => content_managers, :subject => "StoryWeaver: Story got re-published") do |format|
format.html {render :partial => "/user_mailer/re_publish_story", :layout => "email/layout"}
end
end
def story_flagger_email(flaggers,story)
@flaggers = flaggers
@story = story
mail(:to => @flaggers.email, :subject => "StoryWeaver: Story you flagged has been pulled down") do |format|
format.html {render :partial => "/user_mailer/story_flagger_email", :layout => "email/layout"}
end
end
def illustration_flagger_email(flaggers,illustration)
@flaggers = flaggers
@illustration = illustration
mail(:to => @flaggers.email, :subject => "StoryWeaver: Illustration you flagged has been pulled down") do |format|
format.html {render :partial => "/user_mailer/illustration_flagger_email", :layout => "email/layout"}
end
end
def re_published_story_email(content_managers, story, user)
@story = story
@user = user
mail(:to => content_managers, :subject => "StoryWeaver: Story got Re-published") do |format|
format.html {render :partial => "/user_mailer/re_published_story_email", :layout => "email/layout"}
end
end
def story_re_publish_email_to_flagger(flaggers, story)
@flaggers = flaggers
@story = story
mail(:to => @flaggers.email, :subject => "StoryWeaver: Story you flagged got Re-published") do |format|
format.html {render :partial => "/user_mailer/story_re_publish_email_to_flagger", :layout => "email/layout"}
end
end
def submitted_story_mail_to_managers(managers, story, contest)
@story = story
@contest = contest
mail(:to => managers, :subject => "StoryWeaver: Story got submitted to "[email protected]) do |format|
format.html {render :partial => "/user_mailer/submitted_story_email", :layout => "email/layout"}
end
end
def submitted_story_mail_to_user(user, story, contest)
@user = user
@story = story
@contest = contest
mail(:to => @user.email, :subject => "StoryWeaver: Story got submitted to "[email protected]) do |format|
format.html {render :partial => "/user_mailer/submitted_story_mail_to_user", :layout => "email/layout"}
end
end
def assign_language_reviewer(reviewer,language)
@reviewer = reviewer
@language = language
mail(:to => @reviewer.email, :subject => "StoryWeaver: You are assigned as language reviewer") do |format|
format.html {render :partial => "/user_mailer/assign_language_reviewer_mail", :layout => "email/layout"}
end
end
def assign_language_translator(translator,language)
@translator = translator
@language = language
mail(:to => @translator.email, :subject => "StoryWeaver: You are assigned as translator") do |format|
format.html {render :partial => "/user_mailer/assign_language_translator_mail", :layout => "email/layout"}
end
end
def reviewer_rating_comment(content_managers,reviewer_comments,date)
@reviewer_comments = reviewer_comments
@date = date
mail(:to => content_managers, :subject => "Community Reviewers' Activity as on #{ @date }") do |format|
format.html {render :partial => "/user_mailer/reviewer_rating_comment_mail", :layout => "email/layout"}
end
end
def uploaded_illustration(content_managers,illustration)
@illustration = illustration
mail(:to => content_managers, :subject => "StoryWeaver: Illustration has been uploaded") do |format|
format.html {render :partial => "/user_mailer/uploaded_illustration", :layout => "email/layout"}
end
end
def organization_user_signup(content_managers,organization,current_user)
@organization = organization
@current_user = current_user
mail(:to => content_managers, :subject => "StoryWeaver: New organisational user has signed up") do |format|
format.html {render :partial => "/user_mailer/organization_user_signup_mail", :layout => "email/layout"}
end
end
def root_story_derivation(emails, story, root_story)
emails_list = emails
@root_story = root_story
@story = story
mail(:to => emails_list, :subject => "StoryWeaver: New story derivation has been created") do |format|
format.html {render :partial => "/user_mailer/root_story_derivation", :layout => "email/layout"}
end
end
def derivation_of_child_story(emails, story, root_story)
emails_list = emails
@root_story = root_story
@story = story
mail(:to => emails_list, :subject => "StoryWeaver: New story derivation has been created") do |format|
format.html {render :partial => "/user_mailer/derivation_of_child_story", :layout => "email/layout"}
end
end
def translators_one_week_mail(translators, story, first_name)
@story = story
@translator = translators
@first_name = first_name
mail(:to => @translator, :subject => "Your story draft is waiting to be finished!") do |format|
format.html {render :partial => "/user_mailer/translators_one_week_mail", :layout => "email/layout"}
end
end
def translators_three_weeks_mail(translators, story, first_name)
@story = story
@translator = translators
@first_name = first_name
mail(:to => @translator, :subject => "Last reminder: Your story draft is waiting to be finished!") do |format|
format.html {render :partial => "/user_mailer/translators_three_weeks_mail", :layout => "email/layout"}
end
end
def publisher_story_mail_to_authors(authors,story)
@story = story
mail(:to => authors, :subject => "StoryWeaver: Your story has been published") do |format|
format.html {render :partial => "/user_mailer/publisher_story_mail_to_authors", :layout => "email/layout"}
end
end
def publisher_story_mail_to_illustrators(illustrators, story)
@story = story
mail(:to => illustrators, :subject => "StoryWeaver: Story with your illustrations has been published") do |format|
format.html {render :partial => "/user_mailer/publisher_story_mail_to_illustrators", :layout => "email/layout"}
end
end
end
| 40.936585 | 137 | 0.699595 |
da6f14a839626849b9482b61a35cfbac425aa6b5 | 303 | php | PHP | modules/titles/Module.php | kaganov-iliya/yii2-titles | e7bcadb188da3436b896adf11755509eb46baeac | [
"BSD-3-Clause"
] | null | null | null | modules/titles/Module.php | kaganov-iliya/yii2-titles | e7bcadb188da3436b896adf11755509eb46baeac | [
"BSD-3-Clause"
] | null | null | null | modules/titles/Module.php | kaganov-iliya/yii2-titles | e7bcadb188da3436b896adf11755509eb46baeac | [
"BSD-3-Clause"
] | null | null | null | <?php
namespace app\modules\titles;
use Yii;
use app\modules\titles\web\Asset;
class Module extends \yii\base\Module
{
public $controllerNamespace = 'app\modules\titles\controllers';
public function init()
{
parent::init();
Asset::register(Yii::$app->getView());
}
}
| 16.833333 | 67 | 0.653465 |
6610a72cf8b8fcefb80e39b2c2beba514082c125 | 2,374 | py | Python | projeto-escolaCurso/aula.py | HugoItaloMC/MySQL_estudo | 4468ebe14d51405867cea9c842822ad43e98f5b4 | [
"MIT"
] | null | null | null | projeto-escolaCurso/aula.py | HugoItaloMC/MySQL_estudo | 4468ebe14d51405867cea9c842822ad43e98f5b4 | [
"MIT"
] | null | null | null | projeto-escolaCurso/aula.py | HugoItaloMC/MySQL_estudo | 4468ebe14d51405867cea9c842822ad43e98f5b4 | [
"MIT"
] | null | null | null | """
Markers
# Atributo marker = ""
character description
'.' -------- point marker
',' -------- pixel marker
'o' -------- circle Marker
'v' -------- riangle_down marker
'^' -------- triangle_up marker
'<' -------- triangle_left marker
'>' -------- triangle_right marker
'1' -------- tri_down marker
'2' -------- tri_up marker
'3' -------- tri_left marker
'4' -------- tri_right marker
'8' ------- octagon marker
's' ------- square marker
'p' ------- pentagon marker
'P' ------- plus(filled) marker
'*' ------- star marker
'h' ------- hexagon1 marker
'H' ------- hexagon2 marker
'+' ------- plus marker
'x'-------- x marker
'X' ------- x(filled) marker
'D' ------- diamond marker
'd' ------- thin_diamond marker
'|' ------- vline marker
'_' ------- hline marker
=======================================||
Line Styles
# Atributo linestyle = ""
character description
'-' -------- solid line style
'--' ------- dashed line style
'-.' ------- dash-dot line style
':' -------- dotted line style
=======================================||
Colors :
Atributo color=""
character color
'b' ------- blue
'g' ------- green
'r' ------- red
'c' ------- cyan
'm' ------- magenta
'y' ------- yellow
'k' ------- black
'w' ------ white
"""
#Visualizacão de dados em grafico com python
# importando biblioteca
import matplotlib.pyplot as plt
x1 = [1, 3, 5, 7, 9, 11]
y1 = [5 , 7, 2, 3, 1, 8]
x2 = [2, 4, 5, 6, 8, 10]
y2 = [11, 2, 6, 7, 1, 3]
# Legendas
plt.title("Meu Gráfico, teste : ")
plt.xlabel("Eixo X")
plt.ylabel("Eixo Y")
#plt.plot(x, y) # Grafico linear
#plt.bar(x1, y1, label = "Grupo 1") # Gráfico de barras
#plt.bar(x2, y2, label = "Grupo 2")
plt.scatter(x1, y1, label = "Grupo 1", color = "purple", marker = ",", s = 20.25) # Atributo ' s ' refere-se ao tamanho da marcacão
plt.scatter(x2, y2, label = "Grupo 2", color = "green", marker = "_")
plt.plot(x1, y1, color = "black", linestyle="--") # Ligar os pontos com linhas
plt.plot(x2, y2, color = "black", linestyle = "-.")
plt.legend() # ' Commitando ' o bloco acima pro gráfico rodar
#plt.show() # Mostra gráfico
plt.savefig("figura1.png", dpi = 300) # Atributo ' dpi ' refere-se ao tamanho da resoulucão da imagem, podemos salvar com a extensão ' .pdf '
# OBS : A imagem do gráfico será salva dentro da pasta que se encontra o arquivo python
| 16.601399 | 142 | 0.540438 |
7f18ab624137a33dd155824897092d1f4a94e572 | 150 | cs | C# | csharp/ProgressMonitor/MaxThroughputProgressMonitor.cs | pescuma/progressmonitor | 3f930164c16e6e0a94e5ddac7c96d79b15085e21 | [
"MIT"
] | 1 | 2020-06-21T12:08:24.000Z | 2020-06-21T12:08:24.000Z | csharp/ProgressMonitor/MaxThroughputProgressMonitor.cs | pescuma/progressmonitor | 3f930164c16e6e0a94e5ddac7c96d79b15085e21 | [
"MIT"
] | 1 | 2015-06-10T21:48:02.000Z | 2015-06-10T21:48:02.000Z | csharp/ProgressMonitor/MaxThroughputProgressMonitor.cs | pescuma/progressmonitor | 3f930164c16e6e0a94e5ddac7c96d79b15085e21 | [
"MIT"
] | null | null | null | namespace org.pescuma.progressmonitor
{
public interface MaxThroughputProgressMonitor
{
int MinOutupWaitInMs { get; }
}
}
| 18.75 | 50 | 0.66 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.