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
db86cb2152214964ea3189eb8e7326b04bd3a4ef
3,049
php
PHP
app/Models/Campaign.php
LaravelDevBose/e_com_backend
70f60a510294233aa21d579d524e2aa49a00c82e
[ "MIT" ]
null
null
null
app/Models/Campaign.php
LaravelDevBose/e_com_backend
70f60a510294233aa21d579d524e2aa49a00c82e
[ "MIT" ]
18
2019-04-30T21:06:39.000Z
2019-05-21T19:16:07.000Z
app/Models/Campaign.php
LaravelDevBose/e_com_backend
70f60a510294233aa21d579d524e2aa49a00c82e
[ "MIT" ]
1
2019-05-21T18:58:10.000Z
2019-05-21T18:58:10.000Z
<?php namespace App\Models; use App\Traits\ManipulateBy; use Illuminate\Database\Eloquent\Model; class Campaign extends Model { use ManipulateBy; protected static function boot() { parent::boot(); // TODO: Change the autogenerated stub // ManipulateBy::bootManipulateBy(); } const DiscountType =[ 1=>'Fixed', 2=>'Percent' ]; const Status=[ 'Delete'=>0, 'Active'=>1, 'Inactive'=>2, 'Live'=>3, 'Expired'=>4, ]; const ADDS_POSITION=[ 0=>'Select a Position', 1=>'Home Page Top (600X50)' ]; protected $table = 'campaigns'; protected $primaryKey = 'campaign_id'; protected $fillable = [ 'campaign_title', 'campaign_slug', 'campaign_start', 'campaign_end', 'camp_reg_date', 'campaign_details', 'seller_pro_limit', 'campaign_rules', 'total_product', 'adds_attachment_id', 'adds_position', 'attachment_id', 'campaign_status', ]; public function scopeIsActive($query){ return $query->where('campaign_status', Self::Status['Active']); } public function scopeInactive($query){ return $query->where('campaign_status', Self::Status['Inactive']); } public function scopeNotDelete($query){ return $query->where('campaign_status', '!=', Self::Status['Delete']); } public function scopeIsLive($query){ return $query->where('campaign_status', Self::Status['Live']); } public function scopeIsExpired($query){ return $query->where('campaign_status', Self::Status['Expired']); } public function scopeForSeller($query){ return $query->whereIn('campaign_status', [1,3,4]); } public function attachment(){ return $this->hasOne(Attachment::class,'attachment_id', 'attachment_id')->where('folder', 'campaign'); } public function campaign_products(){ return $this->hasMany(CampaignProduct::class, 'campaign_id', 'campaign_id'); } public function addsImage(){ return $this->hasOne(Attachment::class,'attachment_id', 'adds_attachment_id')->where('folder', 'campaign'); } public static function statusView($status){ switch ($status){ case 0: return '<span class="badge badge-danger">Delete</span>'; break; case 1: return '<span class="badge badge-primary">Active</span>'; break; case 2: return '<span class="badge badge-warning">InActive</span>'; break; case 3: return '<span class="badge badge-Success">Live</span>'; break; case 4: return '<span class="badge badge-danger">Expired</span>'; break; default: return '<span class="badge badge-info" >Unknown</span>'; break; } } }
25.838983
115
0.562807
0f6586b45ebcdcfe1e7c0f19f1ae33e5ae3dfdf2
1,251
dart
Dart
test/js_interop_helpers_test/shared_tests.dart
jey/react-dart
389ffd0022f4aaea35b848a6b4654d4f59caee76
[ "BSD-2-Clause" ]
null
null
null
test/js_interop_helpers_test/shared_tests.dart
jey/react-dart
389ffd0022f4aaea35b848a6b4654d4f59caee76
[ "BSD-2-Clause" ]
null
null
null
test/js_interop_helpers_test/shared_tests.dart
jey/react-dart
389ffd0022f4aaea35b848a6b4654d4f59caee76
[ "BSD-2-Clause" ]
null
null
null
// ignore_for_file: deprecated_member_use_from_same_package @JS() library js_function_test; import 'dart:html'; import 'dart:js_util'; import 'package:js/js.dart'; import 'package:react/react_client/react_interop.dart'; import 'package:test/test.dart'; void verifyJsFileLoaded(String filename) { var isLoaded = document.getElementsByTagName('script').any((script) { return Uri.parse((script as ScriptElement).src).pathSegments.last == filename; }); if (!isLoaded) throw new Exception('$filename is not loaded'); } void sharedJsFunctionTests() { group('JS functions:', () { group('markChildValidated', () { test('is function that does not throw when called', () { expect(() => markChildValidated(newObject()), returnsNormally); }); }); group('createReactDartComponentClass', () { test('is function that does not throw when called', () { expect(() => createReactDartComponentClass(null, null), returnsNormally); }); }); group('createReactDartComponentClass2', () { test('is function that does not throw when called', () { expect(() => createReactDartComponentClass2(null, null, JsComponentConfig2(skipMethods: [])), returnsNormally); }); }); }); }
30.512195
119
0.677858
8877bf0cddac2e69ee2e01702972b746026035c9
488
cs
C#
OmpForDotNet.Utility/Parsers/ParallelDirectiveParser.cs
NamiraJV/OmpForDotNet
7fbb791208b2a6e0d6b5f303ba6cff1d05320d20
[ "Apache-2.0" ]
null
null
null
OmpForDotNet.Utility/Parsers/ParallelDirectiveParser.cs
NamiraJV/OmpForDotNet
7fbb791208b2a6e0d6b5f303ba6cff1d05320d20
[ "Apache-2.0" ]
1
2019-01-02T11:07:58.000Z
2019-01-02T11:07:58.000Z
OmpForDotNet.Utility/Parsers/ParallelDirectiveParser.cs
NamiraJV/OmpForDotNet
7fbb791208b2a6e0d6b5f303ba6cff1d05320d20
[ "Apache-2.0" ]
null
null
null
using OmpForDotNet.Utility.Entities; namespace OmpForDotNet.Utility.Parsers { public class ParallelDirectiveParser : DirectiveParser { private const string PARALLEL_CODE = "parallel"; public override OmpDirectiveInfo Parse(string directive) { return new OmpDirectiveInfo(DirectiveType.OMP_PARALLEL_FOR, ParseDirectiveParameters(directive.Substring(directive.IndexOf(PARALLEL_CODE) + PARALLEL_CODE.Length))); } } }
32.533333
120
0.715164
97bb0912722495d33a43ab056a11053e99f96cee
1,003
sh
Shell
tools/osx-notarize.sh
Nandoflo/node
18132c3339ad91ee910a35f00db8958c62e036f5
[ "MIT" ]
20
2020-07-19T19:26:11.000Z
2022-03-01T07:20:00.000Z
tools/osx-notarize.sh
Nandoflo/node
18132c3339ad91ee910a35f00db8958c62e036f5
[ "MIT" ]
41
2020-03-27T13:36:50.000Z
2022-02-10T16:32:08.000Z
tools/osx-notarize.sh
Nandoflo/node
18132c3339ad91ee910a35f00db8958c62e036f5
[ "MIT" ]
1
2020-11-15T20:38:40.000Z
2020-11-15T20:38:40.000Z
#!/bin/bash # Uses gon, from https://github.com/mitchellh/gon, to notarize a generated node-<version>.pkg file # with Apple for installation on macOS Catalina and later as validated by Gatekeeper. set -e gon_version="0.2.2" gon_exe="${HOME}/.gon/gon_${gon_version}" __dirname="$(CDPATH= cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" pkgid="$1" if [ "X${pkgid}" == "X" ]; then echo "Usage: $0 <pkgid>" exit 1 fi if [ "X$NOTARIZATION_ID" == "X" ]; then echo "No NOTARIZATION_ID environment var. Skipping notarization." exit 0 fi set -x mkdir -p "${HOME}/.gon/" if [ ! -f "${gon_exe}" ]; then curl -sL "https://github.com/mitchellh/gon/releases/download/v${gon_version}/gon_${gon_version}_macos.zip" -o "${gon_exe}.zip" (cd "${HOME}/.gon/" && rm -f gon && unzip "${gon_exe}.zip" && mv gon "${gon_exe}") fi cat tools/osx-gon-config.json.tmpl \ | sed -e "s/{{appleid}}/${NOTARIZATION_ID}/" -e "s/{{pkgid}}/${pkgid}/" \ > gon-config.json "${gon_exe}" -log-level=info gon-config.json
26.394737
128
0.644068
bb5dc2d408b6aecea4680d6efabf46d45ae1cfc8
379
cs
C#
RapidXAML.VSIX/RapidXamlToolkit/Logging/ILogger.cs
sibille/Rapid-XAML-Toolkit
2fb135533158b1ec4ee253b8e81ce4c6028f7474
[ "MIT" ]
null
null
null
RapidXAML.VSIX/RapidXamlToolkit/Logging/ILogger.cs
sibille/Rapid-XAML-Toolkit
2fb135533158b1ec4ee253b8e81ce4c6028f7474
[ "MIT" ]
null
null
null
RapidXAML.VSIX/RapidXamlToolkit/Logging/ILogger.cs
sibille/Rapid-XAML-Toolkit
2fb135533158b1ec4ee253b8e81ce4c6028f7474
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; namespace RapidXamlToolkit.Logging { public interface ILogger { void RecordInfo(string message); void RecordFeatureUsage(string feature); void RecordError(string message); void RecordException(Exception exception); } }
19.947368
61
0.699208
68ea5618f9267a40206199be62d6036f9fc4798a
1,595
lua
Lua
assets/src/xgame/plugin/alipay.lua
bsqgm/cocos-lua
cbad3eb61c75bbb3f9fdba866cdc30d0dac54af8
[ "MIT" ]
141
2019-07-09T06:29:35.000Z
2022-03-30T06:25:16.000Z
assets/src/xgame/plugin/alipay.lua
bsqgm/cocos-lua
cbad3eb61c75bbb3f9fdba866cdc30d0dac54af8
[ "MIT" ]
16
2019-12-23T06:53:18.000Z
2021-10-19T17:01:01.000Z
assets/src/xgame/plugin/alipay.lua
bsqgm/cocos-lua
cbad3eb61c75bbb3f9fdba866cdc30d0dac54af8
[ "MIT" ]
47
2019-08-14T11:12:34.000Z
2022-03-30T06:25:19.000Z
local class = require "xgame.class" local util = require "xgame.util" local runtime = require "xgame.runtime" local PluginEvent = require "xgame.PluginEvent" local Dispatcher = require "xgame.Dispatcher" local cjson = require "cjson.safe" local trace = util.trace("[alipay]") local impl local Alipay = class("Alipay", Dispatcher) function Alipay:ctor() impl:setDispatcher(function (...) self:_didResponse(...) end) end function Alipay:_didResponse(action, message) trace("response: %s %s", action, message) if action == "pay" then local info = cjson.decode(message) local status = info.result_status if status == "9000" or status == "8000" then self:dispatch(PluginEvent.PAY_SUCCESS) elseif status == "6001" then self:dispatch(PluginEvent.PAY_CANCEL) else self:dispatch(PluginEvent.PAY_FAILURE) end end end function Alipay:pay(order) impl:pay(assert(order, "no order")) end if runtime.os == "android" then local luaj = require "xgame.luaj" local inst = luaj.new("cclua/plugin/alipay/Alipay") impl = {} function impl:setDispatcher(callback) impl.callback = callback end function impl:pay(order) inst.pay(order, function (...) impl.callback("pay", ...) end) end else impl = setmetatable({}, {__index = function (_, func) return function () trace("function 'cclua.plugin.alipay.%s' not supported", func) end end}) end return Alipay.new()
26.583333
74
0.625078
e76bf625415971f42c3a8a900396fea2d4994fa4
4,007
rs
Rust
src/layer_one/mod.rs
dexterdarwich/toms-data-onion-rust
a795db5173e05491c89a64493533395e2e0f4949
[ "MIT" ]
null
null
null
src/layer_one/mod.rs
dexterdarwich/toms-data-onion-rust
a795db5173e05491c89a64493533395e2e0f4949
[ "MIT" ]
null
null
null
src/layer_one/mod.rs
dexterdarwich/toms-data-onion-rust
a795db5173e05491c89a64493533395e2e0f4949
[ "MIT" ]
null
null
null
use anyhow::{anyhow, Result}; use crate::helpers; /* ==[ Layer 1/6: Bitwise Operations ]========================= Computers are big calculators. They perform operations with numbers -- adding, subtracting, multiplying, etc. They represent numbers using binary digits (ones and zeros) called "bits". For example, here are the decimal numbers zero to ten with their binary representations: Decimal | Binary --------+--------- 0 | 0 1 | 1 2 | 10 3 | 11 4 | 100 5 | 101 6 | 110 7 | 111 8 | 1000 9 | 1001 10 | 1010 In addition to mathematical operations, computers can perform operations that act upon the individual bits of a number. These are called bitwise operations, and there are only about six different ones: AND, OR, XOR, NOT, LEFT-SHIFT, and RIGHT-SHIFT. Bitwise operations are useful when working with binary data at a low level, such as writing device drivers, cryptographic algorithms, or working with binary file formats (as opposed to text formats like XML or JSON). As an example, let's say we have the decimal numbers 10 and 6, each stored in one byte. A byte contains exactly 8 bits, so the binary representation is padded out with zeros on the left. If we ask the computer to perform a bitwise AND operation on these two bytes, it would do this: 00001010 <-- decimal 10 AND 00000110 <-- decimal 6 -------- 00000010 <-- result: decimal 2 Bitwise AND looks at each bit in both of the bytes. If both bits are 1, then the resulting bit is 1, otherwise the resulting bit is 0. Bitwise operations are not really mathematical operations. Notice how "10 AND 6 = 2" doesn't make much sense mathematically. That is because bitwise operations work at the level of individual bits, ignoring of whatever decimal number the bits represent. ---------------------------------------------------- Like all the layers, the payload is again encoded with Adobe-flavoured ASCII85. After ASCII85 decoding the payload, apply the following operations to each byte: 1. Flip every second bit 2. Rotate the bits one position to the right For example: | Binary Decimal Hex ----------------------+------------------------------- Starting value | 1 0 1 1 0 1 0 0 180 B4 | v v v v Flip every second bit | 1 1 1 0 0 0 0 1 225 E1 | \ \ \ \ \ \ \ \ Rotate to the right | 1 1 1 1 0 0 0 0 ) 240 F0 | \_____________/ Here are some hints: - Bits can be flipped easily using XOR. - You can extract specific bits into a separate value using AND. This is called "masking". - You can use OR to combine some of the bits from one value with some of the bits from another value. Just make sure that the unimportant bits are masked (all set to zero). For example, if you want the first 4 bits of a byte combined with the last 4 bits of another byte: 10100000 OR 00001010 = 10101010 - Bit shift operations discard bits on one side, and add zeros to the other side. If you want to retain the bits that will be shifted off the end of a byte, you probably need to mask it into a separate variable before doing the shift. */ pub(crate) fn decode(encoded: &str) -> Result<String> { let flip_mask: u8 = 0x55; // 0h01010101 helpers::decode(encoded).and_then(|mut vec| { vec.iter_mut().for_each(|byte| { let flipped: u8 = *byte ^ flip_mask; *byte = (flipped >> 1) | (((flipped) & 0x01) << 7); }); String::from_utf8(vec).map_err(|e| anyhow!(e.to_string())) }) }
36.427273
66
0.589718
af5e040ab4ec78cb4f106a86d82a0b9d793323b2
1,183
py
Python
Move Zeroes.py
happyandy2017/LeetCode
64863d9d284a72fa23bed40640f7229a0d904f5b
[ "MIT" ]
null
null
null
Move Zeroes.py
happyandy2017/LeetCode
64863d9d284a72fa23bed40640f7229a0d904f5b
[ "MIT" ]
null
null
null
Move Zeroes.py
happyandy2017/LeetCode
64863d9d284a72fa23bed40640f7229a0d904f5b
[ "MIT" ]
null
null
null
""" Move Zeroes Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. Example: Input: [0,1,0,3,12] Output: [1,3,12,0,0] Note: You must do this in-place without making a copy of the array. Minimize the total number of operations. """ class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ i = 0 for j in range(len(nums)): if nums[j]!=0: nums[i],nums[j]=nums[j],nums[i] i+=1 def moveZeroes_0(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ N = len(nums) if N<=1 or 0 not in nums: return None for i in range(N)[::-1]: if nums[i]!=0: continue j=i while j<N-1 and nums[j+1]!=0: temp=nums[j+1] nums[j+1]=nums[j] nums[j]=temp j+=1
25.717391
133
0.501268
7fbd5281d5356e44ffa509a90ee6f82ba555f85b
1,009
php
PHP
web/app/plugins/woocommerce-multilingual/compatibility/class-wcml-ajax-layered-nav-widget.php
Kilbourne/biosphera
d00043a04963575599c9693cc4b49c0db74040ee
[ "MIT" ]
null
null
null
web/app/plugins/woocommerce-multilingual/compatibility/class-wcml-ajax-layered-nav-widget.php
Kilbourne/biosphera
d00043a04963575599c9693cc4b49c0db74040ee
[ "MIT" ]
null
null
null
web/app/plugins/woocommerce-multilingual/compatibility/class-wcml-ajax-layered-nav-widget.php
Kilbourne/biosphera
d00043a04963575599c9693cc4b49c0db74040ee
[ "MIT" ]
1
2019-09-29T17:41:59.000Z
2019-09-29T17:41:59.000Z
<?php /** Class for WooCommerce Advanced Ajax Layered Navigation */ class WCML_Ajax_Layered_Nav_Widget { function __construct() { add_filter('wc_ajax_layered_nav_sizeselector_term_id', array($this, 'wc_ajax_layered_nav_sizeselector_term_id')); add_filter('wc_ajax_layered_nav_query_editor', array($this, 'wc_ajax_layered_nav_query_editor'),10,3); } function wc_ajax_layered_nav_sizeselector_term_id($term_id) { $ulanguage_code = apply_filters( 'wpml_default_language', null ); $term_id = apply_filters( 'wpml_object_id', $term_id, 'category', true, $ulanguage_code ); return $term_id; } function wc_ajax_layered_nav_query_editor($posts, $attribute, $value){ $posts = get_posts( array( 'post_type' => 'product', 'numberposts' => -1, 'post_status' => 'publish', 'fields' => 'ids', 'no_found_rows' => true, 'tax_query' => array( array( 'taxonomy' => $attribute, 'terms' => $value, 'field' => 'term_id' ) ) ) ); return $posts; } }
25.871795
115
0.68781
75569a1e37c495ae722bfa4a4542f2a0e4bb216f
35
css
CSS
Code/WebUi/Content/Styles/style.css
marinoscar/FireAndForget
bf3702fa3e5a9f5afadd53fe15d23e81af152c82
[ "MIT" ]
null
null
null
Code/WebUi/Content/Styles/style.css
marinoscar/FireAndForget
bf3702fa3e5a9f5afadd53fe15d23e81af152c82
[ "MIT" ]
null
null
null
Code/WebUi/Content/Styles/style.css
marinoscar/FireAndForget
bf3702fa3e5a9f5afadd53fe15d23e81af152c82
[ "MIT" ]
null
null
null
.pad-r { padding-right: 10px }
11.666667
23
0.571429
660638e0dcffcab078e2e56bb8c578dfc71b22bf
2,870
py
Python
scripts/whatsmyip.py
sujaykumarh/dotfiles
0873d855c69cb959693cba809c77749b0d6f6213
[ "Apache-2.0", "MIT" ]
3
2021-08-02T06:08:55.000Z
2021-12-15T10:13:14.000Z
scripts/whatsmyip.py
sujaykumarh/dotfiles
0873d855c69cb959693cba809c77749b0d6f6213
[ "Apache-2.0", "MIT" ]
20
2022-01-10T05:23:15.000Z
2022-03-22T18:55:13.000Z
scripts/whatsmyip.py
sujaykumarh/dotfiles
0873d855c69cb959693cba809c77749b0d6f6213
[ "Apache-2.0", "MIT" ]
null
null
null
#!/usr/bin/env python # ################################################################################ # # Copyright Jun, 2020 - present - Sujaykumar.Hublikar <[email protected]> # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ##################################################################################### import sys, argparse, subprocess import urllib.request import socket # App Name _appName = "WhatsMyIp" # App Name _appDesc = "WhatsMyIp Find out your ip and hostname\nUse -h to find how to use" # App Version _appVer = "0.0.1" def externalIp(): _externalIp = urllib.request.urlopen('https://icanhazip.com/').read().decode('utf-8').rstrip().strip() # print(_externalIp) print("External Ip : ", _externalIp) def internalIP(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('255.255.255.0', 1)) # connect() for UDP doesn't send packets local_ip_address = s.getsockname()[0].strip() print("Internal Ip : ", local_ip_address) except: print("Unable to get Local IP") def hostName(): try: host_name = socket.gethostname().strip() print("Hostname : ", host_name) except: print("Unable to get Hostname") def main(): parser = argparse.ArgumentParser(prog=_appName, description=_appDesc) parser.add_argument('-a', '--all', action='store_true', help="Print all the other argument info.") parser.add_argument('-n', '--hostname', action='store_true', help="Finds Hostname") parser.add_argument('-i', '--internal', action='store_true', help="Finds Internal Ip") parser.add_argument('-e', '--external', action='store_true', help="Finds External Ip") parser.add_argument('-v', '--version', action='version', version='%(prog)s v{version}'.format(version=_appVer)) args = parser.parse_args() globals().update(args.__dict__) if len(sys.argv) < 2: print('{name} v{version}'.format(name=_appName, version=_appVer)) print("\nNo argurment specified use --help or -h to learn more") return if(args.all): hostName() internalIP() externalIp() return if(args.hostname): hostName() if(args.internal): internalIP() if(args.external): externalIp() if __name__ == '__main__': main() # Run Main Function
34.166667
115
0.625436
dbcee88f35a8c881f93abc1249093ff02ae8244b
378
php
PHP
index.php
astdb/loop-urls
c73fd26d546e7f558bbf3cefa7d413ef2ecb58ec
[ "MIT" ]
null
null
null
index.php
astdb/loop-urls
c73fd26d546e7f558bbf3cefa7d413ef2ecb58ec
[ "MIT" ]
null
null
null
index.php
astdb/loop-urls
c73fd26d546e7f558bbf3cefa7d413ef2ecb58ec
[ "MIT" ]
null
null
null
<?php if(isset($_GET['_id']) && is_numeric($_GET['_id'])){ $pageid = intval($_GET['_id']); } else { $pageid = '_xx'; } $loop = false; if(isset($_GET['_loop']) && strcmp(trim($_GET['_loop']),'true')==0){ $loop = true; } if(is_file('index.inc.php')){ include_once('index.inc.php'); } else { print "Template error #3248765823"; } exit();
18.9
70
0.534392
7a07d8bf313b940fb0bd61b421838ad5cbc314f5
3,548
swift
Swift
RescueLink/Models/DeviceSettingsRequest.swift
security-union/armore-ios
55ef53de10b71780d67cab48e7d62e28f35baf09
[ "Apache-2.0" ]
3
2021-04-06T02:37:38.000Z
2021-12-10T08:33:42.000Z
RescueLink/Models/DeviceSettingsRequest.swift
security-union/armore-ios
55ef53de10b71780d67cab48e7d62e28f35baf09
[ "Apache-2.0" ]
null
null
null
RescueLink/Models/DeviceSettingsRequest.swift
security-union/armore-ios
55ef53de10b71780d67cab48e7d62e28f35baf09
[ "Apache-2.0" ]
null
null
null
// // DeviceSettingsService.swift // Armore // // Created by Griffin Obeid on 10/30/20. // Copyright © 2020 Security Union. All rights reserved. // import Foundation import Alamofire import CoreLocation func getLocationPermissionState() -> LocationPermissionState { switch CLLocationManager.authorizationStatus() { case .authorizedAlways: return LocationPermissionState.ALWAYS case .authorizedWhenInUse: return LocationPermissionState.USING case .restricted: return LocationPermissionState.ASK case .denied: return LocationPermissionState.NEVER case .notDetermined: return LocationPermissionState.UNKNOWN default: return LocationPermissionState.UNKNOWN } } enum LocationPermissionState: String, Decodable, Encodable { case ALWAYS case USING case ASK case NEVER case UNKNOWN } struct DeviceSettingsRequest: Encodable, Decodable, Equatable { var locationPermissionState: LocationPermissionState var isPowerSaveModeOn: Bool var isNotificationsEnabled: Bool var isBackgroundRefreshOn: Bool var isLocationServicesOn: Bool var osVersion: String var appVersion: String static func buildDeviceSettings() -> DeviceSettingsRequest { let shortVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") let bundleVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") return DeviceSettingsRequest( locationPermissionState: getLocationPermissionState(), isPowerSaveModeOn: ProcessInfo.processInfo.isLowPowerModeEnabled, isNotificationsEnabled: UIApplication.shared.isRegisteredForRemoteNotifications, isBackgroundRefreshOn: UIApplication.shared.backgroundRefreshStatus == UIBackgroundRefreshStatus.available, isLocationServicesOn: CLLocationManager.locationServicesEnabled(), osVersion: UIDevice.current.systemVersion, appVersion: "\(shortVersion ?? "")-\(bundleVersion ?? "")" ) } } struct DeviceSettingsResponse: WithMessage { let message: String? let engineeringError: String? let updated: Bool? func getMessage() -> String? { message } func getEngineeringError() -> String? { engineeringError } } func deviceSettingsRequest( _ deviceSettings: DeviceSettingsRequest, completion: @escaping (ApiResponse<DeviceSettingsResponse>) -> Void) { AF.request( URLs().deviceSettings(), method: .post, parameters: deviceSettings, encoder: JSONParameterEncoder.default, headers: addBaseHeaders([]) ).responseJSON { response in if let data = response.data, var apiResponse = try? JSONDecoder().decode(ApiResponse<DeviceSettingsResponse>.self, from: data) { apiResponse.httpCode = response.response?.statusCode completion(apiResponse) } else { completion(ApiResponse<DeviceSettingsResponse>( success: false, httpCode: response.response?.statusCode, result: DeviceSettingsResponse( message: NSLocalizedString("server_parsing_error", comment: ""), engineeringError: NSLocalizedString("server_parsing_error", comment: ""), updated: nil ) )) } } }
34.115385
110
0.663191
740ef3b34260c1a6971ddc52022f98f395ca63e2
1,148
css
CSS
assets/css/app.css
ejmurra/footballStats
854abb9e24afa0797cc0ed49ab63ad5c6fb3954a
[ "MIT" ]
1
2020-08-07T16:44:47.000Z
2020-08-07T16:44:47.000Z
assets/css/app.css
ejmurra/footballStats
854abb9e24afa0797cc0ed49ab63ad5c6fb3954a
[ "MIT" ]
null
null
null
assets/css/app.css
ejmurra/footballStats
854abb9e24afa0797cc0ed49ab63ad5c6fb3954a
[ "MIT" ]
null
null
null
.display-table { margin: 0 auto; } .display-table th { font-size: .7em; line-height: 1em; } #JameisWinston { background-color: #D50A0A; } #JameisWinston td { color: whitesmoke; } #MarcusMariota { background-color: #002244; } #MarcusMariota td { color: whitesmoke; } svg { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none; } .jameis { fill: none; stroke: #D50A0A; stroke-width: 1.5px; z-index: 10; } .marcus { fill: none; stroke: #002244; stroke-width: 1.5px; z-index: 10; } .unselected { fill: none; stroke: lightgrey; stroke-width: 2px; } .selected { fill: none; stroke-width: 3px; } .spacer { height: 25px; } .tooltip-container { position: absolute; pointer-events: none; padding: 2px 4px 2px 6px; background-color: #eee; border: solid 1px #aaa; } .tooltip-title { text-align: center; font-size: 12px; font-weight: bold; margin-bottom: 4px; } .tooltip-content { font-size: 11px; line-height: 1em; margin-bottom: 4px; } /*# sourceMappingURL=app.css.map */
15.944444
35
0.633275
aa1c30b2e1db2ded34c8c60eb738ac58df6e3498
1,363
rb
Ruby
test/br_nfe/service/sc/florianopolis/cancellation_test.rb
laerciocrestani/br_nfe
cab16bf8268c768bfbc28592e2e5bdbfd18f22f8
[ "MIT" ]
64
2015-09-29T22:01:12.000Z
2021-01-11T18:43:20.000Z
test/br_nfe/service/sc/florianopolis/cancellation_test.rb
laerciocrestani/br_nfe
cab16bf8268c768bfbc28592e2e5bdbfd18f22f8
[ "MIT" ]
4
2016-09-19T19:35:45.000Z
2020-12-04T22:12:27.000Z
test/br_nfe/service/sc/florianopolis/cancellation_test.rb
rcoproc/br_nfe
47e2da3ae41894d69a4b179778f188add7d73dec
[ "MIT" ]
28
2015-12-11T13:28:36.000Z
2021-01-11T18:51:18.000Z
require 'test_helper' describe BrNfe::Service::SC::Florianopolis::Cancellation do subject { FactoryGirl.build(:service_sc_floripa_cancellation) } let(:xsd_text) do f = File.read(BrNfe.root+'/test/br_nfe/service/sc/florianopolis/XSD/TiposNFSe_v2.0.xsd') # Substiruo a localização do arquivo xmldsig-core-schema.xsd conforme a localização da gem f.gsub('xmldsig-core-schema.xsd', BrNfe.root+'/test/br_nfe/service/sc/florianopolis/XSD/xmldsig-core-schema.xsd' ) end let(:schema) { Nokogiri::XML::Schema(xsd_text) } it { must validate_presence_of(:aedf) } it { must validate_presence_of(:serie_number) } it { must validate_length_of(:motive).is_at_most(120) } it { must validate_numericality_of(:serie_number).only_integer.is_less_than_or_equal_to(999999).allow_nil } describe "Validações a partir do arquivo XSD" do it "O xml deve ser válido quando todas as informações possíveis estiverem preenchidas" do subject.assign_attributes({motive: 'Motivo'}) document = Nokogiri::XML(subject.content_xml) errors = schema.validate(document) errors.must_be_empty end it "O xml deve ser válido quando apenas as informações obrigatórias estiverem preenchidas " do subject.assign_attributes({motive: nil}) document = Nokogiri::XML(subject.content_xml) errors = schema.validate(document) errors.must_be_empty end end end
37.861111
116
0.768892
b07ff0f4df821323ec4de2bef89169f8ba5dfd61
365
py
Python
mmdet/models/recognizer/__init__.py
liangxiaoyun/mmdetection-1.1.0-pse-sar
d4f80368949ba74dad13d0a4744a53c82f89577d
[ "Apache-2.0" ]
null
null
null
mmdet/models/recognizer/__init__.py
liangxiaoyun/mmdetection-1.1.0-pse-sar
d4f80368949ba74dad13d0a4744a53c82f89577d
[ "Apache-2.0" ]
1
2021-05-25T07:16:12.000Z
2021-09-01T07:35:01.000Z
mmdet/models/recognizer/__init__.py
liangxiaoyun/mmdetection-1.1.0-pse-sar
d4f80368949ba74dad13d0a4744a53c82f89577d
[ "Apache-2.0" ]
null
null
null
from .base import BaseRecognizer from .decoder import Decoder from .encoder import Encoder from .sar import SAR from .sar_resnet import SAR_ResNet, BasicBlock from .str_lable_converter_for_attention import strLabelConverterForAttention __all__ = [ 'BaseRecognizer', 'Decoder', 'Encoder', 'SAR', 'strLabelConverterForAttention', 'BasicBlock', 'SAR_ResNet' ]
33.181818
83
0.79726
975c751324a9e404f99baad818dfc013b2f64297
1,821
tsx
TypeScript
pages/index.tsx
ekafyi/wargabantuwarga.com
93464a02f144434d02e872f7e42e435483aa9609
[ "MIT" ]
null
null
null
pages/index.tsx
ekafyi/wargabantuwarga.com
93464a02f144434d02e872f7e42e435483aa9609
[ "MIT" ]
null
null
null
pages/index.tsx
ekafyi/wargabantuwarga.com
93464a02f144434d02e872f7e42e435483aa9609
[ "MIT" ]
1
2021-12-11T08:08:56.000Z
2021-12-11T08:08:56.000Z
import { GetStaticProps } from "next"; import Head from "next/head"; import { Script } from "../components/script"; import data from "../data/wbw.json"; type HomeProps = { html: string; css: string; }; export const getStaticProps: GetStaticProps = async () => { return { props: { html: data.html, css: data.css, }, }; }; export default function Home(props: HomeProps) { return ( <> <Head> <style dangerouslySetInnerHTML={{ __html: props.css }} /> </Head> <Script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l] = w[l] || [];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-5X4ZPBX');`, }} /> <noscript> <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5X4ZPBX" height="0" width="0" style={{ display: "none", visibility: "hidden" }} ></iframe> </noscript> <main> <header> <h1> {/* eslint-disable-next-line @next/next/no-img-element */} <img src="https://firebase-kanvas.imgix.net/warga_bantu_warga/hero_banner.png?auto=format,compress,enhance&fm=pjpg&cs=tinysrgb&fit=scale" alt="Warga Bantu Warga" height="291" width="650" style={{ maxWidth: "100%", height: "auto" }} /> </h1> </header> <article className="p-3" dangerouslySetInnerHTML={{ __html: props.html }} ></article> </main> </> ); }
28.453125
146
0.546952
438d779f51ccfada5c5e5fc4a8d52599f3b999f4
203
ts
TypeScript
.storybook/RicardoTheme.ts
dutzi/react-easy-sort
1b05c387c2e9cde6dd1e657b6180d3df07645a11
[ "MIT" ]
54
2021-02-05T08:58:11.000Z
2022-01-30T04:55:18.000Z
.storybook/RicardoTheme.ts
dutzi/react-easy-sort
1b05c387c2e9cde6dd1e657b6180d3df07645a11
[ "MIT" ]
25
2021-02-09T09:13:32.000Z
2022-02-13T22:09:56.000Z
.storybook/RicardoTheme.ts
dutzi/react-easy-sort
1b05c387c2e9cde6dd1e657b6180d3df07645a11
[ "MIT" ]
14
2021-02-05T10:31:10.000Z
2022-01-17T16:44:06.000Z
import { create } from '@storybook/theming' export default create({ base: 'light', brandTitle: 'react-easy-sort', brandImage: 'https://ricardostaticfiles.b-cdn.net/logos/ricardo_logo_pos.svg', })
25.375
80
0.724138
6b7f5bcf26edfe471062376301c84c5687e2de9b
6,159
cpp
C++
utility/SignalProbe.cpp
willcode/PothosComms
6c6ae8ccb6a9c996a67e2ca646aff79c74bb83fa
[ "BSL-1.0" ]
14
2017-10-28T08:40:08.000Z
2022-03-19T06:08:55.000Z
utility/SignalProbe.cpp
BelmY/PothosComms
9aa48b827b3813b3ba2b98773f3359b30ebce346
[ "BSL-1.0" ]
22
2015-08-25T21:18:13.000Z
2016-12-31T02:23:47.000Z
utility/SignalProbe.cpp
pothosware/pothos-comms
cff998cca2c9610d3e7e5480fd4fc692c13d3066
[ "BSL-1.0" ]
13
2018-01-03T15:29:44.000Z
2022-03-19T06:09:00.000Z
// Copyright (c) 2014-2019 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include <Pothos/Framework.hpp> #include <Pothos/Util/QFormat.hpp> #include <cstdint> #include <complex> #include <iostream> #include <algorithm> //min/max #include <chrono> /*********************************************************************** * |PothosDoc Signal Probe * * The signal probe block records the last calculation from a stream of elements. * The signal probe has a slot called "probeValue" will will cause * a signal named "valueTriggered" to emit the most recent value. * The probe will also emit the value automatically at the specified rate * using the "valueChanged" signal. * * The calculation for value can be, the last seen value, * the RMS (root mean square) over the last buffer, * or the mean (average value) over the last buffer. * * |category /Utility * |category /Event * |keywords rms average mean * |alias /blocks/stream_probe * * |param dtype[Data Type] The data type consumed by the stream probe. * |widget DTypeChooser(float=1,cfloat=1,int=1,cint=1) * |default "complex_float32" * |preview disable * * |param mode The calculation mode for the value. * In value mode, this block expects to be fed by an upstream block * that produces a stream of slow-changing values. * Otherwise the value will appear random. * |default "VALUE" * |option [Value] "VALUE" * |option [RMS] "RMS" * |option [Mean] "MEAN" * * |param rate How many calculations per second? * The probe will perform a calculation at most this many times per second. * Incoming samples will be dropped and not processed between calculations. * A special value of 0.0 means perform the calculation on every input window. * |preview valid * |default 0.0 * * |param window How many elements to calculate over? * |default 1024 * * |factory /comms/signal_probe(dtype) * |setter setMode(mode) * |setter setRate(rate) * |setter setWindow(window) **********************************************************************/ template <typename Type, typename ProbeType> class SignalProbe : public Pothos::Block { public: SignalProbe(void): _value(0), _mode("VALUE"), _window(1024), _rate(0.0) { this->setupInput(0, typeid(Type)); this->registerCall(this, POTHOS_FCN_TUPLE(SignalProbe, value)); this->registerCall(this, POTHOS_FCN_TUPLE(SignalProbe, setMode)); this->registerCall(this, POTHOS_FCN_TUPLE(SignalProbe, getMode)); this->registerCall(this, POTHOS_FCN_TUPLE(SignalProbe, setWindow)); this->registerCall(this, POTHOS_FCN_TUPLE(SignalProbe, getWindow)); this->registerCall(this, POTHOS_FCN_TUPLE(SignalProbe, setRate)); this->registerCall(this, POTHOS_FCN_TUPLE(SignalProbe, getRate)); this->registerProbe("value"); this->registerSignal("valueChanged"); this->input(0)->setReserve(1); } ProbeType value(void) { return _value; } void setMode(const std::string &mode) { _mode = mode; } std::string getMode(void) const { return _mode; } void setWindow(const size_t window) { _window = window; this->input(0)->setReserve(window); } size_t getWindow(void) const { return _window; } void setRate(const double rate) { _rate = rate; } double getRate(void) const { return _rate; } void activate(void) { _nextCalc = std::chrono::high_resolution_clock::now(); } void work(void) { auto inPort = this->input(0); const Type *x = inPort->buffer(); const auto N = std::min(_window, inPort->elements()); inPort->consume(N); //check if the time expired or rate is 0.0 auto currentTime = std::chrono::high_resolution_clock::now(); if (_rate != 0.0 and currentTime < _nextCalc) return; //increment for the next calculation time if (_rate != 0.0) { const auto tps = std::chrono::nanoseconds((long long)(1e9/_rate)); _nextCalc += std::chrono::duration_cast<std::chrono::high_resolution_clock::duration>(tps); } if (_mode == "VALUE") _value = Pothos::Util::fromQ<ProbeType>(x[N-1], 0); else if (_mode == "RMS") { double accumulator = 0.0; ProbeType x_n; for (size_t n = 0; n < N; n++) { x_n = Pothos::Util::fromQ<ProbeType>(x[n], 0); const double v = std::abs(x_n); accumulator += v*v; } _value = std::sqrt(accumulator/N); } else if (_mode == "MEAN") { ProbeType mean = 0; for (size_t n = 0; n < N; n++) mean += Pothos::Util::fromQ<ProbeType>(x[n], 0); mean /= N; _value = mean; } this->emitSignal("valueChanged", _value); } private: ProbeType _value; std::string _mode; size_t _window; double _rate; std::chrono::high_resolution_clock::time_point _nextCalc; }; /*********************************************************************** * registration **********************************************************************/ static Pothos::Block *signalProbeFactory(const Pothos::DType &dtype) { #define ifTypeDeclareFactory(type) \ if (dtype == Pothos::DType(typeid(type))) return new SignalProbe<type, double>(); \ if (dtype == Pothos::DType(typeid(std::complex<type>))) return new SignalProbe<std::complex<type>, std::complex<double>>(); ifTypeDeclareFactory(double); ifTypeDeclareFactory(float); ifTypeDeclareFactory(int64_t); ifTypeDeclareFactory(int32_t); ifTypeDeclareFactory(int16_t); ifTypeDeclareFactory(int8_t); throw Pothos::InvalidArgumentException("signalProbeFactory("+dtype.toString()+")", "unsupported type"); } static Pothos::BlockRegistry registerSignalProbe( "/comms/signal_probe", &signalProbeFactory); static Pothos::BlockRegistry registerSignalProbeOldPath( "/blocks/stream_probe", &signalProbeFactory);
31.584615
131
0.610813
200900c1f03289b0752dc6c05191d0892fa8a3b1
895
py
Python
python/tests/test_setup_and_run.py
RabertNIDrive/konduit-serving
7ea2d8fca1b78a6af67cf2b1bb141f81e65ab31b
[ "Apache-2.0" ]
50
2019-10-16T08:46:42.000Z
2021-12-16T08:27:01.000Z
python/tests/test_setup_and_run.py
RabertNIDrive/konduit-serving
7ea2d8fca1b78a6af67cf2b1bb141f81e65ab31b
[ "Apache-2.0" ]
392
2019-10-17T06:51:02.000Z
2022-02-26T11:29:51.000Z
python/tests/test_setup_and_run.py
RabertNIDrive/konduit-serving
7ea2d8fca1b78a6af67cf2b1bb141f81e65ab31b
[ "Apache-2.0" ]
20
2019-10-16T08:47:50.000Z
2021-04-07T08:41:29.000Z
import numpy as np import pytest from konduit import * from konduit.server import Server from konduit.utils import is_port_in_use @pytest.mark.integration def test_setup_and_run_start(): python_config = PythonConfig( python_code="def setup(): pass\ndef run(input): {'output': np.array(input + 2)}", python_inputs={"input": "NDARRAY"}, python_outputs={"output": "NDARRAY"}, setup_and_run=True, ) step = PythonStep().step(python_config) server = Server(steps=step, serving_config=ServingConfig()) _, port, started = server.start() assert started assert is_port_in_use(port) client = server.get_client() data_input = {"default": np.asarray([42.0, 1.0])} try: predicted = client.predict(data_input) print(predicted) server.stop() except Exception as e: print(e) server.stop()
25.571429
89
0.659218
4ba4101a5bbb18c7916f7ba0dabc0272663d911e
5,194
hpp
C++
traceur-core/include/traceur/core/scene/primitive/box.hpp
fabianishere/traceur
93eefd77fc402dbd340dac7760a27b491c44a30f
[ "MIT" ]
2
2018-04-26T09:00:20.000Z
2019-11-02T08:09:03.000Z
traceur-core/include/traceur/core/scene/primitive/box.hpp
fabianishere/traceur
93eefd77fc402dbd340dac7760a27b491c44a30f
[ "MIT" ]
2
2018-01-08T14:43:17.000Z
2018-03-28T12:32:45.000Z
traceur-core/include/traceur/core/scene/primitive/box.hpp
fabianishere/traceur
93eefd77fc402dbd340dac7760a27b491c44a30f
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2017 Traceur 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. */ #ifndef TRACEUR_CORE_SCENE_PRIMITIVE_BOX_H #define TRACEUR_CORE_SCENE_PRIMITIVE_BOX_H #include <limits> #include <traceur/core/scene/primitive/primitive.hpp> namespace traceur { /** * A primitive that represents a box. */ class Box : public Primitive { public: /** * An axis of the box. */ enum class Axis: int { X = 0, Y = 1, Z = 2 }; /** * The minimum vertex in the box. */ glm::vec3 min; /** * The maximum vertex in the box. */ glm::vec3 max; /** * Construct a {@link Box} instance. * * @param[in] material The material of the primitive. */ Box(const std::shared_ptr<traceur::Material> material) : Primitive(glm::vec3(), material), min(glm::vec3()), max(glm::vec3()) {} /** * Construct a {@link Box} instance. * * @param[in] min The minimum vertex in the box. * @param[in] max The maximum vertex in the box. * @param[in] material The material of the primitive. */ Box(const glm::vec3 &min, const glm::vec3 max, const std::shared_ptr<traceur::Material> material) : Primitive((min + max) / 2.f, material), min(min), max(max) {} /** * Construct a {@link Box} as bounding box. * * @return The bounding box instance. */ static Box createBoundingBox() { auto min = glm::vec3(std::numeric_limits<float>::infinity()); auto max = -min; return createBoundingBox(min, max); } /** * Construct a {@link Box} as bounding box. * * @param[in] min The minimum vertex in the box. * @param[in] max The maximum vertex in the box. * @return The bounding box instance. */ static Box createBoundingBox(const glm::vec3 &min, const glm::vec3 &max) { return Box(min, max, std::make_shared<traceur::Material>()); } /** * Determine whether the given ray intersects the shape. * * @param[in] ray The ray to intersect with this shape. * @param[in] hit The intersection structure to which the details will * be written to. * @return <code>true</code> if the shape intersects the ray, otherwise * <code>false</code>. */ inline virtual bool intersect(const traceur::Ray &ray, traceur::Hit &hit) const final { /* TODO precalculate inverse */ glm::vec3 inverse = 1.0f / ray.direction; auto u = (min - ray.origin) * inverse; auto v = (max - ray.origin) * inverse; float tmin = std::fmax(std::fmax(std::fmin(u[0], v[0]), std::fmin(u[1], v[1])), std::fmin(u[2], v[2])); float tmax = std::fmin(std::fmin(std::fmax(u[0], v[0]), std::fmax(u[1], v[1])), std::fmax(u[2], v[2])); if (tmax < 0) return false; if (tmin > tmax) return false; hit.primitive = this; hit.distance = tmin; hit.position = ray.origin + tmin * ray.direction; return true; } /** * Expand this {@link Box} with another box. * * @param[in] other The other box to expand with. * @return The next expanded box with the material properties of this * instance. */ traceur::Box expand(const traceur::Box &other) const { return traceur::Box(glm::min(min, other.min), glm::max(max, other.max), material); } /** * Accept a {@link SceneGraphVisitor} instance to visit this node in * the graph of the scene. * * @param[in] visitor The visitor to accept. */ inline virtual void accept(traceur::SceneGraphVisitor &visitor) const final { visitor.visit(*this); } /** * Return the bounding {@link Box} which encapsulates the whole * primitive. * * @return The bounding {@link Box} instance. */ virtual const traceur::Box & bounding_box() const final { return *this; } /** * Return the longest axis of this box. * * @return The longest axis of the box. */ traceur::Box::Axis longestAxis() const { auto length = max - min; if (length.x > length.y && length.x > length.z) return traceur::Box::Axis::X; if (length.y > length.x && length.y > length.z) return traceur::Box::Axis::Y; return traceur::Box::Axis::Z; } }; } #endif /* TRACEUR_CORE_SCENE_PRIMITIVE_PRIMITIVE_H */
29.01676
106
0.656912
254d1db91268904f4d70eea878c20752ef8d8ace
188
cs
C#
src/SimpleSyslog/LogLevel.cs
JonCanning/SimpleSyslog
6f6450f485e2ce57a6d26ce7e254f692cb5daccf
[ "MIT" ]
10
2015-03-20T11:10:23.000Z
2020-07-08T18:10:48.000Z
src/SimpleSyslog/LogLevel.cs
JonCanning/SimpleSyslog
6f6450f485e2ce57a6d26ce7e254f692cb5daccf
[ "MIT" ]
3
2015-04-03T03:58:43.000Z
2021-11-23T19:07:35.000Z
src/SimpleSyslog/LogLevel.cs
JonCanning/SimpleSyslog
6f6450f485e2ce57a6d26ce7e254f692cb5daccf
[ "MIT" ]
2
2015-11-11T14:18:26.000Z
2021-06-24T16:00:42.000Z
namespace SimpleSyslog { public enum LogLevel { Emergency, Alert, Critical, Error, Warn, Notice, Info, Debug } }
13.428571
24
0.452128
a535c2d7d98479cdc0babf2df6c6b903e9438c69
4,081
rs
Rust
src/context.rs
AndreasOM/cheval
a7dd5d0c370abdaf8aa870b1865f42d6d875487e
[ "MIT" ]
4
2021-05-17T18:29:08.000Z
2022-03-20T18:51:26.000Z
src/context.rs
AndreasOM/cheval
a7dd5d0c370abdaf8aa870b1865f42d6d875487e
[ "MIT" ]
null
null
null
src/context.rs
AndreasOM/cheval
a7dd5d0c370abdaf8aa870b1865f42d6d875487e
[ "MIT" ]
null
null
null
use std::collections::HashMap; use regex::Regex; use expresso::expression::Expression; use expresso::machine::Machine; #[derive(Debug)] pub struct Context { time_step: f64, machine: Machine, } impl Context { pub fn new() -> Self { Self { time_step: 1.0/60.0, machine: Machine::new(), } } pub fn get_mut_machine( &mut self ) -> &mut Machine { &mut self.machine } pub fn set_time_step( &mut self, time_step: f64 ) { self.time_step = time_step; } pub fn time_step( &self ) -> f64 { self.time_step } pub fn set_string( &mut self, name: &str, value: &str ) { // dbg!(&name, &value); self.machine.get_mut_variable_storage().set( name, expresso::variables::Variable::String( value.to_string() ) ); } pub fn set_f32( &mut self, name: &str, value: f32 ) { // dbg!(&name, &value); self.machine.get_mut_variable_storage().set( name, expresso::variables::Variable::F32( value ) ); } pub fn get_string( &self, name: &str ) -> Option< &str > { match self.machine.get_variable_storage().get( name ) { Some( expresso::variables::Variable::String( s ) ) => Some( s ), o => todo!("{:?}", &o), } } pub fn get_f32( &self, name: &str ) -> Option< f32 > { match self.machine.get_variable_storage().get( name ) { Some( expresso::variables::Variable::F32( f ) ) => Some( *f ), None => None, // Why not??? o => { // todo!("{:?}", &o) println!("Error: Can not get as f32: {:?} using 0.0", &o); Some( 0.0 ) }, } } pub fn get_expanded_string( &self, name: &str ) -> Option< &str > { match self.get_string( name ) { None => None, Some( s ) => { Some( s ) }, } } // :TODO: maybe return str instead String to avoid potentially unneeded copies pub fn expand_string_or( &mut self, s: &str, default: &str ) -> String { let re = Regex::new(r"^\$\{([^:]+)(:(.+))?\}$").unwrap(); // :TODO: we could use non greedy matching here let re2 = Regex::new(r"^\$\[([^:]+)(:(.+))?\]$").unwrap(); // :TODO: we could use non greedy matching here if let Some( caps ) = re.captures( &s ) { // dbg!(&caps); let name = &caps[ 1 ]; // dbg!(&name); if let Some( value ) = self.get_string( &name ) { value.to_string() } else { // dbg!("Variable not found", &name); // dbg!("Returning default for", &s, &default); match caps.get( 3 ) { Some( c ) => { self.set_string( &name, c.as_str() ); c.as_str().to_string() }, None => { default.to_string() }, } } } else if let Some( caps ) = re2.captures( &s ) { let mut expression = Expression::new(); expression.from_str( &caps[ 1 ] ); // println!("{}", expression); let mut r = expression.run( &mut self.machine ); match r.pop() { Some( expresso::variables::Variable::I32( i ) ) => { format!("{}", i ) }, Some( expresso::variables::Variable::F32( f ) ) => { format!("{}", f ) }, None => format!("No result" ), r => todo!("Result is not printable {:?}", r ), } // format!("Expression: {}", &caps[ 1 ]) } else { s.to_string() } } pub fn expand_u32_or( &mut self, s: &str, default: u32 ) -> u32 { let s = self.expand_string_or( s, "" ); if let Ok( u ) = s.parse::<u32>() { u } else { default } } /* pub fn expand_var_to_u32_or( &mut self, v: &Variable, default: u32 ) -> u32 { match v.original() { Original::U32( u ) => { u }, Original::STRING( s ) => { let s = self.expand_string_or( &s, "" ); if let Ok( u ) = s.parse::<u32>() { u } else if let Ok( f ) = s.parse::<f32>() { f as u32 } else { default } }, _ => default, } } pub fn expand_var_to_f32_or( &mut self, v: &Variable, default: f32 ) -> f32 { match v.original() { Original::F32( u ) => { u }, Original::U32( u ) => { u as f32 }, Original::STRING( s ) => { let s = self.expand_string_or( &s, "" ); if let Ok( u ) = s.parse::<u32>() { u as f32 } else if let Ok( f ) = s.parse::<f32>() { f } else { default } }, _ => default, } } */ }
24.005882
114
0.545455
b727aa480a6168032cc2e7acfd43d4c59618844f
40,651
cs
C#
SpaceFightForWindows/Controler.cs
Astisus/SpaceFight
32825bd1d5335e1020fa118d80d49cd745b434f5
[ "MIT" ]
3
2015-06-11T16:27:00.000Z
2015-08-28T11:09:00.000Z
SpaceFightForWindows/Controler.cs
Astisus/SpaceFight
32825bd1d5335e1020fa118d80d49cd745b434f5
[ "MIT" ]
null
null
null
SpaceFightForWindows/Controler.cs
Astisus/SpaceFight
32825bd1d5335e1020fa118d80d49cd745b434f5
[ "MIT" ]
null
null
null
#region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.GamerServices; using SpaceShooter.ElementsClass; using SpaceShooter.Tools; #endregion namespace SpaceShooter { /// <summary> /// Klasa odpowiadająca za komunikacje między innymi klasami /// </summary> class Controler { // aktualne okno gry static private int actuallyScreen = Constants.START; static public int mActuallyScreen { get { return actuallyScreen; } } // element, który jest podświetlony - 0 = żaden static public int hoverElement = 0; // zmienna zmiany okna gry static private int nextScreenToChange = 0; // obiekt wybranego statku static private Ship chooseShip = null; // zmienna dotycząca kliknięcia myszką static private MouseState previousMouseState = Mouse.GetState(); static private KeyboardState previousKeyState = Keyboard.GetState(); /// <summary> /// Ustala wielkość okna /// </summary> /// <param name="width">Szerokość w px</param> /// <param name="height">Wysokość w px</param> static public void SetWindowWidthAndHeight(int width, int height) { GUI.mWidth = width; GUI.mHeight = height; } static public void Initialize() { GameLogic.GetShipsProperty(); GameLogic.GetColors(); GameLogic.SetGameModes(); GameLogic.GetSettings(); GameLogic.CreateShips(actuallyScreen, chooseShip); GameLogic.GenerateBackground(); GameLogic.CreateGravityAreas(actuallyScreen, GUI.mWidth, GUI.mHeight); Logger.Info("Inicjalizacja gry."); } static public void Load(ContentManager Content) { GUI.LoadImages(Content); Logger.Info("Załadowanie grafik."); GUI.LoadFonts(Content); Logger.Info("Załadowanie czcionek."); Music.LoadMusic(Content); Music.LoadSounds(Content); } static public void Draw(ref SpriteBatch spriteBatch, GraphicsDevice graphicsDevice) { try { switch (actuallyScreen) { case Constants.START: case Constants.OPTIONS: case Constants.CREDITS: GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_BACKGROUND); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_GRAVITY_AREA); GUI.DrawGravityAreas(ref spriteBatch, GameLogic.GetGravityAreas); GUI.DrawMenu(ref spriteBatch, GameLogic.mHighscore, actuallyScreen, GameLogic.mControlType, GameLogic.mShowingWarnings, GameLogic.mGameMode, GameLogic.mPlaySounds, GameLogic.mPlayMusic, hoverElement); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_EXPLOSION); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_DYNAMIC); GUI.DrawMissiles(ref spriteBatch, GameLogic.GetMissiles); GUI.DrawShips(ref spriteBatch, GameLogic.GetShips); break; case Constants.CHOOSING: GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_BACKGROUND); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_GRAVITY_AREA); GUI.DrawGravityAreas(ref spriteBatch, GameLogic.GetGravityAreas); GUI.DrawMenu(ref spriteBatch, GameLogic.mHighscore, actuallyScreen, GameLogic.mControlType, GameLogic.mShowingWarnings, GameLogic.mGameMode, GameLogic.mPlaySounds, GameLogic.mPlayMusic, hoverElement); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_EXPLOSION); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_DYNAMIC); GUI.DrawMissiles(ref spriteBatch, GameLogic.GetMissiles); GUI.DrawShips(ref spriteBatch, GameLogic.GetShips, actuallyScreen, chooseShip.ID); break; case Constants.TUTORIAL: GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_BACKGROUND); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_GRAVITY_AREA); GUI.DrawGravityAreas(ref spriteBatch, GameLogic.GetGravityAreas); GUI.DrawTutorial(ref spriteBatch, graphicsDevice, GameLogic.mTutorialStep, GameLogic.mControlType); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_EXPLOSION); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_DYNAMIC); GUI.DrawMissiles(ref spriteBatch, GameLogic.GetMissiles); GUI.DrawShips(ref spriteBatch, GameLogic.GetShips); switch (GameLogic.mTutorialStep) { case 2: GUI.DrawTurboPowerBar(ref spriteBatch, graphicsDevice, GameLogic.GetPlayerShip()); break; case 3: case 4: case 5: GUI.DrawShieldBar(ref spriteBatch, graphicsDevice, GameLogic.GetPlayerShip()); GUI.DrawTurboPowerBar(ref spriteBatch, graphicsDevice, GameLogic.GetPlayerShip()); break; } break; case Constants.GAME: GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_BACKGROUND); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_GRAVITY_AREA); GUI.DrawGravityAreas(ref spriteBatch, GameLogic.GetGravityAreas); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_EXPLOSION); GUI.DrawParticles(ref spriteBatch, GameLogic.GetParticles, Constants.PARTICLE_DYNAMIC); GUI.DrawMissiles(ref spriteBatch, GameLogic.GetMissiles); GUI.DrawShips(ref spriteBatch, GameLogic.GetShips); GUI.DrawTurboPowerBar(ref spriteBatch, graphicsDevice, GameLogic.GetPlayerShip()); GUI.DrawShieldBar(ref spriteBatch, graphicsDevice, GameLogic.GetPlayerShip()); GUI.DrawGameInfo(ref spriteBatch, GameLogic.mActuallyPoints, GameLogic.mActuallyCombo); if (GameLogic.mShowingWarnings) { GUI.DrawWarnings(ref spriteBatch, GameLogic.ControlWarnings(), GameLogic.GetPlayerShip()); } break; } } catch (Exception ex) { Logger.Error(ex, "Błąd podczas pętli rysowania"); } } static public void Update() { try { GameLogic.EventProcessing(HandleMouseEvent(), HandleKeyboardEvent()); CheckChangeScreen(); Music.PlayMusic(GameLogic.mPlayMusic, actuallyScreen); switch (actuallyScreen) { case Constants.START: case Constants.OPTIONS: case Constants.CREDITS: hoverElement = CheckActuallyHover(); GameLogic.CreateParticle(); GameLogic.AddNewEnemy(); GameLogic.MoveMissiles(); GameLogic.MoveShips(actuallyScreen); GameLogic.MoveParticles(actuallyScreen); GameLogic.MoveParticleSources(); GameLogic.ControlTurboMode(); GameLogic.ControlExplosion(); GameLogic.UpdatePlayerDilation(); AI.PrepareAILogic(GameLogic.GetShips, GameLogic.GetPlayerShip()); AI.PrepareMenuAILogic(GameLogic.GetShips, GameLogic.GetPlayerShip()); GameLogic.RemoveBadMissile(); GameLogic.DestroyShips(actuallyScreen); GameLogic.RemoveBadShip(actuallyScreen); GameLogic.CrashShip(actuallyScreen); GameLogic.RemoveBadParticle(); break; case Constants.CHOOSING: hoverElement = CheckActuallyHover(); GameLogic.CreateParticle(); GameLogic.MoveMissiles(); GameLogic.RemoveBadMissile(); GameLogic.MoveParticles(actuallyScreen); GameLogic.RotateShip(chooseShip.ID); break; case Constants.TUTORIAL: GameLogic.TutorialProcessing(); break; case Constants.GAME: GameLogic.CreateParticle(); GameLogic.AddNewEnemy(); GameLogic.MoveMissiles(); GameLogic.MoveShips(actuallyScreen); GameLogic.MoveParticles(actuallyScreen); GameLogic.MoveParticleSources(); GameLogic.ControlTurboMode(); GameLogic.ControlExplosion(); GameLogic.UpdatePlayerDilation(); AI.PrepareAILogic(GameLogic.GetShips, GameLogic.GetPlayerShip()); GameLogic.RemoveBadMissile(); GameLogic.RemoveBadParticle(); break; } previousMouseState = Mouse.GetState(); previousKeyState = Keyboard.GetState(); } catch (Exception ex) { Logger.Error(ex, "Błąd podczas aktualizowania stanu rozgrywki"); } } /// <summary> /// Sprawdza, i ewentualnie wykonuje zmiane okna gry. /// </summary> static private void CheckChangeScreen() { switch (actuallyScreen) { case Constants.GAME: if (GameLogic.DestroyShips(actuallyScreen) == 0 || GameLogic.RemoveBadShip(actuallyScreen) == 0 || GameLogic.CrashShip(actuallyScreen) == 0 || GameLogic.DestroyPlayerOutOfRange(actuallyScreen) == 0) { nextScreenToChange = Constants.START; } break; case Constants.TUTORIAL: if (GameLogic.DestroyPlayerOutOfRange(actuallyScreen) == 0) { nextScreenToChange = Constants.START; GameLogic.mTutorialStep = Constants.TUTORIAL_INIT; } if (GameLogic.mTutorialStep > 2) { if (GameLogic.DestroyShips(actuallyScreen) == 0 || GameLogic.RemoveBadShip(actuallyScreen) == 0 || GameLogic.CrashShip(actuallyScreen) == 0) { nextScreenToChange = Constants.START; GameLogic.mTutorialStep = Constants.TUTORIAL_INIT; } } break; } if (nextScreenToChange != 0) { ChangeScreen(nextScreenToChange); nextScreenToChange = 0; } } /// <summary> /// Zawiera instrukcje dotyczące zmiany ekranów /// <param name="newScreen">ID nowego ekranu</param> /// </summary> static private void ChangeScreen(int newScreen) { switch (newScreen) { case Constants.START: if (actuallyScreen != Constants.OPTIONS && actuallyScreen != Constants.CREDITS) { UpdateHighscore(); chooseShip = null; GameLogic.CreateShips(newScreen); GameLogic.CreateGravityAreas(newScreen, GUI.mWidth, GUI.mHeight); GameLogic.ClearParticlesTable(Constants.PARTICLE_GRAVITY_AREA); } break; case Constants.CHOOSING: GameLogic.CreateShips(newScreen, chooseShip, GUI.mWidth, GUI.mHeight); chooseShip = GameLogic.GetShips[0]; break; case Constants.GAME: GameLogic.mActuallyPoints = 0; GameLogic.CreateShips(newScreen, chooseShip); GameLogic.CreateGravityAreas(newScreen, GUI.mWidth, GUI.mHeight); GameLogic.ClearParticlesTable(Constants.PARTICLE_GRAVITY_AREA); break; case Constants.OPTIONS: // instrukcje do opcji break; case Constants.TUTORIAL: GameLogic.mActuallyPoints = 0; GameLogic.CreateShips(newScreen, chooseShip); GameLogic.CreateGravityAreas(newScreen, GUI.mWidth, GUI.mHeight); GameLogic.ClearParticlesTable(Constants.PARTICLE_GRAVITY_AREA); break; } actuallyScreen = newScreen; } /// <summary> /// Sprawdza czy kursor jest nad jakimś polem wyboru /// </summary> /// <returns>Kod podświetlonego elementu</returns> static private int CheckActuallyHover() { Vector2 mouseVect = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); switch (actuallyScreen) { case Constants.START: int mainWidth = (int)GUI.CheckTextSize("menuFont90", "SpaceFight").X; if (CheckClick((GUI.mWidth - mainWidth) / 2 + 30, (GUI.mHeight - 150) / 2, GUI.CheckTextSize("menuFont42", "New game"), mouseVect)) { return 1; } else if (CheckClick((GUI.mWidth - mainWidth) / 2 + 60, (GUI.mHeight - 50) / 2, GUI.CheckTextSize("menuFont42", "Exit"), mouseVect)) { return 2; } else if (CheckClick((GUI.mWidth - mainWidth) / 2 + mainWidth - (int)GUI.CheckTextSize("menuFont42", "Options").X - 30, (GUI.mHeight - 150) / 2, GUI.CheckTextSize("menuFont42", "Options"), mouseVect)) { return 3; } else if (CheckClick((GUI.mWidth - mainWidth) / 2 + mainWidth - (int)GUI.CheckTextSize("menuFont42", "Credits").X - 60, (GUI.mHeight - 50) / 2, GUI.CheckTextSize("menuFont42", "Credits"), mouseVect)) { return 4; } break; case Constants.OPTIONS: // z powodu zmiennego tekstu string controlText, showingWarnText, gameModeText, soundsText, musicText; controlText = showingWarnText = gameModeText = soundsText = musicText = ""; switch (GameLogic.mControlType) { case Constants.CONTROL_KEYBOARD: controlText = "Keyboard"; break; case Constants.CONTROL_MOUSE: controlText = "Mouse"; break; case Constants.CONTROL_MIXED: controlText = "Mixed"; break; } showingWarnText = GameLogic.mShowingWarnings ? "Yes" : "No"; soundsText = GameLogic.mPlaySounds ? "Yes" : "No"; musicText = GameLogic.mPlayMusic ? "Yes" : "No"; switch (GameLogic.mGameMode) { case Constants.MODE_NORMAL: gameModeText = "Normal"; break; case Constants.MODE_HARD: gameModeText = "Hard"; break; case Constants.MODE_TIME: gameModeText = "Time fun"; break; } if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont72", "Back").X) / 2, (GUI.mHeight + 350) / 2, GUI.CheckTextSize("menuFont72", "Back"), mouseVect)) { return 6; } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Control: " + controlText).X) / 2, (GUI.mHeight - 250) / 2, GUI.CheckTextSize("menuFont42", "Control: " + controlText), mouseVect)) { return 1; } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Show warnings: " + showingWarnText).X) / 2, (GUI.mHeight - 150) / 2, GUI.CheckTextSize("menuFont42", "Show warnings: " + showingWarnText), mouseVect)) { return 2; } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Game mode: " + gameModeText).X) / 2, (GUI.mHeight - 50) / 2, GUI.CheckTextSize("menuFont42", "Game mode: " + gameModeText), mouseVect)) { return 3; } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Sounds: " + soundsText).X) / 2, (GUI.mHeight + 50) / 2, GUI.CheckTextSize("menuFont42", "Sounds: " + soundsText), mouseVect)) { return 4; } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Music: " + musicText).X) / 2, (GUI.mHeight + 150) / 2, GUI.CheckTextSize("menuFont42", "Music: " + musicText), mouseVect)) { return 5; } break; case Constants.CREDITS: if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont72", "Back").X) / 2, (GUI.mHeight + 450) / 2, GUI.CheckTextSize("menuFont72", "Back"), mouseVect)) { return 1; } break; case Constants.CHOOSING: int percentHeight = (int)(GUI.mHeight * 0.10); if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont72", "Let's go!").X) / 2, (int)(GUI.mHeight - percentHeight * 2.5), GUI.CheckTextSize("menuFont72", "Let's go!"), mouseVect)) { return 1; } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Tutorial game!").X) / 2, (int)(GUI.mHeight - percentHeight * 1.5), GUI.CheckTextSize("menuFont42", "Tutorial game!"), mouseVect)) { return 2; } break; } return 0; } /// <summary> /// Odpowiada za event myszy /// Rozpoznaje konkretne elementy na mapie i przekazuje wartość do warstwy logiki /// </summary> /// <returns>Zwraca listę intów, pierwszy element listy to kod eventu, drugi to dodatkowe dane</returns> static private List<int> HandleMouseEvent() { Vector2 playerGraphic; List<int> newInputList = new List<int>(); Vector2 mouseVect = new Vector2(Mouse.GetState().X, Mouse.GetState().Y); if (Mouse.GetState().LeftButton == ButtonState.Pressed && previousMouseState.LeftButton == ButtonState.Released) { Ship playerShip = null; switch (actuallyScreen) { case Constants.START: int mainWidth = (int)GUI.CheckTextSize("menuFont90", "SpaceFight").X; if (CheckClick((GUI.mWidth - mainWidth) / 2 + 30, (GUI.mHeight - 150) / 2, GUI.CheckTextSize("menuFont42", "New game"), mouseVect)) { nextScreenToChange = Constants.CHOOSING; newInputList.Add(0); } else if (CheckClick((GUI.mWidth - mainWidth) / 2 + 60, (GUI.mHeight - 50) / 2, GUI.CheckTextSize("menuFont42", "Exit"), mouseVect)) { MainGame.exitGame = true; } else if (CheckClick((GUI.mWidth - mainWidth) / 2 + mainWidth - (int)GUI.CheckTextSize("menuFont42", "Options").X - 30, (GUI.mHeight - 150) / 2, GUI.CheckTextSize("menuFont42", "Options"), mouseVect)) { nextScreenToChange = Constants.OPTIONS; newInputList.Add(0); } else if (CheckClick((GUI.mWidth - mainWidth) / 2 + mainWidth - (int)GUI.CheckTextSize("menuFont42", "Credits").X - 60, (GUI.mHeight - 50) / 2, GUI.CheckTextSize("menuFont42", "Credits"), mouseVect)) { nextScreenToChange = Constants.CREDITS; newInputList.Add(0); } break; case Constants.OPTIONS: // z powodu zmiennego tekstu string controlText, showingWarnText, gameModeText, soundsText, musicText; controlText = showingWarnText = gameModeText = soundsText = musicText = ""; switch (GameLogic.mControlType) { case Constants.CONTROL_KEYBOARD: controlText = "Keyboard"; break; case Constants.CONTROL_MOUSE: controlText = "Mouse"; break; case Constants.CONTROL_MIXED: controlText = "Mixed"; break; } showingWarnText = GameLogic.mShowingWarnings ? "Yes" : "No"; soundsText = GameLogic.mPlaySounds ? "Yes" : "No"; musicText = GameLogic.mPlayMusic ? "Yes" : "No"; switch (GameLogic.mGameMode) { case Constants.MODE_NORMAL: gameModeText = "Normal"; break; case Constants.MODE_HARD: gameModeText = "Hard"; break; case Constants.MODE_TIME: gameModeText = "Time fun"; break; } if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont72", "Back").X) / 2, (GUI.mHeight + 350) / 2, GUI.CheckTextSize("menuFont72", "Back"), mouseVect)) { nextScreenToChange = Constants.START; newInputList.Add(0); } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Control: " + controlText).X) / 2, (GUI.mHeight - 250) / 2, GUI.CheckTextSize("menuFont42", "Control: " + controlText), mouseVect)) { if (GameLogic.mControlType == Constants.CONTROL_KEYBOARD) { GameLogic.mControlType = Constants.CONTROL_MOUSE; } else if (GameLogic.mControlType == Constants.CONTROL_MOUSE) { GameLogic.mControlType = Constants.CONTROL_MIXED; } else if (GameLogic.mControlType == Constants.CONTROL_MIXED) { GameLogic.mControlType = Constants.CONTROL_KEYBOARD; } XmlTool.UpdateSettings("controlType", GameLogic.mControlType.ToString()); newInputList.Add(0); } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Show warnings: " + showingWarnText).X) / 2, (GUI.mHeight - 150) / 2, GUI.CheckTextSize("menuFont42", "Show warnings: " + showingWarnText), mouseVect)) { GameLogic.mShowingWarnings = !GameLogic.mShowingWarnings; XmlTool.UpdateSettings("showingWarnings", Convert.ToInt32(GameLogic.mShowingWarnings).ToString()); newInputList.Add(0); } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Game mode: " + gameModeText).X) / 2, (GUI.mHeight - 50) / 2, GUI.CheckTextSize("menuFont42", "Game mode: " + gameModeText), mouseVect)) { if (GameLogic.mGameMode == Constants.MODE_NORMAL) { GameLogic.mGameMode = Constants.MODE_HARD; GameLogic.mHighscore = GameLogic.gameModes[GameLogic.mGameMode].highscore; } else if (GameLogic.mGameMode == Constants.MODE_HARD) { GameLogic.mGameMode = Constants.MODE_TIME; } else if (GameLogic.mGameMode == Constants.MODE_TIME) { GameLogic.mGameMode = Constants.MODE_NORMAL; } XmlTool.UpdateSettings("gameMode", GameLogic.mGameMode.ToString()); newInputList.Add(0); } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Sounds: " + soundsText).X) / 2, (GUI.mHeight + 50) / 2, GUI.CheckTextSize("menuFont42", "Sounds: " + soundsText), mouseVect)) { GameLogic.mPlaySounds = !GameLogic.mPlaySounds; XmlTool.UpdateSettings("playSounds", Convert.ToInt32(GameLogic.mPlaySounds).ToString()); newInputList.Add(0); } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Music: " + musicText).X) / 2, (GUI.mHeight + 150) / 2, GUI.CheckTextSize("menuFont42", "Music: " + musicText), mouseVect)) { GameLogic.mPlayMusic = !GameLogic.mPlayMusic; XmlTool.UpdateSettings("playMusic", Convert.ToInt32(GameLogic.mPlayMusic).ToString()); newInputList.Add(0); } break; case Constants.CREDITS: if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont72", "Back").X) / 2, (GUI.mHeight + 450) / 2, GUI.CheckTextSize("menuFont72", "Back"), mouseVect)) { nextScreenToChange = Constants.START; newInputList.Add(0); } break; case Constants.CHOOSING: int percentHeight = (int)(GUI.mHeight * 0.10); foreach (Ship ship in GameLogic.GetShips) { playerGraphic = GUI.GetGraphicInfo(ship.name); // nie korzysta z funckji CheckClick, bo mija sie to z sensem if ((mouseVect.X >= ship.vector.X - playerGraphic.X / 2 && mouseVect.X <= ship.vector.X + playerGraphic.X / 2) && (mouseVect.Y >= ship.vector.Y - playerGraphic.Y / 2 && mouseVect.Y <= ship.vector.Y + playerGraphic.Y / 2)) { newInputList.Add(0); chooseShip = ship; } } if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont72", "Let's go!").X) / 2, (int)(GUI.mHeight - percentHeight * 2.5), GUI.CheckTextSize("menuFont72", "Let's go!"), mouseVect)) { nextScreenToChange = Constants.GAME; newInputList.Add(0); } else if (CheckClick((GUI.mWidth - (int)GUI.CheckTextSize("menuFont42", "Tutorial game!").X) / 2, (int)(GUI.mHeight - percentHeight * 1.5), GUI.CheckTextSize("menuFont42", "Tutorial game!"), mouseVect)) { nextScreenToChange = Constants.TUTORIAL; newInputList.Add(0); } break; case Constants.TUTORIAL: playerShip = GameLogic.GetPlayerShip(); playerGraphic = GUI.GetGraphicInfo(playerShip.name); // rozpoczęcie tutorialu if ((GameLogic.mControlType == Constants.CONTROL_MOUSE) && (GameLogic.mTutorialStep == 0)) { newInputList.Add(Constants.NEXT_STEP); } if ((GameLogic.mControlType == Constants.CONTROL_MOUSE) && (GameLogic.mTutorialStep > 2)) { // nie korzysta z funckji CheckClick, bo mija sie to z sensem if ((mouseVect.X >= playerShip.vector.X - playerGraphic.X / 2 && mouseVect.X <= playerShip.vector.X + playerGraphic.X / 2) && (mouseVect.Y >= playerShip.vector.Y - playerGraphic.Y / 2 && mouseVect.Y <= playerShip.vector.Y + playerGraphic.Y / 2)) { // miejsce dla eventu na statku } else { newInputList.Add(Constants.CREATE_MISSILE); } } break; case Constants.GAME: playerShip = GameLogic.GetPlayerShip(); playerGraphic = GUI.GetGraphicInfo(playerShip.name); if (GameLogic.mControlType == Constants.CONTROL_MOUSE) { // nie korzysta z funckji CheckClick, bo mija sie to z sensem if ((mouseVect.X >= playerShip.vector.X - playerGraphic.X / 2 && mouseVect.X <= playerShip.vector.X + playerGraphic.X / 2) && (mouseVect.Y >= playerShip.vector.Y - playerGraphic.Y / 2 && mouseVect.Y <= playerShip.vector.Y + playerGraphic.Y / 2)) { // miejsce dla eventu na statku } else { newInputList.Add(Constants.CREATE_MISSILE); } } break; } } else { if ((actuallyScreen == Constants.GAME || (actuallyScreen == Constants.TUTORIAL && GameLogic.mTutorialStep > 0)) && (GameLogic.mControlType == Constants.CONTROL_MIXED || GameLogic.mControlType == Constants.CONTROL_MOUSE)) { GameLogic.SetMouseInfo(mouseVect); newInputList.Add(Constants.MOVE_SHIP); } } if (Mouse.GetState().RightButton == ButtonState.Pressed && previousMouseState.RightButton == ButtonState.Released) { if (GameLogic.mControlType == Constants.CONTROL_MOUSE) { if (actuallyScreen == Constants.GAME) { newInputList.Add(Constants.TURBO_MODE); } if (actuallyScreen == Constants.TUTORIAL && GameLogic.mTutorialStep > 1) { newInputList.Add(Constants.TURBO_MODE); } } } return newInputList; } /// <summary> /// Odpowiada za eventy klawiatury /// </summary> /// <returns>Lista przechwyconych kodów</returns> static private List<int> HandleKeyboardEvent() { List<int> newInputList = new List<int>(); KeyboardState keyState = Keyboard.GetState(); if (actuallyScreen != Constants.START) { if (keyState.IsKeyDown(Keys.Escape) && previousKeyState.IsKeyUp(Keys.Escape)) { nextScreenToChange = Constants.START; newInputList.Add(0); } } if (actuallyScreen == Constants.GAME) { if (GameLogic.mControlType == Constants.CONTROL_KEYBOARD || GameLogic.mControlType == Constants.CONTROL_MIXED) { if (keyState.IsKeyDown(Keys.Space) && previousKeyState.IsKeyUp(Keys.Space)) { newInputList.Add(Constants.CREATE_MISSILE); } if (keyState.IsKeyDown(Keys.Z)) { newInputList.Add(Constants.TURBO_MODE); } } if (GameLogic.mControlType == Constants.CONTROL_KEYBOARD) { if (keyState.IsKeyDown(Keys.Left)) { newInputList.Add(Constants.LEFT); } if (keyState.IsKeyDown(Keys.Right)) { newInputList.Add(Constants.RIGHT); } if (keyState.IsKeyDown(Keys.Up)) { newInputList.Add(Constants.FORWARD); } if (keyState.IsKeyDown(Keys.X) && previousKeyState.IsKeyUp(Keys.X)) { newInputList.Add(Constants.RUSH); } if (keyState.IsKeyUp(Keys.Up) && previousKeyState.IsKeyDown(Keys.Up)) { newInputList.Add(Constants.FORWARD_ECHO); } } } else if (actuallyScreen == Constants.TUTORIAL) { if ((GameLogic.mControlType == Constants.CONTROL_KEYBOARD || GameLogic.mControlType == Constants.CONTROL_MIXED) && (keyState.IsKeyDown(Keys.Space) && previousKeyState.IsKeyUp(Keys.Space)) && (GameLogic.mTutorialStep == 0)) { newInputList.Add(Constants.NEXT_STEP); } if ((GameLogic.mControlType == Constants.CONTROL_KEYBOARD || GameLogic.mControlType == Constants.CONTROL_MIXED)) { if (keyState.IsKeyDown(Keys.Space) && previousKeyState.IsKeyUp(Keys.Space) && (GameLogic.mTutorialStep > 2)) { newInputList.Add(Constants.CREATE_MISSILE); } if (keyState.IsKeyDown(Keys.Z) && (GameLogic.mTutorialStep > 1)) { newInputList.Add(Constants.TURBO_MODE); } } if (GameLogic.mControlType == Constants.CONTROL_KEYBOARD && (GameLogic.mTutorialStep > Constants.TUTORIAL_INIT)) { if (keyState.IsKeyDown(Keys.Left)) { newInputList.Add(Constants.LEFT); } if (keyState.IsKeyDown(Keys.Right)) { newInputList.Add(Constants.RIGHT); } if (keyState.IsKeyDown(Keys.Up)) { newInputList.Add(Constants.FORWARD); } if (keyState.IsKeyDown(Keys.X) && previousKeyState.IsKeyUp(Keys.X)) { newInputList.Add(Constants.RUSH); } if (keyState.IsKeyUp(Keys.Up) && previousKeyState.IsKeyDown(Keys.Up)) { newInputList.Add(Constants.FORWARD_ECHO); } } } return newInputList; } /// <summary> /// Sprawdza, czy klikniecie miesci sie w polu /// </summary> /// <param name="x">Górny róg (x) pola</param> /// <param name="y">Górny róg (y) pola</param> /// <param name="dVect">Wektor z zakresem pola</param> /// <param name="mouse">Klikniecie</param> /// <returns>true - kliknięcie w pole, false - poza pole</returns> static private bool CheckClick(int x, int y, Vector2 dVect, Vector2 mouse) { if ((mouse.X >= x && mouse.X <= x + dVect.X) && (mouse.Y >= y && mouse.Y <= y + dVect.Y)) { return true; } return false; } /// <summary> /// Przekazuje dane z GUI /// Funkcja służy tylko do komunikacji między GameLogic, a GUI. /// </summary> /// <returns></returns> static public Vector2 TransferGraphicInfo(string name) { return GUI.GetGraphicInfo(name); } /// <summary> /// Aktualizuje odpowiednie highscore /// </summary> static private void UpdateHighscore() { if (GameLogic.mActuallyPoints > GameLogic.mHighscore) { GameLogic.mHighscore = GameLogic.mActuallyPoints; switch (GameLogic.mGameMode) { case Constants.MODE_NORMAL: XmlTool.UpdateSettings("highscoreNormal", GameLogic.mActuallyPoints.ToString()); break; case Constants.MODE_HARD: XmlTool.UpdateSettings("highscoreHard", GameLogic.mActuallyPoints.ToString()); break; case Constants.MODE_TIME: XmlTool.UpdateSettings("highscoreTime", GameLogic.mActuallyPoints.ToString()); break; } } } } }
49.817402
246
0.486359
88d8c7f49d448a4e1baea8547b30013ee48093f5
719
cs
C#
SwfLib/Tags/ControlTags/FileAttributesTag.cs
ZingBallyhoo/SwfLib
f8c887c63a9d5ee91ca1377a5c528590f3bc5cec
[ "MIT" ]
17
2015-07-15T07:22:26.000Z
2022-03-01T05:54:22.000Z
SwfLib/Tags/ControlTags/FileAttributesTag.cs
ZingBallyhoo/SwfLib
f8c887c63a9d5ee91ca1377a5c528590f3bc5cec
[ "MIT" ]
8
2017-11-27T21:38:43.000Z
2021-09-06T17:50:52.000Z
SwfLib/Tags/ControlTags/FileAttributesTag.cs
ZingBallyhoo/SwfLib
f8c887c63a9d5ee91ca1377a5c528590f3bc5cec
[ "MIT" ]
12
2015-07-28T11:00:04.000Z
2021-01-04T04:17:36.000Z
namespace SwfLib.Tags.ControlTags { public class FileAttributesTag : ControlBaseTag { public bool Reserved0; public bool UseDirectBlit; public bool UseGPU; public bool HasMetadata; public bool AllowAbc; public bool SuppressCrossDomainCaching; public bool SwfRelativeUrls; public bool UseNetwork; public uint Reserved; public override SwfTagType TagType { get { return SwfTagType.FileAttributes; } } public override TResult AcceptVistor<TArg, TResult>(ISwfTagVisitor<TArg, TResult> visitor, TArg arg) { return visitor.Visit(this, arg); } } }
23.193548
111
0.611961
b01a8f42a5c5a67dcdeea795b39ac6027400185a
7,580
py
Python
connectome/models/ebm.py
JanaGauss/Connectome
9b59aabfb4040201c72d7ff239b50bb47f092ad1
[ "MIT" ]
1
2022-03-22T15:58:31.000Z
2022-03-22T15:58:31.000Z
connectome/models/ebm.py
JanaGauss/Connectome
9b59aabfb4040201c72d7ff239b50bb47f092ad1
[ "MIT" ]
6
2022-03-16T16:20:14.000Z
2022-03-17T10:54:13.000Z
connectome/models/ebm.py
JanaGauss/Connectome
9b59aabfb4040201c72d7ff239b50bb47f092ad1
[ "MIT" ]
null
null
null
""" wrapper for the explainable boosting machine with integrated feature selection based on the mutual information """ import pandas as pd import numpy as np from sklearn.feature_selection import mutual_info_regression,\ mutual_info_classif from typing import Union from sklearn.datasets import make_classification, make_regression from interpret.glassbox import ExplainableBoostingRegressor, \ ExplainableBoostingClassifier from interpret import show import sys import pickle import os class EBMmi: """ Class that wraps the explainable boosting machine and performs feature selection before fitting the model based on the mutual information scores of the features with the target variable. The integrated feature selection step is necessary as the explainable boosting machine is computationally very costly especially in the case of high number of features. Examples: >>> import numpy as np >>> import pandas as pd >>> # create synthetic data >>> X, y = make_classification(n_informative=15) >>> X = pd.DataFrame( >>> X, >>> columns=["feature_" + str(i) >>> for i in range(X.shape[1])]) >>> X_regr, y_regr = make_regression(n_features=20, n_informative=15) >>> X_regr = pd.DataFrame( >>> X_regr, >>> columns=["feature_" + str(i) >>> for i in range(X_regr.shape[1])]) >>> >>> # initialize some models >>> ebm_class = EBMmi(X, y, classification=True) >>> ebm_regr = EBMmi(X_regr, y_regr, classification=False) >>> >>> # check the size >>> print(sys.getsizeof(ebm_class)*1e-6) >>> >>> # plot functions >>> ebm_class.plot_mi(n=5) >>> ebm_regr.plot_mi(n=5) """ def __init__(self, features: Union[np.ndarray, pd.DataFrame], target: np.ndarray, feature_names: list = None, classification: bool = True, fit_directly: bool = True, **kwargs ): if isinstance(features, pd.DataFrame): self.pddf = True self.feature_names = features.columns elif isinstance(features, np.ndarray): self.pddf = False if feature_names is None: raise ValueError("if using numpy arrays, feature names must " "be provided in a list") self.feature_names = feature_names self.features = features self.target = target self.classification = classification self.mi = mutual_info_classif(features, target) \ if classification \ else mutual_info_regression( features, target) self.mi_features = pd.DataFrame({ "features": self.feature_names, "mutual_information": self.mi }).sort_values( by="mutual_information", ascending=False) self.ebm = ExplainableBoostingClassifier() \ if self.classification \ else ExplainableBoostingRegressor() if fit_directly: self.fit(**kwargs) def fit(self, n_features: int = 650, return_model: bool = False): if n_features > len(self.feature_names): n_features = len(self.feature_names) self.get_selected_features(n_features) if return_model: return self.ebm.fit(self.x_mi, self.target) else: self.ebm = self.ebm.fit(self.x_mi, self.target) def get_selected_features(self, n: int = 650 ) -> Union[pd.DataFrame, np.ndarray]: self.sel_features = list(self.mi_features["features"].iloc[:n]) cols = [col for col in self.feature_names if col in self.sel_features] if not self.pddf: indices = np.array([i for i, f in enumerate(self.feature_names) if f in cols]) self.x_mi = self.features.loc[:, cols].copy() \ if self.pddf \ else self.features[:, indices].copy() return self.x_mi def get_sel_features_names(self) -> list: return self.sel_features def get_mutual_info(self) -> pd.DataFrame: return self.mi_features def predict(self, inputs: pd.DataFrame ) -> np.ndarray: if not isinstance(inputs, pd.DataFrame): raise ValueError("EBM needs a DataFrame as input") sel_cols = [col for col in self.feature_names if col in self.sel_features] input_data = inputs.loc[:, sel_cols].copy() return self.ebm.predict(input_data) def predict_proba(self, inputs) -> np.ndarray: if self.classification: return self.ebm.predict_proba(inputs)[:, 1] else: raise ValueError("predict_proba not available for regression") def plot_mi(self, n: int = 30): self.mi_features.iloc[:n, :].plot.bar( x="features", y="mutual_information") def explain_global(self): show(self.ebm.explain_global()) def explain_local(self, inputs: Union[np.ndarray, pd.DataFrame], target: np.ndarray = None ) -> None: if inputs.shape[1] > len(self.sel_features): # has to be adjusted to also handle np.ndarrays cols = [col for col in inputs.columns if col in self.sel_features] inputs = inputs.loc[:, cols] show(self.ebm.explain_local(inputs, target)) def get_contributions(self, inputs: Union[np.ndarray, pd.DataFrame] ) -> Union[np.ndarray, tuple]: if self.classification: res = self.ebm.predict_and_contrib(inputs) return res[0][:, 1], res[1] else: return self.ebm.predict_and_contrib(inputs) def save_model(self, name: str = "ebm_trained"): with open(name, "wb") as f: pickle.dump(self, f) if __name__ == "__main__": # create synthetic data X, y = make_classification(n_informative=15) X = pd.DataFrame( X, columns=["feature_" + str(i) for i in range(X.shape[1])]) X_regr, y_regr = make_regression(n_features=20, n_informative=15) X_regr = pd.DataFrame( X_regr, columns=["feature_" + str(i) for i in range(X_regr.shape[1])]) # initialize some models ebm_class = EBMmi(X, y, classification=True, fit_directly=True) ebm_regr = EBMmi(X_regr, y_regr, classification=False, fit_directly=True) # fit the models #ebm_class.fit() #ebm_regr.fit() # check the size print(sys.getsizeof(ebm_class)*1e-6) # plot functions ebm_class.plot_mi(n=5) ebm_regr.plot_mi(n=5) # predict functions pred_class = ebm_class.predict(X) print(pred_class) pred_regr = ebm_regr.predict(X_regr) print(pred_regr) # explain functions #ebm_class.explain_global() #ebm_regr.explain_global() ebm_class.save_model("ebm") # local explanations #ebm_class.explain_local(X, y) #ebm_regr.explain_local(X_regr, y_regr) with open("ebm", "rb") as input_file: ebm_class_2 = pickle.load(input_file) pred_class = ebm_class_2.predict(X) print(pred_class) os.remove("ebm")
32.532189
84
0.589314
20be4a1436d8e9d14c0d589ca4a3d96e6b579f94
1,941
py
Python
save_image.py
leafinity/instagram-crawler
f309821208a8334dcb93845cb9de39db5e912ce5
[ "MIT" ]
null
null
null
save_image.py
leafinity/instagram-crawler
f309821208a8334dcb93845cb9de39db5e912ce5
[ "MIT" ]
null
null
null
save_image.py
leafinity/instagram-crawler
f309821208a8334dcb93845cb9de39db5e912ce5
[ "MIT" ]
null
null
null
import os import argparse import json import requests from bs4 import BeautifulSoup FILE_PATH = './' def get_data_set(path): with open(path) as f: return json.loads(f.read()) def get_img_url_by_post_url(url): resp = requests.get(url) if resp.status_code != 200: return None soup = BeautifulSoup(resp.text, 'html.parser') for meta in soup.find_all('meta'): if meta.get('property') == 'og:image': return meta.get('content') def save_image(savepath, url): with open(savepath, 'wb') as handle: response = requests.get(url, stream=True) if not response.ok: return 'fail' for block in response.iter_content(1024): if not block: break handle.write(block) return 'success' def main(filepath, savedir): fail_posts = [] images = get_data_set(filepath) if not os.path.exists(savedir): os.makedirs(savedir) for idx, image in enumerate(images): filename = os.path.join(savedir, '%04d.jpg' % (idx)) status = save_image(filename, image['img_url']) if status == 'fail': image_url = get_img_url_by_post_url(image['key']) if not img_url: fail_posts.append(image) continue status = save_image(filename, image['img_url']) if status == fail: fail_posts.append(image) if fail_posts: with open('fail_posts.json','w') as f: f.write(json.dumps(fail_posts)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-f', '--filepath') parser.add_argument('-s', '--savedir') args = parser.parse_args() if args.filepath: filepath = args.filepath if args.savedir: savedir = args.savedir else: savedir = os.path.dirname(args.filepath) main(filepath, savedir)
25.207792
61
0.59866
b8d8237fdf04b1108c34e35a7480c4beac023005
7,414
dart
Dart
lib/app.dart
mono0926/flutter-animations
bfd3e34a6d57560b0bb2da475112a59334ca29dc
[ "MIT" ]
41
2019-03-03T06:58:17.000Z
2022-01-26T14:35:21.000Z
lib/app.dart
mono0926/flutter-animations
bfd3e34a6d57560b0bb2da475112a59334ca29dc
[ "MIT" ]
null
null
null
lib/app.dart
mono0926/flutter-animations
bfd3e34a6d57560b0bb2da475112a59334ca29dc
[ "MIT" ]
5
2019-12-27T21:03:15.000Z
2022-03-05T06:16:04.000Z
import 'package:animations_app/pages/custom/animated_builder_page.dart'; import 'package:animations_app/pages/custom/animated_switcher_page.dart'; import 'package:animations_app/pages/custom/animated_widget_page.dart'; import 'package:animations_app/pages/custom/animation_controller_set_state_enhanced2_page.dart'; import 'package:animations_app/pages/custom/animation_controller_set_state_enhanced_page.dart'; import 'package:animations_app/pages/custom/animation_controller_set_state_page.dart'; import 'package:animations_app/pages/custom/custom_page.dart'; import 'package:animations_app/pages/custom/implicitly_animated_widget_page.dart'; import 'package:animations_app/pages/flare/apple_lock_page.dart'; import 'package:animations_app/pages/flare/flare_page.dart'; import 'package:animations_app/pages/flight_search/flight_search_page.dart'; import 'package:animations_app/pages/home/home_page.dart'; import 'package:animations_app/pages/implicitly_animated/animated_align.dart'; import 'package:animations_app/pages/implicitly_animated/animated_container.dart'; import 'package:animations_app/pages/implicitly_animated/animated_cross_fade.dart'; import 'package:animations_app/pages/implicitly_animated/animated_default_text_style.dart'; import 'package:animations_app/pages/implicitly_animated/animated_icon.dart'; import 'package:animations_app/pages/implicitly_animated/animated_list.dart'; import 'package:animations_app/pages/implicitly_animated/animated_modal_barrier.dart'; import 'package:animations_app/pages/implicitly_animated/animated_opacity.dart'; import 'package:animations_app/pages/implicitly_animated/animated_padding.dart'; import 'package:animations_app/pages/implicitly_animated/animated_physical_model.dart'; import 'package:animations_app/pages/implicitly_animated/animated_positioned.dart'; import 'package:animations_app/pages/implicitly_animated/animated_positioned_directional.dart'; import 'package:animations_app/pages/implicitly_animated/animated_size_page.dart'; import 'package:animations_app/pages/implicitly_animated/animated_switcher_page.dart'; import 'package:animations_app/pages/implicitly_animated/animated_theme_page.dart'; import 'package:animations_app/pages/implicitly_animated/fade_in_image_page.dart'; import 'package:animations_app/pages/implicitly_animated/hero_page.dart'; import 'package:animations_app/pages/implicitly_animated/implicitly_animated_page.dart'; import 'package:animations_app/pages/transition/align_transition_page.dart'; import 'package:animations_app/pages/transition/decorated_box_transition_page.dart'; import 'package:animations_app/pages/transition/default_text_style_transition_page.dart'; import 'package:animations_app/pages/transition/fade_transition_page.dart'; import 'package:animations_app/pages/transition/positioned_transition_page.dart'; import 'package:animations_app/pages/transition/relative_positioned_transition_page.dart'; import 'package:animations_app/pages/transition/rotation_transition_page.dart'; import 'package:animations_app/pages/transition/scale_transition_page.dart'; import 'package:animations_app/pages/transition/size_transition_page.dart'; import 'package:animations_app/pages/transition/slide_transition_page.dart'; import 'package:animations_app/pages/transition/transition_page.dart'; import 'package:flutter/material.dart'; import 'package:mono_kit/mono_kit.dart'; final rootNavigatorKey = GlobalKey<NavigatorState>(); class App extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( navigatorKey: rootNavigatorKey, title: 'Animations', theme: lightTheme(), darkTheme: darkTheme(), home: HomePage(), routes: { // Animated ImplicitlyAnimatedPage.routeName: (_context) => ImplicitlyAnimatedPage(), AnimatedAlignPage.routeName: (_context) => AnimatedAlignPage(), AnimatedContainerPage.routeName: (_context) => AnimatedContainerPage(), AnimatedCrossFadePage.routeName: (_context) => AnimatedCrossFadePage(), AnimatedDefaultTextStylePage.routeName: (_context) => AnimatedDefaultTextStylePage(), AnimatedIconPage.routeName: (_context) => AnimatedIconPage(), AnimatedListPage.routeName: (_context) => AnimatedListPage(), AnimatedModalBarrierPage.routeName: (_context) => AnimatedModalBarrierPage(), AnimatedOpacityPage.routeName: (_context) => AnimatedOpacityPage(), AnimatedPaddingPage.routeName: (_context) => AnimatedPaddingPage(), AnimatedPhysicalModelPage.routeName: (_context) => AnimatedPhysicalModelPage(), AnimatedPositionedPage.routeName: (_context) => AnimatedPositionedPage(), AnimatedPositionedDirectionalPage.routeName: (_context) => AnimatedPositionedDirectionalPage(), AnimatedThemePage.routeName: (_context) => AnimatedThemePage(), AnimatedSwitcherPage.routeName: (_context) => AnimatedSwitcherPage(), AnimatedSizePage.routeName: (_context) => AnimatedSizePage(), HeroPage.routeName: (_context) => HeroPage(), FadeInImagePage.routeName: (_context) => FadeInImagePage(), // Transition TransitionPage.routeName: (_context) => TransitionPage(), SlideTransitionPage.routeName: (_context) => SlideTransitionPage(), ScaleTransitionPage.routeName: (_context) => ScaleTransitionPage(), RotationTransitionPage.routeName: (_context) => RotationTransitionPage(), SizeTransitionPage.routeName: (_context) => SizeTransitionPage(), FadeTransitionPage.routeName: (_context) => FadeTransitionPage(), PositionedTransitionPage.routeName: (_context) => PositionedTransitionPage(), RelativePositionedTransitionPage.routeName: (_context) => RelativePositionedTransitionPage(), DecoratedBoxTransitionPage.routeName: (_context) => DecoratedBoxTransitionPage(), AlignTransitionPage.routeName: (_context) => AlignTransitionPage(), DefaultTextStyleTransitionPage.routeName: (_context) => DefaultTextStyleTransitionPage(), // ここ配下に別テーマを適用させるためにMaterialAppを使ったが問題あり // - ナビゲーションで戻れない(とりあえずグローバルなrootNavigatorKeyで暫定対処) // - インスペクターがエラーになる FlightSearchPage.routeName: (_context) => MaterialApp( theme: ThemeData(primarySwatch: Colors.red), home: const FlightSearchPage(), ), CustomPage.routeName: (_context) => CustomPage(), AnimationControllerSetStatePage.routeName: (_context) => AnimationControllerSetStatePage(), AnimationControllerSetStateEnhancedPage.routeName: (_context) => AnimationControllerSetStateEnhancedPage(), AnimationControllerSetStateEnhanced2Page.routeName: (_context) => AnimationControllerSetStateEnhanced2Page(), AnimatedWidgetPage.routeName: (_context) => AnimatedWidgetPage(), AnimatedBuilderPage.routeName: (_context) => AnimatedBuilderPage(), AnimatedSwitcher2Page.routeName: (_context) => AnimatedSwitcher2Page(), ImplicitlyAnimatedWidgetPage.routeName: (_context) => ImplicitlyAnimatedWidgetPage(), FlarePage.routeName: (_context) => FlarePage(), AppleLockPage.routeName: (_context) => AppleLockPage(), }, ); } }
59.790323
96
0.771109
23a1f05457a14f414d569f6e00287de5c6aca356
851
js
JavaScript
src/material.test.js
DharmendraVinay/vue-material
26b84a7d676e4cca1d302876c92d00dfe9f3e289
[ "MIT" ]
5
2018-12-13T11:53:41.000Z
2018-12-13T12:16:32.000Z
src/material.test.js
DharmendraVinay/vue-material
26b84a7d676e4cca1d302876c92d00dfe9f3e289
[ "MIT" ]
6
2021-03-09T20:22:35.000Z
2022-02-26T18:53:10.000Z
src/material.test.js
DharmendraVinay/vue-material
26b84a7d676e4cca1d302876c92d00dfe9f3e289
[ "MIT" ]
2
2019-06-09T18:01:38.000Z
2019-10-06T14:49:02.000Z
import Vue from 'vue' import VueMaterial from './index' import mountTemplate from 'test/utils/mountTemplate' Vue.use(VueMaterial) const app = new Vue({ el: '#app', name: 'Root', render: mount => mount('div') }) test('should create vue material instance', async () => { expect(Boolean(Vue.material)).toBe(true) expect(Boolean(app.$material)).toBe(true) expect(Boolean(app.$material.theming)).toBe(true) expect(Boolean(app.$material.locale)).toBe(true) expect(app.$material.ripple).toBe(true) }) test('should have a default theme', async () => { expect(app.$material.theming.theme).toBe('default') }) test('should enable theme by default', async () => { expect(app.$material.theming.enabled).toBe(true) }) test('should not render meta colors by default', async () => { expect(app.$material.theming.metaColors).toBe(false) })
26.59375
62
0.698002
15bd39f23c665d553911422aaf514ecf985b8761
52
dart
Dart
lib/flutter_fcm.dart
wh120/flutter_fcm
0c839506e553c9e201ec2e08f384e52954d6b13d
[ "MIT" ]
8
2021-05-27T14:01:03.000Z
2022-03-22T06:38:02.000Z
lib/flutter_fcm.dart
wh120/flutter_fcm
0c839506e553c9e201ec2e08f384e52954d6b13d
[ "MIT" ]
1
2022-02-02T15:48:06.000Z
2022-03-27T21:53:38.000Z
lib/flutter_fcm.dart
wh120/flutter_fcm
0c839506e553c9e201ec2e08f384e52954d6b13d
[ "MIT" ]
2
2021-08-20T14:51:08.000Z
2022-03-22T06:37:54.000Z
library flutter_fcm; export 'Notification/FCM.dart';
26
31
0.826923
d3a3b0d8499fb5e00c93ee2ab0d5d13953633d20
276
css
CSS
apps/camera/style/loading-screen.css
carlosdp/gaia
18e2e8dc2d9ff19cd1210026367c14956d04eb0d
[ "Apache-2.0" ]
null
null
null
apps/camera/style/loading-screen.css
carlosdp/gaia
18e2e8dc2d9ff19cd1210026367c14956d04eb0d
[ "Apache-2.0" ]
null
null
null
apps/camera/style/loading-screen.css
carlosdp/gaia
18e2e8dc2d9ff19cd1210026367c14956d04eb0d
[ "Apache-2.0" ]
null
null
null
.loading-screen { display: flex; justify-content: center; align-items: center; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); opacity: 0; transition: opacity 300ms; } .loading-screen.visible { opacity: 1; }
16.235294
30
0.648551
0901eb1cb0e837249167b1f904c740f2341b7c1b
657
swift
Swift
iOS/Sources/Presentation/Extension/String+prettyPhoneNumber.swift
Walkhub/Walkhub
9bacb28d8314fbfdc663b5be5d065399bcbd3933
[ "MIT" ]
8
2021-12-31T15:22:42.000Z
2022-01-18T03:24:54.000Z
iOS/Sources/Presentation/Extension/String+prettyPhoneNumber.swift
Walkhub/Walkhub
9bacb28d8314fbfdc663b5be5d065399bcbd3933
[ "MIT" ]
104
2021-12-27T11:31:22.000Z
2022-03-31T13:45:24.000Z
iOS/Sources/Presentation/Extension/String+prettyPhoneNumber.swift
Walkhub/Walkhub
9bacb28d8314fbfdc663b5be5d065399bcbd3933
[ "MIT" ]
2
2022-01-24T12:35:18.000Z
2022-02-06T09:01:14.000Z
import Foundation extension String { func prettyPhoneNumber() -> String { let str = self.replacingOccurrences(of: " ", with: "") let arr = Array(str) if arr.count > 3 { if let regex = try? NSRegularExpression(pattern: "^010([0-9]{3,4})([0-9]{4})", options: .caseInsensitive) { let modString = regex.stringByReplacingMatches( in: str, options: [], range: NSRange(str.startIndex..., in: str), withTemplate: "010 $1 $2" ) return modString } } return self } }
31.285714
119
0.479452
073957da395a725996fc17404dba6ff2164025ee
432
css
CSS
public/libs/css/fix.css
seniorjean/2asoft_caraf
f9113af3f1947fddc903de684892abe1692e4a08
[ "MIT" ]
null
null
null
public/libs/css/fix.css
seniorjean/2asoft_caraf
f9113af3f1947fddc903de684892abe1692e4a08
[ "MIT" ]
null
null
null
public/libs/css/fix.css
seniorjean/2asoft_caraf
f9113af3f1947fddc903de684892abe1692e4a08
[ "MIT" ]
null
null
null
.swal2-backdrop-show{ z-index:999999 !important; } .form-group{ position:relative; } .form-group .controls small.text-danger{ position: absolute; } .form-control.is-invalid { border-color: #f44336; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .form-control.is-valid{ border-color: #4CAF50; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; }
18
40
0.645833
20ececa819ff03f4f08ae3c720d76026e691e1e4
384
cs
C#
cards/BLACK_TEMPLE/BT/Sim_BT_703t.cs
chi-rei-den/Silverfish
0420f58169db32e46df50362034699651cc62f2a
[ "MIT" ]
1
2020-09-04T08:44:54.000Z
2020-09-04T08:44:54.000Z
cards/BLACK_TEMPLE/BT/Sim_BT_703t.cs
chi-rei-den/Silverfish
0420f58169db32e46df50362034699651cc62f2a
[ "MIT" ]
2
2020-04-21T21:55:17.000Z
2020-04-21T22:02:36.000Z
cards/BLACK_TEMPLE/BT/Sim_BT_703t.cs
chi-rei-den/Silverfish
0420f58169db32e46df50362034699651cc62f2a
[ "MIT" ]
null
null
null
/* _BEGIN_TEMPLATE_ { "id": "BT_703t", "name": [ "被诅咒的阴影", "Cursed Shadow" ], "text": [ "<b>潜行</b>", "<b>Stealth</b>" ], "CardClass": "ROGUE", "type": "MINION", "cost": 7, "rarity": null, "set": "BLACK_TEMPLE", "collectible": null, "dbfId": 57498 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_BT_703t : SimTemplate { } }
13.714286
35
0.533854
57f15d3d98f19db10d00f591d461aa2f41805bc1
1,549
php
PHP
tests/Unit/VatTest.php
komantnick/atol-online
d321205ac95cd734504cb478de63a4418ac087f1
[ "MIT" ]
null
null
null
tests/Unit/VatTest.php
komantnick/atol-online
d321205ac95cd734504cb478de63a4418ac087f1
[ "MIT" ]
null
null
null
tests/Unit/VatTest.php
komantnick/atol-online
d321205ac95cd734504cb478de63a4418ac087f1
[ "MIT" ]
null
null
null
<?php /** * Copyright (c) Антон Аксенов (aka Anthony Axenov) * * This code is licensed under MIT. * Этот код распространяется по лицензии MIT. * https://github.com/anthonyaxenov/atol-online/blob/master/LICENSE */ use AtolOnline\{Constants\VatTypes, Entities\Vat}; /** * Class VatTest */ class VatTest extends BasicTestCase { /** * Тестирует каждый тип ставки НДС * * @dataProvider vatProvider * @param string $vat_type Тип НДС * @param float $sum Исходная сумма * @param float $expected_set Ожидаемый результат после установки суммы * @param float $expected_add Ожидаемый результат после прибавления 20р */ public function testVat(string $vat_type, float $sum, float $expected_set, float $expected_add) { $vat = new Vat($vat_type); $this->assertEquals(0, $vat->getFinalSum(), 'Test '.$vat_type.' | 1 step'); $vat->setSum($sum); $this->assertEquals($expected_set, $vat->getFinalSum(), 'Test '.$vat_type.' | 2 step'); $vat->addSum(20); $this->assertEquals($expected_add, $vat->getFinalSum(), 'Test '.$vat_type.' | 3 step'); $vat->addSum(-20); } /** * Провайдер данных для тестирования разных типов ставок НДС * * @return array */ public function vatProvider() { return [ [VatTypes::NONE, 100, 0, 0], [VatTypes::VAT0, 100, 0, 0], [VatTypes::VAT10, 100, 9.09, 10.9], [VatTypes::VAT18, 100, 15.25, 18.3], ]; } }
30.372549
99
0.597805
a9fda73265abffc0726b9948d7c1ef75d05e61ec
2,172
php
PHP
src/CLI/Command/ParseDirectoryCommand.php
d9beuD/bigdb-parser
1f0f36770b439be86544f7329a762f2ef1f0737b
[ "MIT" ]
null
null
null
src/CLI/Command/ParseDirectoryCommand.php
d9beuD/bigdb-parser
1f0f36770b439be86544f7329a762f2ef1f0737b
[ "MIT" ]
null
null
null
src/CLI/Command/ParseDirectoryCommand.php
d9beuD/bigdb-parser
1f0f36770b439be86544f7329a762f2ef1f0737b
[ "MIT" ]
null
null
null
<?php namespace BigdbParser\CLI\Command; use BigdbParser\FileSystem\Directory; use BigdbParser\FileSystem\FileParser; use Doctrine\ORM\EntityManager; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class ParseDirectoryCommand extends Command { protected static $defaultName = 'parse:directory'; protected EntityManager $entityManager; public function __construct(EntityManager $entityManager) { parent::__construct(); $this->entityManager = $entityManager; } protected function configure(): void { $this ->setDescription('Parse a directory.') ->setHelp('This command allows you to parse an entire directory recursively.') ->addArgument('path', InputArgument::OPTIONAL, 'Directory to parse') ->addOption( 'recursive', 'r', InputOption::VALUE_NONE, 'Should the directory be recursively parsed?' ); } protected function initialize(InputInterface $input, OutputInterface $output): void { if ($input->getArgument('path') === null) { $input->setArgument('path', '.'); } } protected function execute(InputInterface $input, OutputInterface $output): int { // Get the absolute directory path $path = new \SplFileInfo($input->getArgument('path')); $output->writeln("Input path: <info>{$path->getRealPath()}</info>"); $directory = new Directory( path: $path, output: $output, recursive: $input->getOption('recursive') ); $directory->parseDirectory(); foreach ($directory->getFiles() as $file) { $fileParser = new FileParser( file: $file, output: $output, entityManager: $this->entityManager ); $fileParser->run(); } return Command::SUCCESS; } }
31.028571
90
0.616022
e66995b041d12cf40e76f1158ecd670f35a7e185
5,762
h
C
thcrap_tasofro/src/pl.h
laenNoCode/thcrap
bda154bb57fa84ad6b88c96532ec2869d9e34d75
[ "Unlicense" ]
359
2015-01-01T17:17:17.000Z
2022-03-27T14:56:19.000Z
thcrap_tasofro/src/pl.h
laenNoCode/thcrap
bda154bb57fa84ad6b88c96532ec2869d9e34d75
[ "Unlicense" ]
145
2015-05-01T05:53:31.000Z
2022-03-31T13:32:53.000Z
thcrap_tasofro/src/pl.h
laenNoCode/thcrap
bda154bb57fa84ad6b88c96532ec2869d9e34d75
[ "Unlicense" ]
43
2015-06-09T11:30:11.000Z
2022-01-30T01:36:00.000Z
/** * Touhou Community Reliant Automatic Patcher * Tasogare Frontier support plugin * * ---- * * On-the-fly th145 pl patcher */ #pragma once #include <string> #include <vector> #include <list> #include <string.h> #include <jansson.h> namespace TasofroPl { enum LineType { EMPTY, LABEL, COMMAND, TEXT }; class ALine { protected: std::vector<std::string> fields; std::string comment; public: ALine(const std::vector<std::string>& fields, const std::string& comment = ""); virtual ~ALine() {} virtual LineType getType() const = 0; virtual std::string toString() const; virtual bool isStaffroll() const; std::string unquote(const std::string& in) const; std::string quote(const std::string& in) const; // Access/update the members in fields. virtual const std::string& get(int n) const; virtual void set(int n, const std::string& value); virtual std::string& operator[](int n); virtual size_t size() const; }; class Empty : public ALine { public: Empty(const std::vector<std::string>& fields, const std::string& comment = ""); ~Empty() {} LineType getType() const; }; class Label : public ALine { private: std::string label; public: Label(const std::vector<std::string>& fields, const std::string& comment = ""); ~Label() {} LineType getType() const; const std::string& get() const; void set(const std::string& label); }; class Command : public ALine { public: Command(const std::vector<std::string>& fields, const std::string& comment = ""); ~Command() {} LineType getType() const; bool isStaffroll() const; // Access/update the command name (index 0) or a parameter (index 1->size). const std::string& get(int n) const; void set(int n, const std::string& value); std::string& operator[](int n); size_t size() const; }; class AText : public ALine { public: enum Syntax { UNKNOWN, STORY, ENDINGS, WIN }; protected: // Patcher state std::string owner; std::string balloonName; std::string last_char; bool is_first_balloon; bool is_last_balloon; int cur_line; int nb_lines; virtual void _patchInit(std::list<ALine*>& file, std::list<ALine*>::iterator& file_it) = 0; // Functions used by the patcher virtual bool parseCommand(json_t *patch, int json_line_num); virtual void beginLine(std::list<ALine*>& file, const std::list<ALine*>::iterator& it) = 0; void patchLine(const char *text, std::list<ALine*>& file, const std::list<ALine*>::iterator& it); virtual void _patchLine(std::string& text, std::list<ALine*>& file, const std::list<ALine*>::iterator& it) = 0; virtual void endLine(); virtual void _patchExit(std::list<ALine*>& file, std::list<ALine*>::iterator& file_it); public: static AText *createText(const std::vector<std::string>& fields, const std::string& comment = "", Syntax syntax = UNKNOWN); AText(const std::vector<std::string>& fields, const std::string& comment = ""); ~AText() {} LineType getType() const; void patch(std::list<ALine*>& file, std::list<ALine*>::iterator& file_it, const std::string& balloonOwner, json_t *patch); }; class StoryText : public AText { protected: void _patchInit(std::list<ALine*>& file, std::list<ALine*>::iterator& file_it); bool parseCommand(json_t *patch, int json_line_num); void beginLine(std::list<ALine*>& file, const std::list<ALine*>::iterator& it); void _patchLine(std::string& text, std::list<ALine*>& file, const std::list<ALine*>::iterator& it); void _patchExit(std::list<ALine*>& file, std::list<ALine*>::iterator& file_it); public: StoryText(const std::vector<std::string>& fields, const std::string& comment = ""); ~StoryText() {} }; class Th155StoryText : public StoryText { protected: bool parseCommand(json_t *patch, int json_line_num); void _patchLine(std::string& text, std::list<ALine*>& file, const std::list<ALine*>::iterator& it); void _patchExit(std::list<ALine*>& file, std::list<ALine*>::iterator& file_it); public: Th155StoryText(const std::vector<std::string>& fields, const std::string& comment = ""); ~Th155StoryText() {} }; class Th155_110StoryText : public Th155StoryText { protected: void beginLine(std::list<ALine*>& file, const std::list<ALine*>::iterator& it); public: Th155_110StoryText(const std::vector<std::string>& fields, const std::string& comment = ""); ~Th155_110StoryText() {} }; class EndingText : public AText { private: bool is_staffroll; protected: void _patchInit(std::list<ALine*>& file, std::list<ALine*>::iterator& file_it); void beginLine(std::list<ALine*>& file, const std::list<ALine*>::iterator& it); void _patchLine(std::string& text, std::list<ALine*>& file, const std::list<ALine*>::iterator& it); void endLine(); void _patchExit(std::list<ALine*>& file, std::list<ALine*>::iterator& file_it); public: EndingText(const std::vector<std::string>& fields, const std::string& comment = ""); ~EndingText() {} }; class WinText : public AText { protected: void _patchInit(std::list<ALine*>& file, std::list<ALine*>::iterator& file_it); void beginLine(std::list<ALine*>& file, const std::list<ALine*>::iterator& it); void _patchLine(std::string& text, std::list<ALine*>& file, const std::list<ALine*>::iterator& it); public: WinText(const std::vector<std::string>& fields, const std::string& comment = ""); ~WinText() {} }; ALine* readLine(const char*& file, size_t& size); ALine* readLineStrictEol(const char*& file, size_t& size); void readField(const char *in, size_t& pos, size_t size, std::string& out); json_t *balloonNumberToLines(json_t *patch, size_t balloon_number); } int patch_pl(void *file_inout, size_t size_out, size_t size_in, const char*, json_t *patch);
28.384236
125
0.682055
cf339e2196737f159def7021442ba397050fb686
2,354
php
PHP
ParkMelaka_WebServices/users.php
ksk102/VehicleParkingSystem
9ccc0646f461963cba7601cabcf07e0fbb853046
[ "MIT" ]
null
null
null
ParkMelaka_WebServices/users.php
ksk102/VehicleParkingSystem
9ccc0646f461963cba7601cabcf07e0fbb853046
[ "MIT" ]
null
null
null
ParkMelaka_WebServices/users.php
ksk102/VehicleParkingSystem
9ccc0646f461963cba7601cabcf07e0fbb853046
[ "MIT" ]
null
null
null
<?php /** * Created by PhpStorm. * User: kskoh * Date: 2/9/18 * Time: 4:28 PM */ class users { //Database connection link private $conn; //Class constructor function __construct(){ //Getting the DbConnect.php file require_once __DIR__ . '/db_connect.php'; //Creating a DbConnect object to connect to the database $db = new db_connect(); //Initializing our connection link of this class //by calling the method connect of DbConnect class $this->conn = $db->connect(); } /* * The read operation * When this method is called it is returning the existing record of the database */ function getUserPassword($user_email, $user_password){ $stmt = $this->conn->prepare("SELECT id FROM users WHERE user_email=? AND user_password=?;"); $user_password = md5($user_password); $stmt->bind_param("ss",$user_email, $user_password); $stmt->execute(); $result = $stmt->get_result(); $stmt->close(); list($id) = $result->fetch_row(); return $id; } function getUserDetail($user_id){ $stmt = $this->conn->prepare("SELECT id, user_email, user_name, user_balance, car_plate_number FROM users WHERE id=?;"); $stmt->bind_param("s",$user_id); $stmt->execute(); $result = $stmt->get_result(); $stmt->close(); $user = array(); list($user['id'], $user['email'], $user['user_name'], $user['user_balance'], $user['car_number']) = $result->fetch_row(); return $user; } function checkEmailExists($email){ $stmt = $this->conn->prepare("SELECT COUNT(1) FROM users WHERE user_email = ?;"); $stmt->bind_param("s", $email); $stmt->execute(); $result = $stmt->get_result(); $stmt->close(); list($exists) = $result->fetch_row(); return $exists; } function createUser($name, $email, $password, $carPlate){ $stmt = $this->conn->prepare("INSERT INTO users (user_email, user_password, user_name, user_balance, car_plate_number) VALUES (?, ?, ?, 0.00, ?);"); $password = md5($password); $stmt->bind_param("ssss", $email, $password, $name, $carPlate); if($stmt->execute()){ return "1"; } return "0"; } }
27.372093
156
0.579439
afedef63bdca456b6bd88fbfb27776340d926f84
1,333
py
Python
testing.py
saddhu1005/BigMartsSalesPrediction
8d6e977b0730684e571869175153d632a69773e7
[ "MIT" ]
1
2020-01-24T16:20:37.000Z
2020-01-24T16:20:37.000Z
testing.py
saddhu1005/BigMartsSalesPrediction
8d6e977b0730684e571869175153d632a69773e7
[ "MIT" ]
1
2019-10-12T13:59:40.000Z
2019-10-12T13:59:40.000Z
testing.py
saddhu1005/BigMartsSalesPrediction
8d6e977b0730684e571869175153d632a69773e7
[ "MIT" ]
null
null
null
######################################## # Running the model on test dataset and saving the predictions import numpy as np import matplotlib.pyplot as mp import pandas as pd from sklearn.externals import joblib # opening the test databases # train_df = pd.read_csv('data/train_data_modified.csv') test_df = pd.read_csv('data/test_data_modified.csv') # Creating the test set X_test = test_df.drop(['Item_Identifier', 'Outlet_Identifier'], axis=1) # Function to predict and save predictions of different regressors def testModel(filename): # Load the saved Model regressor = joblib.load(str("models/"+filename+".sav")) # Predict the results y_pred = regressor.predict(X_test) # Formulate and Export rhe result result = pd.DataFrame({ 'Item_Identifier': test_df['Item_Identifier'], 'Outlet_Identifier': test_df['Outlet_Identifier'], 'Item_Outlet_Sales': y_pred}, columns=['Item_Identifier', 'Outlet_Identifier', 'Item_Outlet_Sales']) result.to_csv(str('data/'+filename+'_result.csv'), index=False) print(filename, ' Model run successfully on test set and predictions are saved') testModel('linear_regressor') testModel('decision_tree_regressor') testModel('random_forest_regressor') testModel('svm_regressor') testModel('gradient_boost_regressor')
34.179487
84
0.715679
45cdfcd90cef99cbb34e23c31e32ba97e02d8a32
239
swift
Swift
TokenDWalletTemplate/Sources/Controllers/Managers/KeychainManager/KeychainCodableAccountsV1.swift
iuriivolochai/ios-app
aa5799420f8a036ce42806bc7481ec6a4307413d
[ "Apache-2.0" ]
25
2019-05-18T11:28:15.000Z
2020-10-01T18:44:44.000Z
TokenDWalletTemplate/Sources/Controllers/Managers/KeychainManager/KeychainCodableAccountsV1.swift
iuriivolochai/ios-app
aa5799420f8a036ce42806bc7481ec6a4307413d
[ "Apache-2.0" ]
null
null
null
TokenDWalletTemplate/Sources/Controllers/Managers/KeychainManager/KeychainCodableAccountsV1.swift
iuriivolochai/ios-app
aa5799420f8a036ce42806bc7481ec6a4307413d
[ "Apache-2.0" ]
9
2019-04-30T08:34:51.000Z
2020-10-01T18:44:49.000Z
import Foundation class KeychainCodableAccountsV1: Codable { // MARK: - Public properties var accounts: [String] // emails // MARK: - init(accounts: [String]) { self.accounts = accounts } }
15.933333
42
0.577406
e26f94f7eda6ba619fc1969489ec21db43d182a5
2,186
js
JavaScript
examples/top-list/common/read-models/index.js
kilimondjaro/resolve
3633be2272eccf31908bef28c85614dce0c19c32
[ "MIT" ]
null
null
null
examples/top-list/common/read-models/index.js
kilimondjaro/resolve
3633be2272eccf31908bef28c85614dce0c19c32
[ "MIT" ]
null
null
null
examples/top-list/common/read-models/index.js
kilimondjaro/resolve
3633be2272eccf31908bef28c85614dce0c19c32
[ "MIT" ]
null
null
null
export default [ { name: 'Rating', projection: { Init: async store => { await store.defineStorage('Rating', [ { name: 'id', type: 'string', index: 'primary' }, { name: 'rating', type: 'number', index: 'secondary' }, { name: 'name', type: 'string' }, { name: 'votes', type: 'json' } ]) }, ItemAppended: async (store, { payload: { id, name } }) => { await store.insert('Rating', { id, name, rating: 0, votes: {} }) }, RatingIncreased: async (store, { payload: { id, userId } }) => { if ( (await store.count('Rating', { id, [`votes.${userId}`]: true })) > 0 ) { return } await store.update( 'Rating', { id }, { $inc: { rating: 1 }, $set: { [`votes.${userId}`]: true } } ) }, RatingDecreased: async (store, { payload: { id, userId } }) => { if ( (await store.count('Rating', { id, [`votes.${userId}`]: true })) < 1 ) { return } await store.update( 'Rating', { id }, { $inc: { rating: -1 }, $unset: { [`votes.${userId}`]: true } } ) } }, resolvers: { TopRating: async (store, args) => { const pageNumber = Math.max( Number.isInteger(args && +args.page) ? +args.page : 0, 0 ) const pageLength = Math.max( Number.isInteger(args && +args.limit) ? +args.limit : 10, 0 ) const skipItems = pageNumber * pageLength return await store.find( 'Rating', {}, { id: 1, rating: 1, name: 1 }, { rating: -1 }, skipItems, pageLength ) }, PagesCount: async (store, args) => { const pageLength = Math.max( Number.isInteger(args && +args.limit) ? +args.limit : 10, 0 ) const count = await store.count('Rating', {}) return count > 0 ? Math.floor((count - 1) / pageLength) + 1 : 0 } } } ]
25.418605
78
0.429094
1a5de1c0e4e9bb66f97b54812e94c92fe0c95dfb
623
cs
C#
src/MicaWPF/Enums.cs
Simnico99/MicaWPF
ee85703ca66b7e33a00bc1a34104ed46e2a9329c
[ "MIT" ]
14
2021-11-08T08:59:39.000Z
2022-03-31T20:33:38.000Z
src/MicaWPF/Enums.cs
Simnico99/MicaWPF
ee85703ca66b7e33a00bc1a34104ed46e2a9329c
[ "MIT" ]
5
2021-11-18T15:19:40.000Z
2022-01-31T18:22:59.000Z
src/MicaWPF/Enums.cs
Simnico99/MicaWPF
ee85703ca66b7e33a00bc1a34104ed46e2a9329c
[ "MIT" ]
null
null
null
namespace MicaWPF; public enum WindowsTheme { Light, Dark, Auto } public enum OsVersion { WindowsOld, Windows10, Windows11Before22523, // Before 22523 Windows11After22523 // After 22523 } public enum BackdropType { None = 1, Mica = 2, Acrylic = 3, Tabbed = 4 } public enum AccentBrushType { Primary, Secondary, Tertiary, Quaternary } public enum TitleBarType { Win32, WinUI } [Flags] internal enum Facility { Null, Rpc, Dispatch, Storage, Itf, Win32 = 7, Windows, Control = 10, Ese = 3678, WinCodec = 2200 }
11.537037
41
0.606742
86f97a27ad3da2821c0519156b081a63a2f420b0
1,335
kt
Kotlin
monitoring/src/main/java/ru/flowernetes/monitoring/domain/usecase/GetTaskStatusInfoUseCaseImpl.kt
b1nd/flowernetes
8eef7e3324642fa4b26a69be69525d79a4873ea4
[ "MIT" ]
3
2020-04-02T20:09:26.000Z
2020-05-27T19:38:34.000Z
monitoring/src/main/java/ru/flowernetes/monitoring/domain/usecase/GetTaskStatusInfoUseCaseImpl.kt
b1nd/flowernetes
8eef7e3324642fa4b26a69be69525d79a4873ea4
[ "MIT" ]
null
null
null
monitoring/src/main/java/ru/flowernetes/monitoring/domain/usecase/GetTaskStatusInfoUseCaseImpl.kt
b1nd/flowernetes
8eef7e3324642fa4b26a69be69525d79a4873ea4
[ "MIT" ]
1
2021-02-27T21:09:56.000Z
2021-02-27T21:09:56.000Z
package ru.flowernetes.monitoring.domain.usecase import org.springframework.stereotype.Component import ru.flowernetes.entity.monitoring.TaskStatusInfo import ru.flowernetes.entity.task.Task import ru.flowernetes.entity.task.TaskStatus import ru.flowernetes.monitoring.api.domain.usecase.GetTaskStatusInfoFromWorkloadUseCase import ru.flowernetes.monitoring.api.domain.usecase.GetTaskStatusInfoUseCase import ru.flowernetes.workload.api.domain.usecase.GetTaskLastWorkloadUseCase @Component class GetTaskStatusInfoUseCaseImpl( private val getTaskLastWorkloadUseCase: GetTaskLastWorkloadUseCase, private val getTaskStatusInfoFromWorkloadUseCase: GetTaskStatusInfoFromWorkloadUseCase ) : GetTaskStatusInfoUseCase { override fun exec(task: Task): TaskStatusInfo { val lastWorkload = getTaskLastWorkloadUseCase.exec(task) ?: return if (task.scheduled) { task.toTaskStatusInfo(TaskStatus.WAITING) } else { task.toTaskStatusInfo(TaskStatus.INACTIVE) } return getTaskStatusInfoFromWorkloadUseCase.exec(lastWorkload) } private fun Task.toTaskStatusInfo(taskStatus: TaskStatus): TaskStatusInfo { return TaskStatusInfo( id, taskStatus = taskStatus, lastTransitionTime = System.currentTimeMillis() ) } }
39.264706
88
0.769288
6d8890720cdea33e98880ed948195abde1e01cd9
1,470
h
C
mdct.h
codefoco/Tremor
276780f298ec64216ae91031a3043f984331e1d4
[ "BSD-3-Clause" ]
3,459
2015-01-07T14:07:09.000Z
2022-03-25T03:51:10.000Z
mdct.h
codefoco/Tremor
276780f298ec64216ae91031a3043f984331e1d4
[ "BSD-3-Clause" ]
1,095
2016-04-10T18:15:33.000Z
2022-03-31T18:21:20.000Z
mdct.h
codefoco/Tremor
276780f298ec64216ae91031a3043f984331e1d4
[ "BSD-3-Clause" ]
549
2015-01-07T14:07:15.000Z
2022-01-07T16:13:05.000Z
/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis 'TREMOR' CODEC SOURCE CODE. * * * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis 'TREMOR' SOURCE CODE IS (C) COPYRIGHT 1994-2002 * * BY THE Xiph.Org FOUNDATION http://www.xiph.org/ * * * ******************************************************************** function: modified discrete cosine transform prototypes ********************************************************************/ #ifndef _OGG_mdct_H_ #define _OGG_mdct_H_ #include "ivorbiscodec.h" #include "misc.h" #define DATA_TYPE ogg_int32_t #define REG_TYPE register ogg_int32_t #ifdef _LOW_ACCURACY_ #define cPI3_8 (0x0062) #define cPI2_8 (0x00b5) #define cPI1_8 (0x00ed) #else #define cPI3_8 (0x30fbc54d) #define cPI2_8 (0x5a82799a) #define cPI1_8 (0x7641af3d) #endif extern void mdct_forward(int n, DATA_TYPE *in, DATA_TYPE *out); extern void mdct_backward(int n, DATA_TYPE *in, DATA_TYPE *out); #endif
27.735849
70
0.485034
be112869d3f68708a0360022af07d9f1e2ad741d
54
ts
TypeScript
js/duotone/cid-briefcase-arrow-right.d.ts
reesretuta/dropshipping-icons
c4b4f40959b1e44abaacd86981b9a896b121f419
[ "CC-BY-4.0", "MIT" ]
null
null
null
js/duotone/cid-briefcase-arrow-right.d.ts
reesretuta/dropshipping-icons
c4b4f40959b1e44abaacd86981b9a896b121f419
[ "CC-BY-4.0", "MIT" ]
null
null
null
js/duotone/cid-briefcase-arrow-right.d.ts
reesretuta/dropshipping-icons
c4b4f40959b1e44abaacd86981b9a896b121f419
[ "CC-BY-4.0", "MIT" ]
null
null
null
export declare const cidBriefcaseArrowRight: string[];
54
54
0.851852
da433af5f14e7657d8076c1cca2b482763012836
1,326
php
PHP
app/Observers/Rydecoin/RydecoinPackageObserver.php
Schneidershades/maz-delivery-backend
1a06e85c76e9b337a170d240c937e714234d3fa8
[ "MIT" ]
null
null
null
app/Observers/Rydecoin/RydecoinPackageObserver.php
Schneidershades/maz-delivery-backend
1a06e85c76e9b337a170d240c937e714234d3fa8
[ "MIT" ]
null
null
null
app/Observers/Rydecoin/RydecoinPackageObserver.php
Schneidershades/maz-delivery-backend
1a06e85c76e9b337a170d240c937e714234d3fa8
[ "MIT" ]
null
null
null
<?php namespace App\Observers\Rydecoin; use App\Models\RydecoinPackage; class RydecoinPackageObserver { /** * Handle the RydecoinPackage "created" event. * * @param \App\Models\RydecoinPackage $rydecoinPackage * @return void */ public function created(RydecoinPackage $rydecoinPackage) { // } /** * Handle the RydecoinPackage "updated" event. * * @param \App\Models\RydecoinPackage $rydecoinPackage * @return void */ public function updated(RydecoinPackage $rydecoinPackage) { // } /** * Handle the RydecoinPackage "deleted" event. * * @param \App\Models\RydecoinPackage $rydecoinPackage * @return void */ public function deleted(RydecoinPackage $rydecoinPackage) { // } /** * Handle the RydecoinPackage "restored" event. * * @param \App\Models\RydecoinPackage $rydecoinPackage * @return void */ public function restored(RydecoinPackage $rydecoinPackage) { // } /** * Handle the RydecoinPackage "force deleted" event. * * @param \App\Models\RydecoinPackage $rydecoinPackage * @return void */ public function forceDeleted(RydecoinPackage $rydecoinPackage) { // } }
20.71875
66
0.606335
a9fdc4bc90d0e5fe4480a7d7e77cfe1c8e28b222
8,153
sql
SQL
backend/sql/generated/insert_data_small.sql
LaZyLinh/team-flex-ICBC
99b962f24aee3758d4cc7cab7936765de818ba60
[ "BSD-2-Clause" ]
null
null
null
backend/sql/generated/insert_data_small.sql
LaZyLinh/team-flex-ICBC
99b962f24aee3758d4cc7cab7936765de818ba60
[ "BSD-2-Clause" ]
null
null
null
backend/sql/generated/insert_data_small.sql
LaZyLinh/team-flex-ICBC
99b962f24aee3758d4cc7cab7936765de818ba60
[ "BSD-2-Clause" ]
null
null
null
-- Features INSERT INTO feature VALUES (1, 'TV'); INSERT INTO feature VALUES (2, 'Private'); INSERT INTO feature VALUES (3, 'Conference Phone'); -- Employees -- INSERT INTO user VALUES (1, 'CLEFAIRYC.3', '[email protected]', 'Charizard', 'Clefairy', 'IT', 1); -- INSERT INTO user VALUES (2, 'DROWZEEM.4', '[email protected]', 'Mankey', 'Drowzee', 'IT', 1); -- INSERT INTO user VALUES (3, 'GENGARD.6', '[email protected]', 'Dugtrio', 'Gengar', 'Finance', 1); -- INSERT INTO user VALUES (4, 'BELLSPROUTD.8', '[email protected]', 'Dragonair', 'Bellsprout', 'Marketing', 1); -- INSERT INTO user VALUES (5, 'CHARMELEONP.6', '[email protected]', 'Primeape', 'Charmeleon', 'Customer Service', 1); -- INSERT INTO user VALUES (6, 'SANDSLASHM.6', '[email protected]', 'Moltres', 'Sandslash', 'HR', 1); -- INSERT INTO user VALUES (7, 'MCSLOWBROG.1', '[email protected]', 'Gastly', 'McSlowbro', 'HR', 1); -- INSERT INTO user VALUES (8, 'SQUIRTLES.2', '[email protected]', 'Shellder', 'Squirtle', 'Customer Service', 1); -- INSERT INTO user VALUES (9, 'NIDORINOM.2', '[email protected]', 'Mankey', 'Nidorino', 'Finance', 1); -- INSERT INTO user VALUES (10, 'GOLDEENC.0', '[email protected]', 'Cloyster', 'Goldeen', 'Finance', 1); -- Floors and Workspaces INSERT INTO floor VALUES (1, 1, 'Vancouver Building 1', 'Vancouver', '1', NULL); INSERT INTO workspace VALUES ('1V1-001', '1V1-001', 1, 1); INSERT INTO workspacefeature VALUES ('1V1-001', 1); INSERT INTO workspace VALUES ('1V1-002', '1V1-002', 2, 1); INSERT INTO workspacefeature VALUES ('1V1-002', 1); INSERT INTO workspacefeature VALUES ('1V1-002', 2); INSERT INTO workspace VALUES ('1V1-003', '1V1-003', 3, 1); INSERT INTO workspacefeature VALUES ('1V1-003', 1); INSERT INTO workspacefeature VALUES ('1V1-003', 3); INSERT INTO floor VALUES (2, 2, 'Vancouver Building 1', 'Vancouver', '1', NULL); INSERT INTO workspace VALUES ('1V2-001', '1V2-001', 4, 2); INSERT INTO workspacefeature VALUES ('1V2-001', 1); INSERT INTO workspace VALUES ('1V2-002', '1V2-002', 5, 2); INSERT INTO workspacefeature VALUES ('1V2-002', 1); INSERT INTO workspacefeature VALUES ('1V2-002', 2); INSERT INTO workspace VALUES ('1V2-003', '1V2-003', 6, 2); INSERT INTO workspacefeature VALUES ('1V2-003', 1); INSERT INTO workspacefeature VALUES ('1V2-003', 3); INSERT INTO floor VALUES (3, 1, 'North Vancouver Building 1', 'North Vancouver', '1', NULL); INSERT INTO workspace VALUES ('1NV1-001', '1NV1-001', 7, 3); INSERT INTO workspacefeature VALUES ('1NV1-001', 1); INSERT INTO workspace VALUES ('1NV1-002', '1NV1-002', 8, 3); INSERT INTO workspacefeature VALUES ('1NV1-002', 1); INSERT INTO workspacefeature VALUES ('1NV1-002', 2); INSERT INTO workspace VALUES ('1NV1-003', '1NV1-003', 9, 3); INSERT INTO workspacefeature VALUES ('1NV1-003', 1); INSERT INTO workspacefeature VALUES ('1NV1-003', 3); INSERT INTO floor VALUES (4, 2, 'North Vancouver Building 1', 'North Vancouver', '1', NULL); INSERT INTO workspace VALUES ('1NV2-001', '1NV2-001', 10, 4); INSERT INTO workspacefeature VALUES ('1NV2-001', 1); INSERT INTO workspace VALUES ('1NV2-002', '1NV2-002', NULL, 4); INSERT INTO workspacefeature VALUES ('1NV2-002', 1); INSERT INTO workspacefeature VALUES ('1NV2-002', 2); INSERT INTO workspace VALUES ('1NV2-003', '1NV2-003', NULL, 4); INSERT INTO workspacefeature VALUES ('1NV2-003', 1); INSERT INTO workspacefeature VALUES ('1NV2-003', 3); INSERT INTO floor VALUES (5, 1, 'West Vancouver Building 1', 'West Vancouver', '1', NULL); INSERT INTO workspace VALUES ('1WV1-001', '1WV1-001', NULL, 5); INSERT INTO workspacefeature VALUES ('1WV1-001', 1); INSERT INTO workspace VALUES ('1WV1-002', '1WV1-002', NULL, 5); INSERT INTO workspacefeature VALUES ('1WV1-002', 1); INSERT INTO workspacefeature VALUES ('1WV1-002', 2); INSERT INTO workspace VALUES ('1WV1-003', '1WV1-003', NULL, 5); INSERT INTO workspacefeature VALUES ('1WV1-003', 1); INSERT INTO workspacefeature VALUES ('1WV1-003', 3); INSERT INTO floor VALUES (6, 2, 'West Vancouver Building 1', 'West Vancouver', '1', NULL); INSERT INTO workspace VALUES ('1WV2-001', '1WV2-001', NULL, 6); INSERT INTO workspacefeature VALUES ('1WV2-001', 1); INSERT INTO workspace VALUES ('1WV2-002', '1WV2-002', NULL, 6); INSERT INTO workspacefeature VALUES ('1WV2-002', 1); INSERT INTO workspacefeature VALUES ('1WV2-002', 2); INSERT INTO workspace VALUES ('1WV2-003', '1WV2-003', NULL, 6); INSERT INTO workspacefeature VALUES ('1WV2-003', 1); INSERT INTO workspacefeature VALUES ('1WV2-003', 3); -- Availabilities and Bookings INSERT INTO availability VALUES (1, '2020-03-28', '2020-03-31', '1V1-002', 'Study the past... if you would divine the future.'); INSERT INTO booking VALUES (1, 1, '2020-03-28', '2020-03-29', 1, 1, '1V1-002'); INSERT INTO availability VALUES (2, '2020-03-29', '2020-04-01', '1V1-003', 'Peace comes from within. Do not seek it without.'); INSERT INTO booking VALUES (1, 2, '2020-03-29', '2020-03-30', 2, 2, '1V1-003'); INSERT INTO availability VALUES (3, '2020-03-30', '2020-04-02', '1V2-001', NULL); INSERT INTO booking VALUES (1, 3, '2020-03-30', '2020-03-31', 3, 3, '1V2-001'); INSERT INTO availability VALUES (4, '2020-03-31', '2020-04-03', '1V2-002', NULL); INSERT INTO booking VALUES (1, 4, '2020-03-31', '2020-04-01', 4, 4, '1V2-002'); INSERT INTO availability VALUES (5, '2020-04-01', '2020-04-04', '1V2-003', NULL); INSERT INTO booking VALUES (1, 5, '2020-04-01', '2020-04-03', 5, 5, '1V2-003'); INSERT INTO availability VALUES (6, '2020-04-02', '2020-04-05', '1NV1-001', NULL); INSERT INTO booking VALUES (1, 6, '2020-04-02', '2020-04-02', 6, 6, '1NV1-001'); INSERT INTO availability VALUES (7, '2020-04-03', '2020-04-06', '1NV1-002', NULL); INSERT INTO booking VALUES (1, 7, '2020-04-03', '2020-04-05', 7, 7, '1NV1-002'); INSERT INTO availability VALUES (8, '2020-04-04', '2020-04-07', '1NV1-003', 'Trouble is only opportunity in work clothes.'); INSERT INTO booking VALUES (1, 8, '2020-04-04', '2020-04-04', 8, 8, '1NV1-003'); INSERT INTO availability VALUES (9, '2020-04-05', '2020-04-08', '1NV2-001', NULL); INSERT INTO booking VALUES (1, 9, '2020-04-05', '2020-04-05', 9, 9, '1NV2-001'); INSERT INTO availability VALUES (10, '2020-04-06', '2020-04-09', '1NV2-002', 'Genius is one percent inspiration and ninety-nine percent perspiration.'); INSERT INTO booking VALUES (1, 10, '2020-04-06', '2020-04-07', 0, 10, '1NV2-002'); INSERT INTO availability VALUES (11, '2020-04-07', '2020-04-10', '1NV2-003', NULL); INSERT INTO booking VALUES (1, 11, '2020-04-07', '2020-04-07', 1, 11, '1NV2-003'); INSERT INTO availability VALUES (12, '2020-04-08', '2020-04-11', '1WV1-001', NULL); INSERT INTO booking VALUES (1, 12, '2020-04-08', '2020-04-08', 2, 12, '1WV1-001'); INSERT INTO availability VALUES (13, '2020-04-09', '2020-04-12', '1WV1-002', NULL); INSERT INTO booking VALUES (1, 13, '2020-04-09', '2020-04-11', 3, 13, '1WV1-002'); INSERT INTO availability VALUES (14, '2020-04-10', '2020-04-13', '1WV1-003', 'Having nothing... nothing can he lose.'); INSERT INTO booking VALUES (1, 14, '2020-04-10', '2020-04-11', 4, 14, '1WV1-003'); INSERT INTO availability VALUES (15, '2020-04-11', '2020-04-14', '1WV2-001', NULL); INSERT INTO booking VALUES (1, 15, '2020-04-11', '2020-04-11', 5, 15, '1WV2-001'); INSERT INTO availability VALUES (16, '2020-04-12', '2020-04-15', '1WV2-002', 'What you give is what you get.'); INSERT INTO booking VALUES (1, 16, '2020-04-12', '2020-04-13', 6, 16, '1WV2-002'); INSERT INTO availability VALUES (17, '2020-04-13', '2020-04-16', '1WV2-003', NULL); INSERT INTO booking VALUES (1, 17, '2020-04-13', '2020-04-15', 7, 17, '1WV2-003'); INSERT INTO availability VALUES (18, '2020-04-14', '2020-04-17', '1V1-001', NULL); INSERT INTO booking VALUES (1, 18, '2020-04-14', '2020-04-15', 8, 18, '1V1-001'); INSERT INTO availability VALUES (19, '2020-04-15', '2020-04-18', '1V1-002', NULL); INSERT INTO booking VALUES (1, 19, '2020-04-15', '2020-04-16', 9, 19, '1V1-002'); INSERT INTO availability VALUES (20, '2020-04-16', '2020-04-19', '1V1-003', NULL); INSERT INTO booking VALUES (1, 20, '2020-04-16', '2020-04-18', 0, 20, '1V1-003');
67.941667
152
0.683797
97a2640f3d996067acfe390b81b648361f2772a7
1,261
ts
TypeScript
src/app/app.routing.ts
otojunior/angular-basic-seed
b49b74b30c6134219666f15d7ddc766c09f0c2fb
[ "MIT" ]
null
null
null
src/app/app.routing.ts
otojunior/angular-basic-seed
b49b74b30c6134219666f15d7ddc766c09f0c2fb
[ "MIT" ]
null
null
null
src/app/app.routing.ts
otojunior/angular-basic-seed
b49b74b30c6134219666f15d7ddc766c09f0c2fb
[ "MIT" ]
null
null
null
import { ModuleWithProviders } from "@angular/core"; import { RouterModule, Routes } from "@angular/router"; import { MunicipioListComponent } from "./component/municipio-list.component" import { MunicipioEditComponent } from "./component/municipio-edit.component" import { MunicipioEditResolver } from "./resolver/municipio-edit.resolver" import { MunicipioNewResolver } from "./resolver/municipio-new.resolver" import { MunicipioCloneResolver } from "./resolver/municipio-clone.resolver" const appRoutes: Routes = [ { path: '', redirectTo: 'municipio', pathMatch: 'full' }, { path: 'municipio', component: MunicipioListComponent }, { path: 'municipio/novo', component: MunicipioEditComponent, resolve: { municipioResolver: MunicipioNewResolver } }, { path: 'municipio/clone', component: MunicipioEditComponent, resolve: { municipioResolver: MunicipioCloneResolver } }, { path: 'municipio/:id', component: MunicipioEditComponent, resolve: { municipioResolver: MunicipioEditResolver } } ]; export const routing = RouterModule.forRoot(appRoutes);
28.659091
77
0.64314
c9db4dfb2ede43e629da98d8d540d3eb84670ba1
546
ts
TypeScript
packages/tygen-reflector/src/reflection/index.ts
s-panferov/tygen
f6764aff7ec89fbe4b5c67880ddff5e9ca392ae2
[ "MIT" ]
61
2018-05-29T08:20:18.000Z
2022-02-09T07:59:15.000Z
packages/tygen-reflector/src/reflection/index.ts
serializedowen/tygen
f6764aff7ec89fbe4b5c67880ddff5e9ca392ae2
[ "MIT" ]
32
2015-09-05T09:39:43.000Z
2016-05-07T09:58:14.000Z
packages/tygen-reflector/src/reflection/index.ts
s-panferov/docscript
f6764aff7ec89fbe4b5c67880ddff5e9ca392ae2
[ "MIT" ]
4
2018-09-10T00:52:58.000Z
2020-08-07T19:53:33.000Z
export * from './reflection' export * from './class/reflection' export * from './enum/reflection' export * from './function/reflection' export * from './interface/reflection' export * from './module/reflection' export * from './property/reflection' export * from './signature/reflection' export * from './type-alias/reflection' export * from './type-parameter/reflection' export * from './variable/reflection' export * from './package' export * from './_type/reflection' export * from './search/reflection' export * from './inventory/reflection'
34.125
43
0.725275
455d4ac84bbfbb9d70c3d0397888a8ff5167289f
4,426
py
Python
covid19/segmentation/crop_bbox.py
salvacarrion/mltests
e4ac9711c1c80171f302edc88011fbe06e754490
[ "MIT" ]
null
null
null
covid19/segmentation/crop_bbox.py
salvacarrion/mltests
e4ac9711c1c80171f302edc88011fbe06e754490
[ "MIT" ]
1
2022-01-01T06:09:26.000Z
2022-01-01T06:09:26.000Z
covid19/segmentation/crop_bbox.py
salvacarrion/mltests
e4ac9711c1c80171f302edc88011fbe06e754490
[ "MIT" ]
null
null
null
import glob import json import os from pathlib import Path import cv2 import numpy as np import pandas as pd import tqdm from matplotlib import pyplot as plt def read_img(filename): img = cv2.imread(filename, 0) img = img.astype(np.uint8) return img def show_img(img, cmap="gray", title=""): plt.imshow(img, cmap=cmap) plt.title(title) plt.show() def binarize(img): thr_val, img = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU) return img def get_bounding_boxes(img, threshold_area=1, scaling=1.0): # Find contours ctrs, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Clean areas cleaned_ctrs = [] for ctr in ctrs: area = cv2.contourArea(ctr) if area > threshold_area: cleaned_ctrs.append(ctr) # Bboxes bboxes = [] ctrs = cleaned_ctrs for ctr in ctrs: x, y, w, h = cv2.boundingRect(ctr) values = [v / scaling for v in [x, y, w, h]] bboxes.append(values) # Concat bboxes ctrs = np.concatenate(ctrs) x, y, w, h = cv2.boundingRect(ctrs) concat_bboxes = [[v / scaling for v in [x, y, w, h]]] return bboxes, concat_bboxes def draw_bounding_boxes(img, boxes, scaling=1.0, width=2): # 256=>w=2; 512=>w=5; large=>w=10 new_img = np.array(img) new_img = cv2.cvtColor(new_img, cv2.COLOR_GRAY2RGB) # Draw bounding boxes for box in boxes: top_left = (int(box[0] * scaling), int(box[1] * scaling)) bottom_right = (int(box[0] * scaling + box[2] * scaling), int(box[1] * scaling + box[3] * scaling)) cv2.rectangle(new_img, top_left, bottom_right, (0, 255, 0), width) return new_img def pad_img(img): max_side = max(*img.shape) img_padded = np.zeros((max_side, max_side), np.uint8) ax, ay = (max_side - img.shape[1]) // 2, (max_side - img.shape[0]) // 2 img_padded[ay:img.shape[0] + ay, ax:ax + img.shape[1]] = img return img_padded def expand_bboxes(bboxes, margin_factor): new_bboxes = [] for (x, y, w, h) in bboxes: x, y = x * (1.0 - margin_factor), y * (1.0 - margin_factor) w, h = w * (1.0 + margin_factor), h * (1.0 + margin_factor) new_bboxes.append([x, y, w, h]) return new_bboxes def get_all_masks_files(masks_dir, pred_masks_dir): masks_files = [file for file in glob.glob(os.path.join(masks_dir, "*.png"))] pred_masks_files = [file for file in glob.glob(os.path.join(pred_masks_dir, "*.png"))] return masks_files, pred_masks_files def main(base_path=".", target_size=512, margin_factor=0.05): # path = os.path.join(base_path, "masks256_pred", "sub-S10880_ses-E18932_run-1.png") # Testing # Create output not exists images_output_path = os.path.join(base_path, f"images{target_size}_crop") Path(images_output_path).mkdir(parents=True, exist_ok=True) # Get files raw_images_dir = os.path.join(base_path, "images_raw") df = pd.read_csv(os.path.join(base_path, "bboxes.csv")) # Process masks for i, row in tqdm.tqdm(df.iterrows(), total=len(df)): bboxes, interest_region = json.loads(row["bboxes"]), json.loads(row["interest_region"]) file = row["filepath"] fname = os.path.split(file)[1] # Read image img = read_img(os.path.join(raw_images_dir, file)) # show_img(img) # Pad image max_side = max(*img.shape) img = pad_img(img) # show_img(img) # Expand bboxes bboxes = expand_bboxes(bboxes, margin_factor=margin_factor) interest_region = expand_bboxes(interest_region, margin_factor=margin_factor) # # Draw bboxes # img_bboxes = draw_bounding_boxes(img, bboxes, scaling=max_side) # show_img(img_bboxes) # Crop x, y, w, h = [int(v * max_side) for v in interest_region[0]] img = img[y:y + h, x:x + w] # show_img(img) # Pad image (again) img = pad_img(img) # show_img(img) # Resize img = cv2.resize(img, (target_size, target_size), interpolation=cv2.INTER_LANCZOS4) # show_img(img) # Save image cv2.imwrite(os.path.join(images_output_path, fname), img) asdasd = 3 print("Done!") if __name__ == "__main__": BASE_PATH = "/home/scarrion/datasets/covid19/front" # Run script main(base_path=BASE_PATH)
28.74026
107
0.62404
b548b0a9f3b93cebc2a0d2e54d2082aabfcf1a2a
104
rb
Ruby
config/initializers/content_relations.rb
SandStorman/notebooktest
d8633bc551680650f43b417efab0f6d12f4c6120
[ "MIT" ]
318
2016-09-19T03:42:55.000Z
2022-03-25T23:59:28.000Z
config/initializers/content_relations.rb
SandStorman/notebooktest
d8633bc551680650f43b417efab0f6d12f4c6120
[ "MIT" ]
599
2016-09-05T03:27:53.000Z
2022-03-31T12:16:52.000Z
config/initializers/content_relations.rb
SandStorman/notedocker
d8633bc551680650f43b417efab0f6d12f4c6120
[ "MIT" ]
89
2016-09-19T04:06:57.000Z
2022-02-20T22:33:41.000Z
Rails.application.config.content_relations = {} Rails.application.config.inverse_content_relations = {}
34.666667
55
0.826923
e278c470b134aa1510a0b3b306999c29ce5714b7
2,891
py
Python
ibemc/management/commands/check_concepts.py
cchmc-bmi-os/harvest_inc
ae1fecb6df9b78d9daafb1879c02c7fefb6a8a79
[ "BSD-2-Clause" ]
null
null
null
ibemc/management/commands/check_concepts.py
cchmc-bmi-os/harvest_inc
ae1fecb6df9b78d9daafb1879c02c7fefb6a8a79
[ "BSD-2-Clause" ]
null
null
null
ibemc/management/commands/check_concepts.py
cchmc-bmi-os/harvest_inc
ae1fecb6df9b78d9daafb1879c02c7fefb6a8a79
[ "BSD-2-Clause" ]
null
null
null
from optparse import make_option from django.core.management.base import BaseCommand, CommandError from avocado.models import DataCategory, DataConcept, DataField import urllib2, json # CONCEPT_SET = ['all', ] BASE_URL = 'http://127.0.0.1:8005' def check_py_concept(c): """Checks that a concept is defined by at least one field. """ fields = DataField.objects.filter(concepts=c.id) if fields.count() > 0: pass ##print('Concept {} defined by {} -- OK'.format(c.id, ','.join([str(f.id) for f in fields]))) else: raise Exception('Concept is not defined by any field.') def check_api_concept(c): url = BASE_URL + '/api/concepts/' + str(c.id) + '/' response = urllib2.urlopen(url) data = json.loads(response.read()) assert len(data) > 0, 'Error: concept json does not contain information' def check_api_field(c): url = BASE_URL + '/api/fields/' + str(c.id) + '/' response = urllib2.urlopen(url) data = json.loads(response.read()) assert len(data) > 0, 'Error: Field json does not contain information' def check_concepts(concepts): to_delete = [] for c in concepts: try: check_py_concept(c) check_api_concept(c) print('Concept {} - OK'.format(c.id)) except Exception as E: print('Error in definition of concept id {}'.format(c.id)) print(E) to_delete.append(c) print('Concept to be deleted') DataConcept.objects.filter(id__in=[c.id for c in to_delete]).delete() print('{} Concepts deleted'.format(len(to_delete))) def check_fields(fields): to_delete = [] for c in fields: try: check_api_field(c) print('Field {} - OK'.format(c.id)) except Exception as E: print('Error in definition of field id {}'.format(c.id)) print(E) ## to_delete.append(c) ## print('Field to be deleted') ## DataField.objects.filter(id__in=[c.id for c in to_delete]).delete() ## print('{} Fields deleted'.format(len(to_delete))) print('No field deleted - check code') class Command(BaseCommand): """Check the definition of each concept. """ help = 'Check the definition of the concepts defined in the database' option_list = BaseCommand.option_list + ( make_option( '--concepts', dest='concepts', default='all', help='Load the specified set of concepts.', ), ) def handle(self, *args, **options): print('Start...') # concepts = DataConcept.objects.all() # print('Number of concepts = {}'.format(concepts.count())) # check_concepts(concepts) fields = DataField.objects.all() print('Number of fileds = {}'.format(fields.count())) check_fields(fields) print('Done.')
31.423913
106
0.606019
dd73395a39a5b2b72066c6371ad1d7dafd4bfd46
448
java
Java
src/main/java/mod/flatcoloredblocks/client/IClientSide.java
AlgorithmX2/FlatColoredBlocks
2564f8ce766ef31cd5ade3ad6afda2ae67eb88a1
[ "MIT" ]
17
2015-12-18T04:44:44.000Z
2021-01-13T17:55:38.000Z
src/main/java/mod/flatcoloredblocks/client/IClientSide.java
AlgorithmX2/FlatColoredBlocks
2564f8ce766ef31cd5ade3ad6afda2ae67eb88a1
[ "MIT" ]
77
2015-12-14T20:14:28.000Z
2021-06-21T03:33:06.000Z
src/main/java/mod/flatcoloredblocks/client/IClientSide.java
AlgorithmX2/FlatColoredBlocks
2564f8ce766ef31cd5ade3ad6afda2ae67eb88a1
[ "MIT" ]
17
2016-01-05T02:18:58.000Z
2021-02-13T19:04:35.000Z
package mod.flatcoloredblocks.client; import mod.flatcoloredblocks.block.BlockFlatColored; import mod.flatcoloredblocks.block.ItemBlockFlatColored; import mod.flatcoloredblocks.craftingitem.ItemColoredBlockCrafter; public interface IClientSide { void configureBlockRender( BlockFlatColored cb, ItemBlockFlatColored cbi ); public void configureCraftingRender( ItemColoredBlockCrafter crafterItem ); void preinit(); void init(); }
21.333333
66
0.823661
e2bd66e8d76f104ecc91e767250c4a1a23b2a1e0
15,987
py
Python
aiida_siesta/data/psf.py
mailhexu/aiida_siesta_plugin
313ef4b3532b54d8d0c81788b683c53cb4701965
[ "MIT" ]
null
null
null
aiida_siesta/data/psf.py
mailhexu/aiida_siesta_plugin
313ef4b3532b54d8d0c81788b683c53cb4701965
[ "MIT" ]
2
2019-05-12T22:11:46.000Z
2019-05-13T11:46:16.000Z
aiida_siesta/data/psf.py
mailhexu/aiida_siesta_plugin
313ef4b3532b54d8d0c81788b683c53cb4701965
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ This module manages the PSF pseudopotentials in the local repository. """ from aiida.common.utils import classproperty from aiida.orm.data.singlefile import SinglefileData __copyright__ = u"Copyright (c), 2015, ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE (Theory and Simulation of Materials (THEOS) and National Centre for Computational Design and Discovery of Novel Materials (NCCR MARVEL)), Switzerland and ROBERT BOSCH LLC, USA. All rights reserved." __license__ = "MIT license, see LICENSE.txt file" __version__ = "0.9.10" __contributors__ = "Victor M. Garcia-Suarez, Andrea Cepellotti" PSFGROUP_TYPE = 'data.psf.family' def get_pseudos_from_structure(structure, family_name): """ Given a family name (a PsfFamily group in the DB) and a AiiDA structure, return a dictionary associating each kind name with its PsfData object. :raise MultipleObjectsError: if more than one PSF for the same element is found in the group. :raise NotExistent: if no PSF for an element in the group is found in the group. """ from aiida.common.exceptions import NotExistent, MultipleObjectsError family_pseudos = {} family = PsfData.get_psf_group(family_name) for node in family.nodes: if isinstance(node, PsfData): if node.element in family_pseudos: raise MultipleObjectsError( "More than one PSF for element {} found in " "family {}".format(node.element, family_name)) family_pseudos[node.element] = node pseudo_list = {} for kind in structure.kinds: symbol = kind.symbol try: pseudo_list[kind.name] = family_pseudos[symbol] except KeyError: raise NotExistent("No PSF for element {} found in family {}". format(symbol, family_name)) return pseudo_list def upload_psf_family(folder, group_name, group_description, stop_if_existing=True): """ Upload a set of PSF files in a given group. :param folder: a path containing all PSF files to be added. Only files ending in .PSF (case-insensitive) are considered. :param group_name: the name of the group to create. If it exists and is non-empty, a UniquenessError is raised. :param group_description: a string to be set as the group description. Overwrites previous descriptions, if the group was existing. :param stop_if_existing: if True, check for the md5 of the files and, if the file already exists in the DB, raises a MultipleObjectsError. If False, simply adds the existing PsfData node to the group. """ import os import aiida.common from aiida.common import aiidalogger from aiida.orm import Group from aiida.common.exceptions import UniquenessError, NotExistent from aiida.backends.utils import get_automatic_user from aiida.orm.querybuilder import QueryBuilder if not os.path.isdir(folder): raise ValueError("folder must be a directory") # only files, and only those ending with .psf or .PSF; # go to the real file if it is a symlink files = [ os.path.realpath(os.path.join(folder, i)) for i in os.listdir(folder) if os.path.isfile(os.path.join(folder, i)) and i.lower().endswith('.psf') ] nfiles = len(files) try: group = Group.get(name=group_name, type_string=PSFGROUP_TYPE) group_created = False except NotExistent: group = Group( name=group_name, type_string=PSFGROUP_TYPE, user=get_automatic_user()) group_created = True if group.user != get_automatic_user(): raise UniquenessError("There is already a PsfFamily group with name {}" ", but it belongs to user {}, therefore you " "cannot modify it".format( group_name, group.user.email)) # Always update description, even if the group already existed group.description = group_description # NOTE: GROUP SAVED ONLY AFTER CHECKS OF UNICITY pseudo_and_created = [] for f in files: md5sum = aiida.common.utils.md5_file(f) qb = QueryBuilder() qb.append(PsfData, filters={'attributes.md5': {'==': md5sum}}) existing_psf = qb.first() #existing_psf = PsfData.query(dbattributes__key="md5", # dbattributes__tval = md5sum) if existing_psf is None: # return the psfdata instances, not stored pseudo, created = PsfData.get_or_create( f, use_first=True, store_psf=False) # to check whether only one psf per element exists # NOTE: actually, created has the meaning of "to_be_created" pseudo_and_created.append((pseudo, created)) else: if stop_if_existing: raise ValueError("A PSF with identical MD5 to " " {} cannot be added with stop_if_existing" "".format(f)) existing_psf = existing_psf[0] pseudo_and_created.append((existing_psf, False)) # check whether pseudo are unique per element elements = [(i[0].element, i[0].md5sum) for i in pseudo_and_created] # If group already exists, check also that I am not inserting more than # once the same element if not group_created: for aiida_n in group.nodes: # Skip non-pseudos if not isinstance(aiida_n, PsfData): continue elements.append((aiida_n.element, aiida_n.md5sum)) elements = set(elements) # Discard elements with the same MD5, that would # not be stored twice elements_names = [e[0] for e in elements] if not len(elements_names) == len(set(elements_names)): duplicates = set( [x for x in elements_names if elements_names.count(x) > 1]) duplicates_string = ", ".join(i for i in duplicates) raise UniquenessError("More than one PSF found for the elements: " + duplicates_string + ".") # At this point, save the group, if still unstored if group_created: group.store() # save the psf in the database, and add them to group for pseudo, created in pseudo_and_created: if created: pseudo.store() aiidalogger.debug("New node {} created for file {}".format( pseudo.uuid, pseudo.filename)) else: aiidalogger.debug("Reusing node {} for file {}".format( pseudo.uuid, pseudo.filename)) # Add elements to the group all togetehr group.add_nodes(pseudo for pseudo, created in pseudo_and_created) nuploaded = len([_ for _, created in pseudo_and_created if created]) return nfiles, nuploaded def parse_psf(fname, check_filename=True): """ Try to get relevant information from the PSF. For the moment, only the element name. If check_filename is True, raise a ParsingError exception if the filename does not start with the element name. """ import os from aiida.common.exceptions import ParsingError # TODO: move these data in a 'chemistry' module from aiida.orm.data.structure import _valid_symbols parsed_data = {} with open(fname) as f: # Parse the element element = None for element in f.read().split(): break # Only first letter capitalized! if element is None: raise ParsingError( "Unable to find the element of PSF {}".format(fname)) element = element.capitalize() if element not in _valid_symbols: raise ParsingError( "Unknown element symbol {} for file {}".format(element, fname)) if check_filename: if not os.path.basename(fname).lower().startswith(element.lower()): raise ParsingError("Filename {0} was recognized for element " "{1}, but the filename does not start " "with {1}".format(fname, element)) parsed_data['element'] = element return parsed_data class PsfData(SinglefileData): """ Function not yet documented. """ @classmethod def get_or_create(cls, filename, use_first=False, store_psf=True): """ Pass the same parameter of the init; if a file with the same md5 is found, that PsfData is returned. :param filename: an absolute filename on disk :param use_first: if False (default), raise an exception if more than \ one potential is found.\ If it is True, instead, use the first available pseudopotential. :param bool store_psf: If false, the PsfData objects are not stored in the database. default=True. :return (psf, created): where psf is the PsfData object, and create is either\ True if the object was created, or False if the object was retrieved\ from the DB. """ import aiida.common.utils import os if not os.path.abspath(filename): raise ValueError("filename must be an absolute path") md5 = aiida.common.utils.md5_file(filename) pseudos = cls.from_md5(md5) if len(pseudos) == 0: if store_psf: instance = cls(file=filename).store() return (instance, True) else: instance = cls(file=filename) return (instance, True) else: if len(pseudos) > 1: if use_first: return (pseudos[0], False) else: raise ValueError( "More than one copy of a pseudopotential " "with the same MD5 has been found in the " "DB. pks={}".format( ",".join([str(i.pk) for i in pseudos]))) else: return (pseudos[0], False) @classproperty def psffamily_type_string(cls): return PSFGROUP_TYPE def store(self, *args, **kwargs): """ Store the node, reparsing the file so that the md5 and the element are correctly reset. """ from aiida.common.exceptions import ParsingError, ValidationError import aiida.common.utils psf_abspath = self.get_file_abs_path() if not psf_abspath: raise ValidationError("No valid PSF was passed!") parsed_data = parse_psf(psf_abspath) md5sum = aiida.common.utils.md5_file(psf_abspath) try: element = parsed_data['element'] except KeyError: raise ParsingError("No 'element' parsed in the PSF file {};" " unable to store".format(self.filename)) self._set_attr('element', str(element)) self._set_attr('md5', md5sum) return super(PsfData, self).store(*args, **kwargs) @classmethod def from_md5(cls, md5): """ Return a list of all PSF pseudopotentials that match a given MD5 hash. Note that the hash has to be stored in a _md5 attribute, otherwise the pseudo will not be found. """ queryset = cls.query(dbattributes__key='md5', dbattributes__tval=md5) return list(queryset) def set_file(self, filename): """ I pre-parse the file to store the attributes. """ from aiida.common.exceptions import ParsingError import aiida.common.utils parsed_data = parse_psf(filename) md5sum = aiida.common.utils.md5_file(filename) try: element = parsed_data['element'] except KeyError: raise ParsingError("No 'element' parsed in the PSF file {};" " unable to store".format(self.filename)) super(PsfData, self).set_file(filename) self._set_attr('element', str(element)) self._set_attr('md5', md5sum) def get_psf_family_names(self): """ Get the list of all psf family names to which the pseudo belongs """ from aiida.orm import Group return [ _.name for _ in Group.query( nodes=self, type_string=self.psffamily_type_string) ] @property def element(self): return self.get_attr('element', None) @property def md5sum(self): return self.get_attr('md5', None) def _validate(self): from aiida.common.exceptions import ValidationError, ParsingError import aiida.common.utils super(PsfData, self)._validate() psf_abspath = self.get_file_abs_path() if not psf_abspath: raise ValidationError("No valid PSF was passed!") try: parsed_data = parse_psf(psf_abspath) except ParsingError: raise ValidationError("The file '{}' could not be " "parsed".format(psf_abspath)) md5 = aiida.common.utils.md5_file(psf_abspath) try: element = parsed_data['element'] except KeyError: raise ValidationError("No 'element' could be parsed in the PSF " "file {}".format(psf_abspath)) try: attr_element = self.get_attr('element') except AttributeError: raise ValidationError("attribute 'element' not set.") try: attr_md5 = self.get_attr('md5') except AttributeError: raise ValidationError("attribute 'md5' not set.") if attr_element != element: raise ValidationError("Attribute 'element' says '{}' but '{}' was " "parsed instead.".format( attr_element, element)) if attr_md5 != md5: raise ValidationError("Attribute 'md5' says '{}' but '{}' was " "parsed instead.".format(attr_md5, md5)) @classmethod def get_psf_group(cls, group_name): """ Return the PsfFamily group with the given name. """ from aiida.orm import Group return Group.get( name=group_name, type_string=cls.psffamily_type_string) @classmethod def get_psf_groups(cls, filter_elements=None, user=None): """ Return all names of groups of type PsfFamily, possibly with some filters. :param filter_elements: A string or a list of strings. If present, returns only the groups that contains one Psf for every element present in the list. Default=None, meaning that all families are returned. :param user: if None (default), return the groups for all users. If defined, it should be either a DbUser instance, or a string for the username (that is, the user email). """ from aiida.orm import Group group_query_params = {"type_string": cls.psffamily_type_string} if user is not None: group_query_params['user'] = user if isinstance(filter_elements, basestring): filter_elements = [filter_elements] if filter_elements is not None: actual_filter_elements = {_.capitalize() for _ in filter_elements} group_query_params['node_attributes'] = { 'element': actual_filter_elements } all_psf_groups = Group.query(**group_query_params) groups = [(g.name, g) for g in all_psf_groups] # Sort by name groups.sort() # Return the groups, without name return [_[1] for _ in groups]
36.088036
278
0.604741
7572c5acacbbd92d18d0485b0a50d89d56de621e
7,941
css
CSS
client/src/components/Faculty/faculty.css
abhilasha007/SocStudy
fd58d3e6027c9a197f0469016da64ea21a1addad
[ "MIT" ]
2
2022-03-29T04:02:50.000Z
2022-03-30T04:04:12.000Z
client/src/components/Faculty/faculty.css
abhilasha007/SocStudy
fd58d3e6027c9a197f0469016da64ea21a1addad
[ "MIT" ]
null
null
null
client/src/components/Faculty/faculty.css
abhilasha007/SocStudy
fd58d3e6027c9a197f0469016da64ea21a1addad
[ "MIT" ]
1
2022-03-29T04:03:15.000Z
2022-03-29T04:03:15.000Z
@charset "utf-8"; /************* For Main Tag*************/ @media only screen and (max-width: 600px) { main { top: 5; margin-top: 12.8vh; display: flex; justify-content: flex-start; height: 175vh; } .Title { background-color: #053c5e; width: 30vw; margin-right: -30vw; position: fixed; height: 100vh; } .Title > div { width: 80%; color: white; display: flex; justify-content: center; align-items: center; height: 9vh; margin: 40vh 0vw 0vw 40px; font-size: 7vh; border-top: 4px solid white; border-bottom: 4px solid white; text-align: center; } .Content { margin-left: 29vw; width: 70vw; height: 100vh; /* background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)), url(Background.png); */ background-size: cover; background-attachment: scroll; margin-right: -10px; } .Faculty-Context { margin-left: 30vw; /* background: url(Background.png); */ background-position: right; background-attachment: fixed; background-repeat: no-repeat; width: 70vw; } .Content-elements { height: 20%; width: 80%; display: flex; border-bottom: solid 2px#EF494E; color: white; justify-content: center; margin-left: 8vw; padding-bottom: 10px; margin-top: 20px; } .Content-elements:first-child { margin-top: 15vh; } .Photo-part { width: 15%; margin: 5px 30px 10px 0px; } .Photo-part img { border-radius: 100%; } .Detail-part { width: 80%; font-size: 15px; line-height: 5px; } .email { float: left; } .phone { float: right; } } @media only screen and (min-width: 600px) and (max-width: 767px) { main { top: 5; margin-top: 12.8vh; display: flex; justify-content: flex-start; height: 175vh; } .Title { display: flex; flex-direction: column; background-color: #053c5e; justify-content: center; align-items: center; height: 100%; width: 33%; color: white; position: fixed; margin-left: 15rem; } .Title h2 { width: 100%; padding: auto; text-align: center; } .Title hr { width: 70%; display: block; } .Content { margin-left: 20vw; width: 73vw; height: 100vh; /* background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)), url(Background.png); */ background-size: cover; background-attachment: scroll; margin-right: -10px; margin-top: 5rem; } .Faculty-Context { margin-left: 30vw; /* background: url(Background.png); */ background-position: right; background-attachment: fixed; background-repeat: no-repeat; width: 70vw; } .Content-elements { height: 20%; width: 80%; display: flex; border-bottom: solid 2px#EF494E; color: white; justify-content: center; margin-left: 35vw; padding-bottom: 10px; margin-top: 20px; } .Content-elements:first-child { margin-top: 15vh; } .Photo-part { width: 15%; margin: 5px 30px 10px 0px; } .Photo-part img { border-radius: 100%; } .Detail-part { width: 80%; font-size: 15px; line-height: 5px; } .email { float: left; } .phone { float: right; } } @media only screen and (min-width: 768px) and (max-width: 991px) { main { top: 5; margin-top: 12.8vh; display: flex; justify-content: flex-start; height: 175vh; } .Title { display: flex; flex-direction: column; background-color: #053c5e; justify-content: center; align-items: center; height: 100%; width: 33%; color: white; position: fixed; margin-left: 11rem; } .Title h2 { width: 100%; padding: auto; text-align: center; } .Title hr { width: 70%; display: block; } .Content { margin-left: 29vw; width: 70vw; height: 100vh; /* background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)), url(Background.png); */ background-size: cover; background-attachment: scroll; margin-right: -10px; } .Faculty-Context { margin-left: 30vw; /* background: url(Background.png); */ background-position: right; background-attachment: fixed; background-repeat: no-repeat; width: 70vw; margin-bottom: 10rem; } .Content-elements { height: 20%; width: 80%; display: flex; border-bottom: solid 2px#EF494E; color: white; justify-content: center; margin-left: 23vw; padding-bottom: 10px; margin-top: 20px; } .Content-elements:first-child { margin-top: 15vh; } .Photo-part { width: 15%; margin: 5px 30px 10px 0px; } .Photo-part img { border-radius: 100%; } .Detail-part { width: 80%; font-size: 15px; line-height: 5px; } .email { float: left; } .phone { float: right; } } @media only screen and (min-width: 992px) and (max-width: 1199px) { main { top: 5; margin-top: 12.8vh; display: flex; justify-content: flex-start; height: 175vh; } .Title { display: flex; flex-direction: column; background-color: #053c5e; justify-content: center; align-items: center; height: 100%; width: 33%; color: white; position: fixed; margin-left: 5rem; } .Title h2 { width: 100%; padding: auto; text-align: center; } .Title hr { width: 70%; display: block; } .Content { margin-left: 30vw; width: 70vw; height: 100vh; /* background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)), url(Background.png); */ background-size: cover; background-attachment: scroll; margin-right: -10px; } .Faculty-Context { margin-left: 36vw; /* background: url(Background.png); */ background-position: right; background-attachment: fixed; background-repeat: no-repeat; width: 70vw; margin-top: 2rem; } .Content-elements { height: 20%; width: 80%; display: flex; border-bottom: solid 2px#EF494E; color: white; justify-content: center; margin-left: 15vw; padding-bottom: 10px; margin-top: 1rem; } .Content-elements:first-child { margin-top: 15vh; } .Photo-part { width: 15%; margin: 5px 30px 10px 0px; } .Photo-part img { border-radius: 100%; } .Detail-part { width: 80%; font-size: 15px; line-height: 5px; } .email { float: left; } .phone { float: right; } } @media only screen and (min-width: 1200px) { main { top: 5; margin-top: 12.8vh; display: flex; justify-content: flex-start; height: 175vh; } .Title { display: flex; flex-direction: column; background-color: #053c5e; justify-content: center; align-items: center; height: 100%; width: 30%; color: white; position: fixed; left: 0.0rem; } .Title h2 { width: 100%; padding: auto; text-align: center; } .Title hr { width: 70%; display: block; } /****************************/ .Faculty-Context { margin-left: 30vw; /* background: url(Background.png); */ background-position: right; background-attachment: fixed; background-repeat: no-repeat; width: 70vw; margin-top: 2rem; } .Content-elements { height: 20%; width: 80%; display: flex; border-bottom: solid 2px#EF494E; color: white; justify-content: center; margin-left: 10vw; padding-bottom: 10px; margin-top: 20px; } .Content-elements:first-child { margin-top: 15vh; } .Photo-part { width: 15%; margin: 5px 30px 10px 0px; } .Photo-part img { border-radius: 100%; } .Detail-part { width: 80%; font-size: 15px; line-height: 5px; } .email { float: left; } .phone { float: right; } }
17.338428
71
0.576376
ff3c4a4bcfb8454213da396938dea2316d2eeee7
2,931
py
Python
evenflow/scrapers/article/article_scraper.py
underscorefan/itsachemtrail_gatherer
7f85c09fa465d730f66935a5d683dc79f9f250db
[ "MIT" ]
null
null
null
evenflow/scrapers/article/article_scraper.py
underscorefan/itsachemtrail_gatherer
7f85c09fa465d730f66935a5d683dc79f9f250db
[ "MIT" ]
null
null
null
evenflow/scrapers/article/article_scraper.py
underscorefan/itsachemtrail_gatherer
7f85c09fa465d730f66935a5d683dc79f9f250db
[ "MIT" ]
null
null
null
import abc import re from typing import Optional from aiohttp import ClientSession as Sess from newspaper.configuration import Configuration as NConf from functools import partial from dirtyfunc import Either, Left from evenflow import utreq from evenflow.streams.messages.article_extended import ArticleExtended from evenflow.urlman import functions class ArchivedURLNotFound(Exception): """raised when original url is not found in archive.* websites""" pass class ArticleScraper(abc.ABC): @abc.abstractmethod async def get_data(self, session: Sess, conf: NConf, timeout: Optional[int]) -> Either[Exception, ArticleExtended]: pass class DefaultArticleScraper(ArticleScraper): def __init__(self, article_link: str, source: str, fake: bool): self.article_link = article_link self.partial = partial(ArticleExtended, url_to_visit=article_link, scraped_from=source, fake=fake) async def get_data(self, session: Sess, conf: NConf, timeout: Optional[int]) -> Either[Exception, ArticleExtended]: try: maybe_html = await utreq.get_html(self.article_link, session, timeout) maybe_article = maybe_html.map(lambda html: self.partial(conf=conf, html=html)) corrected_title = maybe_article.map(lambda a: a.correct_title()) return corrected_title.map(lambda a: a.remove_newlines_from_fields()) except Exception as e: return Left(e) class Archive(DefaultArticleScraper): def __init__(self, article_link: str, source: str, fake: bool): super().__init__(article_link, source, fake) @staticmethod def title_extraction(article: ArticleExtended) -> ArticleExtended: url = article.soup.select_one("#HEADER > table input")["value"] if url: return article.set_actual_url(url).update_date() raise ArchivedURLNotFound(f"url not found for {article.url_to_visit}, scraped_from: {article.scraped_from}") async def get_data(self, session: Sess, conf: NConf, timeout: Optional[int]) -> Either[Exception, ArticleExtended]: maybe_article = await super().get_data(session, conf, timeout) return maybe_article.flat_map(lambda a: Either.attempt(partial(self.title_extraction, a))) class WebArchive(DefaultArticleScraper): def __init__(self, article_link: str, source: str, fake: bool): super().__init__(article_link, source, fake) async def get_data(self, session: Sess, conf: NConf, timeout: Optional[int]) -> Either[Exception, ArticleExtended]: maybe_url = re.findall("(https?://[^\\s]+)", functions.maintain_path(self.article_link)) if len(maybe_url) > 0: maybe_article = await super().get_data(session, conf, timeout) return maybe_article.map(lambda a: a.set_actual_url(maybe_url[0]).update_date()) return Left(ArchivedURLNotFound(f"encoded URL not found in {self.article_link}"))
43.102941
119
0.720232
4267fef5d55662e856050f2e2304812c0e67eccd
1,097
zsh
Shell
zsh/zshrc.zsh
ashencone/configs
e6c8ec27d0c633b822845fdfecba0784d8ac18bf
[ "MIT" ]
1
2022-03-02T15:27:17.000Z
2022-03-02T15:27:17.000Z
zsh/zshrc.zsh
ashencone/configs
e6c8ec27d0c633b822845fdfecba0784d8ac18bf
[ "MIT" ]
null
null
null
zsh/zshrc.zsh
ashencone/configs
e6c8ec27d0c633b822845fdfecba0784d8ac18bf
[ "MIT" ]
null
null
null
# Zinit installer if [[ ! -f $HOME/.local/share/zinit/zinit.git/zinit.zsh ]]; then print -P "%F{33} %F{220}Installing %F{33}ZDHARMA-CONTINUUM%F{220} Initiative Plugin Manager (%F{33}zdharma-continuum/zinit%F{220})…%f" command mkdir -p "$HOME/.local/share/zinit" && command chmod g-rwX "$HOME/.local/share/zinit" command git clone https://github.com/zdharma-continuum/zinit "$HOME/.local/share/zinit/zinit.git" && \ print -P "%F{33} %F{34}Installation successful.%f%b" || \ print -P "%F{160} The clone has failed.%f%b" fi # Load zinit source "$HOME/.local/share/zinit/zinit.git/zinit.zsh" # Load important zinit annexes zinit light-mode for \ zdharma-continuum/zinit-annex-as-monitor \ zdharma-continuum/zinit-annex-bin-gem-node \ zdharma-continuum/zinit-annex-patch-dl \ zdharma-continuum/zinit-annex-rust # Core plugins zinit light zdharma-continuum/fast-syntax-highlighting zinit light zsh-users/zsh-autosuggestions # Starship prompt eval "$(starship init zsh)" # Command alias alias ls=exa # Enable completions autoload -U compinit && compinit
34.28125
138
0.713765
0033ea820990dfc334c5c5fc2af7c370bd72262f
6,931
rs
Rust
src/lib.rs
smallstepman/orgize
ae185d2f65f0f0cd8a3f7220f15714881118dd75
[ "MIT" ]
null
null
null
src/lib.rs
smallstepman/orgize
ae185d2f65f0f0cd8a3f7220f15714881118dd75
[ "MIT" ]
null
null
null
src/lib.rs
smallstepman/orgize
ae185d2f65f0f0cd8a3f7220f15714881118dd75
[ "MIT" ]
null
null
null
//! A Rust library for parsing orgmode files. //! //! [Live demo](https://orgize.herokuapp.com/) //! //! # Parse //! //! To parse a orgmode string, simply invoking the [`Org::parse`] function: //! //! [`Org::parse`]: struct.Org.html#method.parse //! //! ```rust //! use orgize::Org; //! //! Org::parse("* DONE Title :tag:"); //! ``` //! //! or [`Org::parse_custom`]: //! //! [`Org::parse_custom`]: struct.Org.html#method.parse_custom //! //! ```rust //! use orgize::{Org, ParseConfig}; //! //! Org::parse_custom( //! "* TASK Title 1", //! &ParseConfig { //! // custom todo keywords //! todo_keywords: (vec!["TASK".to_string()], vec![]), //! ..Default::default() //! }, //! ); //! ``` //! //! # Iter //! //! [`Org::iter`] function will returns an iterator of [`Event`]s, which is //! a simple wrapper of [`Element`]. //! //! [`Org::iter`]: struct.Org.html#method.iter //! [`Event`]: enum.Event.html //! [`Element`]: elements/enum.Element.html //! //! ```rust //! use orgize::Org; //! //! for event in Org::parse("* DONE Title :tag:").iter() { //! // handling the event //! } //! ``` //! //! **Note**: whether an element is container or not, it will appears twice in one loop. //! One as [`Event::Start(element)`], one as [`Event::End(element)`]. //! //! [`Event::Start(element)`]: enum.Event.html#variant.Start //! [`Event::End(element)`]: enum.Event.html#variant.End //! //! # Render html //! //! You can call the [`Org::write_html`] function to generate html directly, which //! uses the [`DefaultHtmlHandler`] internally: //! //! [`Org::write_html`]: struct.Org.html#method.write_html //! [`DefaultHtmlHandler`]: export/struct.DefaultHtmlHandler.html //! //! ```rust //! use orgize::Org; //! //! let mut writer = Vec::new(); //! Org::parse("* title\n*section*").write_html(&mut writer).unwrap(); //! //! assert_eq!( //! String::from_utf8(writer).unwrap(), //! "<main><h1>title</h1><section><p><b>section</b></p></section></main>" //! ); //! ``` //! //! # Render html with custom `HtmlHandler` //! //! To customize html rendering, simply implementing [`HtmlHandler`] trait and passing //! it to the [`Org::write_html_custom`] function. //! //! [`HtmlHandler`]: export/trait.HtmlHandler.html //! [`Org::write_html_custom`]: struct.Org.html#method.write_html_custom //! //! The following code demonstrates how to add a id for every headline and return //! own error type while rendering. //! //! ```rust //! use std::convert::From; //! use std::io::{Error as IOError, Write}; //! use std::string::FromUtf8Error; //! //! use orgize::export::{DefaultHtmlHandler, HtmlHandler}; //! use orgize::{Element, Org}; //! use slugify::slugify; //! //! #[derive(Debug)] //! enum MyError { //! IO(IOError), //! Heading, //! Utf8(FromUtf8Error), //! } //! //! // From<std::io::Error> trait is required for custom error type //! impl From<IOError> for MyError { //! fn from(err: IOError) -> Self { //! MyError::IO(err) //! } //! } //! //! impl From<FromUtf8Error> for MyError { //! fn from(err: FromUtf8Error) -> Self { //! MyError::Utf8(err) //! } //! } //! //! #[derive(Default)] //! struct MyHtmlHandler(DefaultHtmlHandler); //! //! impl HtmlHandler<MyError> for MyHtmlHandler { //! fn start<W: Write>(&mut self, mut w: W, element: &Element) -> Result<(), MyError> { //! if let Element::Title(title) = element { //! if title.level > 6 { //! return Err(MyError::Heading); //! } else { //! write!( //! w, //! "<h{0}><a id=\"{1}\" href=\"#{1}\">", //! title.level, //! slugify!(&title.raw), //! )?; //! } //! } else { //! // fallthrough to default handler //! self.0.start(w, element)?; //! } //! Ok(()) //! } //! //! fn end<W: Write>(&mut self, mut w: W, element: &Element) -> Result<(), MyError> { //! if let Element::Title(title) = element { //! write!(w, "</a></h{}>", title.level)?; //! } else { //! self.0.end(w, element)?; //! } //! Ok(()) //! } //! } //! //! fn main() -> Result<(), MyError> { //! let mut writer = Vec::new(); //! let mut handler = MyHtmlHandler::default(); //! Org::parse("* title\n*section*").write_html_custom(&mut writer, &mut handler)?; //! //! assert_eq!( //! String::from_utf8(writer)?, //! "<main><h1><a id=\"title\" href=\"#title\">title</a></h1>\ //! <section><p><b>section</b></p></section></main>" //! ); //! //! Ok(()) //! } //! ``` //! //! **Note**: as I mentioned above, each element will appears two times while iterating. //! And handler will silently ignores all end events from non-container elements. //! //! So if you want to change how a non-container element renders, just redefine the `start` //! function and leave the `end` function unchanged. //! //! # Serde //! //! `Org` struct have already implemented serde's `Serialize` trait. It means you can //! serialize it into any format supported by serde, such as json: //! //! ```rust //! use orgize::Org; //! use serde_json::{json, to_string}; //! //! let org = Org::parse("I 'm *bold*."); //! #[cfg(feature = "ser")] //! println!("{}", to_string(&org).unwrap()); //! //! // { //! // "type": "document", //! // "children": [{ //! // "type": "section", //! // "children": [{ //! // "type": "paragraph", //! // "children":[{ //! // "type": "text", //! // "value":"I 'm " //! // }, { //! // "type": "bold", //! // "children":[{ //! // "type": "text", //! // "value": "bold" //! // }] //! // }, { //! // "type":"text", //! // "value":"." //! // }] //! // }] //! // }] //! // } //! ``` //! //! # Features //! //! By now, orgize provides three features: //! //! + `ser`: adds the ability to serialize `Org` and other elements using `serde`, enabled by default. //! //! + `chrono`: adds the ability to convert `Datetime` into `chrono` structs, disabled by default. //! //! + `syntect`: provides [`SyntectHtmlHandler`] for highlighting code block, disabled by default. //! //! [`SyntectHtmlHandler`]: export/struct.SyntectHtmlHandler.html //! //! # License //! //! MIT mod config; pub mod elements; pub mod export; mod headline; mod org; mod parse; mod parsers; mod validate; // Re-export of the indextree crate. pub use indextree; #[cfg(feature = "syntect")] pub use syntect; pub use config::ParseConfig; pub use elements::Element; pub use headline::{Document, Headline}; pub use org::{Event, Org}; pub use validate::ValidationError; #[cfg(feature = "wasm")] mod wasm;
28.174797
102
0.530804
6ddf90073a3b42c55669c4d6f95fc4335fbc76cb
2,353
h
C
common/include/routing/blob.h
honzatran/llvm-message-routing
6878dffb935efe44fa8fdf443bfb9905ea604d29
[ "MIT" ]
null
null
null
common/include/routing/blob.h
honzatran/llvm-message-routing
6878dffb935efe44fa8fdf443bfb9905ea604d29
[ "MIT" ]
null
null
null
common/include/routing/blob.h
honzatran/llvm-message-routing
6878dffb935efe44fa8fdf443bfb9905ea604d29
[ "MIT" ]
null
null
null
#ifndef ROUTING_BLOB_H #define ROUTING_BLOB_H #include "buffer.h" #include <routing/stdext.h> #include <routing/logger.h> #include <string> #include <cstdio> #include <type_traits> #include <spdlog/fmt/fmt.h> #include <boost/optional.hpp> namespace routing { class Serializing_blob; class Blob { public: Blob() : m_buffer(0) { } Blob(int size) : m_buffer(size), m_offset(0) { } template <typename T> friend Blob& operator<<(Blob& blob, T value) { blob.m_buffer.set(value, blob.m_offset); blob.m_offset += sizeof(T); return blob; } void reset(); friend Blob& operator<<(Blob& blob, Buffer_view value) { blob.m_buffer.copy_from(blob.m_offset, value); blob.m_offset += value.get_length(); return blob; } std::size_t size() const { return m_offset; } std::size_t capacity() const { return m_buffer.capacity(); } std::size_t remaining() const { return capacity() - size(); } void save_to_file(std::string const& path); private: friend class Serializing_blob; Buffer m_buffer; std::size_t m_offset{0}; }; class Serializing_blob { public: Serializing_blob() : m_filename(""), m_blob(0) { m_logger = get_default_logger("Serializing_blob"); } Serializing_blob(std::string const& filename, int buffer_size) : m_filename(filename), m_blob(buffer_size) { m_logger = get_default_logger("Serializing_blob"); } ~Serializing_blob() { store_and_reset(); } template <typename T> friend Serializing_blob& operator<<(Serializing_blob& blob, T value) { if (sizeof(T) > blob.m_blob.remaining()) { blob.store_and_reset(); } blob.m_blob << value; return blob; } friend Serializing_blob& operator<<( Serializing_blob& blob, Buffer_view value) { if (value.get_length() > blob.m_blob.remaining()) { blob.store_and_reset(); } if (value.get_length() > blob.m_blob.capacity()) { return blob; } blob.m_blob << value; return blob; } private: std::string m_filename; Blob m_blob; Logger_t m_logger; void store_and_reset(); }; } #endif
18.24031
72
0.59796
8cf761e17212d1d409221654d63143a971ae48f1
1,268
lua
Lua
op/glm-mhd-update-psi.lua
rumpie/warp-chris-moore
2b59483743603629de1796b197eb6cd0802000f4
[ "MIT" ]
null
null
null
op/glm-mhd-update-psi.lua
rumpie/warp-chris-moore
2b59483743603629de1796b197eb6cd0802000f4
[ "MIT" ]
null
null
null
op/glm-mhd-update-psi.lua
rumpie/warp-chris-moore
2b59483743603629de1796b197eb6cd0802000f4
[ "MIT" ]
null
null
null
local class = require 'ext.class' local template = require 'template' local ffi = require 'ffi' local GLM_MHD_UpdatePsi = class() function GLM_MHD_UpdatePsi:init(args) self.solver = assert(args.solver) end function GLM_MHD_UpdatePsi:getSolverCode() local solver = self.solver return template([[ kernel void updatePsi( constant <?=solver.solver_t?>* solver, global <?=eqn.cons_t?>* UBuf, real dt ) { SETBOUNDS(0,0); real3 x = cell_x(i); global <?=eqn.cons_t?>* U = UBuf + index; //TODO don't need the whole eigen here, just the Ch <? if not eqn.useFixedCh then ?> real Ch = 0; <? for side=0,solver.dim-1 do ?>{ <?=eqn.eigen_t?> eig = eigen_forCell_<?=side?>(solver, *U, x); Ch = max(Ch, eig.Ch); }<? end ?> <? end ?> U->psi *= exp(-dt * Ch * Ch / (Cp * Cp) * U->psi); } ]], { solver = solver, eqn = solver.eqn, }) end function GLM_MHD_UpdatePsi:refreshSolverProgram() local solver = self.solver self.updatePsiKernelObj = solver.solverProgramObj:kernel('updatePsi', solver.solverBuf, solver.UBuf) end local realptr = ffi.new'realparam[1]' local function real(x) realptr[0] = x return realptr end function GLM_MHD_UpdatePsi:step(dt) local dtArg = real(dt) self.updatePsiKernelObj.obj:setArg(2, dtArg) end return GLM_MHD_UpdatePsi
22.245614
101
0.694006
74ef8801715da4361ed81825b8ffcbf094e69a5a
1,235
css
CSS
HUTECH_HKK/Caro3/src/index.css
luonghieu184/OLP-FOSS-2019
10c7a87977b37ecd7cd5f7141d3863250fbee15b
[ "Apache-2.0" ]
null
null
null
HUTECH_HKK/Caro3/src/index.css
luonghieu184/OLP-FOSS-2019
10c7a87977b37ecd7cd5f7141d3863250fbee15b
[ "Apache-2.0" ]
13
2021-03-02T00:49:34.000Z
2022-03-03T22:58:35.000Z
HUTECH_HKK/Caro3/src/index.css
luonghieu184/OLP-FOSS-2019
10c7a87977b37ecd7cd5f7141d3863250fbee15b
[ "Apache-2.0" ]
7
2019-12-05T01:16:25.000Z
2020-11-30T06:52:33.000Z
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"); body { font: 14px "Century Gothic", Futura, sans-serif; margin: 20px; } ol, ul { padding-left: 30px; } .board-row:after { clear: both; content: ""; display: table; } .status { margin-bottom: 10px; } .square { background: #fff; border: 1px solid #999; float: left; font-size: 24px; line-height: 34px; height: 34px; margin-right: -1px; margin-top: -1px; padding: 0; text-align: center; width: 34px; } .square:focus { outline: none; } .kbd-navigation .square:focus { background: #ddd; } .game { padding: 50px; display: flex; flex-direction: row; } .game-board { margin: 0 auto; } .game-config { display: block; margin-bottom: 20px; } .fixed-size { width: 100px; display: inline-block; } .btn-bold { font-weight: bold; } .square-highlight { color: #00cd29; } .save-game-blockchain { margin-top: 10px; } .footer { position: fixed; display: block; width: 100%; background: rgb(197, 197, 197); text-align: center; bottom: 0; } button.btn { margin: 17px 0px; } button.btn.btn-info { margin: 10px 0; padding: 2px 11px; } button.btn { margin: 2px 0px !important; }
13.571429
85
0.636437
e7369e35e29aea102978f0761b24436a881e287f
839
php
PHP
resources/views/livewire/in-dev-modal.blade.php
Creekmore108/zp_front_end
88a46109a9adee4c8ba90ab0702fca388749ba97
[ "MIT" ]
null
null
null
resources/views/livewire/in-dev-modal.blade.php
Creekmore108/zp_front_end
88a46109a9adee4c8ba90ab0702fca388749ba97
[ "MIT" ]
null
null
null
resources/views/livewire/in-dev-modal.blade.php
Creekmore108/zp_front_end
88a46109a9adee4c8ba90ab0702fca388749ba97
[ "MIT" ]
null
null
null
<div> <x-modal wire:model="show"> <x-slot name="title"> <h1 class="text-lg font-bold text-center">We are still in Development</h1> </x-slot> <x-slot name="body"> <p>Refer to the "Contact Us" form or subscribe to our email list to be notified when we are production ready. </p> </x-slot> <x-slot name="footer"> <x-button @click="show = false" class="inline-flex justify-center py-2 px-4 shadow-sm text-sm font-medium rounded-md text-gray-900 bg-gradient-to-r from-yellow-600 to-yellow-800 hover:text-white hover:from-yellow-800 hover:to-yellow-600 focus:outline-none focus:ring-1 focus:ring-yellow-800 focus:border-yellow-600 "> Close </x-button> </x-slot> </x-modal> </div>
49.352941
333
0.584029
58fd69fc02652c836bc7d99d03c7bca8615b6668
6,272
css
CSS
public/css/iobio_style.css
iobio/homepage
89758fb440a9bece3c6212e6beb7713486c64456
[ "MIT" ]
null
null
null
public/css/iobio_style.css
iobio/homepage
89758fb440a9bece3c6212e6beb7713486c64456
[ "MIT" ]
2
2018-08-07T23:41:02.000Z
2019-03-20T17:52:18.000Z
public/css/iobio_style.css
iobio/homepage
89758fb440a9bece3c6212e6beb7713486c64456
[ "MIT" ]
null
null
null
.bg-primary{ background: #00c6ff !important; /* fallback for old browsers */ background: -webkit-linear-gradient(to right, #00c6ff, #0072ff) !important; /* Chrome 10-25, Safari 5.1-6 */ background: linear-gradient(to right, #00c6ff, #0072ff) !important; /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */ } .btn-app-primary { color: #fff; background-color: #04a1ff; border-color: #04a1ff; } .apps-subnav:hover{ color: #04a1ff !important } .avatar-headshot{ margin-bottom: -150px; margin-top: -50px; margin-right: 10px; border: 7px solid #fff; padding: 0; } .blog-card-snippet{ height: 205px; } .post-content p { text-align: left !important; line-height: 1.6 !important; } .post-content h2, .post-content .h2, .post-content h3, .post-content .h3 { margin-top: 40px; } .post-content img.shadow { margin-top: 50px; margin-bottom: 50px; box-shadow: 6px 11px 68px -7px rgba(0, 0, 0, 0.25) !important; } @media (min-width: 1200px){ .half-block { margin: auto; max-width: 1000px; } .container { max-width: 1140px !important; } } @media (min-width: 1400px){ .container { max-width: 1340px !important; } } .active.center { -webkit-filter: grayscale(0); /* Safari 6.0 - 9.0 */ filter: grayscale(0); filter: blur(0px); -webkit-filter: blur(0px); } .rounded{ height: 100px } .aside-link-term{ font-size: 1.1rem !important; font-weight: 500 !important; } #BeforeActiveSliderContent{ color: #0073ff; font-size: 26px; margin-top: 10px; font-weight: 600; /* text-shadow: 1px 1px 1px #797979; */ } #ActiveSliderContent{ width:600px; word-break: break-all; } .owl-carousel .owl-nav .owl-prev::before { /* content: "" !important; */ content: "<" !important; } .owl-carousel .owl-nav .owl-next::before { /* content: "" !important; */ content: ">" !important; } .btn-outline-light{ color: rgba(255, 255, 255, 0.75); border-color: rgba(255, 255, 255, 0.75); background-color: transparent; background-image: none; } .horizontal-underline { width:40px; border-bottom: 1px solid rgb(70,70,70); margin-left:auto;margin-right:auto } .navbar-nav .nav-link{ font-size: 1.01rem; font-weight: 600; } .blinking-cursor { font-weight: 400; font-size: 30px; color: #2E3D48; -webkit-animation: 1s blink step-end infinite; -moz-animation: 1s blink step-end infinite; -ms-animation: 1s blink step-end infinite; -o-animation: 1s blink step-end infinite; animation: 1s blink step-end infinite; } @keyframes "blink" { from, to { color: transparent; } 50% { color: black; } } @-moz-keyframes blink { from, to { color: transparent; } 50% { color: black; } } @-webkit-keyframes "blink" { from, to { color: transparent; } 50% { color: black; } } @-ms-keyframes "blink" { from, to { color: transparent; } 50% { color: black; } } @-o-keyframes "blink" { from, to { color: transparent; } 50% { color: black; } } .avatar-xl{ height: 225px !important; width: 225px !important; } .avatar-xs{ height: 25px !important; width: 25px !important; } .subscribeEmailBox{ width: 80% !important } @media only screen and (max-width: 807px) { .subscribeEmailBox { width: 100% !important } .subscribeEmailBoxButtonOne { width: 100% !important; margin-top: 10px !important; } } #footerSubscribeForm { margin-left:60px; } @media only screen and (max-width: 414px) { .footerSubscribbeBox { width: 100% !important } .footerSubscribbeBoxButton { width: 100% !important; margin-top: 10px !important; } #footerSubscribeForm { margin-left: 0; } } #notification-bar{ top:0; height:56px; position:fixed; background:white; width:100%; z-index:1500; padding:10px; box-shadow: 0 4px 2px -2px #d1d1d1eb; } #header-bar{ top: 0; } @media only screen and (max-width: 1000px) { #notification-bar { display: none !important; } #header-bar { top: 0 !important; } .navbar{ padding: 7px 9px 7px 10px !important } .navbar-brand{ font-size: 30px !important } } .sponsors-img{ width:200px; height:150px; /*Scale down will take the necessary specified space that is 100px x 100px without stretching the image*/ object-fit:scale-down; } /* * Developer page * */ #developer .section .section-title { color: rgb(100,100,100); font-size: 40px; text-align: left} #developer .section { font-size: 15px; text-align: justify;} #developer .section .library { margin-top: 20px; padding-left: 30px;} #developer .section .library-title { font-size: 25px;} #developer .sub-section { margin: 20px 0px 0px 20px;} #developer .sub-section .section-title { font-size:20px; text-decoration: underline;} #developer ul#visualizations { font-size:8px; padding: 0; list-style-type: none; } #developer ul#visualizations li { display:inline-block; margin-left: 60px; margin-top: 20px;} #developer ul#visualizations .viz-title { text-align: center; font-size: 20px; font-family: 'Open Sans';} #developer ul#visualizations rect { fill: rgba(120,176,194,0.5) } #developer ul#visualizations .alignment polygon { fill: rgba(120,176,194,0.5) } #developer ul#visualizations .cds rect { fill: rgba(120,176,194,0.5); stroke: rgb(120,176,194);} #developer ul#visualizations .utr rect { fill: rgba(120,176,194,0.5); stroke: rgb(120,176,194);} #developer ul#visualizations .glyphicon { font-size: 15px;} #developer ul#visualizations a { text-decoration: none; color: rgb(110,110,110);} #developer ul#visualizations a:hover { text-decoration: none; color: rgb(70,70,70);} #alignment-viz .iobio-alignment polygon { fill: rgb(120,176,194); } .iobio-gene .utr rect { fill: rgba(120,176,194,0.6); stroke: rgb(120,176,194); } .iobio-gene .cds rect { fill: rgba(120,176,194,0.6); stroke: rgb(120,176,194); } #piechooser-viz { text-align: center; } #piechooser-viz .iobio-pie .iobio-percent { font-size: 20px;} #piechooser-viz .iobio-pie .iobio-count { font-size: 12px;} #piechooser-viz .arc text { fill: white; font-size: 10px; font-weight: normal; } #piechooser-viz circle#all-circle:hover { fill: #F7F3BA;} #piechooser-viz circle#all-circle.selected { fill: #F7F3BA; stroke-width: 1.5px;}
21.627586
140
0.664381
bf81a1871380c2423711f4937f4b3344e43938a9
2,153
rb
Ruby
lib/recurly/xml.rb
ivanovv/recurly-client-ruby
639a64e61d13af686bc3c6b9b0c0eb0e8390b84f
[ "MIT", "Unlicense" ]
null
null
null
lib/recurly/xml.rb
ivanovv/recurly-client-ruby
639a64e61d13af686bc3c6b9b0c0eb0e8390b84f
[ "MIT", "Unlicense" ]
3
2021-05-20T23:06:15.000Z
2022-02-26T10:22:56.000Z
lib/recurly/xml.rb
ivanovv/recurly-client-ruby
639a64e61d13af686bc3c6b9b0c0eb0e8390b84f
[ "MIT", "Unlicense" ]
null
null
null
module Recurly class XML class << self def cast el return if el.attribute 'nil' if el.attribute 'type' type = el.attribute('type').value end case type when 'array' then el.elements.map { |e| XML.cast e } when 'boolean' then el.text == 'true' when 'date' then Date.parse el.text when 'datetime' then DateTime.parse el.text when 'float' then el.text.to_f when 'integer' then el.text.to_i else # FIXME: Move some of this logic to Resource.from_xml? [el.name, type].each do |name| next unless name resource_name = Helper.classify name if Recurly.const_defined? resource_name, false return Recurly.const_get(resource_name, false).from_xml el end end if el.elements.empty? el.text else Hash[el.elements.map { |e| [e.name, XML.cast(e)] }] end end end def filter text xml = XML.new text xml.each do |el| el = XML.new el case el.name when "number" text = el.text.to_s last = text[-4, 4] el.text = "#{text[0, text.length - 4].to_s.gsub(/\d/, '*')}#{last}" when "verification_value" el.text = el.text.to_s.gsub(/\d/, '*') end end xml.to_s end end attr_reader :root def initialize xml @root = xml.is_a?(String) ? super : xml end # Adds an element to the root. def add_element name, value = nil value = value.respond_to?(:xmlschema) ? value.xmlschema : value.to_s XML.new super(name, value) end # Iterates over the root's elements. def each_element xpath = nil return enum_for :each_element unless block_given? super end # Returns the root's name. def name super end # Returns an XML string. def to_s super end end end if defined? Nokogiri require 'recurly/xml/nokogiri' else require 'recurly/xml/rexml' end
24.747126
79
0.544821
b36c8a97fb7c15fe393804e7d445e8c6d76aec26
3,421
py
Python
poco/drivers/cocosjs/__init__.py
kaluluosi/Poco
6874cd45ef843f5e90872e22bae41233bbaf4462
[ "Apache-2.0" ]
1,444
2018-01-24T03:27:52.000Z
2022-03-31T07:40:57.000Z
poco/drivers/cocosjs/__init__.py
kaluluosi/Poco
6874cd45ef843f5e90872e22bae41233bbaf4462
[ "Apache-2.0" ]
524
2018-03-14T01:08:06.000Z
2022-03-31T08:21:52.000Z
poco/drivers/cocosjs/__init__.py
kaluluosi/Poco
6874cd45ef843f5e90872e22bae41233bbaf4462
[ "Apache-2.0" ]
268
2018-01-25T03:58:33.000Z
2022-03-24T08:18:59.000Z
# -*- coding: utf-8 -*- # @Author: gzliuxin # @Email: [email protected] # @Date: 2017-07-14 19:47:51 from poco.pocofw import Poco from poco.agent import PocoAgent from poco.freezeui.hierarchy import FrozenUIHierarchy, FrozenUIDumper from poco.utils.simplerpc.utils import sync_wrapper from poco.utils.airtest import AirtestInput, AirtestScreen from poco.utils.simplerpc.rpcclient import RpcClient from poco.utils.simplerpc.transport.ws import WebSocketClient from poco.utils import six if six.PY3: from urllib.parse import urlparse else: from urlparse import urlparse from airtest.core.api import connect_device, device as current_device from airtest.core.helper import device_platform __all__ = ['CocosJsPoco'] DEFAULT_PORT = 5003 DEFAULT_ADDR = ('localhost', DEFAULT_PORT) class CocosJsPocoAgent(PocoAgent): def __init__(self, port, device=None): self.device = device or current_device() if not self.device: self.device = connect_device("Android:///") platform_name = device_platform(self.device) if platform_name == 'Android': local_port, _ = self.device.adb.setup_forward('tcp:{}'.format(port)) ip = self.device.adb.host or 'localhost' port = local_port elif platform_name == 'IOS': # Note: ios is now support for now. # ip = device.get_ip_address() # use iproxy first ip = 'localhost' local_port, _ = self.device.instruct_helper.setup_proxy(port) port = local_port else: ip = self.device.get_ip_address() # transport self.conn = WebSocketClient('ws://{}:{}'.format(ip, port)) self.c = RpcClient(self.conn) self.c.connect() hierarchy = FrozenUIHierarchy(Dumper(self.c)) screen = AirtestScreen() inputs = AirtestInput() super(CocosJsPocoAgent, self).__init__(hierarchy, inputs, screen, None) @property def rpc(self): return self.c def get_sdk_version(self): return self.rpc.call("getSDKVersion") class Dumper(FrozenUIDumper): def __init__(self, rpcclient): super(Dumper, self).__init__() self.rpcclient = rpcclient @sync_wrapper def dumpHierarchy(self, onlyVisibleNode=True): # NOTE: cocosjs 的driver里,这个rpc方法名首字母是小写,特别注意! return self.rpcclient.call("dump", onlyVisibleNode) class CocosJsPoco(Poco): """docstring for CocosJsPoco""" def __init__(self, addr=DEFAULT_ADDR, device=None, **options): if not isinstance(addr, (tuple, list, six.string_types)): raise TypeError('Argument "addr" should be `tuple[2]`, `list[2]` or `string` only. Got {}' .format(type(addr))) try: if isinstance(addr, (list, tuple)): ip, port = addr else: port = urlparse(addr).port if not port: raise ValueError except ValueError: raise ValueError('Argument "addr" should be a tuple[2] or string format. e.g. ' '["localhost", 5003] or "ws://localhost:5003". Got {}'.format(repr(addr))) agent = CocosJsPocoAgent(port, device) if 'action_interval' not in options: options['action_interval'] = 0.5 super(CocosJsPoco, self).__init__(agent, **options)
33.871287
103
0.63461
f4ba7fc0203eb760889abdfa78a8f449c39177c7
6,095
ts
TypeScript
src/app/app.component.ts
ashbeelghouri/slideshow-angular
0cedadc758591e692e2edaba45d162eb24f60153
[ "MIT" ]
null
null
null
src/app/app.component.ts
ashbeelghouri/slideshow-angular
0cedadc758591e692e2edaba45d162eb24f60153
[ "MIT" ]
null
null
null
src/app/app.component.ts
ashbeelghouri/slideshow-angular
0cedadc758591e692e2edaba45d162eb24f60153
[ "MIT" ]
null
null
null
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { currentpage = 0; mySlideshow: any; slideTime = 2000; play = false; images = [ { title: "At the beach", url: "https://images.unsplash.com/photo-1468413253725-0d5181091126?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MjR8fGJlYWNofGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Fighting Bulls", url: "https://images.unsplash.com/photo-1595293842982-951cf26e7b6c?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=751&q=80" }, { title: "Expensive Rings", url: "https://images.unsplash.com/photo-1558446757-426e7886ed28?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTN8fGV4cGVuc2l2ZXxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Some spilled coffee", url: "https://images.unsplash.com/photo-1459755486867-b55449bb39ff?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTZ8fGNvZmZlZXxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Isn't it best bird?", url: "https://images.unsplash.com/photo-1511876484235-b5246a4d6dd5?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTB8fGJpcmRzfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Feel the adventure", url: "https://images.unsplash.com/photo-1515552726023-7125c8d07fb3?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NHx8YWR2ZW50dXJlfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Keep me green or I won't be seen", url: "https://images.unsplash.com/photo-1498925008800-019c7d59d903?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8ZW52aXJvbm1lbnR8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Happiness", url: "https://images.unsplash.com/photo-1533227268428-f9ed0900fb3b?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mnx8aGFwcHl8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Code Fast, Learn Mistakes", url: "https://images.unsplash.com/photo-1498050108023-c5249f4df085?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxzZWFyY2h8MXx8Y29kaW5nfGVufDB8fDB8&auto=format&fit=crop&w=500&q=60" }, { title: "Gold is ricketting rich", url: "https://images.unsplash.com/photo-1498721425774-488298864da7?ixid=MXwxMjA3fDB8MHxzZWFyY2h8OHx8Z29sZHxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Dance like you are a knight", url: "https://images.unsplash.com/photo-1581417478175-a9ef18f210c2?ixid=MXwxMjA3fDB8MHxzZWFyY2h8M3x8Y2x1YnxlbnwwfHwwfA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Loyalty is the royalty", url: "https://images.unsplash.com/photo-1587300003388-59208cc962cb?ixid=MXwxMjA3fDB8MHxzZWFyY2h8NXx8ZG9nfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Yeah! I can fly", url: "https://images.unsplash.com/photo-1554234362-59a913f24b78?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MjV8fGtpdGVzfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "In search of perfect", url: "https://images.unsplash.com/photo-1452421822248-d4c2b47f0c81?ixid=MXwxMjA3fDB8MHxzZWFyY2h8N3x8YWR2ZW50dXJlfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Black, All day long", url: "https://images.unsplash.com/photo-1494698853255-d0fa521abc6c?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTJ8fGFwcGxlfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Simply Berries", url: "https://images.unsplash.com/photo-1563746098251-d35aef196e83?ixid=MXwxMjA3fDB8MHxzZWFyY2h8M3x8ZnJ1aXRzfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Yellow, yes the bees", url: "https://images.unsplash.com/photo-1441633980922-d18ca151ee64?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTd8fGhvbmV5fGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Jarred, I am candy", url: "https://images.unsplash.com/photo-1519687079572-8a59631f3685?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTJ8fGNhbmRpZXN8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Sleeplessness", url: "https://images.unsplash.com/photo-1561036269-89d6ffdee89b?ixid=MXwxMjA3fDB8MHxzZWFyY2h8N3x8c2xlZXBsZXNzfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "Believe in me, I won't control you", url: "https://images.unsplash.com/photo-1485827404703-89b55fcc595e?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MTB8fHRlY2hub2xvZ3l8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" }, { title: "The World", url: "https://images.unsplash.com/photo-1526778548025-fa2f459cd5c1?ixid=MXwxMjA3fDB8MHxzZWFyY2h8M3x8d29ybGR8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60" } ]; constructor() { this.slideshow(); } stopSlider() { clearInterval(this.mySlideshow); } slideshowToggle(val: any = undefined) { if (!val) { this.play = !this.play; } else { this.play = val; } this.slideshow(); } slideshow() { console.log("play", this.play); this.stopSlider(); if (this.play) { this.playSlideShow(); } } playSlideShow() { let self = this; this.mySlideshow = setInterval(function () { if (self.images && self.currentpage < self.images.length - 1) { self.currentpage += 1; } else { self.currentpage = 0; } }, self.slideTime); } checkWindowIndex(i: number) { var showPages = 4; if (this.currentpage == 0) { showPages = 6; } if (this.currentpage == 1) { showPages = 5; } if (this.currentpage == 2) { showPages = 4; } return Math.abs(this.currentpage - i) < showPages; } setSliderTime(time: number) { this.slideTime = time; this.slideshow(); } }
37.857143
184
0.688433
e101324798fde32cfe8326194f5da47bb1db8705
6,909
go
Go
pkg/acceptance/util_cluster.go
gmsecrieru/cockroach
1519cdadbac46b302c06f88d5d178368e94d8937
[ "MIT", "BSD-3-Clause" ]
null
null
null
pkg/acceptance/util_cluster.go
gmsecrieru/cockroach
1519cdadbac46b302c06f88d5d178368e94d8937
[ "MIT", "BSD-3-Clause" ]
null
null
null
pkg/acceptance/util_cluster.go
gmsecrieru/cockroach
1519cdadbac46b302c06f88d5d178368e94d8937
[ "MIT", "BSD-3-Clause" ]
1
2020-09-02T04:52:55.000Z
2020-09-02T04:52:55.000Z
// Copyright 2015 The Cockroach Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. package acceptance import ( "context" "io/ioutil" "os" "path/filepath" "regexp" "strings" "testing" "time" "github.com/cockroachdb/cockroach/pkg/acceptance/cluster" "github.com/cockroachdb/cockroach/pkg/acceptance/localcluster" "github.com/cockroachdb/cockroach/pkg/testutils" "github.com/cockroachdb/cockroach/pkg/util/binfetcher" "github.com/cockroachdb/cockroach/pkg/util/log" "github.com/pkg/errors" ) const ( localTest = "runMode=local" dockerTest = "runMode=docker" ) // RunLocal runs the given acceptance test using a bare cluster. func RunLocal(t *testing.T, testee func(t *testing.T)) { t.Run(localTest, testee) } // RunDocker runs the given acceptance test using a Docker cluster. func RunDocker(t *testing.T, testee func(t *testing.T)) { t.Run(dockerTest, testee) } // turns someTest#123 into someTest when invoked with ReplicaAllLiteralString. // This is useful because the go test harness automatically disambiguates // subtests in that way when they are invoked multiple times with the same name, // and we sometimes call RunDocker multiple times in tests. var reStripTestEnumeration = regexp.MustCompile(`#\d+$`) // runTestWithCluster runs the passed in test against the configuration // specified by the flags. If any options are specified, they may mutate the // test config before it runs. func runTestWithCluster( t *testing.T, testFunc func(context.Context, *testing.T, cluster.Cluster, cluster.TestConfig), options ...func(*cluster.TestConfig), ) { cfg := readConfigFromFlags() ctx := context.Background() for _, opt := range options { opt(&cfg) } cluster := StartCluster(ctx, t, cfg) log.Infof(ctx, "cluster started successfully") defer cluster.AssertAndStop(ctx, t) testFunc(ctx, t, cluster, cfg) } // StartCluster starts a cluster from the relevant flags. All test clusters // should be created through this command since it sets up the logging in a // unified way. func StartCluster(ctx context.Context, t *testing.T, cfg cluster.TestConfig) (c cluster.Cluster) { var completed bool defer func() { if !completed && c != nil { c.AssertAndStop(ctx, t) } }() parts := strings.Split(t.Name(), "/") if len(parts) < 2 { t.Fatal("must invoke RunLocal or RunDocker") } var runMode string for _, part := range parts[1:] { part = reStripTestEnumeration.ReplaceAllLiteralString(part, "") switch part { case localTest: fallthrough case dockerTest: if runMode != "" { t.Fatalf("test has more than one run mode: %s and %s", runMode, part) } runMode = part } } switch runMode { case localTest: pwd, err := os.Getwd() if err != nil { t.Fatal(err) } dataDir, err := ioutil.TempDir(pwd, ".localcluster") if err != nil { t.Fatal(err) } logDir := *flagLogDir if logDir != "" { logDir = filepath.Join(logDir, filepath.Clean(t.Name())) } perNodeCfg := localcluster.MakePerNodeFixedPortsCfg(len(cfg.Nodes)) for i := 0; i < len(cfg.Nodes); i++ { // TODO(tschottdorf): handle Nodes[i].Stores properly. if cfg.Nodes[i].Version != "" { nCfg := perNodeCfg[i] nCfg.Binary = GetBinary(ctx, t, cfg.Nodes[i].Version) perNodeCfg[i] = nCfg } } clusterCfg := localcluster.ClusterConfig{ Ephemeral: true, DataDir: dataDir, LogDir: logDir, NumNodes: len(cfg.Nodes), PerNodeCfg: perNodeCfg, } l := localcluster.New(clusterCfg) l.Start(ctx) c = &localcluster.LocalCluster{Cluster: l} case dockerTest: logDir := *flagLogDir if logDir != "" { logDir = filepath.Join(logDir, filepath.Clean(t.Name())) } l := cluster.CreateDocker(ctx, cfg, logDir, stopper) l.Start(ctx) c = l default: t.Fatalf("unable to run in mode %q, use either RunLocal or RunDocker", runMode) } // Don't wait for replication unless requested (usually it is). if !cfg.NoWait && cfg.InitMode != cluster.INIT_NONE { wantedReplicas := 3 if numNodes := c.NumNodes(); numNodes < wantedReplicas { wantedReplicas = numNodes } // Looks silly, but we actually start zero-node clusters in the // reference tests. if wantedReplicas > 0 { log.Infof(ctx, "waiting for first range to have %d replicas", wantedReplicas) testutils.SucceedsSoon(t, func() error { select { case <-stopper.ShouldStop(): t.Fatal("interrupted") case <-time.After(time.Second): } // Always talk to node 0 because it's guaranteed to exist. db, err := c.NewDB(ctx, 0) if err != nil { t.Fatal(err) } rows, err := db.Query(`SELECT array_length(replicas, 1) FROM crdb_internal.ranges LIMIT 1`) if err != nil { // Versions <= 1.1 do not contain the crdb_internal table, which is what's used // to determine whether a cluster has up-replicated. This is relevant for the // version upgrade acceptance test. Just skip the replication check for this case. if testutils.IsError(err, "(table|relation) \"crdb_internal.ranges\" does not exist") { return nil } t.Fatal(err) } defer rows.Close() var foundReplicas int if rows.Next() { if err = rows.Scan(&foundReplicas); err != nil { t.Fatalf("unable to scan for length of replicas array: %s", err) } if log.V(1) { log.Infof(ctx, "found %d replicas", foundReplicas) } } else { return errors.Errorf("no ranges listed") } if foundReplicas < wantedReplicas { return errors.Errorf("expected %d replicas, only found %d", wantedReplicas, foundReplicas) } return nil }) } // Ensure that all nodes are serving SQL by making sure a simple // read-only query succeeds. for i := 0; i < c.NumNodes(); i++ { testutils.SucceedsSoon(t, func() error { db, err := c.NewDB(ctx, i) if err != nil { return err } if _, err := db.Exec("SHOW DATABASES"); err != nil { return err } return nil }) } } completed = true return c } // GetBinary retrieves a binary for the specified version and returns it. func GetBinary(ctx context.Context, t *testing.T, version string) string { t.Helper() bin, err := binfetcher.Download(ctx, binfetcher.Options{ Binary: "cockroach", Dir: ".localcluster_cache", Version: version, }) if err != nil { t.Fatalf("unable to set up binary for v%s: %s", version, err) } return bin }
28.2
98
0.680272
38b410f5a25070c674519109d818d521b9f3c41c
2,942
php
PHP
application/libraries/template.php
dianadipratama1/ci3-siskep
32f865e775daa5266c612fcab7993f36d42437c8
[ "MIT" ]
null
null
null
application/libraries/template.php
dianadipratama1/ci3-siskep
32f865e775daa5266c612fcab7993f36d42437c8
[ "MIT" ]
null
null
null
application/libraries/template.php
dianadipratama1/ci3-siskep
32f865e775daa5266c612fcab7993f36d42437c8
[ "MIT" ]
null
null
null
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ class Template { protected $_ci; function __construct() { $this->_ci = &get_instance(); } function displayutama($template=NULL, $data = NULL) { if($template!=NULL) $data['_content'] = $this->_ci->load->view($template, $data, TRUE); $data['_header'] = $this->_ci->load->view('template_backend/header', $data, TRUE); $data['_footer'] = $this->_ci->load->view('template_backend/footer', $data, TRUE); $data['_menu'] = $this->_ci->load->view('template_backend/menuutama', $data, TRUE); $data['_sidebar'] = $this->_ci->load->view('template_backend/templateutama', $data); } function display($template=NULL, $data = NULL) { if($template!=NULL) $data['_content'] = $this->_ci->load->view($template, $data, TRUE); $data['_header'] = $this->_ci->load->view('template_backend/header', $data, TRUE); $data['_footer'] = $this->_ci->load->view('template_backend/footer', $data, TRUE); $data['_menu'] = $this->_ci->load->view('template_backend/menu', $data, TRUE); $data['_sidebar'] = $this->_ci->load->view('template_backend/template', $data); } function displaysetting($template=NULL, $data = NULL) { if($template!=NULL) $data['_content'] = $this->_ci->load->view($template, $data, TRUE); $data['_header'] = $this->_ci->load->view('template_backend/header', $data, TRUE); $data['_footer'] = $this->_ci->load->view('template_backend/footer', $data, TRUE); $data['_menu'] = $this->_ci->load->view('template_backend/menusetting', $data, TRUE); $data['_sidebar'] = $this->_ci->load->view('template_backend/template', $data); } function displaypayroll($template=NULL, $data = NULL) { if($template!=NULL) $data['_content'] = $this->_ci->load->view($template, $data, TRUE); $data['_header'] = $this->_ci->load->view('template_backend/header', $data, TRUE); $data['_footer'] = $this->_ci->load->view('template_backend/footer', $data, TRUE); $data['_menu'] = $this->_ci->load->view('template_backend/menupayroll', $data, TRUE); $data['_sidebar'] = $this->_ci->load->view('template_backend/template', $data); } function front($template, $data = NULL) { $data['_content'] = $this->_ci->load->view($template, $data, TRUE); // $data['_content'] = $this->_ci->load->view($template, $data, TRUE); // $data['_header'] = $this->_ci->load->view('template_frontend/header', $data, TRUE); // $data['_footer'] = $this->_ci->load->view('template_frontend/footer', $data, TRUE); // $data['_menu'] = $this->_ci->load->view('template_frontend/menu', $data, TRUE); $data['_sidebar'] = $this->_ci->load->view('template_frontend/template', $data); } } ?>
44.575758
93
0.598232
5480923c4a37a72a0efe8c4ce844ee01cedff96d
1,090
rb
Ruby
app/abilities/lecture_ability.rb
fosterfarrell9/mampf
16443c46db74180e128b16b77aebb1a399b84d94
[ "MIT" ]
20
2017-10-25T08:06:47.000Z
2020-07-25T22:18:11.000Z
app/abilities/lecture_ability.rb
fosterfarrell9/mampf
16443c46db74180e128b16b77aebb1a399b84d94
[ "MIT" ]
59
2017-10-12T16:31:30.000Z
2020-10-07T11:46:45.000Z
app/abilities/lecture_ability.rb
fosterfarrell9/mampf
16443c46db74180e128b16b77aebb1a399b84d94
[ "MIT" ]
8
2019-07-08T10:16:20.000Z
2020-09-14T16:08:36.000Z
class LectureAbility include CanCan::Ability def initialize(user) clear_aliased_actions can :new, Lecture do user.course_editor? end can :create, Lecture do |lecture| user.can_edit?(lecture.course) end can [:edit, :update, :update_teacher, :update_editors, :destroy, :add_forum, :publish, :lock_forum, :unlock_forum, :destroy_forum, :import_media, :remove_imported_medium, :show_subscribers, :import_toc, :edit_structures, :close_comments, :open_comments], Lecture do |lecture| user.can_edit?(lecture) end # there is a redirect to the subscription page inside the controller # if the lecture is not a subscribed lecture of the user can :show, Lecture can :search, Lecture can [:show_announcements, :organizational, :show_structures, :search_examples, :show_random_quizzes, :display_course], Lecture do |lecture| lecture.in?(user.lectures) end can :subscribe_page, Lecture do |lecture| lecture.published? || !user.generic? end end end
27.948718
80
0.679817
54179c993d404376b65bdae146a29180d2f5c984
735
css
CSS
prepojenia/client/src/components/Navigation.css
mirecmrozek/verejne.digital
8aed7311d75b6d15c8c4b5bbbf0d15ade3ce031a
[ "Apache-2.0" ]
null
null
null
prepojenia/client/src/components/Navigation.css
mirecmrozek/verejne.digital
8aed7311d75b6d15c8c4b5bbbf0d15ade3ce031a
[ "Apache-2.0" ]
213
2018-04-23T12:49:38.000Z
2019-02-28T09:55:07.000Z
prepojenia/client/src/components/Navigation.css
mirecmrozek/verejne.digital
8aed7311d75b6d15c8c4b5bbbf0d15ade3ce031a
[ "Apache-2.0" ]
1
2018-08-03T11:13:04.000Z
2018-08-03T11:13:04.000Z
.sidebarnav { align-self: flex-start; width: 100%; margin-bottom: auto; } .navbar-header { float: none; background-color: inherit; } .navbar-toggle { display: block; margin-right: 0; } .navbar-brand { padding-left: 0; padding-right: 10px; font-family: 'Source Code Pro', monospace; color: #333333; font-size: 14px; font-weight: 400; text-align: left; } .bolder { font-weight: 700; } .navbar-brand:hover { color: #333333; } .navbar-collapse.collapse { display: none!important; } .navbar-nav { float: none!important; } .navbar-nav > li { float: none; } .navbar-collapse.collapse.in{ display: block !important; } .icon-bar { background-color: #cddae3; width: 24px; height: 4px; }
13.125
44
0.64898
7762ba6506b2bc443d9c49e78488f43ded6d20ef
239
dart
Dart
lib/src/category.dart
Jack-G-Smith/foursquare-dart
748e45e1d535d70bde8b1b2c699045bb8b03015a
[ "MIT" ]
null
null
null
lib/src/category.dart
Jack-G-Smith/foursquare-dart
748e45e1d535d70bde8b1b2c699045bb8b03015a
[ "MIT" ]
null
null
null
lib/src/category.dart
Jack-G-Smith/foursquare-dart
748e45e1d535d70bde8b1b2c699045bb8b03015a
[ "MIT" ]
null
null
null
class Category { Category({this.categoryId, this.name}); final String? categoryId; final String? name; factory Category.fromJson(Map<String, dynamic> json) { return Category(categoryId: json['id'], name: json['name']); } }
21.727273
64
0.686192
8a6cdede775876d04982c215c7881096e8e0a11b
965
sql
SQL
src/main/resources/db/migration/sqlserver/V1.0.1.3__conceptset_generation_info.sql
mav7014/WebAPI
22c8ee269ba9729038ffe5baabef0425a5fe897e
[ "Apache-2.0" ]
14
2018-03-27T01:19:16.000Z
2019-12-04T06:20:03.000Z
src/main/resources/db/migration/sqlserver/V1.0.1.3__conceptset_generation_info.sql
mav7014/WebAPI
22c8ee269ba9729038ffe5baabef0425a5fe897e
[ "Apache-2.0" ]
3
2017-06-13T15:51:07.000Z
2017-06-13T15:58:23.000Z
src/main/resources/db/migration/sqlserver/V1.0.1.3__conceptset_generation_info.sql
mav7014/WebAPI
22c8ee269ba9729038ffe5baabef0425a5fe897e
[ "Apache-2.0" ]
4
2019-02-04T23:20:08.000Z
2019-12-09T19:33:33.000Z
IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'concept_set' AND TABLE_SCHEMA ='dbo' )) BEGIN ALTER TABLE [${ohdsiSchema}].[concept_set] ADD CONSTRAINT [PK_concept_set] PRIMARY KEY CLUSTERED ( [concept_set_id] ASC ) END ; CREATE TABLE [${ohdsiSchema}].[concept_set_generation_info]( [concept_set_id] INT NOT NULL, [source_id] INT NOT NULL, [generation_type] INT NOT NULL, [start_time] DATETIME NOT NULL, [execution_duration] INT NULL, [status] INT NOT NULL, [is_valid] INT NOT NULL, CONSTRAINT [PK_concept_set_generation_info] PRIMARY KEY CLUSTERED ( [concept_set_id] ASC, [source_id] ASC ), CONSTRAINT [FK_concept_set_generation_info_concept_set] FOREIGN KEY([concept_set_id]) REFERENCES [${ohdsiSchema}].[concept_set] ([concept_set_id]) ON UPDATE CASCADE ON DELETE CASCADE ) ON [PRIMARY] ;
33.275862
110
0.705699
2faff3758198e47eb0efab51b5ceb7515ba56700
1,345
py
Python
sync_repo.py
ewhitesides/pulp_operations
b6a3541559e48c717926b245bbbf2dd87638e093
[ "MIT" ]
null
null
null
sync_repo.py
ewhitesides/pulp_operations
b6a3541559e48c717926b245bbbf2dd87638e093
[ "MIT" ]
1
2021-06-17T04:35:05.000Z
2021-06-17T04:35:05.000Z
sync_repo.py
ewhitesides/pulp_operations
b6a3541559e48c717926b245bbbf2dd87638e093
[ "MIT" ]
null
null
null
""" script to sync repos from repo_data.py """ import urllib3 import pulp_operations from repo_data import repo_data #disable ssl warnings for now urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) #sync items from repo_data for os in repo_data: for repo in repo_data[os]: for source_name, source_url in repo_data[os][repo].items(): #try syncing repo_name = f"{os}-{repo}" remote_name = f"{os}-{repo}-{source_name}" remote_url = source_url pulp_operations.sync(repo_name, remote_name, remote_url) #if particular source fails, continue to next one except Exception: continue #optional example for use with a configured signing service # SIGNSERVICE_NAME = 'sign-metadata' # for os in repo_data: # for repo in repo_data[os]: # for source_name, source_url in repo_data[os][repo].items(): # #try syncing # repo_name = f"{os}-{repo}" # remote_name = f"{os}-{repo}-{source_name}" # remote_url = source_url # pulp_operations.sync(repo_name, remote_name, remote_url, SIGNSERVICE_NAME) # #if particular source fails, continue to next one # except Exception: # continue
32.02381
88
0.620074
9666df7c72388267b6004901f7b19d422d6ab13e
9,611
sql
SQL
sql/script.sql
vito-royeca/speedtester
7e783b58f96f412b1226db25c29ee3b31bbc11ca
[ "BSD-3-Clause" ]
null
null
null
sql/script.sql
vito-royeca/speedtester
7e783b58f96f412b1226db25c29ee3b31bbc11ca
[ "BSD-3-Clause" ]
null
null
null
sql/script.sql
vito-royeca/speedtester
7e783b58f96f412b1226db25c29ee3b31bbc11ca
[ "BSD-3-Clause" ]
null
null
null
-- -- PostgreSQL database dump -- -- Dumped from database version 12.8 -- Dumped by pg_dump version 13.3 SET statement_timeout = 0; SET lock_timeout = 0; SET idle_in_transaction_session_timeout = 0; SET client_encoding = 'UTF8'; SET standard_conforming_strings = on; SELECT pg_catalog.set_config('search_path', '', false); SET check_function_bodies = false; SET xmloption = content; SET client_min_messages = warning; SET row_security = off; -- -- Name: speedtest(json); Type: FUNCTION; Schema: public; Owner: speedtest -- CREATE FUNCTION public.speedtest(json) RETURNS void LANGUAGE plpgsql AS $_$ DECLARE _json ALIAS FOR $1; server_id bigint; client_id integer; BEGIN --server SELECT id INTO server_id FROM server WHERE id = (_json->'server' ->> 'id')::bigint; IF NOT FOUND THEN INSERT INTO server( id, url, lat, lon, name, country, cc, sponsor, host, d, latency) VALUES( (_json->'server' ->> 'id')::bigint, (_json->'server' ->> 'url')::character varying, (_json->'server' ->> 'lat')::double precision, (_json->'server' ->> 'lon')::double precision, (_json->'server' ->> 'name')::character varying, (_json->'server' ->> 'country')::character varying, (_json->'server' ->> 'cc')::character varying, (_json->'server' ->> 'sponsor')::character varying, (_json->'server' ->> 'host')::character varying, (_json->'server' ->> 'd')::double precision, (_json->'server' ->> 'latency')::double precision); SELECT id INTO server_id FROM server WHERE id = (_json->'server' ->> 'id')::bigint; ELSE UPDATE server SET url = (_json->'server' ->> 'url')::character varying, lat = (_json->'server' ->> 'lat')::double precision, lon = (_json->'server' ->> 'lon')::double precision, name = (_json->'server' ->> 'name')::character varying, country = (_json->'server' ->> 'country')::character varying, cc = (_json->'server' ->> 'cc')::character varying, sponsor = (_json->'server' ->> 'sponsor')::character varying, host = (_json->'server' ->> 'host')::character varying, d = (_json->'server' ->> 'd')::double precision, latency = (_json->'server' ->> 'latency')::double precision, date_updated = now() WHERE id = server_id; END IF; -- client SELECT id INTO client_id FROM client WHERE isp = _json->'client' ->> 'isp' AND country = _json->'client' ->> 'country'; IF NOT FOUND THEN INSERT INTO client( id, ip, lat, lon, isp, country) VALUES( nextval('client_id_seq'), (_json->'client' ->> 'ip')::inet, (_json->'client' ->> 'lat')::double precision, (_json->'client' ->> 'lon')::double precision, (_json->'client' ->> 'isp')::character varying, (_json->'client' ->> 'country')::character varying); SELECT id INTO client_id FROM client WHERE isp = _json->'client' ->> 'isp' AND country = _json->'client' ->> 'country'; ELSE UPDATE client SET ip = (_json->'client' ->> 'ip')::inet, lat = (_json->'client' ->> 'lat')::double precision, lon = (_json->'client' ->> 'lon')::double precision, isp = (_json->'client' ->> 'isp')::character varying, country = (_json->'client' ->> 'country')::character varying, date_updated = now() WHERE id = client_id; END IF; -- speedtest INSERT INTO speedtest( id, server, client, download, upload, ping, bytes_sent, bytes_received) VALUES( nextval('speedtest_id_seq'), server_id, client_id, (_json->>'download')::double precision, (_json->>'upload')::double precision, (_json->>'ping')::double precision, (_json->>'bytes_sent')::bigint, (_json->>'bytes_received')::bigint); END; $_$; ALTER FUNCTION public.speedtest(json) OWNER TO speedtest; SET default_tablespace = ''; SET default_table_access_method = heap; -- -- Name: client; Type: TABLE; Schema: public; Owner: speedtest -- CREATE TABLE public.client ( id integer NOT NULL, ip inet, lat double precision, lon double precision, isp character varying, country character varying, date_added timestamp with time zone DEFAULT now(), date_updated timestamp with time zone DEFAULT now() ); ALTER TABLE public.client OWNER TO speedtest; -- -- Name: client_id_seq; Type: SEQUENCE; Schema: public; Owner: speedtest -- CREATE SEQUENCE public.client_id_seq AS integer START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.client_id_seq OWNER TO speedtest; -- -- Name: client_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: speedtest -- ALTER SEQUENCE public.client_id_seq OWNED BY public.client.id; -- -- Name: server; Type: TABLE; Schema: public; Owner: speedtest -- CREATE TABLE public.server ( id bigint NOT NULL, url character varying, lat double precision, lon double precision, name character varying, country character varying, cc character varying, sponsor character varying, host character varying, d double precision, latency double precision, date_added timestamp with time zone DEFAULT now(), date_updated timestamp with time zone DEFAULT now() ); ALTER TABLE public.server OWNER TO speedtest; -- -- Name: speedtest; Type: TABLE; Schema: public; Owner: speedtest -- CREATE TABLE public.speedtest ( id integer NOT NULL, server bigint, client integer NOT NULL, download double precision, upload double precision, ping double precision, bytes_sent bigint, bytes_received bigint, date_added timestamp with time zone DEFAULT now() ); ALTER TABLE public.speedtest OWNER TO speedtest; -- -- Name: speedtest_client_seq; Type: SEQUENCE; Schema: public; Owner: speedtest -- CREATE SEQUENCE public.speedtest_client_seq AS integer START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.speedtest_client_seq OWNER TO speedtest; -- -- Name: speedtest_client_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: speedtest -- ALTER SEQUENCE public.speedtest_client_seq OWNED BY public.speedtest.client; -- -- Name: speedtest_id_seq; Type: SEQUENCE; Schema: public; Owner: speedtest -- CREATE SEQUENCE public.speedtest_id_seq AS integer START WITH 1 INCREMENT BY 1 NO MINVALUE NO MAXVALUE CACHE 1; ALTER TABLE public.speedtest_id_seq OWNER TO speedtest; -- -- Name: speedtest_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: speedtest -- ALTER SEQUENCE public.speedtest_id_seq OWNED BY public.speedtest.id; -- -- Name: speedtest_run; Type: VIEW; Schema: public; Owner: postgres -- CREATE VIEW public.speedtest_run AS SELECT c.isp, c.ip AS client_ip, (((('('::text || c.lat) || ','::text) || c.lon) || ')'::text) AS client_coord, s.sponsor AS server, (((('('::text || s.lat) || ','::text) || s.lon) || ')'::text) AS server_coord, (((s.name)::text || ', '::text) || (s.cc)::text) AS server_loc, round((s.d)::numeric, 2) AS server_distance, round(((p.download / (1000000)::double precision))::numeric, 2) AS download_mbps, round(((p.upload / (1000000)::double precision))::numeric, 2) AS upload_mbps, round((p.ping)::numeric, 2) AS ping_ms, p.date_added FROM ((public.speedtest p LEFT JOIN public.server s ON ((p.server = s.id))) LEFT JOIN public.client c ON ((p.client = c.id))); ALTER TABLE public.speedtest_run OWNER TO postgres; -- -- Name: client id; Type: DEFAULT; Schema: public; Owner: speedtest -- ALTER TABLE ONLY public.client ALTER COLUMN id SET DEFAULT nextval('public.client_id_seq'::regclass); -- -- Name: speedtest id; Type: DEFAULT; Schema: public; Owner: speedtest -- ALTER TABLE ONLY public.speedtest ALTER COLUMN id SET DEFAULT nextval('public.speedtest_id_seq'::regclass); -- -- Name: speedtest client; Type: DEFAULT; Schema: public; Owner: speedtest -- ALTER TABLE ONLY public.speedtest ALTER COLUMN client SET DEFAULT nextval('public.speedtest_client_seq'::regclass); -- -- Name: client client_pkey; Type: CONSTRAINT; Schema: public; Owner: speedtest -- ALTER TABLE ONLY public.client ADD CONSTRAINT client_pkey PRIMARY KEY (id); -- -- Name: server server_pkey; Type: CONSTRAINT; Schema: public; Owner: speedtest -- ALTER TABLE ONLY public.server ADD CONSTRAINT server_pkey PRIMARY KEY (id); -- -- Name: speedtest speedtest_pkey; Type: CONSTRAINT; Schema: public; Owner: speedtest -- ALTER TABLE ONLY public.speedtest ADD CONSTRAINT speedtest_pkey PRIMARY KEY (id); -- -- Name: speedtest client_fkey; Type: FK CONSTRAINT; Schema: public; Owner: speedtest -- ALTER TABLE ONLY public.speedtest ADD CONSTRAINT client_fkey FOREIGN KEY (client) REFERENCES public.client(id); -- -- Name: speedtest server_fkey; Type: FK CONSTRAINT; Schema: public; Owner: speedtest -- ALTER TABLE ONLY public.speedtest ADD CONSTRAINT server_fkey FOREIGN KEY (server) REFERENCES public.server(id); -- -- PostgreSQL database dump complete --
27.46
123
0.630632
57eec217f47b66356d9042591085ec20960ebdee
4,561
php
PHP
application/models/Report_model.php
cdterry87/ProjectManagerPt2
5fc7a8cd445d710eec97250753cf20bc5dae0e9a
[ "MIT" ]
1
2019-01-17T14:17:54.000Z
2019-01-17T14:17:54.000Z
application/models/Report_model.php
cdterry87/ProjectManagerPt2
5fc7a8cd445d710eec97250753cf20bc5dae0e9a
[ "MIT" ]
14
2019-01-16T18:39:24.000Z
2019-02-05T21:06:48.000Z
application/models/Report_model.php
cdterry87/ProjectManagerPt2
5fc7a8cd445d710eec97250753cf20bc5dae0e9a
[ "MIT" ]
1
2019-01-17T14:22:58.000Z
2019-01-17T14:22:58.000Z
<?php defined('BASEPATH') or exit('No direct script access allowed'); class Report_model extends PROJECTS_Model { /* -------------------------------------------------------------------------------- * Get all customers. * -------------------------------------------------------------------------------- */ public function get_my_departments_where() { $departments = $_SESSION['employee_departments']; $where=''; if (!empty($departments)) { foreach ($departments as $code => $desc) { $where.="department_id='".$code."' OR "; } $where="(".substr($where, 0, -4).")"; return $where; } return false; } public function get_customers() { $this->db->select('*'); $this->db->from('customers'); $this->db->where('customer_status', 'live'); $this->db->order_by('customer_name'); $query=$this->db->get(); return $query->result_array(); } public function get_customers_open_projects($customer_id) { $where = $this->get_my_departments_where(); $this->db->distinct(); $this->db->select('project_name, project_date'); if (trim($where)=='') { $this->db->from('projects'); } else { $this->db->from('projects, departments_projects'); $this->db->where('projects.project_id=departments_projects.project_id'); $this->db->where($where); } $this->db->where('customer_id', $customer_id); $this->db->where('project_status', 'I'); $this->db->order_by('project_date'); $query=$this->db->get(); return $query->result_array(); } public function get_customers_open_support($customer_id) { $where = $this->get_my_departments_where(); $this->db->select('support_name, support_date, support_time'); if (trim($where)=='') { $this->db->from('support'); } else { $this->db->from('support, departments_support'); $this->db->where('support.support_id=departments_support.support_id'); $this->db->where($where); } $this->db->where('customer_id', $customer_id); $this->db->where('support_status', 'O'); $this->db->order_by('support_date, support_time'); $query=$this->db->get(); return $query->result_array(); } public function open_projects_support() { $customers = $this->get_customers(); $data = []; if (!empty($customers)) { foreach ($customers as $key => $customer) { $data[$customer['customer_name']] = array( 'projects' => $this->get_customers_open_projects($customer['customer_id']), 'support' => $this->get_customers_open_support($customer['customer_id']), ); } } $report = '<h1>Open Projects/Support</h1>'; foreach ($data as $key => $val) { $report .= "<h2>".$key."</h2>"; if (!empty($val['projects']) or !empty($val['support'])) { foreach ($val as $type => $items) { if (!empty($items)) { $report .= "<ul>"; $report .= "<li class='headers'><h3>".ucfirst($type)."</h3></li>"; if (!empty($items)) { $report .= "<ul>"; foreach ($items as $key3 => $item) { if ($type == 'projects') { $report .= "<li>".$this->format->date($item['project_date'])." - ".$item['project_name']."</li>"; } if ($type == 'support') { $report .= "<li>".$this->format->date($item['support_date'])." - ".$item['support_name']."</li>"; } } $report .= "</ul>"; } $report .= "</ul>"; } } } else { $report .= "<ul><li>No open projects/support for this site.</li></ul>"; } } return $report; } }
34.816794
134
0.426442
3852f19d73a4253bb24c93c5d0a89f5c86d31705
2,684
php
PHP
app/Http/Controllers/TagsController.php
aicosta/sweet
24e28deda9c4361a452d89a38dd9683877123174
[ "MIT" ]
null
null
null
app/Http/Controllers/TagsController.php
aicosta/sweet
24e28deda9c4361a452d89a38dd9683877123174
[ "MIT" ]
null
null
null
app/Http/Controllers/TagsController.php
aicosta/sweet
24e28deda9c4361a452d89a38dd9683877123174
[ "MIT" ]
null
null
null
<?php namespace Sweet\Http\Controllers; use Illuminate\Http\Request; use Sweet\Http\Requests; use Sweet\Order; use Sweet\Customer; use Sweet\invoice; use Sweet\Product\Providers; class TagsController extends Controller { public function getList($fornecedor = false){ $providers = Providers::orderBy('name')->get(); if($fornecedor){ $orders = \DB::table('orders') ->leftJoin('order_items', 'orders.id', '=', 'order_items.orders_id') ->leftJoin('products', 'order_items.sku', '=', 'products.sku') ->leftJoin('providers', 'providers.id', '=', 'products.providers_id') ->leftJoin('invoices', 'orders.id', '=', 'invoices.orders_id') ->where('order_statuses_id',2) ->where('envio','<>','me2') ->where('providers_id', $fornecedor) ->select('orders.*', 'products.*', 'providers.name as fornecedor', 'order_items.sku as psku', 'order_items.name as pname','invoices.number') ->get(); }else{ $orders = \DB::table('orders') ->leftJoin('order_items', 'orders.id', '=', 'order_items.orders_id') ->leftJoin('products', 'order_items.sku', '=', 'products.sku') ->leftJoin('providers', 'providers.id', '=', 'products.providers_id') ->leftJoin('invoices', 'orders.id', '=', 'invoices.orders_id') ->where('order_statuses_id',2) ->where('envio','<>','me2') ->select('orders.*', 'products.*', 'providers.name as fornecedor', 'order_items.sku as psku', 'order_items.name as pname','invoices.number') ->get(); } return view('tags.list')->with(compact('providers','orders')); } public function getListMe2($fornecedor = false){ $orders = \DB::table('orders') ->join('order_items', 'orders.id', '=', 'order_items.orders_id') ->join('products', 'order_items.sku', '=', 'products.sku') ->join('providers', 'providers.id', '=', 'products.providers_id') ->join('invoices', 'orders.id', '=', 'invoices.orders_id') ->where('order_statuses_id',2) ->where('envio','me2') ->select('orders.*', 'products.*', 'providers.name as fornecedor','invoices.number') ->get(); return view('tags.me2')->with(compact('orders')); } }
47.928571
164
0.505961
4445147b7da188f6330a5a30ccddf0a8c0007b74
11,186
py
Python
tests/old/test_tifread.py
richardt94/landshark
e4f347857a750d050d2cd568c6bcbd8f4a6c1f7f
[ "Apache-2.0" ]
10
2019-03-05T23:53:58.000Z
2021-12-17T08:27:05.000Z
tests/old/test_tifread.py
richardt94/landshark
e4f347857a750d050d2cd568c6bcbd8f4a6c1f7f
[ "Apache-2.0" ]
7
2019-03-05T05:39:02.000Z
2020-02-03T01:10:40.000Z
tests/old/test_tifread.py
richardt94/landshark
e4f347857a750d050d2cd568c6bcbd8f4a6c1f7f
[ "Apache-2.0" ]
8
2019-03-23T22:55:25.000Z
2021-01-12T05:14:31.000Z
# """Tests for the tif reading importer module.""" # from collections import namedtuple # import numpy as np # import rasterio.transform # import pytest # from landshark.importers import tifread # def test_match(): # """ # Checks that _match can pull out a property from a bunch of image-like # objects when that property is the same for each (default behaviour). # """ # Im = namedtuple('Im', ['prop']) # name = 'myprop' # true_answer = 1 # images = [Im(prop=true_answer) for k in range(10)] # prop = tifread._match(lambda x: x.prop, images, name) # assert prop == true_answer # def test_match_nomatch(mocker): # """ # Checks that _match correctly identifies a non-matching property and # calls the right error functions. # """ # Im = namedtuple('Im', ['prop']) # name = 'myprop' # images = [Im(prop=k) for k in range(10)] # mocked_mismatch = mocker.patch('landshark.importers.tifread._fatal_mismatch') # tifread._match(lambda x: x.prop, images, name) # mocked_mismatch.assert_called_once_with(list(range(10)), images, name) # def test_fatal_mismatch(mocker): # """Checks fatal mismatch calls log.fatal with some sensible text.""" # mock_error = mocker.patch('landshark.importers.tifread.log.error') # property_list = list(range(3)) # Im = namedtuple('Im', ['name']) # images = [Im(name="n{}".format(i)) for i in range(3)] # name = "myname" # with pytest.raises(Exception): # tifread._fatal_mismatch(property_list, images, name) # true_answer = 'No match for myname:\nn0: 0\nn1: 1\nn2: 2' # mock_error.assert_called_once_with(true_answer) # def test_names(): # """Checks names are generated sanely for bands.""" # Im = namedtuple('Im', ['name', 'count']) # im1 = Im(name="A", count=1) # im2 = Im(name="B", count=2) # bands = [tifread.Band(image=im1, index=1), # tifread.Band(image=im2, index=1), # tifread.Band(image=im2, index=2)] # name = tifread._names(bands) # true_answer = ["A", "B_1", "B_2"] # assert name == true_answer # def test_missing(): # """Checks missing correctly converts types of nodatavals.""" # Im = namedtuple('Im', ['nodatavals', 'count']) # im1 = Im(count=1, nodatavals=[1.0]) # im2 = Im(count=2, nodatavals=[2.0, 3.0]) # bands = [tifread.Band(image=im1, index=1), # tifread.Band(image=im2, index=1), # tifread.Band(image=im2, index=2)] # res = tifread._missing(bands, np.int32) # true_answer = [1, 2, 3] # assert res == true_answer # im3 = Im(count=2, nodatavals=[1.0, None]) # bands[0] = tifread.Band(image=im3, index=2) # res2 = tifread._missing(bands, np.int32) # true_answer2 = [None, 2, 3] # assert res2 == true_answer2 # def test_bands(): # """Checks that bands are correctly listed from images.""" # Im = namedtuple('Im', ['dtypes']) # im1 = Im(dtypes=[np.float32, np.float32, np.float32]) # im2 = Im(dtypes=[np.int32, np.int32]) # true_band = [ # tifread.Band(image=im1, index=1), # tifread.Band(image=im1, index=2), # tifread.Band(image=im1, index=3), # tifread.Band(image=im2, index=1), # tifread.Band(image=im2, index=2) # ] # res = tifread._bands([im1, im2]) # assert res == true_band # def test_blockrows(): # """Checks blocksize does something sane.""" # Im = namedtuple('Im', ['block_shapes']) # im1 = Im(block_shapes=[(1, 10), (2, 100)]) # im2 = Im(block_shapes=[(3, 30)]) # bands = [tifread.Band(image=im1, index=1), # tifread.Band(image=im1, index=2), # tifread.Band(image=im2, index=1)] # blocksize = tifread._block_rows(bands) # assert blocksize == 3 # def test_windows(): # """Checks window list covers whole image.""" # w_list = tifread._windows(1024, 768, 10) # assert np.all([k[1] == (0, 1024) for k in w_list]) # assert np.all([k[0][1] - k[0][0] == 10 for k in w_list[:-1]]) # assert w_list[-1][0][0] < 768 # assert w_list[-1][0][1] == 768 # w_list = tifread._windows(1024, 450, 5) # assert np.all([k[1] == (0, 1024) for k in w_list]) # assert np.all([k[0][1] - k[0][0] == 5 for k in w_list]) # assert w_list[-1][0][0] == 445 # assert w_list[-1][0][1] == 450 # def test_read(mocker): # """Checks that read calls the right image functions in the right order.""" # a1 = [np.random.rand(10, 25) * 100, # np.random.rand(10, 25) * 50, # np.random.rand(10, 25) * 10] # a2 = [np.random.rand(10, 25) * 100, # np.random.rand(10, 25) * 50, # np.random.rand(10, 25) * 10] # answers = [np.concatenate((i1[..., np.newaxis], # i2[..., np.newaxis]), axis=-1).astype(np.int32) # for i1, i2 in zip(a1, a2)] # im = mocker.Mock() # im.read = mocker.Mock(side_effect=a1) # im2 = mocker.Mock() # im2.read = mocker.Mock(side_effect=a2) # bands = [tifread.Band(image=im, index=1), tifread.Band(image=im2, index=2)] # windows = [((0, 10), (0, 25)), ((10, 20), (0, 25)), ((20, 30), (0, 25))] # it = tifread._read(bands, windows, dtype=np.int32) # for res, ans in zip(it, answers): # assert np.all(res == ans) # assert im.read.call_count == 3 # assert im2.read.call_count == 3 # for im_calls, im2_calls, w in zip(im.read.call_args_list, # im2.read.call_args_list, # windows): # assert im_calls[0][0] == 1 # assert im2_calls[0][0] == 2 # assert im_calls[1] == {'window': w} # assert im2_calls[1] == {'window': w} # @pytest.mark.parametrize("block_rows", [None, 3]) # def test_imagestack(mocker, block_rows): # """Constructs and image stack ensuring it calls all the right fns.""" # call = mocker.mock_module.call # m_open = mocker.patch('landshark.importers.tifread.rasterio.open') # m_open.return_value = [mocker.Mock(), mocker.Mock()] # width = 10 # height = 20 # affine = rasterio.transform.IDENTITY # m_match = mocker.patch('landshark.importers.tifread._match') # m_match.side_effect = [width, height, affine] # m_bands = mocker.patch('landshark.importers.tifread._bands') # # m_bands.return_value = tifread.BandCollection(ordinal=[mocker.Mock()], # # categorical=[mocker.Mock()]) # m_bands.return_value = [mocker.Mock()] # m_names = mocker.patch('landshark.importers.tifread._names') # m_names.return_value = mocker.Mock() # m_block_rows = mocker.patch('landshark.importers.tifread._block_rows') # m_block_rows.return_value = 2 # m_missing = mocker.patch('landshark.importers.tifread._missing') # m_missing.return_value = mocker.Mock() # m_windows = mocker.patch('landshark.importers.tifread._windows') # m_windows.return_value = mocker.Mock() # m_pixels = mocker.patch('landshark.importers.tifread.pixel_coordinates') # m_pixels.return_value = (np.zeros((10, 2)), np.zeros((10, 2))) # ord_paths = ['my/ord/path', 'my/other/ord/path'] # cat_paths = ['my/cat/path', 'my/other/cat/path'] # stack = tifread.ImageStack(ord_paths, cat_paths, block_rows) # m_open_calls = [call(ord_paths[0], 'r'), call(ord_paths[1], 'r'), # call(cat_paths[0], 'r'), call(cat_paths[1], 'r')] # m_open.assert_has_calls(m_open_calls, any_order=False) # assert stack.width == width # assert stack.height == height # assert stack.affine == affine # assert stack.ordinal_bands == m_bands.return_value # assert stack.categorical_bands == m_bands.return_value # assert stack.ordinal_names == m_names.return_value # assert stack.categorical_names == m_names.return_value # assert stack.ordinal_dtype == np.float32 # assert stack.categorical_dtype == np.int32 # assert stack.windows == m_windows.return_value # assert stack.block_rows == (block_rows if block_rows # else m_block_rows.return_value) # m_missing_calls = [ # call(m_bands.return_value, dtype=stack.ordinal_dtype), # call(m_bands.return_value, dtype=stack.categorical_dtype) # ] # m_missing.assert_has_calls(m_missing_calls, any_order=True) # m_read = mocker.patch('landshark.importers.tifread._read') # stack.categorical_blocks() # m_read.assert_called_with(stack.categorical_bands, # stack.windows, # stack.categorical_dtype) # stack.ordinal_blocks() # m_read.assert_called_with(stack.ordinal_bands, # stack.windows, # stack.ordinal_dtype) # class FakeImage: # def __init__(self, name, width, height, affine, dtypes, block_rows): # self.name = name # self.width = width # self.affine = affine # self.height = height # self.dtypes = dtypes # self.count = len(self.dtypes) # self.nodatavals = [-1.0 for i in range(self.count)] # self.block_shapes = [(block_rows, width) for w in range(self.count)] # def test_imagestack_real(mocker): # affine = rasterio.transform.IDENTITY # im1 = FakeImage(name='im1', width=10, height=5, affine=affine, # dtypes=[np.dtype('uint8'), np.dtype('int32')], # block_rows=2) # im2 = FakeImage(name='im2', width=10, height=5, affine=affine, # dtypes=[np.dtype('float32'), np.dtype('float64')], # block_rows=3) # m_open = mocker.patch('landshark.importers.tifread.rasterio.open') # m_open.side_effect = iter([im1, im2]) # cat_paths = ['path1'] # ord_paths = ['path2'] # stack = tifread.ImageStack(cat_paths, ord_paths) # cat_bands = [tifread.Band(image=im1, index=1), # tifread.Band(image=im1, index=2)] # ord_bands = [tifread.Band(image=im2, index=1), # tifread.Band(image=im2, index=2)] # assert stack.affine == affine # assert stack.width == 10 # assert stack.height == 5 # assert stack.block_rows == 3 # assert stack.categorical_bands == cat_bands # assert stack.ordinal_bands == ord_bands # assert stack.categorical_dtype == np.int32 # assert stack.ordinal_dtype == np.float32 # assert stack.categorical_missing == [-1, -1] # assert stack.ordinal_missing == [-1., -1.] # assert stack.categorical_names == ['im1_1', 'im1_2'] # assert stack.ordinal_names == ['im2_1', 'im2_2'] # assert stack.windows == [((0, 3), (0, 10)), ((3, 5), (0, 10))] # assert np.all(stack.coordinates_x == np.arange(10 + 1, dtype=float)) # assert np.all(stack.coordinates_y == np.arange(5 + 1, dtype=float)) # def test_block_shape(): # """Checks the (simple) multiplication for total size.""" # width = 4 # height = 5 # nbands = 3 # w = ((1, 1 + height), (3, 3 + width)) # r = tifread._block_shape(w, nbands) # assert r == (height, width, nbands)
39.111888
83
0.601645
1a7eb665f1175d04280b4b3ece8a8e86e93d07f8
39,044
py
Python
tests/networks/splitting/test_multi_splitting_base.py
mtcrawshaw/meta-world
b511885af4405715c7b35f8295cef88021a926be
[ "MIT" ]
4
2021-09-21T07:24:26.000Z
2022-03-25T00:28:33.000Z
tests/networks/splitting/test_multi_splitting_base.py
mtcrawshaw/meta
b511885af4405715c7b35f8295cef88021a926be
[ "MIT" ]
null
null
null
tests/networks/splitting/test_multi_splitting_base.py
mtcrawshaw/meta
b511885af4405715c7b35f8295cef88021a926be
[ "MIT" ]
null
null
null
""" Unit tests for meta/networks/splitting/multi_splitting_base.py. """ import math import random from itertools import product from typing import Dict, Any, List import numpy as np from scipy import stats import torch import torch.nn.functional as F from gym.spaces import Box from meta.networks.utils import init_base from meta.networks.splitting import BaseMultiTaskSplittingNetwork from meta.utils.estimate import alpha_to_threshold from tests.helpers import DEFAULT_SETTINGS, get_obs_batch from tests.networks.splitting import BASE_SETTINGS from tests.networks.splitting.templates import ( TOL, gradients_template, backward_template, grad_diffs_template, grad_stats_template, score_template, ) def test_forward_shared() -> None: """ Test forward() when all regions of the splitting network are fully shared. The function computed by the network should be f(x) = 3 * tanh(2 * tanh(x + 1) + 2) + 3. """ # Set up case. dim = BASE_SETTINGS["obs_dim"] + BASE_SETTINGS["num_tasks"] observation_subspace = Box( low=-np.inf, high=np.inf, shape=(BASE_SETTINGS["obs_dim"],) ) observation_subspace.seed(DEFAULT_SETTINGS["seed"]) hidden_size = dim # Construct network. network = BaseMultiTaskSplittingNetwork( input_size=dim, output_size=dim, num_tasks=BASE_SETTINGS["num_tasks"], num_layers=BASE_SETTINGS["num_layers"], hidden_size=hidden_size, device=BASE_SETTINGS["device"], ) # Set network weights. state_dict = network.state_dict() for i in range(BASE_SETTINGS["num_layers"]): weight_name = "regions.%d.0.0.weight" % i bias_name = "regions.%d.0.0.bias" % i state_dict[weight_name] = torch.Tensor((i + 1) * np.identity(dim)) state_dict[bias_name] = torch.Tensor((i + 1) * np.ones(dim)) network.load_state_dict(state_dict) # Construct batch of observations concatenated with one-hot task vectors. obs, task_indices = get_obs_batch( batch_size=BASE_SETTINGS["num_processes"], obs_space=observation_subspace, num_tasks=BASE_SETTINGS["num_tasks"], ) # Get output of network. output = network(obs, task_indices) # Computed expected output of network. expected_output = 3 * torch.tanh(2 * torch.tanh(obs + 1) + 2) + 3 # Test output of network. assert torch.allclose(output, expected_output) def test_forward_single() -> None: """ Test forward() when all regions of the splitting network are fully shared except one. The function computed by the network should be f(x) = 3 * tanh(2 * tanh(x + 1) + 2) + 3 for tasks 0 and 1 and f(x) = 3 * tanh(-2 * tanh(x + 1) - 2) + 3 for tasks 2 and 3. """ # Set up case. dim = BASE_SETTINGS["obs_dim"] + BASE_SETTINGS["num_tasks"] observation_subspace = Box( low=-np.inf, high=np.inf, shape=(BASE_SETTINGS["obs_dim"],) ) observation_subspace.seed(DEFAULT_SETTINGS["seed"]) hidden_size = dim # Construct network. network = BaseMultiTaskSplittingNetwork( input_size=dim, output_size=dim, num_tasks=BASE_SETTINGS["num_tasks"], num_layers=BASE_SETTINGS["num_layers"], hidden_size=hidden_size, device=BASE_SETTINGS["device"], ) # Split the network at the second layer. Tasks 0 and 1 stay assigned to the original # copy and tasks 2 and 3 are assigned to the new copy. network.split(1, 0, [0, 1], [2, 3]) # Set network weights. state_dict = network.state_dict() for i in range(BASE_SETTINGS["num_layers"]): weight_name = "regions.%d.0.0.weight" % i bias_name = "regions.%d.0.0.bias" % i state_dict[weight_name] = torch.Tensor((i + 1) * np.identity(dim)) state_dict[bias_name] = torch.Tensor((i + 1) * np.ones(dim)) weight_name = "regions.1.1.0.weight" bias_name = "regions.1.1.0.bias" state_dict[weight_name] = torch.Tensor(-2 * np.identity(dim)) state_dict[bias_name] = torch.Tensor(-2 * np.ones(dim)) network.load_state_dict(state_dict) # Construct batch of observations concatenated with one-hot task vectors. obs, task_indices = get_obs_batch( batch_size=BASE_SETTINGS["num_processes"], obs_space=observation_subspace, num_tasks=BASE_SETTINGS["num_tasks"], ) # Get output of network. output = network(obs, task_indices) # Computed expected output of network. expected_output = torch.zeros(obs.shape) for i, (ob, task) in enumerate(zip(obs, task_indices)): if task in [0, 1]: expected_output[i] = 3 * torch.tanh(2 * torch.tanh(ob + 1) + 2) + 3 elif task in [2, 3]: expected_output[i] = 3 * torch.tanh(-2 * torch.tanh(ob + 1) - 2) + 3 else: raise NotImplementedError # Test output of network. assert torch.allclose(output, expected_output) def test_forward_multiple() -> None: """ Test forward() when none of the layers are fully shared. The function computed by the network should be: - f(x) = 3 * tanh(2 * tanh(x + 1) + 2) + 3 for task 0 - f(x) = -3 * tanh(-2 * tanh(x + 1) - 2) - 3 for task 1 - f(x) = -3 * tanh(1/2 * tanh(-x - 1) + 1/2) - 3 for task 2 - f(x) = 3 * tanh(-2 * tanh(-x - 1) - 2) + 3 for task 3 """ # Set up case. dim = BASE_SETTINGS["obs_dim"] + BASE_SETTINGS["num_tasks"] observation_subspace = Box( low=-np.inf, high=np.inf, shape=(BASE_SETTINGS["obs_dim"],) ) observation_subspace.seed(DEFAULT_SETTINGS["seed"]) hidden_size = dim # Construct network. network = BaseMultiTaskSplittingNetwork( input_size=dim, output_size=dim, num_tasks=BASE_SETTINGS["num_tasks"], num_layers=BASE_SETTINGS["num_layers"], hidden_size=hidden_size, device=BASE_SETTINGS["device"], ) # Split the network at the second layer. Tasks 0 and 1 stay assigned to the original # copy and tasks 2 and 3 are assigned to the new copy. network.split(0, 0, [0, 1], [2, 3]) network.split(1, 0, [0, 2], [1, 3]) network.split(1, 0, [0], [2]) network.split(2, 0, [0, 3], [1, 2]) # Set network weights. state_dict = network.state_dict() for i in range(BASE_SETTINGS["num_layers"]): for j in range(3): weight_name = "regions.%d.%d.0.weight" % (i, j) bias_name = "regions.%d.%d.0.bias" % (i, j) if weight_name not in state_dict: continue if j == 0: state_dict[weight_name] = torch.Tensor((i + 1) * np.identity(dim)) state_dict[bias_name] = torch.Tensor((i + 1) * np.ones(dim)) elif j == 1: state_dict[weight_name] = torch.Tensor(-(i + 1) * np.identity(dim)) state_dict[bias_name] = torch.Tensor(-(i + 1) * np.ones(dim)) elif j == 2: state_dict[weight_name] = torch.Tensor(1 / (i + 1) * np.identity(dim)) state_dict[bias_name] = torch.Tensor(1 / (i + 1) * np.ones(dim)) else: raise NotImplementedError network.load_state_dict(state_dict) # Construct batch of observations concatenated with one-hot task vectors. obs, task_indices = get_obs_batch( batch_size=BASE_SETTINGS["num_processes"], obs_space=observation_subspace, num_tasks=BASE_SETTINGS["num_tasks"], ) # Get output of network. output = network(obs, task_indices) # Computed expected output of network. expected_output = torch.zeros(obs.shape) for i, (ob, task) in enumerate(zip(obs, task_indices)): if task == 0: expected_output[i] = 3 * torch.tanh(2 * torch.tanh(ob + 1) + 2) + 3 elif task == 1: expected_output[i] = -3 * torch.tanh(-2 * torch.tanh(ob + 1) - 2) - 3 elif task == 2: expected_output[i] = ( -3 * torch.tanh(1 / 2 * torch.tanh(-ob - 1) + 1 / 2) - 3 ) elif task == 3: expected_output[i] = 3 * torch.tanh(-2 * torch.tanh(-ob - 1) - 2) + 3 else: raise NotImplementedError # Test output of network. assert torch.allclose(output, expected_output) def test_split_single() -> None: """ Test that split() correctly sets new parameters when we perform a single split. """ # Set up case. dim = BASE_SETTINGS["obs_dim"] + BASE_SETTINGS["num_tasks"] observation_subspace = Box( low=-np.inf, high=np.inf, shape=(BASE_SETTINGS["obs_dim"],) ) observation_subspace.seed(DEFAULT_SETTINGS["seed"]) hidden_size = dim # Construct network. network = BaseMultiTaskSplittingNetwork( input_size=dim, output_size=dim, num_tasks=BASE_SETTINGS["num_tasks"], num_layers=BASE_SETTINGS["num_layers"], hidden_size=hidden_size, device=BASE_SETTINGS["device"], ) # Split the network at the last layer, so that tasks 0 and 2 stay assigned to the # original copy and tasks 1 and 3 are assigned to the new copy. network.split(2, 0, [0, 2], [1, 3]) # Check the parameters of the network. param_names = [name for name, param in network.named_parameters()] # Construct expected parameters of network. region_copies = {i: [0] for i in range(BASE_SETTINGS["num_layers"])} region_copies[2].append(1) expected_params = [] for region, copies in region_copies.items(): for copy in copies: expected_params.append("regions.%d.%d.0.weight" % (region, copy)) expected_params.append("regions.%d.%d.0.bias" % (region, copy)) # Test actual parameter names. assert set(param_names) == set(expected_params) def test_split_multiple() -> None: """ Test that split() correctly sets new parameters when we perform multiple splits. """ # Set up case. dim = BASE_SETTINGS["obs_dim"] + BASE_SETTINGS["num_tasks"] observation_subspace = Box( low=-np.inf, high=np.inf, shape=(BASE_SETTINGS["obs_dim"],) ) observation_subspace.seed(DEFAULT_SETTINGS["seed"]) hidden_size = dim # Construct network. network = BaseMultiTaskSplittingNetwork( input_size=dim, output_size=dim, num_tasks=BASE_SETTINGS["num_tasks"], num_layers=BASE_SETTINGS["num_layers"], hidden_size=hidden_size, device=BASE_SETTINGS["device"], ) # Split the network at the first layer once and the last layer twice. network.split(0, 0, [0, 1], [2, 3]) network.split(2, 0, [0, 2], [1, 3]) network.split(2, 1, [1], [3]) # Check the parameters of the network. param_names = [name for name, param in network.named_parameters()] # Construct expected parameters of network. region_copies = {i: [0] for i in range(BASE_SETTINGS["num_layers"])} region_copies[0].extend([1]) region_copies[2].extend([1, 2]) expected_params = [] for region, copies in region_copies.items(): for copy in copies: expected_params.append("regions.%d.%d.0.weight" % (region, copy)) expected_params.append("regions.%d.%d.0.bias" % (region, copy)) # Test actual parameter names. assert set(param_names) == set(expected_params) def test_backward_shared() -> None: """ Test that the backward() function correctly computes gradients in the case of a fully shared network. """ splits_args = [] backward_template(BASE_SETTINGS, splits_args) def test_backward_single() -> None: """ Test that the backward() function correctly computes gradients in the case of a single split. """ splits_args = [ {"region": 1, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] backward_template(BASE_SETTINGS, splits_args) def test_backward_multiple() -> None: """ Test that the backward() function correctly computes gradients in the case of multiple splits. """ splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 1, "copy": 0, "group1": [0], "group2": [2]}, {"region": 2, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] backward_template(BASE_SETTINGS, splits_args) def test_task_grads_shared() -> None: """ Test that `get_task_grads()` correctly computes task-specific gradients at each region of the network in the case of a fully shared network. """ splits_args = [] gradients_template(BASE_SETTINGS, splits_args) def test_task_grads_single() -> None: """ Test that `get_task_grads()` correctly computes task-specific gradients at each region of the network in the case of a single split network. """ splits_args = [ {"region": 1, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] gradients_template(BASE_SETTINGS, splits_args) def test_task_grads_multiple() -> None: """ Test that `get_task_grads()` correctly computes task-specific gradients at each region of the network in the case of a multiple split network. """ splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 1, "copy": 0, "group1": [0], "group2": [2]}, {"region": 2, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] gradients_template(BASE_SETTINGS, splits_args) def test_task_grad_diffs_zero_euclidean() -> None: """ Test that `get_task_grad_diffs()` correctly computes the pairwise Euclidean distance between task-specific gradients at each region when these gradients are hard-coded to zero. """ settings = dict(BASE_SETTINGS) settings["metric"] = "sqeuclidean" grad_diffs_template(settings, "zero") def test_task_grad_diffs_rand_identical_euclidean() -> None: """ Test that `get_task_grad_diffs()` correctly computes the pairwise Euclidean distance between task-specific gradients at each region when these gradients are random, but identical across tasks. """ settings = dict(BASE_SETTINGS) settings["metric"] = "sqeuclidean" grad_diffs_template(settings, "rand_identical") def test_task_grad_diffs_rand_euclidean() -> None: """ Test that `get_task_grad_diffs()` correctly computes the pairwise Euclidean distance between task-specific gradients at each region when these gradients are random. """ settings = dict(BASE_SETTINGS) settings["metric"] = "sqeuclidean" grad_diffs_template(settings, "rand") def test_task_grad_diffs_zero_cosine() -> None: """ Test that `get_task_grad_diffs()` correctly computes the pairwise cosine distance between task-specific gradients at each region when these gradients are hard-coded to zero. """ settings = dict(BASE_SETTINGS) settings["metric"] = "cosine" grad_diffs_template(settings, "zero") def test_task_grad_diffs_rand_identical_cosine() -> None: """ Test that `get_task_grad_diffs()` correctly computes the pairwise cosine distance between task-specific gradients at each region when these gradients are random, but identical across tasks. """ settings = dict(BASE_SETTINGS) settings["metric"] = "cosine" grad_diffs_template(settings, "rand_identical") def test_task_grad_diffs_rand_cosine() -> None: """ Test that `get_task_grad_diffs()` correctly computes the pairwise cosine distance between task-specific gradients at each region when these gradients are random. """ settings = dict(BASE_SETTINGS) settings["metric"] = "cosine" grad_diffs_template(settings, "rand") def test_task_grad_stats_zero_euclidean_shared() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when the gradients are always zero, with a fully shared network. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "sqeuclidean" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "zero", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_rand_zero_euclidean_shared() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when the gradients are random, while some tasks randomly have gradients set to zero, with a fully shared network. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "sqeuclidean" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "rand_zero", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_rand_euclidean_shared() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when these gradients are random, with a fully shared network. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "sqeuclidean" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "rand", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_zero_euclidean_split() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when the gradients are always zero, with a split network. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "sqeuclidean" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 1, "copy": 1, "group1": [1], "group2": [3]}, {"region": 2, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "zero", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_rand_zero_euclidean_split() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when the gradients are random, while some tasks randomly have gradients set to zero, with a split network. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "sqeuclidean" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 1, "copy": 1, "group1": [1], "group2": [3]}, {"region": 2, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "rand_zero", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_rand_euclidean_split() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when these gradients are random, with a split network. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "sqeuclidean" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 1, "copy": 1, "group1": [1], "group2": [3]}, {"region": 2, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "rand", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_zero_cosine_shared() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when the gradients are always zero, with a fully shared network using cosine distance. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "cosine" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "zero", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_rand_zero_cosine_shared() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when the gradients are random, while some tasks randomly have gradients set to zero, with a fully shared network using cosine distance. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "cosine" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "rand_zero", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_rand_cosine_shared() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when these gradients are random, with a fully shared network using cosine distance. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "cosine" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "rand", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_zero_cosine_split() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when the gradients are always zero, with a split network using cosine distance. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "cosine" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 1, "copy": 1, "group1": [1], "group2": [3]}, {"region": 2, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "zero", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_rand_zero_cosine_split() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when the gradients are random, while some tasks randomly have gradients set to zero, with a split network using cosine distance. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "cosine" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 1, "copy": 1, "group1": [1], "group2": [3]}, {"region": 2, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "rand_zero", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_task_grad_stats_rand_cosine_split() -> None: """ Test that `update_grad_stats()` correctly computes gradient statistics over multiple steps when these gradients are random, with a split network using cosine distance. """ # Set up case. settings = dict(BASE_SETTINGS) settings["metric"] = "cosine" settings["hidden_size"] = settings["obs_dim"] + settings["num_tasks"] + 2 ema_threshold = alpha_to_threshold(settings["ema_alpha"]) # Construct series of splits. splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 1, "copy": 1, "group1": [1], "group2": [3]}, {"region": 2, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] # Construct a sequence of task gradients. settings["num_steps"] = max(settings["split_step_threshold"], ema_threshold) + 20 dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = get_region_sizes(settings) task_grads = make_task_gradients( "rand", settings["num_steps"], settings["num_tasks"], settings["num_layers"], region_sizes, ) # Run test. grad_stats_template(settings, task_grads, splits_args) def test_sharing_score_shared() -> None: """ Test that the sharing score is correctly computed for a fully shared network. """ # Set up case. settings = dict(BASE_SETTINGS) dim = settings["obs_dim"] + settings["num_tasks"] settings["input_size"] = dim settings["output_size"] = dim settings["hidden_size"] = dim splits_args = [] expected_score = 1.0 # Call template. score_template(settings, splits_args, expected_score) def test_sharing_score_separate() -> None: """ Test that the sharing score is correctly computed for a fully separated network, i.e. a network with no sharing. """ # Set up case. settings = dict(BASE_SETTINGS) dim = settings["obs_dim"] + settings["num_tasks"] settings["input_size"] = dim settings["output_size"] = dim settings["hidden_size"] = dim splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 0, "copy": 0, "group1": [0], "group2": [1]}, {"region": 0, "copy": 1, "group1": [2], "group2": [3]}, {"region": 1, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0], "group2": [1]}, {"region": 1, "copy": 1, "group1": [2], "group2": [3]}, {"region": 2, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 2, "copy": 0, "group1": [0], "group2": [1]}, {"region": 2, "copy": 1, "group1": [2], "group2": [3]}, ] expected_score = 0.0 # Call template. score_template(settings, splits_args, expected_score) def test_sharing_score_split_1() -> None: """ Test that the sharing score is correctly computed for a network with half of each region shared. """ # Set up case. settings = dict(BASE_SETTINGS) dim = settings["obs_dim"] + settings["num_tasks"] settings["input_size"] = dim settings["output_size"] = dim settings["hidden_size"] = dim splits_args = [ {"region": 0, "copy": 0, "group1": [0, 1], "group2": [2, 3]}, {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 2, "copy": 0, "group1": [0, 3], "group2": [1, 2]}, ] expected_score = 2.0 / 3.0 # Call template. score_template(settings, splits_args, expected_score) def test_sharing_score_split_2() -> None: """ Test that the sharing score is correctly computed for a network with half of each region shared. """ # Set up case. settings = dict(BASE_SETTINGS) dim = settings["obs_dim"] + settings["num_tasks"] settings["input_size"] = settings["obs_dim"] settings["output_size"] = dim settings["hidden_size"] = dim splits_args = [ {"region": 1, "copy": 0, "group1": [0, 2], "group2": [1, 3]}, {"region": 2, "copy": 0, "group1": [0], "group2": [1, 2, 3]}, {"region": 2, "copy": 1, "group1": [1], "group2": [2, 3]}, ] dim = settings["obs_dim"] + settings["num_tasks"] region_sizes = [ settings["obs_dim"] * dim + dim, dim ** 2 + dim, dim ** 2 + dim, ] region_scores = [1.0, 2.0 / 3.0, 1.0 / 3.0] expected_score = sum( [score * size for score, size in zip(region_scores, region_sizes)] ) / sum(region_sizes) # Call template. score_template(settings, splits_args, expected_score) def test_shared_regions_shared() -> None: """ Test that the shared regions are correctly computed by `SplittingMap.shared_regions()` in the case of a fully shared network. """ # Construct network. dim = BASE_SETTINGS["obs_dim"] + BASE_SETTINGS["num_tasks"] network = BaseMultiTaskSplittingNetwork( input_size=dim, output_size=dim, num_tasks=BASE_SETTINGS["num_tasks"], num_layers=BASE_SETTINGS["num_layers"], hidden_size=dim, device=BASE_SETTINGS["device"], ) # Compute expected shared regions. expected_is_shared = torch.zeros( network.num_tasks, network.num_tasks, network.num_regions ) for task1, task2 in product(range(network.num_tasks), range(network.num_tasks)): if task1 == task2: continue for region in range(network.num_regions): expected_is_shared[task1, task2, region] = 1 # Compare expected to actual. assert torch.all(expected_is_shared == network.splitting_map.shared_regions()) def test_shared_regions_single() -> None: """ Test that the shared regions are correctly computed by `SplittingMap.shared_regions()` in the case of a network with a single split. """ # Construct network. dim = BASE_SETTINGS["obs_dim"] + BASE_SETTINGS["num_tasks"] network = BaseMultiTaskSplittingNetwork( input_size=dim, output_size=dim, num_tasks=BASE_SETTINGS["num_tasks"], num_layers=BASE_SETTINGS["num_layers"], hidden_size=dim, device=BASE_SETTINGS["device"], ) # Perform splits. network.split(1, 0, [0, 1], [2, 3]) # Compute expected shared regions. expected_is_shared = torch.zeros( network.num_tasks, network.num_tasks, network.num_regions ) for task1, task2 in product(range(network.num_tasks), range(network.num_tasks)): if task1 == task2: continue for region in range(network.num_regions): if region == 1 and (task1 // 2) != (task2 // 2): expected_is_shared[task1, task2, region] = 0 else: expected_is_shared[task1, task2, region] = 1 # Compare expected to actual. print(expected_is_shared) print(network.splitting_map.shared_regions()) assert torch.all(expected_is_shared == network.splitting_map.shared_regions()) def test_shared_regions_multiple() -> None: """ Test that the shared regions are correctly computed by `SplittingMap.shared_regions()` in the case of a network with a single split. """ # Construct network. dim = BASE_SETTINGS["obs_dim"] + BASE_SETTINGS["num_tasks"] network = BaseMultiTaskSplittingNetwork( input_size=dim, output_size=dim, num_tasks=BASE_SETTINGS["num_tasks"], num_layers=BASE_SETTINGS["num_layers"], hidden_size=dim, device=BASE_SETTINGS["device"], ) # Perform splits. network.split(0, 0, [0, 1], [2, 3]) network.split(1, 0, [0, 2], [1, 3]) network.split(1, 0, [0], [2]) network.split(2, 0, [0, 3], [1, 2]) # Compute expected shared regions. expected_is_shared = torch.zeros( network.num_tasks, network.num_tasks, network.num_regions ) for task1, task2 in product(range(network.num_tasks), range(network.num_tasks)): if task1 == task2: continue for region in range(network.num_regions): val = 1 if region == 0 and (task1 // 2) != (task2 // 2): val = 0 elif region == 1 and (task1, task2) not in [(1, 3), (3, 1)]: val = 0 elif region == 2 and task1 + task2 != 3: val = 0 expected_is_shared[task1, task2, region] = val # Compare expected to actual. assert torch.all(expected_is_shared == network.splitting_map.shared_regions()) def make_task_gradients( grad_type: str, num_steps: int, num_tasks: int, num_layers: int, region_sizes: List[int], ) -> torch.Tensor: """ Construct dummy task gradients. """ # Generate gradients. max_layer_size = max(region_sizes) if grad_type == "zero": task_grads = torch.zeros(num_steps, num_tasks, num_layers, max_layer_size) elif grad_type == "rand_zero": task_grads = torch.rand(num_steps, num_tasks, num_layers, max_layer_size) task_grads *= ( (torch.rand(num_steps, num_tasks) < 0.5).unsqueeze(-1).unsqueeze(-1) ) elif grad_type == "rand_identical": task_grads = torch.rand(num_steps, 1, num_layers, max_layer_size) task_grads = task_grads.expand(-1, num_tasks, -1, -1) elif grad_type == "rand": task_grads = torch.rand(num_steps, num_tasks, num_layers, max_layer_size) else: raise NotImplementedError # Zero out values that don't correspond to a parameter (this happens since layers # have different sizes). for layer in range(num_layers): task_grads[:, :, layer, region_sizes[layer] :] = 0.0 return task_grads def get_region_sizes(settings: Dict[str, Any]) -> List[int]: """ Compute size of each layer in network specified by `settings`. """ dim = settings["num_tasks"] + settings["obs_dim"] region_sizes = [] for region in range(settings["num_layers"]): if region == 0: region_size = settings["hidden_size"] * (dim + 1) elif region == settings["num_layers"] - 1: region_size = dim * (settings["hidden_size"] + 1) else: region_size = settings["hidden_size"] ** 2 + settings["hidden_size"] region_sizes.append(region_size) return region_sizes
34.15923
88
0.637383
990a40f6e1cbe45cce35f5e60d450c05bbae9140
9,401
lua
Lua
TreeSyncOrderer.lrplugin/TreeSyncOrdererExport.lua
DaveBurns/rc_treeSyncOrderer
e6d4c823dbe6202e8509d75212322985e9db773b
[ "Artistic-2.0" ]
null
null
null
TreeSyncOrderer.lrplugin/TreeSyncOrdererExport.lua
DaveBurns/rc_treeSyncOrderer
e6d4c823dbe6202e8509d75212322985e9db773b
[ "Artistic-2.0" ]
null
null
null
TreeSyncOrderer.lrplugin/TreeSyncOrdererExport.lua
DaveBurns/rc_treeSyncOrderer
e6d4c823dbe6202e8509d75212322985e9db773b
[ "Artistic-2.0" ]
null
null
null
--[[ TreeSyncOrdererExport.lua --]] local TreeSyncOrdererExport, dbg, dbgf = Export:newClass{ className = 'TreeSyncOrdererExport' } --[[ To extend special export class, which as far as I can see, would never be necessary, unless this came from a template, and plugin author did not want to change it, but extend instead. --]] function TreeSyncOrdererExport:newClass( t ) return Export.newClass( self, t ) end --[[ Called to create a new object to handle the export dialog box functionality. --]] function TreeSyncOrdererExport:newDialog( t ) local o = Export.newDialog( self, t ) return o end --[[ Called to create a new object to handle the export functionality. --]] function TreeSyncOrdererExport:newExport( t ) local o = Export.newExport( self, t ) return o end -- E X P O R T D I A L O G B O X M E T H O D S --[[ Export parameter change handler. This would be in base property-service class. Note: can not be method, since calling sequence is fixed. Probably best if derived class just overwrites this if property change handling is desired --]] function TreeSyncOrdererExport:propertyChangeHandlerMethod( props, name, value ) app:call( Call:new{ name = "expPropChgHdlr", guard = App.guardSilent, main = function( context, props, name, value ) Export.propertyChangeHandlerMethod( self, props, name, value ) dbg( "Extended export property changed" ) end }, props, name, value ) end --[[ Called when dialog box is opening. Maybe derived type just overwrites this one, since property names must be hardcoded per export. Another option would be to just add all properties to the change handler, then derived function can just ignore changes, or not. --]] function TreeSyncOrdererExport:startDialogMethod( props ) Export.startDialogMethod( self, props ) -- @8/Jan/2012 this is a no-op, but that may change. --view:setObserver( props, 'noname', TreeSyncOrdererExport, Export.propertyChangeHandler ) end --[[ Called when dialog box is closing. --]] function TreeSyncOrdererExport:endDialogMethod( props, why ) Debug.pauseIf( why==nil, "why?" ) Export.endDialogMethod( self, props, why ) end --[[ Fetch top sections of export dialog box. Base export class replicates plugin manager top section. Override to change or add to sections. --]] function TreeSyncOrdererExport:sectionsForTopOfDialogMethod( vf, props ) local sections = Export.sectionsForTopOfDialogMethod( self, vf, props ) local s1 = { -- title -- synopsis... } --s1[#s1 + 1] = vf:row { --} if not tab:isEmpty( sections ) then if not tab:isEmpty( s1 ) then tab:appendArray( sections, { s1 } ) -- append in place. return sections else return sections end elseif not tab:isEmpty( s1 ) then return { s1 } else return {} end end --[[ Fetch bottom sections of export dialog box. Base export class returns nothing. Override to change or add to sections. --]] function TreeSyncOrdererExport:sectionsForBottomOfDialogMethod( vf, props ) local sections = Export.sectionsForBottomOfDialogMethod( self, vf, props ) local s1 = { -- title -- synopsis... } --s1[#s1 + 1] = vf:row { --} if not tab:isEmpty( sections ) then if not tab:isEmpty( s1 ) then tab:appendArray( sections, { s1 } ) -- append in place. return sections else return sections end elseif not tab:isEmpty( s1 ) then return { s1 } else return {} end end -- E X P O R T M E T H O D S --[[ Called immediately after creating the export object which assigns function-context and export-context member variables. This is the one to override if you want to change everything about the rendering process (preserving nothing from the base export class). --]] function TreeSyncOrdererExport:processRenderedPhotosMethod() Export.processRenderedPhotosMethod( self ) -- note: photo rend & photo fail methods are overridden to circumvent errors due to skipped rendering. end -- Determine if requisite filter is inserted and is at position #1. -- (no way to tell if filters from *other* plugins are below it). function TreeSyncOrdererExport:isReqFiltered( settings ) local filterIdOrd = settings.LR_exportFiltersFromThisPlugin if not tab:is( filterIdOrd ) then return false, "no filters" end if tab:countItems( filterIdOrd ) > 1 then return false, "only one filter should be inserted" end if filterIdOrd.TreeSyncOrdererExportFilter then if filterIdOrd.TreeSyncOrdererExportFilter == 1 then return true else return false, "filter is not at top - it must be - remove all other filters." end else Debug.pause( "Wrong filter inserted - bug?" ) return false, "Wrong filter inserted - bug?" end end --[[ Remove photos not to be rendered, or whatever. Default behavior is to do nothing except assume all exported photos will be rendered. Override for something different... --]] function TreeSyncOrdererExport:checkBeforeRendering() -- reminder: new instance is created (with check-status nil) for each invocation. local go, noGo = tso:checkSel() if go then -- go -- some msg may have been logged. elseif go == nil then -- unsure app:logW( noGo ) -- log warning and keep on truckin' else -- go is false app:logW( noGo ) self:cancelExport() -- remove all photos to export from export session. return end local sts, err = self:isReqFiltered( self.exportParams or error( "no export params" ) ) if sts then app:logV( "Requisite filter is present." ) else app:logW( "Filter config not copacetic - ^1 - export will do nothing. To remedy, use preset provided with plugin, or insert 'TreeSync Orderer' filter (post-process action) and remove all others.", err or "no errm" ) self:cancelExport() -- remove all photos to export from export session. end return end --[[ Process one rendered photo. Called in the renditions loop. This is the method to override if you want to do something different with the photos being rendered... --]] function TreeSyncOrdererExport:processRenderedPhoto( rendition, photoPath ) Debug.pause( rendition, photoPath, rendition.wasSkipped ) -- exp-path. --Export.processRenderedPhoto( self, rendition, photoPath ) app:logW( "Photo was rendered - it shouldn't be. Seems the export filter isn't, well, filtering..." ) end --[[ Process one rendering failure. process-rendered-photo or process-rendering-failure - one or the other will be called depending on whether the photo was successfully rendered or not. Default behavior is to log an error and keep on truckin'... --]] function TreeSyncOrdererExport:processRenderingFailure( rendition, message ) --Export.processRenderingFailure( self, rendition, message ) - dont do this (failed rendering is the norm for this plugin) -- note: although rendition was skipped the was-skipped flag won't be set - dunno why not. -- message will typically be nil Debug.pauseIf( message ~= nil, "hm - got msg", message ) -- could log something, but what's the point? ###2 end --[[ Handle special export service... Note: The base export service method essentially divides the export task up and calls individual methods for doing the pieces. This is the one to override to change what get logged at the outset of the service, or you the partitioning into sub-tasks is not to your liking... --]] function TreeSyncOrdererExport:service() Export.service( self ) end --[[ Handle special export finale... --]] function TreeSyncOrdererExport:finale( service, status, message ) app:log( str:format( "^1 finale, ^2 rendered.", service.name, str:plural( self.nPhotosRendered, "photo" ) ) ) Export.finale( self, service, status, message ) end ----------------------------------------------------------------------------------------- -- E X P O R T S E T T I N G S TreeSyncOrdererExport.showSections = {}--'exportLocation', 'fileNaming', 'fileSettings', 'imageSettings', 'outputSharpening', 'metadata', 'video', 'watermarking' } --TreeSyncOrdererExport.hideSections = { 'exportLocation', 'fileNaming', 'fileSettings', 'imageSettings', 'outputSharpening', 'metadata', 'video', 'watermarking' } -- the same as positive form. -- TreeSyncOrdererExport.allowFileFormats = { 'JPEG' } -- TreeSyncOrdererExport.allowColorSpaces = { 'sRGB' } local exportParams = {} exportParams[#exportParams + 1] = { key = 'one', default = false } TreeSyncOrdererExport.exportPresetFields = exportParams -- Direct inheritance so extended function members are recognized by Lightroom. TreeSyncOrdererExport:inherit( Export ) return TreeSyncOrdererExport
30.62215
223
0.659079
71642d7e7b13f05171346594724502ffaca56048
16,045
tab
SQL
carstarts/500/5.tab
Priyaaks/libDAI_P
9f43da31b530bdf1d81d59213823029ff8902e4f
[ "BSD-2-Clause" ]
null
null
null
carstarts/500/5.tab
Priyaaks/libDAI_P
9f43da31b530bdf1d81d59213823029ff8902e4f
[ "BSD-2-Clause" ]
null
null
null
carstarts/500/5.tab
Priyaaks/libDAI_P
9f43da31b530bdf1d81d59213823029ff8902e4f
[ "BSD-2-Clause" ]
null
null
null
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 1 1 1 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 0 0 0 0 0 1 1 1 0 1 0 0 1 1 0 0 0 1 0 0 0 1 0 0 1 0 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 0 1 1 0 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 0 0 0 0 0 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 0 0 0 0 0 1 1 1 0 0 0 0 1 0 0 0 0 0 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 0 0 1 0 1 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 1 1 0 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 0 0 0 0 0 1 1 0 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 0 0 0 0 0 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 1 0 0 1 0 0 1 0 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 1 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 0 0 0 0 0 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 0 0 0 0 0 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 1 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 0 0 0 0 0 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 0 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 0 0 1 0 0 1 0 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 1 0 0 1 0 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 0 0 0 0 0 1 1 1 1 0 0 0 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 0 0 0 0 0 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 1 0 0 1 0 1 0 0 0 1 1 1 0 1 0 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 1 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 0 0 0 1 0 0 1 0 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 0 0 0 0 0 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 0 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 0 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 1 0 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 1 1 0 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1 1 0 1 1 0 0 0 1 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 0 0 1 0 0 0 0 0 1 1 1 0 1 1 0 1 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 1 1 1 1 0 1 1 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 0 1 1 0 0 1 0 0 0 0 0 1 1 1 0 1 1 0 1 1 0 0 0 1
31.898608
43
0.406731
e29f8b537b51af5de7eca4e6fc0ab8899d7f36d1
3,631
js
JavaScript
test/unit/repository/FileRepository.test.js
epayet/simple-restful
cfa7c600960d5fcdabfd5190a58c6b54c1fd3455
[ "Unlicense" ]
2
2017-01-20T14:11:54.000Z
2019-02-10T22:16:11.000Z
test/unit/repository/FileRepository.test.js
epayet/simple-restful
cfa7c600960d5fcdabfd5190a58c6b54c1fd3455
[ "Unlicense" ]
1
2016-08-19T15:33:44.000Z
2016-08-19T15:33:44.000Z
test/unit/repository/FileRepository.test.js
epayet/simple-restful
cfa7c600960d5fcdabfd5190a58c6b54c1fd3455
[ "Unlicense" ]
null
null
null
import sinon from 'sinon' import { expect } from 'chai' import fsp from 'fs-promise' import fs from 'fs' import FileRepository from '../../../src/repository/FileRepository' describe('Unit: FileRepository', function() { let repository beforeEach(function() { let options = { folderPath: 'test' } repository = new FileRepository(options) }) beforeEach(function() { sinon.stub(fsp, 'writeFile').returns(Promise.resolve()) sinon.stub(fsp, 'readFile') sinon.stub(fsp, 'unlink').returns(Promise.resolve()) sinon.stub(fsp, 'readdir') sinon.stub(fs, 'existsSync').returns(true) sinon.stub(fs, 'mkdirSync') }) afterEach(function() { fsp.writeFile.restore() fsp.readFile.restore() fsp.unlink.restore() fsp.readdir.restore() fs.mkdirSync.restore() fs.existsSync.restore() }) describe('init', function() { it('should raise an error if the folder path is undefined', function() { expect(() => new FileRepository()).to.throw(Error) }) }) describe('add', function() { let newData = {stuff: 'stuff'} it('should create the first data', function(done) { repository.add(newData) .then(() => { expect(fsp.writeFile.calledWith('test/0.json', JSON.stringify(newData))).to.equal(true) done() }) .catch(done) }) it('should create the folder if it does not exist', function(done) { fs.existsSync.returns(false) repository.add(newData) .then(() => { expect(fs.mkdirSync.calledWith('test')).to.equal(true) done() }) .catch(done) }) }) describe('get', function() { it('should read a file', function(done) { let simpleData = {__id: 0, stuff: 'stuff'} fsp.readFile.returns(Promise.resolve(JSON.stringify(simpleData))) repository.get(simpleData.__id) .then(result => { expect(result).to.deep.equal(simpleData) done() }) }) }) describe('getAll', function() { it('should get an empty array when folder exists but empty', function(done) { fsp.readdir.returns(Promise.resolve([])) repository.getAll() .then(allData => { expect(allData).to.deep.equal([]) done() }) .catch(done) }) it('should the existing data as a collection', function(done) { let existingData = [{__id: 0, stuff: 'stuff'}] fsp.readdir.returns(Promise.resolve(['0.json'])) fsp.readFile.returns(Promise.resolve(JSON.stringify(existingData[0]))) repository.getAll() .then(allData => { expect(allData).to.deep.equal(existingData) done() }) .catch(done) }) it('should get an empty collection when folder does not exist', function(done) { fs.existsSync.returns(false) repository.getAll() .then(allData => { expect(allData).to.deep.equal([]) done() }) .catch(done) }) }) describe('delete', function() { it('should delete a file', function(done) { repository.delete(0) .then(() => { expect(fsp.unlink.calledWith('test/0.json')) done() }) }) }) describe('update', function() { it('should overwrite existing file', function(done) { let dataWithNewValues = {__id: 0, stuff: 'other stuff'} repository.update(0, dataWithNewValues) .then(updatedData => { expect(fsp.writeFile.calledWith('test/0.json', JSON.stringify(dataWithNewValues))).to.equal(true) done() }) }) }) })
26.122302
107
0.587717
cf130c89c2b04f2ae12ed38377bf02504f377b08
4,707
php
PHP
application/views/ks/ttd.php
cahya93/sis
4feb5fcd40836e3b067d33d152b60fb36d987701
[ "MIT" ]
null
null
null
application/views/ks/ttd.php
cahya93/sis
4feb5fcd40836e3b067d33d152b60fb36d987701
[ "MIT" ]
null
null
null
application/views/ks/ttd.php
cahya93/sis
4feb5fcd40836e3b067d33d152b60fb36d987701
[ "MIT" ]
2
2020-12-22T13:17:16.000Z
2020-12-24T07:05:33.000Z
<div class="row"> <section> <div class="container"> <div class="m-signature-pad-body"> <p>Priview Tanda Tangan</p> <img src="<?= base_url('') . $data['ttd']; ?>" alt=""> </div> </div> </section> <section> <div class="container"> <input type="hidden" name="id" id="id" value="<?= $data['id']; ?>" readonly> <div class="m-signature-pad-body mb-3"> <p>Tanda Tangan Disini</p> <div id="signature-pad"> <canvas width="200px" height="200px"></canvas> <div class="m-signature-pad-footer mt-3"> <button type="button" id="save2" data-action="save" class="btn btn-primary"><i class="fa fa-check"></i> Save</button> <button type="button" data-action="clear" class="btn btn-danger"><i class="fa fa-trash"></i> Clear</button> </div> </div> </div> </div> </section> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Warning!</h4> </div> <div class="modal-body"> <div class="alert alert-danger"> Sign before you submit! </div> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-body"> <div class="alert alert-success"> Tanda tangan berhasil diupdate!!! </div> </div> </div> </div> </div> <script> var wrapper = document.getElementById("signature-pad"), clearButton = wrapper.querySelector("[data-action=clear]"), saveButton = wrapper.querySelector("[data-action=save]"), canvas = wrapper.querySelector("canvas"), signaturePad; function resizeCanvas() { var ratio = window.devicePixelRatio || 1; canvas.width = canvas.offsetWidth * ratio; canvas.height = canvas.offsetHeight * ratio; canvas.getContext("2d").scale(ratio, ratio); } signaturePad = new SignaturePad(canvas); clearButton.addEventListener("click", function(event) { signaturePad.clear(); }); saveButton.addEventListener("click", function(event) { if (signaturePad.isEmpty()) { $('#myModal').modal('show'); } else { $.ajax({ type: "POST", url: "<?php echo base_url(); ?>ks/insert_single_signature", data: { 'image': signaturePad.toDataURL(), 'id': $('#id').val(), 'nama': $('#nama').val(), 'rowno': $('#rowno').val() }, success: function(datas1) { signaturePad.clear(); $('#myModal2').modal('show'); setTimeout(function() { window.location.reload(1); }, 3000); $('.sukses').html(datas1); } }); } }); </script> <style type="text/css"> .previewsign { border: 1px dashed #ccc; border-radius: 5px; color: #bbbabb; height: 220px; width: 200px; text-align: center; /* float: right; */ vertical-align: middle; /* top: 73px; position: fixed; right: 35px; */ } .m-signature-pad-body { border: 1px dashed #ccc; border-radius: 5px; color: #bbbabb; height: 253px; width: 200px; text-align: center; /* float: right; */ vertical-align: middle; /* top: 73px; */ /* position: fixed; */ /* left: 33px; */ } .m-signature-pad-footer { /* bottom: 250px; */ /* left: 218px; */ position: center, absolute; } .boxarea { color: #000; margin: 16px 0; padding: 16px 0; float: left; width: 100%; } .img { right: 0; position: absolute; } </style> </body> </html>
29.980892
141
0.483323
aff7e24e17d8499260bf4f3436f23fb19a372356
936
dart
Dart
example/lib/video_list.dart
JamalBelilet/youtube_player_flutter
09babf334f03f1502d56cd0591e7a5a9b154e736
[ "MIT" ]
1
2020-01-03T10:31:01.000Z
2020-01-03T10:31:01.000Z
example/lib/video_list.dart
JamalBelilet/youtube_player_flutter
09babf334f03f1502d56cd0591e7a5a9b154e736
[ "MIT" ]
null
null
null
example/lib/video_list.dart
JamalBelilet/youtube_player_flutter
09babf334f03f1502d56cd0591e7a5a9b154e736
[ "MIT" ]
1
2020-06-20T22:40:01.000Z
2020-06-20T22:40:01.000Z
import 'package:flutter/material.dart'; import 'package:youtube_player_flutter/youtube_player_flutter.dart'; class VideoList extends StatefulWidget { @override _VideoListState createState() => _VideoListState(); } class _VideoListState extends State<VideoList> { var videoIds = <String>[ "BBAyRBTfsOU", "7QUtEmBT_-w", "QbSzrWYqNRg", "nONOGLMzXjc", "sf3oOx90j9Y", ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Video List"), ), body: ListView.separated( itemBuilder: (context, index) => YoutubePlayer( context: context, videoId: videoIds[index], autoPlay: false, showVideoProgressIndicator: true, ), separatorBuilder: (_, i) => SizedBox( height: 10.0, ), itemCount: videoIds.length, ), ); } }
24
68
0.601496
b8d4aec9ee5797c3238a827e79810263f86300f7
19,990
h
C
packages/core/List.h
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
2
2021-05-06T19:56:26.000Z
2021-05-27T16:41:56.000Z
packages/core/List.h
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
54
2021-03-30T18:45:12.000Z
2022-03-17T20:13:04.000Z
packages/core/List.h
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
1
2021-05-14T16:34:08.000Z
2021-05-14T16:34:08.000Z
/* * Copyright (c) 2021, University of Washington * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the University of Washington nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF WASHINGTON AND CONTRIBUTORS * “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF WASHINGTON OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __list__ #define __list__ /****************************************************************************** * INCLUDES ******************************************************************************/ #include "RTExcept.h" #include <stdlib.h> #include <assert.h> /****************************************************************************** * LIST TEMPLATE ******************************************************************************/ template <class T, int LIST_BLOCK_SIZE=256> class List { protected: /*-------------------------------------------------------------------- * Types *--------------------------------------------------------------------*/ typedef struct list_block_t { T data[LIST_BLOCK_SIZE]; int offset; struct list_block_t* next; } list_node_t; public: /*-------------------------------------------------------------------- * Iterator Subclass *--------------------------------------------------------------------*/ class Iterator { public: Iterator (const List& l); ~Iterator (void); const T& operator[] (int index) const; const int length; private: const list_node_t** blocks; }; /*-------------------------------------------------------------------- * Methods *--------------------------------------------------------------------*/ List (void); List (const List& l1); virtual ~List (void); int add (const T& data); bool remove (int index); T& get (int index); bool set (int index, T& data, bool with_delete=true); int length (void) const; void clear (void); void sort (void); T& operator[] (int index); List& operator= (const List& l1); protected: /*-------------------------------------------------------------------- * Data *--------------------------------------------------------------------*/ list_node_t head; list_node_t* tail; int len; list_node_t* prevnode; int prevblock; /*-------------------------------------------------------------------- * Methods *--------------------------------------------------------------------*/ void initialize (void); void copy (const List& l1); list_node_t* newNode (void); virtual void freeNode (typename List<T, LIST_BLOCK_SIZE>::list_node_t* node, int index); void quicksort (T* array, int start, int end); int quicksortpartition (T* array, int start, int end); }; /****************************************************************************** * MANAGED LIST TEMPLATE ******************************************************************************/ template <class T, int LIST_BLOCK_SIZE=256, bool is_array=false> class MgList: public List<T, LIST_BLOCK_SIZE> { public: MgList (void); ~MgList (void); private: void freeNode (typename List<T, LIST_BLOCK_SIZE>::list_node_t* node, int index); }; /****************************************************************************** * ITERATOR METHODS ******************************************************************************/ /*---------------------------------------------------------------------------- * Constructor *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> List<T, LIST_BLOCK_SIZE>::Iterator::Iterator(const List& l): length(l.len) { int num_blocks = (length + (LIST_BLOCK_SIZE - 1)) / LIST_BLOCK_SIZE; blocks = new const List<T, LIST_BLOCK_SIZE>::list_node_t* [num_blocks]; const List<T, LIST_BLOCK_SIZE>::list_node_t* curr_block = &l.head; for(int b = 0; b < num_blocks; b++) { assert(curr_block); blocks[b] = curr_block; curr_block = curr_block->next; } } /*---------------------------------------------------------------------------- * Destructor *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> List<T, LIST_BLOCK_SIZE>::Iterator::~Iterator(void) { delete [] blocks; } /*---------------------------------------------------------------------------- * [] *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> const T& List<T, LIST_BLOCK_SIZE>::Iterator::operator[](int index) const { if( (index < length) && (index >= 0) ) { int node_block = index / LIST_BLOCK_SIZE; int node_offset = index % LIST_BLOCK_SIZE; const List<T, LIST_BLOCK_SIZE>::list_node_t* block = blocks[node_block]; return block->data[node_offset]; } else { throw RunTimeException(CRITICAL, "List::Iterator index out of range"); } } /****************************************************************************** * LIST METHODS ******************************************************************************/ /*---------------------------------------------------------------------------- * Constructor *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> List<T, LIST_BLOCK_SIZE>::List(void) { initialize(); } /*---------------------------------------------------------------------------- * Copy Constructor *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> List<T, LIST_BLOCK_SIZE>::List(const List<T, LIST_BLOCK_SIZE>& l1) { initialize(); copy(l1); } /*---------------------------------------------------------------------------- * Destructor *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> List<T, LIST_BLOCK_SIZE>::~List(void) { clear(); } /*---------------------------------------------------------------------------- * add *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> int List<T, LIST_BLOCK_SIZE>::add(const T& data) { /* Check if Current Node is Full */ if(tail->offset >= LIST_BLOCK_SIZE) { tail->next = newNode(); tail = tail->next; } /* Add Element to Tail */ tail->data[tail->offset] = data; tail->offset++; /* Increment Length and Return Index */ int index = len++; return index; } /*---------------------------------------------------------------------------- * remove *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> bool List<T, LIST_BLOCK_SIZE>::remove(int index) { if( (index < len) && (index >= 0) ) { int node_block = index / LIST_BLOCK_SIZE; int node_offset = index % LIST_BLOCK_SIZE; list_node_t* curr = &head; list_node_t* prev = NULL; for(int i = 0; i < node_block; i++) { prev = curr; curr = curr->next; } /* Remove the Data */ freeNode(curr, node_offset); /* Reset Previous Node Memory */ prevnode = &head; prevblock = 0; /* Last Item In List */ if(node_offset == (curr->offset - 1)) { curr->offset--; if(curr->offset == 0) { /* Current Block Is Empty */ if(prev) // check that current block isn't head { delete prev->next; prev->next = NULL; } } } else /* Middle Item In List */ { /* Shift for Each Block */ int start_offset = node_offset; int curr_offset = index; while(curr != NULL) { /* Shift Current Block */ for(int i = start_offset; (i < LIST_BLOCK_SIZE - 1) && (curr_offset < len - 1); i++) { curr->data[i] = curr->data[i + 1]; curr_offset++; } /* Shift Last Item */ if(curr_offset < (len - 1) && curr->next != NULL) { curr->data[LIST_BLOCK_SIZE - 1] = curr->next->data[0]; curr_offset++; if(curr_offset >= (len - 1)) { /* Next Block Is Empty */ delete curr->next; curr->next = NULL; } } else { curr->offset--; } /* Goto Next Block */ start_offset = 0; curr = curr->next; } } /* Update Length */ len--; /* Recalculate the Tail */ int tail_block = len / LIST_BLOCK_SIZE; tail = &head; for (int i = 0; i < tail_block; i++) { assert(tail); tail = tail->next; } /* Return Success */ return true; } return false; } /*---------------------------------------------------------------------------- * get *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> T& List<T, LIST_BLOCK_SIZE>::get(int index) { if( (index < len) && (index >= 0) ) { int node_block = index / LIST_BLOCK_SIZE; int node_offset = index % LIST_BLOCK_SIZE; list_node_t* curr = &head; if(node_block == prevblock) { curr = prevnode; } else if(node_block > prevblock) { curr = prevnode; for(int i = prevblock; i < node_block; i++) { assert(curr); curr = curr->next; } prevblock = node_block; prevnode = curr; } else { for(int i = 0; i < node_block; i++) { assert(curr); curr = curr->next; } prevblock = node_block; prevnode = curr; } assert(curr); return curr->data[node_offset]; } else { throw RunTimeException(CRITICAL, "List::get index out of range"); } } /*---------------------------------------------------------------------------- * set * * with_delete which is defaulted to true, can be set to false for times when * the list is reordered in place and the caller wants control over deallocation *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> bool List<T, LIST_BLOCK_SIZE>::set(int index, T& data, bool with_delete) { if( (index < len) && (index >= 0) ) { int node_block = index / LIST_BLOCK_SIZE; int node_offset = index % LIST_BLOCK_SIZE; list_node_t* curr = &head; if(node_block == prevblock) { curr = prevnode; } else if(node_block > prevblock) { curr = prevnode; for(int i = prevblock; i < node_block; i++) curr = curr->next; prevblock = node_block; prevnode = curr; } else { for(int i = 0; i < node_block; i++) curr = curr->next; prevblock = node_block; prevnode = curr; } if(with_delete) freeNode(curr, node_offset); curr->data[node_offset] = data; return true; } else { return false; } } /*---------------------------------------------------------------------------- * length *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> int List<T, LIST_BLOCK_SIZE>::length(void) const { return len; } /*---------------------------------------------------------------------------- * clear *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> void List<T, LIST_BLOCK_SIZE>::clear(void) { /* Delete Head */ for(int i = 0; i < head.offset; i++) freeNode(&head, i); /* Delete Rest of List */ list_node_t* curr = head.next; while(curr != NULL) { for(int i = 0; i < curr->offset; i++) freeNode(curr, i); curr->offset = 0; list_node_t* prev = curr; curr = curr->next; delete prev; } /* Clean Up Parameters */ head.offset = 0; head.next = NULL; tail = &head; len = 0; } /*---------------------------------------------------------------------------- * sort *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> void List<T, LIST_BLOCK_SIZE>::sort(void) { /* Allocate Array */ T* array = new T[len]; /* Build Array */ for(int i = 0; i < len; i++) { array[i] = get(i); } /* Sort Array */ quicksort(array, 0, len - 1); /* Write Array */ for(int i = 0; i < len; i++) { set(i, array[i], false); } /* Deallocate Array */ delete [] array; } /*---------------------------------------------------------------------------- * [] *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> T& List<T, LIST_BLOCK_SIZE>::operator[](int index) { return get(index); } /*---------------------------------------------------------------------------- * = *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> List<T, LIST_BLOCK_SIZE>& List<T, LIST_BLOCK_SIZE>::operator= (const List<T, LIST_BLOCK_SIZE>& l1) { clear(); copy(l1); return *this; } /*---------------------------------------------------------------------------- * initialize *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> void List<T, LIST_BLOCK_SIZE>::initialize(void) { head.offset = 0; head.next = NULL; tail = &head; len = 0; prevnode = &head; prevblock = 0; } /*---------------------------------------------------------------------------- * = *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> void List<T, LIST_BLOCK_SIZE>::copy(const List<T, LIST_BLOCK_SIZE>& l1) { const list_node_t* curr = &l1.head; while(curr) { for(int i = 0; i < curr->offset; i++) { add(curr->data[i]); } curr = curr->next; } } /*---------------------------------------------------------------------------- * newNode *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> typename List<T, LIST_BLOCK_SIZE>::list_node_t* List<T, LIST_BLOCK_SIZE>::newNode(void) { list_node_t* node = new list_node_t; node->next = NULL; node->offset = 0; return node; } /*---------------------------------------------------------------------------- * freeNode *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> void List<T, LIST_BLOCK_SIZE>::freeNode(typename List<T, LIST_BLOCK_SIZE>::list_node_t* node, int index) { (void)node; (void)index; } /*---------------------------------------------------------------------------- * quicksort *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> void List<T, LIST_BLOCK_SIZE>::quicksort(T* array, int start, int end) { if(start < end) { int partition = quicksortpartition(array, start, end); quicksort(array, start, partition); quicksort(array, partition + 1, end); } } /*---------------------------------------------------------------------------- * quicksortpartition *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE> int List<T, LIST_BLOCK_SIZE>::quicksortpartition(T* array, int start, int end) { double pivot = array[(start + end) / 2]; start--; end++; while(true) { while (array[++start] < pivot); while (array[--end] > pivot); if (start >= end) return end; T tmp = array[start]; array[start] = array[end]; array[end] = tmp; } } /****************************************************************************** * MANAGED LIST METHODS ******************************************************************************/ /*---------------------------------------------------------------------------- * Constructor *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE, bool is_array> MgList<T, LIST_BLOCK_SIZE, is_array>::MgList(void): List<T, LIST_BLOCK_SIZE>() { } /*---------------------------------------------------------------------------- * Destructor *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE, bool is_array> MgList<T, LIST_BLOCK_SIZE, is_array>::~MgList(void) { List<T, LIST_BLOCK_SIZE>::clear(); } /*---------------------------------------------------------------------------- * freeNode *----------------------------------------------------------------------------*/ template <class T, int LIST_BLOCK_SIZE, bool is_array> void MgList<T, LIST_BLOCK_SIZE, is_array>::freeNode(typename List<T, LIST_BLOCK_SIZE>::list_node_t* node, int index) { if(!is_array) delete node->data[index]; else delete [] node->data[index]; } #endif /* __list__ */
32.138264
116
0.403202
f5d211cd294da87443f24d79742d1a0c0f1f1d6c
83
css
CSS
app/assets/stylesheets/application.css
jbpawlik/formulary
4fb306a68fbc7b043c31ba0faf69c3afef1041b8
[ "BSD-2-Clause" ]
null
null
null
app/assets/stylesheets/application.css
jbpawlik/formulary
4fb306a68fbc7b043c31ba0faf69c3afef1041b8
[ "BSD-2-Clause" ]
null
null
null
app/assets/stylesheets/application.css
jbpawlik/formulary
4fb306a68fbc7b043c31ba0faf69c3afef1041b8
[ "BSD-2-Clause" ]
null
null
null
@import "bootstrap"; body { display: inline-flex; flex-direction: column; }
9.222222
25
0.662651
ff4a359ca1800ca600a5729e06887729c91a3548
8,631
py
Python
bopy/optimizer.py
TomPretty/bopy
940ad1f2935219304495f5b129cc8dde22b49f4d
[ "MIT" ]
1
2020-04-06T13:43:25.000Z
2020-04-06T13:43:25.000Z
bopy/optimizer.py
TomPretty/bopy
940ad1f2935219304495f5b129cc8dde22b49f4d
[ "MIT" ]
18
2020-02-14T21:52:04.000Z
2020-03-04T20:40:13.000Z
bopy/optimizer.py
TomPretty/bopy
940ad1f2935219304495f5b129cc8dde22b49f4d
[ "MIT" ]
2
2020-02-12T11:43:58.000Z
2020-04-06T13:43:27.000Z
from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Callable, Dict, Tuple import numpy as np from dppy.finite_dpps import FiniteDPP from scipydirect import minimize from .acquisition import ( AcquisitionFunction, OneShotBatchAcquisitionFunction, SequentialBatchAcquisitionFunction, ) from .bounds import Bounds @dataclass class OptimizationResult: """Optimization result. Parameters ---------- x_min : np.ndarray of shape (batch_size, n_dimensions) The argmin. f_min : np.ndarray of shape (batch_size,) The min. """ x_min: np.ndarray f_min: np.ndarray class Optimizer(ABC): """An acquisition function Optimizer. Optimizers find the minimum of a given acquisition function. This minimum is then used as the next query location of the objective function. Parameters ---------- acquisition_function : AcquisitionFunction The acquisition function. bounds : Bounds The parameter bounds. """ def __init__(self, acquisition_function: AcquisitionFunction, bounds: Bounds): self.acquisition_function = acquisition_function self.bounds = bounds def optimize(self) -> OptimizationResult: """Optimize an acquisition function. Optimizes the `acquisition_function` over the `surrogate` model, within the `bounds`. Returns ------- optimization_result: OptimizationResult The result of optimization. """ x_min, f_min = self._optimize() return OptimizationResult(x_min=x_min, f_min=f_min) @abstractmethod def _optimize(self) -> Tuple[np.ndarray, np.ndarray]: """Optimize an acquisition function.""" class DirectOptimizer(Optimizer): """Direct acquisition function Optimizer. This is a wrapper around the DIRECT global optimizer. Specifically, we use the scipydirect implementation. Parameters ---------- acquisition_function : AcquisitionFunction The acquisition function. bounds : Bounds The parameter bounds. direct_kwargs : Dict[str, Any] Kwargs passed to scipydirect.minimize. """ def __init__( self, acquisition_function: AcquisitionFunction, bounds: Bounds, **direct_kwargs: Dict[str, Any] ): super().__init__(acquisition_function, bounds) self.direct_kwargs = direct_kwargs def _optimize(self) -> Tuple[np.ndarray, np.ndarray]: def objective(x): return self.acquisition_function(x.reshape(1, -1)) res = minimize( objective, bounds=list(zip(self.bounds.lowers, self.bounds.uppers)), **self.direct_kwargs ) x_min = res.x f_min = res.fun return np.array([x_min]), np.array([f_min]) class SequentialBatchOptimizer(Optimizer): """Sequential Batch Optimizer. This is a batch optimizer that selects a batch by sequentially selecting points from a SequentialBatchAcquisitionFunction. This proceeds by repeatedly optimizing then updating said acquisition function. Parameters ---------- acquisition_function : SequentialBatchAcquisitionFunction The sequential batch acquisition function to be optimized. bounds : Bounds The parameter bounds. base_optimizer : Optimizer The underlying optimizer used to optimize the acquisition function. batch_size : int The size of the batch. """ def __init__( self, acquisition_function: SequentialBatchAcquisitionFunction, bounds: Bounds, base_optimizer: Optimizer, batch_size: int, ): super().__init__(acquisition_function, bounds) self.base_optimizer = base_optimizer self.batch_size = batch_size self.x_mins = [] self.f_mins = [] def _optimize(self) -> Tuple[np.ndarray, np.ndarray]: self.start_batch() self.acquisition_function.start_batch() for _ in range(self.batch_size): res = self.base_optimizer.optimize() self.add_to_batch(res) self.acquisition_function.add_to_batch(res) self.acquisition_function.finish_batch() return self.get_batch() def start_batch(self) -> None: """Prepare to start creating a batch.""" self.x_mins = [] self.f_mins = [] def add_to_batch(self, optimization_result: OptimizationResult) -> None: """Add the newly selected point to the batch.""" self.x_mins.append(optimization_result.x_min) self.f_mins.append(optimization_result.f_min) def get_batch(self) -> None: """Get the resulting batch.""" return np.concatenate(self.x_mins), np.concatenate(self.f_mins) class OneShotBatchOptimizerStrategy(ABC): """One-shot Batch Optimizer Strategy. Strategies implement a `select` method for selecting a batch of trial locations given all of the evaluations of an aquisition function during a single pass of global optimization. """ @abstractmethod def select( self, x: np.ndarray, a_x: np.ndarray, batch_size: int ) -> Tuple[np.ndarray, np.ndarray]: """Select a batch of points.""" raise NotImplementedError class OneShotBatchOptimizerRandomSamplingStrategy(OneShotBatchOptimizerStrategy): """One-shot Batch Optimizer Random Sampling Strategy. The random sampling strategy simply randomly samples a subset of the acquistion function evaluations. """ def select( self, x: np.ndarray, a_x: np.ndarray, batch_size: int ) -> Tuple[np.ndarray, np.ndarray]: """Select a batch of points by random sampling.""" indicies = np.random.choice(range(len(x)), size=batch_size) return x[indicies], a_x[indicies] class OneShotBatchOptimizerKDPPSamplingStrategy(OneShotBatchOptimizerStrategy): """One-shot Batch Optimizer k-DPP Sampling Strategy. The k-DPP sampling strategy samples a subset of the acquistion function evaluations from a k-DPP. Parameters ---------- kernel : Callable[[np.ndarray], np.ndarray] The kernel to compute the likelihood matrix for the dpp. alpha : float Small constant added to the diagonal of the likelihood matrix, by defaul 1e-5. """ def __init__(self, kernel: Callable[[np.ndarray], np.ndarray], alpha: float = 1e-5): super().__init__() self.kernel = kernel self.alpha = alpha def select( self, x: np.ndarray, a_x: np.ndarray, batch_size: int ) -> Tuple[np.ndarray, np.ndarray]: """Select a batch of points by sampling from a k-dpp.""" likelihood = self.kernel(x) + self.alpha * np.eye(len(x)) dpp = FiniteDPP("likelihood", L=likelihood) dpp.sample_exact_k_dpp(size=batch_size) indices = dpp.list_of_samples[0] return x[indices], a_x[indices] class OneShotBatchOptimizer(Optimizer): """One-shot Batch Optimizer. The one-shot optimizer selects a batch of points using just a single global optimization pass. This works by using `base_optimizer` to optimize the `acquisition_function` and then selecting a batch from all the evaluations using a `strategy`. Parameters ---------- acquisition_function : OneShotBatchAcquisitionFunction A one-shot batch acquisition function. bounds : Bounds The parameter bounds. base_optimizer : Optimizer The base optimizer that runs global optimization of the acquisition_function. batch_size : int The size of the batch. strategy : OneShotBatchOptimizerStrategy The strategy used to select a batch of points given all the evaluations during a global optimization of the acquisition function. """ def __init__( self, acquisition_function: OneShotBatchAcquisitionFunction, bounds: Bounds, base_optimizer: Optimizer, batch_size: int, strategy: OneShotBatchOptimizerStrategy, ): super().__init__(acquisition_function, bounds) self.base_optimizer = base_optimizer self.batch_size = batch_size self.strategy = strategy def _optimize(self) -> Tuple[np.ndarray, np.ndarray]: self.acquisition_function.start_optimization() self.base_optimizer.optimize() xs, a_xs = self.acquisition_function.get_evaluations() xs, a_xs = self.strategy.select(xs, a_xs, self.batch_size) return xs, a_xs
31.158845
88
0.671185
716167942ebc77c12acf158d0b5fdede95ac61c4
3,016
rb
Ruby
vendor/RMagick4J/lib/rmagick4j/draw.rb
nicksieger/advent-jruby
4f3d678ed6888aabcdd69d5372d80ed78989425d
[ "MIT" ]
1
2016-05-08T19:48:17.000Z
2016-05-08T19:48:17.000Z
vendor/RMagick4J/lib/rmagick4j/draw.rb
nicksieger/advent-jruby
4f3d678ed6888aabcdd69d5372d80ed78989425d
[ "MIT" ]
null
null
null
vendor/RMagick4J/lib/rmagick4j/draw.rb
nicksieger/advent-jruby
4f3d678ed6888aabcdd69d5372d80ed78989425d
[ "MIT" ]
null
null
null
module Magick class Draw def annotate(img, width, height, x, y, text, &add) instance_eval &add if add text = parse_string(text) @draw.annotate(img._image, width, height, x, y, text) self end def clone b = Draw.new b.primitives = @primitives.clone b._draw = @draw.clone b.freeze if self.frozen? b end def draw(image) @draw.clone.draw(image._image, Magick4J.CommandParser.parse(@primitives)) self end def fill= fill @draw.fill = Magick4J.ColorDatabase.query_default(fill) self end def font_family= font_family @draw.font_family = font_family self end def font_weight= font_weight font_weight = {BoldWeight => 700, NormalWeight => 400}[font_weight] @draw.font_weight = font_weight end def get_multiline_type_metrics(*args) raise ArgumentError.new('wrong number of arguments (#{args.length})') if not (1..2) === args.length string = parse_string(args.last) image = args.first._image if args.length == 2 type_metrics_from_java(@draw.getMultilineTypeMetrics(string, image)) end def get_type_metrics(*args) raise ArgumentError.new('wrong number of arguments (#{args.length})') if not (1..2) === args.length string = parse_string(args.last) image = args.first._image if args.length == 2 type_metrics_from_java(@draw.getTypeMetrics(string, image)) end def font= font # TODO end def gravity= gravity @draw.setGravity(gravity._val) end def initialize # Docs say that you can initialize with a block, but it doesn't really work because it inits an ImageInfo not a DrawInfo. # instance_eval &add if add @draw = Magick4J::DrawInfo.new @primitives = '' end def inspect if @primitives == '' '(no primitives defined)' else @primitives end end def pointsize= pointsize @draw.setPointSize(pointsize) end def primitive primitive # TODO Concat in a string like they do, then use helper to parse later @primitives << "\n" unless @primitives.empty? @primitives << primitive.gsub(/[\r|\n]/, '') self end def rotation= rotation @draw.rotate(rotation) self end def stroke= stroke @draw.setStroke(Magick4J.ColorDatabase.queryDefault(stroke)) self end private def parse_string(text) text.split(/\\n/).join("\n") end def type_metrics_from_java(jmetrics) metrics = TypeMetric.new metrics.ascent = jmetrics.getAscent metrics.descent = jmetrics.getDescent metrics.height = jmetrics.getHeight metrics.max_advance = jmetrics.getMaxAdvance metrics.width = jmetrics.getWidth metrics end protected def primitives=(value) @primitives = value.to_str end def _draw=(value) @draw = value end end end
24.128
127
0.629973
1b531f1ba2773a1a2fd3cfbf312ba91b54f25097
22,320
cs
C#
Assembly-CSharp/Pathfinding/VectorMath.cs
FreyaFreed/mordheim
5aab3cbfbb6653a50109b5222f18ccfc7df2af7d
[ "CC0-1.0" ]
4
2020-01-02T11:35:16.000Z
2020-04-08T22:52:14.000Z
Assembly-CSharp/Pathfinding/VectorMath.cs
FreyaFreed/mordheim
5aab3cbfbb6653a50109b5222f18ccfc7df2af7d
[ "CC0-1.0" ]
null
null
null
Assembly-CSharp/Pathfinding/VectorMath.cs
FreyaFreed/mordheim
5aab3cbfbb6653a50109b5222f18ccfc7df2af7d
[ "CC0-1.0" ]
null
null
null
using System; using UnityEngine; namespace Pathfinding { public static class VectorMath { public static global::UnityEngine.Vector3 ClosestPointOnLine(global::UnityEngine.Vector3 lineStart, global::UnityEngine.Vector3 lineEnd, global::UnityEngine.Vector3 point) { global::UnityEngine.Vector3 vector = global::UnityEngine.Vector3.Normalize(lineEnd - lineStart); float d = global::UnityEngine.Vector3.Dot(point - lineStart, vector); return lineStart + d * vector; } public static float ClosestPointOnLineFactor(global::UnityEngine.Vector3 lineStart, global::UnityEngine.Vector3 lineEnd, global::UnityEngine.Vector3 point) { global::UnityEngine.Vector3 rhs = lineEnd - lineStart; float sqrMagnitude = rhs.sqrMagnitude; if ((double)sqrMagnitude <= 1E-06) { return 0f; } return global::UnityEngine.Vector3.Dot(point - lineStart, rhs) / sqrMagnitude; } public static float ClosestPointOnLineFactor(global::Pathfinding.Int3 lineStart, global::Pathfinding.Int3 lineEnd, global::Pathfinding.Int3 point) { global::Pathfinding.Int3 rhs = lineEnd - lineStart; float sqrMagnitude = rhs.sqrMagnitude; float num = (float)global::Pathfinding.Int3.Dot(point - lineStart, rhs); if (sqrMagnitude != 0f) { num /= sqrMagnitude; } return num; } public static float ClosestPointOnLineFactor(global::Pathfinding.Int2 lineStart, global::Pathfinding.Int2 lineEnd, global::Pathfinding.Int2 point) { global::Pathfinding.Int2 b = lineEnd - lineStart; double num = (double)b.sqrMagnitudeLong; double num2 = (double)global::Pathfinding.Int2.DotLong(point - lineStart, b); if (num != 0.0) { num2 /= num; } return (float)num2; } public static global::UnityEngine.Vector3 ClosestPointOnSegment(global::UnityEngine.Vector3 lineStart, global::UnityEngine.Vector3 lineEnd, global::UnityEngine.Vector3 point) { global::UnityEngine.Vector3 vector = lineEnd - lineStart; float sqrMagnitude = vector.sqrMagnitude; if ((double)sqrMagnitude <= 1E-06) { return lineStart; } float value = global::UnityEngine.Vector3.Dot(point - lineStart, vector) / sqrMagnitude; return lineStart + global::UnityEngine.Mathf.Clamp01(value) * vector; } public static global::UnityEngine.Vector3 ClosestPointOnSegmentXZ(global::UnityEngine.Vector3 lineStart, global::UnityEngine.Vector3 lineEnd, global::UnityEngine.Vector3 point) { lineStart.y = point.y; lineEnd.y = point.y; global::UnityEngine.Vector3 vector = lineEnd - lineStart; global::UnityEngine.Vector3 a = vector; a.y = 0f; float magnitude = a.magnitude; global::UnityEngine.Vector3 vector2 = (magnitude <= float.Epsilon) ? global::UnityEngine.Vector3.zero : (a / magnitude); float value = global::UnityEngine.Vector3.Dot(point - lineStart, vector2); return lineStart + global::UnityEngine.Mathf.Clamp(value, 0f, a.magnitude) * vector2; } public static float SqrDistancePointSegmentApproximate(int x, int z, int px, int pz, int qx, int qz) { float num = (float)(qx - px); float num2 = (float)(qz - pz); float num3 = (float)(x - px); float num4 = (float)(z - pz); float num5 = num * num + num2 * num2; float num6 = num * num3 + num2 * num4; if (num5 > 0f) { num6 /= num5; } if (num6 < 0f) { num6 = 0f; } else if (num6 > 1f) { num6 = 1f; } num3 = (float)px + num6 * num - (float)x; num4 = (float)pz + num6 * num2 - (float)z; return num3 * num3 + num4 * num4; } public static float SqrDistancePointSegmentApproximate(global::Pathfinding.Int3 a, global::Pathfinding.Int3 b, global::Pathfinding.Int3 p) { float num = (float)(b.x - a.x); float num2 = (float)(b.z - a.z); float num3 = (float)(p.x - a.x); float num4 = (float)(p.z - a.z); float num5 = num * num + num2 * num2; float num6 = num * num3 + num2 * num4; if (num5 > 0f) { num6 /= num5; } if (num6 < 0f) { num6 = 0f; } else if (num6 > 1f) { num6 = 1f; } num3 = (float)a.x + num6 * num - (float)p.x; num4 = (float)a.z + num6 * num2 - (float)p.z; return num3 * num3 + num4 * num4; } public static float SqrDistancePointSegment(global::UnityEngine.Vector3 a, global::UnityEngine.Vector3 b, global::UnityEngine.Vector3 p) { global::UnityEngine.Vector3 a2 = global::Pathfinding.VectorMath.ClosestPointOnSegment(a, b, p); return (a2 - p).sqrMagnitude; } public static float SqrDistanceSegmentSegment(global::UnityEngine.Vector3 s1, global::UnityEngine.Vector3 e1, global::UnityEngine.Vector3 s2, global::UnityEngine.Vector3 e2) { global::UnityEngine.Vector3 vector = e1 - s1; global::UnityEngine.Vector3 vector2 = e2 - s2; global::UnityEngine.Vector3 vector3 = s1 - s2; float num = global::UnityEngine.Vector3.Dot(vector, vector); float num2 = global::UnityEngine.Vector3.Dot(vector, vector2); float num3 = global::UnityEngine.Vector3.Dot(vector2, vector2); float num4 = global::UnityEngine.Vector3.Dot(vector, vector3); float num5 = global::UnityEngine.Vector3.Dot(vector2, vector3); float num6 = num * num3 - num2 * num2; float num7 = num6; float num8 = num6; float num9; float num10; if (num6 < 1E-06f) { num9 = 0f; num7 = 1f; num10 = num5; num8 = num3; } else { num9 = num2 * num5 - num3 * num4; num10 = num * num5 - num2 * num4; if (num9 < 0f) { num9 = 0f; num10 = num5; num8 = num3; } else if (num9 > num7) { num9 = num7; num10 = num5 + num2; num8 = num3; } } if (num10 < 0f) { num10 = 0f; if (-num4 < 0f) { num9 = 0f; } else if (-num4 > num) { num9 = num7; } else { num9 = -num4; num7 = num; } } else if (num10 > num8) { num10 = num8; if (-num4 + num2 < 0f) { num9 = 0f; } else if (-num4 + num2 > num) { num9 = num7; } else { num9 = -num4 + num2; num7 = num; } } float d = (global::System.Math.Abs(num9) >= 1E-06f) ? (num9 / num7) : 0f; float d2 = (global::System.Math.Abs(num10) >= 1E-06f) ? (num10 / num8) : 0f; return (vector3 + d * vector - d2 * vector2).sqrMagnitude; } public static float SqrDistanceXZ(global::UnityEngine.Vector3 a, global::UnityEngine.Vector3 b) { global::UnityEngine.Vector3 vector = a - b; return vector.x * vector.x + vector.z * vector.z; } public static long SignedTriangleAreaTimes2XZ(global::Pathfinding.Int3 a, global::Pathfinding.Int3 b, global::Pathfinding.Int3 c) { return (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z); } public static float SignedTriangleAreaTimes2XZ(global::UnityEngine.Vector3 a, global::UnityEngine.Vector3 b, global::UnityEngine.Vector3 c) { return (b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z); } public static bool RightXZ(global::UnityEngine.Vector3 a, global::UnityEngine.Vector3 b, global::UnityEngine.Vector3 p) { return (b.x - a.x) * (p.z - a.z) - (p.x - a.x) * (b.z - a.z) < -1.401298E-45f; } public static bool RightXZ(global::Pathfinding.Int3 a, global::Pathfinding.Int3 b, global::Pathfinding.Int3 p) { return (long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) < 0L; } public static bool RightOrColinear(global::UnityEngine.Vector2 a, global::UnityEngine.Vector2 b, global::UnityEngine.Vector2 p) { return (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y) <= 0f; } public static bool RightOrColinear(global::Pathfinding.Int2 a, global::Pathfinding.Int2 b, global::Pathfinding.Int2 p) { return (long)(b.x - a.x) * (long)(p.y - a.y) - (long)(p.x - a.x) * (long)(b.y - a.y) <= 0L; } public static bool RightOrColinearXZ(global::UnityEngine.Vector3 a, global::UnityEngine.Vector3 b, global::UnityEngine.Vector3 p) { return (b.x - a.x) * (p.z - a.z) - (p.x - a.x) * (b.z - a.z) <= 0f; } public static bool RightOrColinearXZ(global::Pathfinding.Int3 a, global::Pathfinding.Int3 b, global::Pathfinding.Int3 p) { return (long)(b.x - a.x) * (long)(p.z - a.z) - (long)(p.x - a.x) * (long)(b.z - a.z) <= 0L; } public static bool IsClockwiseMarginXZ(global::UnityEngine.Vector3 a, global::UnityEngine.Vector3 b, global::UnityEngine.Vector3 c) { return (b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z) <= float.Epsilon; } public static bool IsClockwiseXZ(global::UnityEngine.Vector3 a, global::UnityEngine.Vector3 b, global::UnityEngine.Vector3 c) { return (b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z) < 0f; } public static bool IsClockwiseXZ(global::Pathfinding.Int3 a, global::Pathfinding.Int3 b, global::Pathfinding.Int3 c) { return global::Pathfinding.VectorMath.RightXZ(a, b, c); } public static bool IsClockwiseOrColinearXZ(global::Pathfinding.Int3 a, global::Pathfinding.Int3 b, global::Pathfinding.Int3 c) { return global::Pathfinding.VectorMath.RightOrColinearXZ(a, b, c); } public static bool IsClockwiseOrColinear(global::Pathfinding.Int2 a, global::Pathfinding.Int2 b, global::Pathfinding.Int2 c) { return global::Pathfinding.VectorMath.RightOrColinear(a, b, c); } public static bool IsColinearXZ(global::Pathfinding.Int3 a, global::Pathfinding.Int3 b, global::Pathfinding.Int3 c) { return (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z) == 0L; } public static bool IsColinearXZ(global::UnityEngine.Vector3 a, global::UnityEngine.Vector3 b, global::UnityEngine.Vector3 c) { float num = (b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z); return num <= 1E-07f && num >= -1E-07f; } public static bool IsColinearAlmostXZ(global::Pathfinding.Int3 a, global::Pathfinding.Int3 b, global::Pathfinding.Int3 c) { long num = (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z); return num > -1L && num < 1L; } public static bool SegmentsIntersect(global::Pathfinding.Int2 start1, global::Pathfinding.Int2 end1, global::Pathfinding.Int2 start2, global::Pathfinding.Int2 end2) { return global::Pathfinding.VectorMath.RightOrColinear(start1, end1, start2) != global::Pathfinding.VectorMath.RightOrColinear(start1, end1, end2) && global::Pathfinding.VectorMath.RightOrColinear(start2, end2, start1) != global::Pathfinding.VectorMath.RightOrColinear(start2, end2, end1); } public static bool SegmentsIntersectXZ(global::Pathfinding.Int3 start1, global::Pathfinding.Int3 end1, global::Pathfinding.Int3 start2, global::Pathfinding.Int3 end2) { return global::Pathfinding.VectorMath.RightOrColinearXZ(start1, end1, start2) != global::Pathfinding.VectorMath.RightOrColinearXZ(start1, end1, end2) && global::Pathfinding.VectorMath.RightOrColinearXZ(start2, end2, start1) != global::Pathfinding.VectorMath.RightOrColinearXZ(start2, end2, end1); } public static bool SegmentsIntersectXZ(global::UnityEngine.Vector3 start1, global::UnityEngine.Vector3 end1, global::UnityEngine.Vector3 start2, global::UnityEngine.Vector3 end2) { global::UnityEngine.Vector3 vector = end1 - start1; global::UnityEngine.Vector3 vector2 = end2 - start2; float num = vector2.z * vector.x - vector2.x * vector.z; if (num == 0f) { return false; } float num2 = vector2.x * (start1.z - start2.z) - vector2.z * (start1.x - start2.x); float num3 = vector.x * (start1.z - start2.z) - vector.z * (start1.x - start2.x); float num4 = num2 / num; float num5 = num3 / num; return num4 >= 0f && num4 <= 1f && num5 >= 0f && num5 <= 1f; } public static global::UnityEngine.Vector3 LineDirIntersectionPointXZ(global::UnityEngine.Vector3 start1, global::UnityEngine.Vector3 dir1, global::UnityEngine.Vector3 start2, global::UnityEngine.Vector3 dir2) { float num = dir2.z * dir1.x - dir2.x * dir1.z; if (num == 0f) { return start1; } float num2 = dir2.x * (start1.z - start2.z) - dir2.z * (start1.x - start2.x); float d = num2 / num; return start1 + dir1 * d; } public static global::UnityEngine.Vector3 LineDirIntersectionPointXZ(global::UnityEngine.Vector3 start1, global::UnityEngine.Vector3 dir1, global::UnityEngine.Vector3 start2, global::UnityEngine.Vector3 dir2, out bool intersects) { float num = dir2.z * dir1.x - dir2.x * dir1.z; if (num == 0f) { intersects = false; return start1; } float num2 = dir2.x * (start1.z - start2.z) - dir2.z * (start1.x - start2.x); float d = num2 / num; intersects = true; return start1 + dir1 * d; } public static bool RaySegmentIntersectXZ(global::Pathfinding.Int3 start1, global::Pathfinding.Int3 end1, global::Pathfinding.Int3 start2, global::Pathfinding.Int3 end2) { global::Pathfinding.Int3 @int = end1 - start1; global::Pathfinding.Int3 int2 = end2 - start2; long num = (long)(int2.z * @int.x - int2.x * @int.z); if (num == 0L) { return false; } long num2 = (long)(int2.x * (start1.z - start2.z) - int2.z * (start1.x - start2.x)); long num3 = (long)(@int.x * (start1.z - start2.z) - @int.z * (start1.x - start2.x)); return (num2 < 0L ^ num < 0L) && (num3 < 0L ^ num < 0L) && (num < 0L || num3 <= num) && (num >= 0L || num3 > num); } public static bool LineIntersectionFactorXZ(global::Pathfinding.Int3 start1, global::Pathfinding.Int3 end1, global::Pathfinding.Int3 start2, global::Pathfinding.Int3 end2, out float factor1, out float factor2) { global::Pathfinding.Int3 @int = end1 - start1; global::Pathfinding.Int3 int2 = end2 - start2; long num = (long)(int2.z * @int.x - int2.x * @int.z); if (num == 0L) { factor1 = 0f; factor2 = 0f; return false; } long num2 = (long)(int2.x * (start1.z - start2.z) - int2.z * (start1.x - start2.x)); long num3 = (long)(@int.x * (start1.z - start2.z) - @int.z * (start1.x - start2.x)); factor1 = (float)num2 / (float)num; factor2 = (float)num3 / (float)num; return true; } public static bool LineIntersectionFactorXZ(global::UnityEngine.Vector3 start1, global::UnityEngine.Vector3 end1, global::UnityEngine.Vector3 start2, global::UnityEngine.Vector3 end2, out float factor1, out float factor2) { global::UnityEngine.Vector3 vector = end1 - start1; global::UnityEngine.Vector3 vector2 = end2 - start2; float num = vector2.z * vector.x - vector2.x * vector.z; if (num <= 1E-05f && num >= -1E-05f) { factor1 = 0f; factor2 = 0f; return false; } float num2 = vector2.x * (start1.z - start2.z) - vector2.z * (start1.x - start2.x); float num3 = vector.x * (start1.z - start2.z) - vector.z * (start1.x - start2.x); float num4 = num2 / num; float num5 = num3 / num; factor1 = num4; factor2 = num5; return true; } public static float LineRayIntersectionFactorXZ(global::Pathfinding.Int3 start1, global::Pathfinding.Int3 end1, global::Pathfinding.Int3 start2, global::Pathfinding.Int3 end2) { global::Pathfinding.Int3 @int = end1 - start1; global::Pathfinding.Int3 int2 = end2 - start2; int num = int2.z * @int.x - int2.x * @int.z; if (num == 0) { return float.NaN; } int num2 = int2.x * (start1.z - start2.z) - int2.z * (start1.x - start2.x); int num3 = @int.x * (start1.z - start2.z) - @int.z * (start1.x - start2.x); if ((float)num3 / (float)num < 0f) { return float.NaN; } return (float)num2 / (float)num; } public static float LineIntersectionFactorXZ(global::UnityEngine.Vector3 start1, global::UnityEngine.Vector3 end1, global::UnityEngine.Vector3 start2, global::UnityEngine.Vector3 end2) { global::UnityEngine.Vector3 vector = end1 - start1; global::UnityEngine.Vector3 vector2 = end2 - start2; float num = vector2.z * vector.x - vector2.x * vector.z; if (num == 0f) { return -1f; } float num2 = vector2.x * (start1.z - start2.z) - vector2.z * (start1.x - start2.x); return num2 / num; } public static global::UnityEngine.Vector3 LineIntersectionPointXZ(global::UnityEngine.Vector3 start1, global::UnityEngine.Vector3 end1, global::UnityEngine.Vector3 start2, global::UnityEngine.Vector3 end2) { bool flag; return global::Pathfinding.VectorMath.LineIntersectionPointXZ(start1, end1, start2, end2, out flag); } public static global::UnityEngine.Vector3 LineIntersectionPointXZ(global::UnityEngine.Vector3 start1, global::UnityEngine.Vector3 end1, global::UnityEngine.Vector3 start2, global::UnityEngine.Vector3 end2, out bool intersects) { global::UnityEngine.Vector3 a = end1 - start1; global::UnityEngine.Vector3 vector = end2 - start2; float num = vector.z * a.x - vector.x * a.z; if (num == 0f) { intersects = false; return start1; } float num2 = vector.x * (start1.z - start2.z) - vector.z * (start1.x - start2.x); float d = num2 / num; intersects = true; return start1 + a * d; } public static global::UnityEngine.Vector2 LineIntersectionPoint(global::UnityEngine.Vector2 start1, global::UnityEngine.Vector2 end1, global::UnityEngine.Vector2 start2, global::UnityEngine.Vector2 end2) { bool flag; return global::Pathfinding.VectorMath.LineIntersectionPoint(start1, end1, start2, end2, out flag); } public static global::UnityEngine.Vector2 LineIntersectionPoint(global::UnityEngine.Vector2 start1, global::UnityEngine.Vector2 end1, global::UnityEngine.Vector2 start2, global::UnityEngine.Vector2 end2, out bool intersects) { global::UnityEngine.Vector2 a = end1 - start1; global::UnityEngine.Vector2 vector = end2 - start2; float num = vector.y * a.x - vector.x * a.y; if (num == 0f) { intersects = false; return start1; } float num2 = vector.x * (start1.y - start2.y) - vector.y * (start1.x - start2.x); float d = num2 / num; intersects = true; return start1 + a * d; } public static global::UnityEngine.Vector3 SegmentIntersectionPointXZ(global::UnityEngine.Vector3 start1, global::UnityEngine.Vector3 end1, global::UnityEngine.Vector3 start2, global::UnityEngine.Vector3 end2, out bool intersects) { global::UnityEngine.Vector3 a = end1 - start1; global::UnityEngine.Vector3 vector = end2 - start2; float num = vector.z * a.x - vector.x * a.z; if (num == 0f) { intersects = false; return start1; } float num2 = vector.x * (start1.z - start2.z) - vector.z * (start1.x - start2.x); float num3 = a.x * (start1.z - start2.z) - a.z * (start1.x - start2.x); float num4 = num2 / num; float num5 = num3 / num; if (num4 < 0f || num4 > 1f || num5 < 0f || num5 > 1f) { intersects = false; return start1; } intersects = true; return start1 + a * num4; } public static bool SegmentIntersectsBounds(global::UnityEngine.Bounds bounds, global::UnityEngine.Vector3 a, global::UnityEngine.Vector3 b) { a -= bounds.center; b -= bounds.center; global::UnityEngine.Vector3 b2 = (a + b) * 0.5f; global::UnityEngine.Vector3 vector = a - b2; global::UnityEngine.Vector3 vector2 = new global::UnityEngine.Vector3(global::System.Math.Abs(vector.x), global::System.Math.Abs(vector.y), global::System.Math.Abs(vector.z)); global::UnityEngine.Vector3 extents = bounds.extents; return global::System.Math.Abs(b2.x) <= extents.x + vector2.x && global::System.Math.Abs(b2.y) <= extents.y + vector2.y && global::System.Math.Abs(b2.z) <= extents.z + vector2.z && global::System.Math.Abs(b2.y * vector.z - b2.z * vector.y) <= extents.y * vector2.z + extents.z * vector2.y && global::System.Math.Abs(b2.x * vector.z - b2.z * vector.x) <= extents.x * vector2.z + extents.z * vector2.x && global::System.Math.Abs(b2.x * vector.y - b2.y * vector.x) <= extents.x * vector2.y + extents.y * vector2.x; } public static float LineCircleIntersectionFactor(global::UnityEngine.Vector3 circleCenter, global::UnityEngine.Vector3 linePoint1, global::UnityEngine.Vector3 linePoint2, float radius) { float num; global::UnityEngine.Vector3 rhs = global::Pathfinding.VectorMath.Normalize(linePoint2 - linePoint1, out num); global::UnityEngine.Vector3 lhs = linePoint1 - circleCenter; float num2 = global::UnityEngine.Vector3.Dot(lhs, rhs); float num3 = num2 * num2 - (lhs.sqrMagnitude - radius * radius); if (num3 < 0f) { num3 = 0f; } float num4 = -num2 + global::UnityEngine.Mathf.Sqrt(num3); return (num <= 1E-05f) ? 0f : (num4 / num); } public static bool ReversesFaceOrientations(global::UnityEngine.Matrix4x4 matrix) { global::UnityEngine.Vector3 lhs = matrix.MultiplyVector(new global::UnityEngine.Vector3(1f, 0f, 0f)); global::UnityEngine.Vector3 rhs = matrix.MultiplyVector(new global::UnityEngine.Vector3(0f, 1f, 0f)); global::UnityEngine.Vector3 rhs2 = matrix.MultiplyVector(new global::UnityEngine.Vector3(0f, 0f, 1f)); float num = global::UnityEngine.Vector3.Dot(global::UnityEngine.Vector3.Cross(lhs, rhs), rhs2); return num < 0f; } public static bool ReversesFaceOrientationsXZ(global::UnityEngine.Matrix4x4 matrix) { global::UnityEngine.Vector3 vector = matrix.MultiplyVector(new global::UnityEngine.Vector3(1f, 0f, 0f)); global::UnityEngine.Vector3 vector2 = matrix.MultiplyVector(new global::UnityEngine.Vector3(0f, 0f, 1f)); float num = vector.x * vector2.z - vector2.x * vector.z; return num < 0f; } public static global::UnityEngine.Vector3 Normalize(global::UnityEngine.Vector3 v, out float magnitude) { magnitude = v.magnitude; if (magnitude > 1E-05f) { return v / magnitude; } return global::UnityEngine.Vector3.zero; } public static global::UnityEngine.Vector2 Normalize(global::UnityEngine.Vector2 v, out float magnitude) { magnitude = v.magnitude; if (magnitude > 1E-05f) { return v / magnitude; } return global::UnityEngine.Vector2.zero; } public static global::UnityEngine.Vector3 ClampMagnitudeXZ(global::UnityEngine.Vector3 v, float maxMagnitude) { float num = v.x * v.x + v.z * v.z; if (num > maxMagnitude * maxMagnitude && maxMagnitude > 0f) { float num2 = maxMagnitude / global::UnityEngine.Mathf.Sqrt(num); v.x *= num2; v.z *= num2; } return v; } public static float MagnitudeXZ(global::UnityEngine.Vector3 v) { return global::UnityEngine.Mathf.Sqrt(v.x * v.x + v.z * v.z); } } }
38.482759
514
0.66698
a000b9813b740e22ba48a6895f809fcd7e62c73f
3,496
tsx
TypeScript
src/containers/StatDisplay/StatDisplayList.tsx
vegerot/slippi-stats
fb9ec0c750b96f9dc78f614f8cc90d3719f749b8
[ "MIT" ]
9
2020-11-14T17:26:35.000Z
2022-02-01T19:04:02.000Z
src/containers/StatDisplay/StatDisplayList.tsx
vegerot/slippi-stats
fb9ec0c750b96f9dc78f614f8cc90d3719f749b8
[ "MIT" ]
null
null
null
src/containers/StatDisplay/StatDisplayList.tsx
vegerot/slippi-stats
fb9ec0c750b96f9dc78f614f8cc90d3719f749b8
[ "MIT" ]
4
2020-11-14T17:47:20.000Z
2021-11-09T02:56:09.000Z
/** @jsx jsx */ import { css, jsx } from "@emotion/core"; import { reorder } from "lib/util"; import React from "react"; import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd"; import { Theme } from "styles/theme"; import { Divider } from "./Divider"; import { StatDisplayItem } from "./StatDisplayItem"; import { Statistic } from "./Statistic"; interface StatDisplayListProps { theme: Theme; stats: string; setStats: (s: string) => void; } export const StatDisplayList: React.FC<StatDisplayListProps> = (props) => { const { theme, stats, setStats } = props; const [items, setItems] = React.useState<string[]>(stats.split(",")); React.useEffect(() => { setItems(stats.split(",")); }, [stats]); const updateStats = (statIds: string[]) => { // First update the local state setItems(statIds); // Then update the URL state setStats(statIds.join(",")); }; const onDragEnd = (result: any) => { // dropped outside the list if (!result.destination) { return; } const newItems = reorder(items, result.source.index, result.destination.index); updateStats(newItems); }; const onRemove = (statId: string) => { const newItems = items.filter((s) => s !== statId); updateStats(newItems); }; return ( <DragDropContext onDragEnd={onDragEnd}> <Droppable droppableId="droppable"> {(dropProvided, dropSnapshot) => ( <div {...dropProvided.droppableProps} ref={dropProvided.innerRef} css={css` margin: -1rem 0; `} > {items.map((item, index) => { const key = item ? item : "divider"; return ( <Draggable key={key} draggableId={key} index={index}> {(dragProvided, dragSnapshot) => { const additionalStyles = item ? null : dragProvided.dragHandleProps; return ( <StatDisplayItem ref={dragProvided.innerRef} hasItem={Boolean(item)} isDraggingOver={dropSnapshot.isDraggingOver} {...dragProvided.draggableProps} {...additionalStyles} style={dragProvided.draggableProps.style} > {item ? ( <div css={css` position: relative; `} > <Statistic statId={item} theme={theme} {...dragProvided.dragHandleProps} /> <div className="remove" onClick={() => onRemove(item)}> ✕ <span css={css` margin-left: 1rem; `} > REMOVE </span> </div> </div> ) : ( <Divider /> )} </StatDisplayItem> ); }} </Draggable> ); })} {dropProvided.placeholder} </div> )} </Droppable> </DragDropContext> ); };
32.981132
103
0.451659
33c1cb69c767a0d26c451cd9cf7f2a811816ce01
47
c
C
tests/binutils-2.30/src/ld/testsuite/ld-elf/pr18458b.c
sillywalk/grazz
a0adb1a90d41ff9006d8c1476546263f728b3c83
[ "Apache-2.0" ]
3
2021-05-04T17:09:06.000Z
2021-10-04T07:19:26.000Z
tests/binutils-2.30/src/ld/testsuite/ld-elf/pr18458b.c
sillywalk/grazz
a0adb1a90d41ff9006d8c1476546263f728b3c83
[ "Apache-2.0" ]
null
null
null
tests/binutils-2.30/src/ld/testsuite/ld-elf/pr18458b.c
sillywalk/grazz
a0adb1a90d41ff9006d8c1476546263f728b3c83
[ "Apache-2.0" ]
null
null
null
extern void a (void); void b (void) { a(); }
6.714286
21
0.531915
e21b817631e4dbbd81cca04721af4756f107ecb8
29,637
py
Python
svg_parser.py
jkramarz/meerk40t
57c4c3c957bece764ea27cdab91ed1f0a511a759
[ "MIT" ]
null
null
null
svg_parser.py
jkramarz/meerk40t
57c4c3c957bece764ea27cdab91ed1f0a511a759
[ "MIT" ]
null
null
null
svg_parser.py
jkramarz/meerk40t
57c4c3c957bece764ea27cdab91ed1f0a511a759
[ "MIT" ]
null
null
null
import re from xml.etree.ElementTree import iterparse from path import Angle # SVG STATIC VALUES SVG_NAME_TAG = 'svg' SVG_ATTR_VERSION = 'version' SVG_VALUE_VERSION = '1.1' SVG_ATTR_XMLNS = 'xmlns' SVG_VALUE_XMLNS = 'http://www.w3.org/2000/svg' SVG_ATTR_XMLNS_LINK = 'xmlns:xlink' SVG_VALUE_XLINK = 'http://www.w3.org/1999/xlink' SVG_ATTR_XMLNS_EV = 'xmlns:ev' SVG_VALUE_XMLNS_EV = 'http://www.w3.org/2001/xml-events' SVG_ATTR_WIDTH = 'width' SVG_ATTR_HEIGHT = 'height' SVG_ATTR_VIEWBOX = 'viewBox' SVG_TAG_PATH = 'path' SVG_TAG_GROUP = 'g' SVG_TAG_RECT = 'rect' SVG_TAG_CIRCLE = 'circle' SVG_TAG_ELLIPSE = 'ellipse' SVG_TAG_LINE = 'line' SVG_TAG_POLYLINE = 'polyline' SVG_TAG_POLYGON = 'polygon' SVG_TAG_TEXT = 'text' SVG_TAG_IMAGE = 'image' SVG_ATTR_DATA = 'd' SVG_ATTR_FILL = 'fill' SVG_ATTR_STROKE = 'stroke' SVG_ATTR_STROKE_WIDTH = 'stroke-width' SVG_ATTR_TRANSFORM = 'transform' SVG_ATTR_STYLE = 'style' SVG_ATTR_CENTER_X = 'cx' SVG_ATTR_CENTER_Y = 'cy' SVG_ATTR_RADIUS_X = 'rx' SVG_ATTR_RADIUS_Y = 'ry' SVG_ATTR_RADIUS = 'r' SVG_ATTR_POINTS = 'points' SVG_ATTR_PRESERVEASPECTRATIO = 'preserveAspectRatio' SVG_ATTR_X = 'x' SVG_ATTR_Y = 'y' SVG_ATTR_TAG = 'tag' SVG_TRANSFORM_MATRIX = 'matrix' SVG_TRANSFORM_TRANSLATE = 'translate' SVG_TRANSFORM_SCALE = 'scale' SVG_TRANSFORM_ROTATE = 'rotate' SVG_TRANSFORM_SKEW_X = 'skewX' SVG_TRANSFORM_SKEW_Y = 'skewY' SVG_VALUE_NONE = 'none' COORD_PAIR_TMPLT = re.compile( r'([\+-]?\d*[\.\d]\d*[eE][\+-]?\d+|[\+-]?\d*[\.\d]\d*)' + r'(?:\s*,\s*|\s+|(?=-))' + r'([\+-]?\d*[\.\d]\d*[eE][\+-]?\d+|[\+-]?\d*[\.\d]\d*)' ) # Leaf node to pathd values. def path2pathd(path): return path.get(SVG_ATTR_DATA, '') def ellipse2pathd(ellipse): """converts the parameters from an ellipse or a circle to a string for a Path object d-attribute""" cx = ellipse.get(SVG_ATTR_CENTER_X, None) cy = ellipse.get(SVG_ATTR_CENTER_Y, None) rx = ellipse.get(SVG_ATTR_RADIUS_X, None) ry = ellipse.get(SVG_ATTR_RADIUS_X, None) r = ellipse.get(SVG_ATTR_RADIUS, None) if r is not None: rx = ry = float(r) else: rx = float(rx) ry = float(ry) cx = float(cx) cy = float(cy) d = '' d += 'M' + str(cx - rx) + ',' + str(cy) d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(2 * rx) + ',0' d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(-2 * rx) + ',0' return d def polyline2pathd(polyline, is_polygon=False): """converts the string from a polyline parameters to a string for a Path object d-attribute""" polyline_d = polyline.get(SVG_ATTR_POINTS, None) if polyline_d is None: return '' points = COORD_PAIR_TMPLT.findall(polyline_d) closed = (float(points[0][0]) == float(points[-1][0]) and float(points[0][1]) == float(points[-1][1])) # The `parse_path` call ignores redundant 'z' (closure) commands # e.g. `parse_path('M0 0L100 100Z') == parse_path('M0 0L100 100L0 0Z')` # This check ensures that an n-point polygon is converted to an n-Line path. if is_polygon and closed: points.append(points[0]) d = 'M' + 'L'.join('{0} {1}'.format(x, y) for x, y in points) if is_polygon or closed: d += 'z' return d def polygon2pathd(polyline): """converts the string from a polygon parameters to a string for a Path object d-attribute. Note: For a polygon made from n points, the resulting path will be composed of n lines (even if some of these lines have length zero). """ return polyline2pathd(polyline, True) def rect2pathd(rect): """Converts an SVG-rect element to a Path d-string. The rectangle will start at the (x,y) coordinate specified by the rectangle object and proceed counter-clockwise.""" x0, y0 = float(rect.get(SVG_ATTR_X, 0)), float(rect.get(SVG_ATTR_Y, 0)) w, h = float(rect.get(SVG_ATTR_WIDTH, 0)), float(rect.get(SVG_ATTR_HEIGHT, 0)) x1, y1 = x0 + w, y0 x2, y2 = x0 + w, y0 + h x3, y3 = x0, y0 + h d = ("M{} {} L {} {} L {} {} L {} {} z" "".format(x0, y0, x1, y1, x2, y2, x3, y3)) return d def line2pathd(l): return 'M' + l['x1'] + ' ' + l['y1'] + 'L' + l['x2'] + ' ' + l['y2'] # PathTokens class. class PathTokens: """Path Tokens is the class for the general outline of how SVG Pathd objects are stored. Namely, a single non-'e' character and a collection of floating point numbers. While this is explicitly used for SVG pathd objects the method for serializing command data in this fashion is also useful as a standalone class.""" def __init__(self, command_elements): self.command_elements = command_elements commands = '' for k in command_elements: commands += k self.COMMAND_RE = re.compile("([" + commands + "])") self.FLOAT_RE = re.compile("[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?") self.elements = None self.command = None self.last_command = None self.parser = None def _tokenize_path(self, pathdef): for x in self.COMMAND_RE.split(pathdef): if x in self.command_elements: yield x for token in self.FLOAT_RE.findall(x): yield token def get(self): """Gets the element from the stack.""" return self.elements.pop() def pre_execute(self): """Called before any command element is executed.""" pass def post_execute(self): """Called after any command element is executed.""" pass def new_command(self): """Called when command element is switched.""" pass def parse(self, pathdef): self.elements = list(self._tokenize_path(pathdef)) # Reverse for easy use of .pop() self.elements.reverse() while self.elements: if self.elements[-1] in self.command_elements: self.last_command = self.command self.command = self.get() self.new_command() else: if self.command is None: raise ValueError("Invalid command.") # could be faulty implicit or unaccepted element. self.pre_execute() self.command_elements[self.command]() self.post_execute() # SVG Path Tokens. class SVGPathTokens(PathTokens): """Utilizes the general PathTokens class to parse SVG pathd strings. This class has been updated to account for SVG 2.0 version of the zZ command. Points are stored in complex numbers with the real being the x-value and the imaginary part being the y-value.""" def __init__(self): PathTokens.__init__(self, { 'M': self.move_to, 'm': self.move_to, 'L': self.line_to, 'l': self.line_to, "H": self.h_to, "h": self.h_to, "V": self.v_to, "v": self.v_to, "C": self.cubic_to, "c": self.cubic_to, "S": self.smooth_cubic_to, "s": self.smooth_cubic_to, "Q": self.quad_to, "q": self.quad_to, "T": self.smooth_quad_to, "t": self.smooth_quad_to, "A": self.arc_to, "a": self.arc_to, "Z": self.close, "z": self.close }) self.parser = None self.absolute = False def svg_parse(self, parser, pathdef): self.parser = parser self.absolute = False self.parser.start() self.parse(pathdef) self.parser.end() def get_pos(self): if self.command == 'Z': return "z" # After Z, all further expected values are also Z. coord0 = self.get() if coord0 == 'z' or coord0 == 'Z': self.command = 'Z' return "z" coord1 = self.get() position = (float(coord0), float(coord1)) if not self.absolute: current_pos = self.parser.current_point if current_pos is None: return position return [position[0] + current_pos[0], position[1] + current_pos[1]] return position def move_to(self): # Moveto command. pos = self.get_pos() self.parser.move(pos) # Implicit moveto commands are treated as lineto commands. # So we set command to lineto here, in case there are # further implicit commands after this moveto. self.command = 'L' def line_to(self): pos = self.get_pos() self.parser.line(pos) def h_to(self): x = float(self.get()) if self.absolute: self.parser.absolute_h(x) else: self.parser.relative_h(x) def v_to(self): y = float(self.get()) if self.absolute: self.parser.absolute_v(y) else: self.parser.relative_v(y) def cubic_to(self): control1 = self.get_pos() control2 = self.get_pos() end = self.get_pos() self.parser.cubic(control1, control2, end) def smooth_cubic_to(self): control2 = self.get_pos() end = self.get_pos() self.parser.smooth_cubic(control2, end) def quad_to(self): control = self.get_pos() end = self.get_pos() self.parser.quad(control, end) def smooth_quad_to(self): end = self.get_pos() self.parser.smooth_quad(end) def arc_to(self): rx = float(self.get()) ry = float(self.get()) rotation = float(self.get()) arc = float(self.get()) sweep = float(self.get()) end = self.get_pos() self.parser.arc(rx, ry, rotation, arc, sweep, end) def close(self): # Close path self.parser.closed() self.command = None def new_command(self): self.absolute = self.command.isupper() def post_execute(self): if self.command == 'Z': # Z might have been triggered inside commands. self.close() def parse_svg_path(parser, pathdef): """Parses the SVG path.""" tokens = SVGPathTokens() tokens.svg_parse(parser, pathdef) def _tokenize_transform(transform_str): """Generator to create transform parse elements. Will return tuples(command, list(values)) TODO: Convert to 2D CSS transforms from SVG 1.1 for SVG 2.0. In addition to SVG commands, 2D CSS has: translateX, translateY, scaleX, scaleY 2D CSS angles haves units: "deg" tau / 360, "rad" tau/tau, "grad" tau/400, "turn" tau. 2D CSS distances have length/percentages: "px", "cm", "mm", "in", "pt", etc. (+|-)?d+% """ if not transform_str: return transform_regex = '(?u)(' \ + SVG_TRANSFORM_MATRIX + '|' \ + SVG_TRANSFORM_TRANSLATE + '|' \ + SVG_TRANSFORM_SCALE + '|' \ + SVG_TRANSFORM_ROTATE + '|' \ + SVG_TRANSFORM_SKEW_X + '|' \ + SVG_TRANSFORM_SKEW_Y + \ ')[\s\t\n]*\(([^)]+)\)' transform_re = re.compile(transform_regex) float_re = re.compile("[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?") for sub_element in transform_re.findall(transform_str): yield sub_element[0], tuple(map(float, float_re.findall(sub_element[1]))) def parse_viewbox_transform(svg_element): """ SVG 1.1 7.2, SVG 2.0 8.2 equivalent transform of an SVG viewport. With regards to https://github.com/w3c/svgwg/issues/215 use 8.2 version. It creates a matrix equal to that viewport expected. :param svg_element: dict containing the relevant svg entries. :return: string of the SVG transform commands to account for the viewbox. """ if SVG_ATTR_VIEWBOX in svg_element: # Let vb-x, vb-y, vb-width, vb-height be the min-x, min-y, # width and height values of the viewBox attribute respectively. viewbox = svg_element[SVG_ATTR_VIEWBOX] vb = viewbox.split(" ") vb_x = float(vb[0]) vb_y = float(vb[1]) vb_width = float(vb[2]) vb_height = float(vb[3]) else: vb_x = 0.0 vb_y = 0.0 vb_width = 100.0 vb_height = 100.0 # Let e-x, e-y, e-width, e-height be the position and size of the element respectively. if SVG_ATTR_X in svg_element: e_x = parse_svg_distance(svg_element[SVG_ATTR_X]) else: e_x = 0 if SVG_ATTR_Y in svg_element: e_y = parse_svg_distance(svg_element[SVG_ATTR_Y]) else: e_y = 0 if SVG_ATTR_WIDTH in svg_element: e_width = parse_svg_distance(svg_element[SVG_ATTR_WIDTH]) else: e_width = 100.0 if SVG_ATTR_WIDTH in svg_element: e_width = parse_svg_distance(svg_element[SVG_ATTR_WIDTH]) else: e_width = 100.0 if SVG_ATTR_HEIGHT in svg_element: e_height = parse_svg_distance(svg_element[SVG_ATTR_HEIGHT]) else: e_height = e_width # Let align be the align value of preserveAspectRatio, or 'xMidYMid' if preserveAspectRatio is not defined. # Let meetOrSlice be the meetOrSlice value of preserveAspectRatio, or 'meet' if preserveAspectRatio is not defined # or if meetOrSlice is missing from this value. if SVG_ATTR_PRESERVEASPECTRATIO in svg_element: aspect = svg_element[SVG_ATTR_PRESERVEASPECTRATIO] aspect_slice = aspect.slice(' ') try: align = aspect_slice[0] except IndexError: align = 'xMidYMid' try: meet_or_slice = aspect_slice[1] except IndexError: meet_or_slice = 'meet' else: align = 'xMidYMid' meet_or_slice = 'meet' # Initialize scale-x to e-width/vb-width. scale_x = e_width / vb_width # Initialize scale-y to e-height/vb-height. scale_y = e_height / vb_height # If align is not 'none' and meetOrSlice is 'meet', set the larger of scale-x and scale-y to the smaller. if align != SVG_VALUE_NONE and meet_or_slice == 'meet': scale_x = max(scale_x, scale_y) scale_y = scale_x # Otherwise, if align is not 'none' and meetOrSlice is 'slice', set the smaller of scale-x and scale-y to the larger elif align != SVG_VALUE_NONE and meet_or_slice == 'slice': scale_x = min(scale_x, scale_y) scale_y = scale_x # Initialize translate-x to e-x - (vb-x * scale-x). translate_x = e_x - (vb_x * scale_x) # Initialize translate-y to e-y - (vb-y * scale-y) translate_y = e_y - (vb_y * scale_y) # If align contains 'xMid', add (e-width - vb-width * scale-x) / 2 to translate-x. align = align.lower() if 'xmid' in align: translate_x += (e_width - vb_width * scale_x) / 2.0 # If align contains 'xMax', add (e-width - vb-width * scale-x) to translate-x. if 'xmax' in align: translate_x += e_width - vb_width * scale_x # If align contains 'yMid', add (e-height - vb-height * scale-y) / 2 to translate-y. if 'ymid' in align: translate_y += (e_height - vb_height * scale_y) / 2.0 # If align contains 'yMax', add (e-height - vb-height * scale-y) to translate-y. if 'ymax' in align: translate_y += (e_height - vb_height * scale_y) if translate_x == 0 and translate_y == 0: if scale_x == 1 and scale_y == 1: return "" # Nothing happens. else: return "scale(%f, %f)" % (scale_x, scale_y) else: if scale_x == 1 and scale_y == 1: return "translate(%f, %f)" % (translate_x, translate_y) else: return "scale(%f, %f) translate(%f, %f)" % (scale_x, scale_y, translate_x, translate_y) def parse_svg_distance(distance_str): if distance_str.endswith('mm'): return float(distance_str[:-2]) * 3.7795 if distance_str.endswith('cm'): return float(distance_str[:-2]) * 37.795 if distance_str.endswith('in'): return float(distance_str[:-2]) * 96.0 if distance_str.endswith('px'): return float(distance_str[:-2]) if distance_str.endswith('pt'): return float(distance_str[:-2]) * 1.3333 if distance_str.endswith('pc'): return float(distance_str[:-2]) * 16 return float(distance_str) def parse_svg_transform(transform_str, obj): """Parses the svg transform tag. Currently parses SVG 1.1 transformations. With regard to SVG 2.0 would be CSS transformations, and require a superset. For typical usecase these will be given a path.Matrix.""" if not transform_str: return if not isinstance(transform_str, str): raise TypeError('Must provide a string to parse') for name, params in _tokenize_transform(transform_str): if SVG_TRANSFORM_MATRIX == name: obj.pre_cat(*params) elif SVG_TRANSFORM_TRANSLATE == name: obj.pre_translate(*params) elif SVG_TRANSFORM_SCALE == name: obj.pre_scale(*params) elif SVG_TRANSFORM_ROTATE == name: obj.pre_rotate(Angle.degrees(params[0]), *params[1:]) elif SVG_TRANSFORM_SKEW_X == name: obj.pre_skew_x(Angle.degrees(params[0]), *params[1:]) elif SVG_TRANSFORM_SKEW_Y == name: obj.pre_skew_y(Angle.degrees(params[0]), *params[1:]) def parse_svg_file(f, viewport_transform=False): """Parses the SVG file. Style elements are split into their proper values. Transform elements are concatenated and unparsed. Leaf node elements are turned into pathd values.""" stack = [] values = {} for event, elem in iterparse(f, events=('start', 'end')): if event == 'start': stack.append(values) current_values = values values = {} values.update(current_values) # copy of dictionary attributes = elem.attrib if SVG_ATTR_STYLE in attributes: for equate in attributes[SVG_ATTR_STYLE].split(";"): equal_item = equate.split(":") if len(equal_item) == 2: attributes[equal_item[0]] = equal_item[1] if SVG_ATTR_TRANSFORM in attributes: new_transform = attributes[SVG_ATTR_TRANSFORM] if SVG_ATTR_TRANSFORM in values: current_transform = values[SVG_ATTR_TRANSFORM] attributes[SVG_ATTR_TRANSFORM] = current_transform + " " + new_transform else: attributes[SVG_ATTR_TRANSFORM] = new_transform # will be used to update values. values.update(attributes) tag = elem.tag if tag.startswith('{'): tag = tag[28:] # Removing namespace. http://www.w3.org/2000/svg: if SVG_NAME_TAG == tag: if viewport_transform: new_transform = parse_viewbox_transform(values) if SVG_ATTR_TRANSFORM in attributes: values[SVG_ATTR_TRANSFORM] += " " + new_transform else: values[SVG_ATTR_TRANSFORM] = new_transform yield values continue elif SVG_TAG_GROUP == tag: continue elif SVG_TAG_PATH == tag: values[SVG_ATTR_DATA] = path2pathd(values) elif SVG_TAG_CIRCLE == tag: values[SVG_ATTR_DATA] = ellipse2pathd(values) elif SVG_TAG_ELLIPSE == tag: values[SVG_ATTR_DATA] = ellipse2pathd(values) elif SVG_TAG_LINE == tag: values[SVG_ATTR_DATA] = line2pathd(values) elif SVG_TAG_POLYLINE == tag: values[SVG_ATTR_DATA] = polyline2pathd(values) elif SVG_TAG_POLYGON == tag: values[SVG_ATTR_DATA] = polygon2pathd(values) elif SVG_TAG_RECT == tag: values[SVG_ATTR_DATA] = rect2pathd(values) elif SVG_TAG_IMAGE == tag: values[SVG_TAG_IMAGE] = True # Has no pathd data, but yields as element. pass else: continue values[SVG_ATTR_TAG] = tag yield values else: # End event. # The iterparse spec makes it clear that internal text data is undefined except at the end. tag = elem.tag if tag.startswith('{'): tag = tag[28:] # Removing namespace. http://www.w3.org/2000/svg: if SVG_TAG_TEXT == tag: values[SVG_ATTR_TAG] = tag values[SVG_TAG_TEXT] = elem.text yield values values = stack.pop() # SVG Color Parsing def color_rgb(r, g, b): return int(0xFF000000 | ((r & 255) << 16) | ((g & 255) << 8) | (b & 255)) # defining predefined colors permitted by svg: https://www.w3.org/TR/SVG11/types.html#ColorKeywords svg_color_dict = { "aliceblue": color_rgb(240, 248, 255), "antiquewhite": color_rgb(250, 235, 215), "aqua": color_rgb(0, 255, 255), "aquamarine": color_rgb(127, 255, 212), "azure": color_rgb(240, 255, 255), "beige": color_rgb(245, 245, 220), "bisque": color_rgb(255, 228, 196), "black": color_rgb(0, 0, 0), "blanchedalmond": color_rgb(255, 235, 205), "blue": color_rgb(0, 0, 255), "blueviolet": color_rgb(138, 43, 226), "brown": color_rgb(165, 42, 42), "burlywood": color_rgb(222, 184, 135), "cadetblue": color_rgb(95, 158, 160), "chartreuse": color_rgb(127, 255, 0), "chocolate": color_rgb(210, 105, 30), "coral": color_rgb(255, 127, 80), "cornflowerblue": color_rgb(100, 149, 237), "cornsilk": color_rgb(255, 248, 220), "crimson": color_rgb(220, 20, 60), "cyan": color_rgb(0, 255, 255), "darkblue": color_rgb(0, 0, 139), "darkcyan": color_rgb(0, 139, 139), "darkgoldenrod": color_rgb(184, 134, 11), "darkgray": color_rgb(169, 169, 169), "darkgreen": color_rgb(0, 100, 0), "darkgrey": color_rgb(169, 169, 169), "darkkhaki": color_rgb(189, 183, 107), "darkmagenta": color_rgb(139, 0, 139), "darkolivegreen": color_rgb(85, 107, 47), "darkorange": color_rgb(255, 140, 0), "darkorchid": color_rgb(153, 50, 204), "darkred": color_rgb(139, 0, 0), "darksalmon": color_rgb(233, 150, 122), "darkseagreen": color_rgb(143, 188, 143), "darkslateblue": color_rgb(72, 61, 139), "darkslategray": color_rgb(47, 79, 79), "darkslategrey": color_rgb(47, 79, 79), "darkturquoise": color_rgb(0, 206, 209), "darkviolet": color_rgb(148, 0, 211), "deeppink": color_rgb(255, 20, 147), "deepskyblue": color_rgb(0, 191, 255), "dimgray": color_rgb(105, 105, 105), "dimgrey": color_rgb(105, 105, 105), "dodgerblue": color_rgb(30, 144, 255), "firebrick": color_rgb(178, 34, 34), "floralwhite": color_rgb(255, 250, 240), "forestgreen": color_rgb(34, 139, 34), "fuchsia": color_rgb(255, 0, 255), "gainsboro": color_rgb(220, 220, 220), "ghostwhite": color_rgb(248, 248, 255), "gold": color_rgb(255, 215, 0), "goldenrod": color_rgb(218, 165, 32), "gray": color_rgb(128, 128, 128), "grey": color_rgb(128, 128, 128), "green": color_rgb(0, 128, 0), "greenyellow": color_rgb(173, 255, 47), "honeydew": color_rgb(240, 255, 240), "hotpink": color_rgb(255, 105, 180), "indianred": color_rgb(205, 92, 92), "indigo": color_rgb(75, 0, 130), "ivory": color_rgb(255, 255, 240), "khaki": color_rgb(240, 230, 140), "lavender": color_rgb(230, 230, 250), "lavenderblush": color_rgb(255, 240, 245), "lawngreen": color_rgb(124, 252, 0), "lemonchiffon": color_rgb(255, 250, 205), "lightblue": color_rgb(173, 216, 230), "lightcoral": color_rgb(240, 128, 128), "lightcyan": color_rgb(224, 255, 255), "lightgoldenrodyellow": color_rgb(250, 250, 210), "lightgray": color_rgb(211, 211, 211), "lightgreen": color_rgb(144, 238, 144), "lightgrey": color_rgb(211, 211, 211), "lightpink": color_rgb(255, 182, 193), "lightsalmon": color_rgb(255, 160, 122), "lightseagreen": color_rgb(32, 178, 170), "lightskyblue": color_rgb(135, 206, 250), "lightslategray": color_rgb(119, 136, 153), "lightslategrey": color_rgb(119, 136, 153), "lightsteelblue": color_rgb(176, 196, 222), "lightyellow": color_rgb(255, 255, 224), "lime": color_rgb(0, 255, 0), "limegreen": color_rgb(50, 205, 50), "linen": color_rgb(250, 240, 230), "magenta": color_rgb(255, 0, 255), "maroon": color_rgb(128, 0, 0), "mediumaquamarine": color_rgb(102, 205, 170), "mediumblue": color_rgb(0, 0, 205), "mediumorchid": color_rgb(186, 85, 211), "mediumpurple": color_rgb(147, 112, 219), "mediumseagreen": color_rgb(60, 179, 113), "mediumslateblue": color_rgb(123, 104, 238), "mediumspringgreen": color_rgb(0, 250, 154), "mediumturquoise": color_rgb(72, 209, 204), "mediumvioletred": color_rgb(199, 21, 133), "midnightblue": color_rgb(25, 25, 112), "mintcream": color_rgb(245, 255, 250), "mistyrose": color_rgb(255, 228, 225), "moccasin": color_rgb(255, 228, 181), "navajowhite": color_rgb(255, 222, 173), "navy": color_rgb(0, 0, 128), "oldlace": color_rgb(253, 245, 230), "olive": color_rgb(128, 128, 0), "olivedrab": color_rgb(107, 142, 35), "orange": color_rgb(255, 165, 0), "orangered": color_rgb(255, 69, 0), "orchid": color_rgb(218, 112, 214), "palegoldenrod": color_rgb(238, 232, 170), "palegreen": color_rgb(152, 251, 152), "paleturquoise": color_rgb(175, 238, 238), "palevioletred": color_rgb(219, 112, 147), "papayawhip": color_rgb(255, 239, 213), "peachpuff": color_rgb(255, 218, 185), "peru": color_rgb(205, 133, 63), "pink": color_rgb(255, 192, 203), "plum": color_rgb(221, 160, 221), "powderblue": color_rgb(176, 224, 230), "purple": color_rgb(128, 0, 128), "red": color_rgb(255, 0, 0), "rosybrown": color_rgb(188, 143, 143), "royalblue": color_rgb(65, 105, 225), "saddlebrown": color_rgb(139, 69, 19), "salmon": color_rgb(250, 128, 114), "sandybrown": color_rgb(244, 164, 96), "seagreen": color_rgb(46, 139, 87), "seashell": color_rgb(255, 245, 238), "sienna": color_rgb(160, 82, 45), "silver": color_rgb(192, 192, 192), "skyblue": color_rgb(135, 206, 235), "slateblue": color_rgb(106, 90, 205), "slategray": color_rgb(112, 128, 144), "slategrey": color_rgb(112, 128, 144), "snow": color_rgb(255, 250, 250), "springgreen": color_rgb(0, 255, 127), "steelblue": color_rgb(70, 130, 180), "tan": color_rgb(210, 180, 140), "teal": color_rgb(0, 128, 128), "thistle": color_rgb(216, 191, 216), "tomato": color_rgb(255, 99, 71), "turquoise": color_rgb(64, 224, 208), "violet": color_rgb(238, 130, 238), "wheat": color_rgb(245, 222, 179), "white": color_rgb(255, 255, 255), "whitesmoke": color_rgb(245, 245, 245), "yellow": color_rgb(255, 255, 0), "yellowgreen": color_rgb(154, 205, 50) } def parse_svg_color_lookup(color_string): """Parse SVG Color by Keyword on dictionary lookup""" return svg_color_dict.get(color_string, 0xFF000000) def parse_svg_color_hex(hex_string): """Parse SVG Color by Hex String""" h = hex_string.lstrip('#') size = len(h) if size == 8: return int(h[:8], 16) elif size == 6: return int(h[:6], 16) elif size == 4: return int(h[3] + h[3] + h[2] + h[2] + h[1] + h[1] + h[0] + h[0], 16) elif size == 3: return int(h[2] + h[2] + h[1] + h[1] + h[0] + h[0], 16) return 0xFF000000 def parse_svg_color_rgb(values): """Parse SVG Color, RGB value declarations """ int_values = list(map(int, values)) return color_rgb(int_values[0], int_values[1], int_values[2]) def parse_svg_color_rgbp(values): """Parse SVG color, RGB percent value declarations""" ratio = 255.0 / 100.0 values = list(map(float, values)) return color_rgb(int(values[0] * ratio), int(values[1] * ratio), int(values[2] * ratio)) def parse_svg_color(color_string): """Parse SVG color, will return a set value.""" hex_re = re.compile(r'^#?([0-9A-Fa-f]{3,8})$') match = hex_re.match(color_string) if match: return parse_svg_color_hex(color_string) rgb_re = re.compile(r'rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)') match = rgb_re.match(color_string) if match: return parse_svg_color_rgb(match.groups()) rgbp_re = re.compile(r'rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)') match = rgbp_re.match(color_string) if match: return parse_svg_color_rgbp(match.groups()) return parse_svg_color_lookup(color_string)
36.86194
121
0.585518
a3376e1829b03c5dd02c46a357e4ff179b9a5df1
236
ts
TypeScript
client/src/buffer-utils.ts
Xapphire13/arduino-notifier
0daaf0b394fcf148981239702d641b447e742ca6
[ "MIT" ]
null
null
null
client/src/buffer-utils.ts
Xapphire13/arduino-notifier
0daaf0b394fcf148981239702d641b447e742ca6
[ "MIT" ]
null
null
null
client/src/buffer-utils.ts
Xapphire13/arduino-notifier
0daaf0b394fcf148981239702d641b447e742ca6
[ "MIT" ]
null
null
null
export function viewToString(view: DataView): string { const parts: string[] = []; for (let i = 0; i < view.byteLength; i++) { parts.push(`0x${view.getUint8(i).toString(16).padStart(2, "0")}`); } return parts.join(" "); }
23.6
70
0.605932
38b9a5ce25b16f651e24951de14ae2d59101729e
2,583
php
PHP
app/chat/socket/Base.php
Sky9th/sky-admin-api
e16326ee902b627fd758660cf6669b5065a80712
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
app/chat/socket/Base.php
Sky9th/sky-admin-api
e16326ee902b627fd758660cf6669b5065a80712
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
app/chat/socket/Base.php
Sky9th/sky-admin-api
e16326ee902b627fd758660cf6669b5065a80712
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
<?php namespace app\chat\socket; use app\common\logic\UserAuth; use think\Container; use think\swoole\Websocket; class Base { public static string $CACHE_CHAT_USER_LIST = 'chat_user_list'; public static string $CACHE_CHAT_TYPING_LIST = 'chat_typing_list'; public Websocket $websocket; public $session = []; public $userInfo = []; public $fd; public $user_id; public array $userList = []; public function __construct(Container $container){ $this->websocket = $container->make(\think\swoole\Websocket::class); $userList = cache(Base::$CACHE_CHAT_USER_LIST); $this->userList = $userList ? $userList : []; $this->fd = $this->websocket->getSender(); if (isset($this->userList[$this->fd])) { $this->userInfo = $this->userList[$this->fd]; $this->user_id = isset($this->userInfo['id']) ? $this->userInfo['id'] : 0; } } public function isLogin ($sessionKey) { $this->session = UserAuth::checkSession($sessionKey); if ($this->session) { $this->session['sessionKey'] = $sessionKey; $this->user_id = $this->session['user_id']; $this->userInfo = UserAuth::info($this->session['user_id'])->toArray(); $this->setUserList($this->fd); } } public function setUserList($fd, $remove = false) { foreach ($this->userList as $key => $value){ if (isset($value['id']) && $this->user_id == $value['id']) { unset($this->userList[$key]); } } if($remove){ unset($this->userList[$fd]); } else { $this->userList[$fd] = array_merge([ "create_time" => time(), "isLogin" => !!$this->session, "sessionKey" => $this->session ? $this->session['sessionKey'] : '' ], $this->userInfo); } cache(Base::$CACHE_CHAT_USER_LIST, $this->userList); } public function getUserList($fd = null) { return $fd && isset($this->userList[$fd]) ? [$fd=>$this->userList[$fd]] : $this->userList; } public function broadcast($data, $event = null) { var_dump('---------broadcast--------'); $senders = array_keys($this->userList); foreach ($senders as $sender) { var_dump('---------sender:'.$sender); if($event) { $this->websocket->to($sender)->emit($event, $data); } else { $this->websocket->to($sender)->push($data); } } } }
33.115385
98
0.536973
c68915543d403e05b5ebd5f855336910b2ff5224
44
py
Python
editorcontainer/rightclickmenu/__init__.py
AutomataRaven/azaharTEA
2d5a7d96b37bca9b3a914e305e493824a0f60207
[ "MIT" ]
5
2019-03-10T16:33:21.000Z
2021-04-07T17:24:32.000Z
editorcontainer/rightclickmenu/__init__.py
Errantgod/azaharTEA
2d5a7d96b37bca9b3a914e305e493824a0f60207
[ "MIT" ]
8
2017-02-11T06:21:28.000Z
2017-02-22T05:50:35.000Z
editorcontainer/rightclickmenu/__init__.py
Errantgod/azaharTEA
2d5a7d96b37bca9b3a914e305e493824a0f60207
[ "MIT" ]
2
2019-10-05T20:20:15.000Z
2020-06-28T18:46:58.000Z
__all__ = ['rightclickmenu.RightClickMenu']
22
43
0.795455
f4ca95c337a3ec4499396393da0abba45fe3acfd
210
ts
TypeScript
src/app/components/child-dashboard/index.ts
extrude575757/story-squad-fe-archived
aa189c7e25ef2d524bee75e68d4cb1e8a0013cce
[ "MIT" ]
null
null
null
src/app/components/child-dashboard/index.ts
extrude575757/story-squad-fe-archived
aa189c7e25ef2d524bee75e68d4cb1e8a0013cce
[ "MIT" ]
null
null
null
src/app/components/child-dashboard/index.ts
extrude575757/story-squad-fe-archived
aa189c7e25ef2d524bee75e68d4cb1e8a0013cce
[ "MIT" ]
2
2021-07-09T02:43:48.000Z
2021-12-05T10:52:20.000Z
export * from './creative-content-submission'; export * from './welcome-card/welcome-card.component'; export * from './kid-progress/kid-progress.component'; export * from './team-join/team-join.component';
42
55
0.72381
435a12b7a5726b37f256744b68f76173492c15c7
1,112
tsx
TypeScript
src/components/Research.tsx
win11905/cv
391064b5d48cb82eac9747cecc148b88a78af299
[ "MIT" ]
null
null
null
src/components/Research.tsx
win11905/cv
391064b5d48cb82eac9747cecc148b88a78af299
[ "MIT" ]
11
2020-07-20T10:35:48.000Z
2021-09-01T18:46:16.000Z
src/components/Research.tsx
pongsaphol/cv
6f8567c8cddd58deba8df05981082f5876c2d2a8
[ "MIT" ]
null
null
null
import React from 'react' import { Box, Flex, Heading, Text, Link } from '@chakra-ui/core' import { IResearch, research } from '../constants/research' import { Card } from './Card' import { Title } from './Title' export const Research = () => { return ( <React.Fragment> <Title title="Research" size="lg" /> <Flex direction="column" mt={6} width={[23 / 24, 23 / 24, 22 / 24, 21 / 24]} mx="auto" > <Flex flexWrap="wrap" alignItems="center"> {research.map((item: IResearch) => ( <Box width={['100%', 1 / 2, 1 / 2, 1 / 3]} px={5} py={3}> <Card {...research}> <Heading size="md">{item.name}</Heading> <a href={item.href} target="_blank"> <Link color="gray.500" target="_blank"> arxiv </Link> </a> <Text color="gray.800" mt={2}> {item.desc} </Text> </Card> </Box> ))} </Flex> </Flex> </React.Fragment> ) }
29.263158
69
0.447842
68348db5319bfa399e8851a0d3f577c39f329f1c
1,287
php
PHP
resources/views/setup.blade.php
tkoop/project_deployer
933cce0643ce0c16b49c6f80a58fe9513d2f2566
[ "MIT" ]
null
null
null
resources/views/setup.blade.php
tkoop/project_deployer
933cce0643ce0c16b49c6f80a58fe9513d2f2566
[ "MIT" ]
null
null
null
resources/views/setup.blade.php
tkoop/project_deployer
933cce0643ce0c16b49c6f80a58fe9513d2f2566
[ "MIT" ]
null
null
null
<x-guest-layout> <x-slot name="title">Setup</x-slot> <div class="mx-auto max-w-7xl sm:px-6 lg:px-8"> <div class="overflow-hidden bg-white shadow-sm sm:rounded-lg"> <div class="p-6 bg-white border-b border-gray-200"> <p class="mb-5"><img src="full_logo.svg" style="height:55px"></p> <h1 class="mb-5 text-xl">Set up</h1> <!-- Session Status --> <x-auth-session-status class="mb-4" :status="session('status')" /> <!-- Validation Errors --> <x-auth-validation-errors class="mb-4" :status="session('errors')" /> <form method="post"> @csrf <div class="mb-5"> Please create the admin password:<br> <input type="text" name="password" value="{{ $password }}" style="padding:0px 8px"> </div> <div class="mb-5"> <x-button onclick="window.location = '/'">Do It</x-button> </div> </form> </div> </div> </div> <style> .help { color: gray; padding-left: 20px; } </style> </x-guest-layout>
28.6
107
0.445998
6b7c6f0c0cedd0b9bec0880af64c3bde5cadbcdf
9,717
js
JavaScript
js/site.js
SuperEnoki/amani
a8ce46bf276aa7e1d626c23eb3a37088f64d0a53
[ "MIT" ]
1
2021-08-25T11:13:04.000Z
2021-08-25T11:13:04.000Z
js/site.js
SuperEnoki/amani
a8ce46bf276aa7e1d626c23eb3a37088f64d0a53
[ "MIT" ]
null
null
null
js/site.js
SuperEnoki/amani
a8ce46bf276aa7e1d626c23eb3a37088f64d0a53
[ "MIT" ]
1
2021-08-31T09:53:49.000Z
2021-08-31T09:53:49.000Z
jQuery(document).ready(function($) { "use strict"; // Initializing scripts var amani_grid = '.blog-feed'; var amani_grid_item = '.grid-item'; function amani_init() { amani_magic_masonry(); // Instagram image width/height fix $('.header-instagram').imagesLoaded(function() { var header_instagram_width = $('.header-instagram li').width(); $('.header-instagram li').css('max-height', header_instagram_width); $('.header-instagram').addClass('visible'); }); $('.footer-instagram').imagesLoaded(function() { var footer_instagram_width = $('.footer-instagram li').width(); $('.footer-instagram li').css('max-height', footer_instagram_width); $('.footer-instagram').addClass('visible'); }); } /* BEGIN */ // Menu dividing to fist - last half var main_nav_length = Math.floor($('.main-nav div > ul > li').length / 2) + 1; $('.main-nav div > ul > li:nth-child(n + ' + main_nav_length + ')').addClass('last-half'); // Search form click $(document).on('click', '.search-trigger', function(e) { $('body').addClass('search-active'); setTimeout(function() { $('.search-wrap input').focus(); }, 300); }); $('.search-wrap').on('click', function(e) { var target = $(e.target); if($(target).is('input') === false) { $('body').removeClass('search-active'); } }); // Escape Key $(document).keyup(function(e) { if (e.keyCode == 27) { // escape key maps to keycode `27` $('body').removeClass('search-active'); $('body').removeClass('menu-active'); } }); // Responsive hamburger click $(document).on('click', '.responsive-menu-trigger', function() { if($('body').hasClass('menu-active')) { $('body').removeClass('menu-active'); } else { history.pushState({id: 'menu'}, '', ''); $('body').addClass('menu-active'); } }); window.addEventListener("popstate", function(e) { if(history.state.id == 'menu') { $('body').removeClass('menu-active'); } }); $('.responsive-wrap').on('click', function(e) { var target = $(e.target); if($(target).is('a') === false) { $('body').removeClass('menu-active'); } }); // Scrolltop click $(document).on('click', '.scrolltop', function() { $('html, body').animate({ scrollTop: 0 }, 300); }); // Wrap Calendar in Divs for better styling $('.widget_calendar td:not(:has(>a))').wrapInner('<div></div>'); // Responsive submenu click $(document).on('click', '.responsive-nav .menu-item-has-children > a', function(e) { e.preventDefault(); var curmenu = $(this).parent(); var submenu = $(this).parent().find('> ul'); if(submenu.is(':visible')) { submenu.hide(); curmenu.removeClass('active'); curmenu.parent().find('> li').show(); } else { submenu.show(); curmenu.addClass('active'); curmenu.parent().find('> li:not(.active)').hide(); } }); // Dropdown menu $('nav ul.menu li').hover(function() { var timeout = $(this).data('timeout'); var $currentUl = $(this).find('> ul'); if(timeout) clearTimeout(timeout); if($currentUl.hasClass('visible') === false && $currentUl.length > 0) { $(this).find('> ul').addClass('visible'); } }, function() { $(this).data('timeout', setTimeout($.proxy(function() { $(this).find('> ul').removeClass('visible'); }, this), 200)); }); // Infinite Scroll $.bktis = { containerSelector: '.blog-feed', postSelector: '.grid-item', paginationSelector: '.navigation', nextSelector: '.next', loadingHtml: '', show: function(elems) { elems.show(); }, nextPageUrl: null, init: function(options) { for (var key in options) { $.bktis[key] = options[key]; } $(function() { $.bktis.extractNextPageUrl($('body')); $(window).bind('scroll', $.bktis.scroll); $.bktis.scroll(); }); }, scroll: function() { $($.bktis.containerSelector).imagesLoaded(function() { if ($.bktis.nearBottom() && $.bktis.shouldLoadNextPage()) { $.bktis.loadNextPage(); } }); }, nearBottom: function() { var scrollTop = $(window).scrollTop(), windowHeight = $(window).height(), lastPostOffset = $($.bktis.containerSelector).find($.bktis.postSelector).last().offset(); if (!lastPostOffset) return; return (scrollTop > (lastPostOffset.top - windowHeight)); }, shouldLoadNextPage: function() { return !!$.bktis.nextPageUrl; }, loadNextPage: function() { var nextPageUrl = $.bktis.nextPageUrl, loading = $($.bktis.loadingHtml); $.bktis.nextPageUrl = null; loading.insertAfter($.bktis.containerSelector); $.get(nextPageUrl, function(html) { var dom = $(html), posts = dom.find($.bktis.containerSelector).find($.bktis.postSelector); $.bktis.show(posts.hide().appendTo($.bktis.containerSelector)); $.bktis.extractNextPageUrl(dom); $.bktis.scroll(); }); }, extractNextPageUrl: function(dom) { var pagination = dom.find($.bktis.paginationSelector); $.bktis.nextPageUrl = pagination.find($.bktis.nextSelector).attr('href'); pagination.remove(); } } if($('.theme-body').hasClass('infinite_scroll') == true) { $.bktis.init({ containerSelector: amani_grid, postSelector: amani_grid_item, paginationSelector: '.navigation', nextSelector: '.next', loadingHtml: '<div class="infinite-scroll-spinner"></div>', show: function(elems) { elems.show(); amani_init(); } }); } // Magic Masonry function amani_magic_masonry() { const grid = document.querySelector('.blog_layout-masonry' + ' ' + amani_grid); // checking if grid container exist if(typeof(grid) != 'undefined' && grid != null) { $(amani_grid).append("<div class='infinite-scroll-spinner'></div>"); $(amani_grid).imagesLoaded(function() { const rowHeight = parseInt($(grid).css("grid-auto-rows")); const rowGap = parseInt($(grid).css("grid-row-gap")); grid.style.gridAutoRows = "auto"; grid.style.alignItems = "self-start"; grid.querySelectorAll(amani_grid_item).forEach(item => { item.style.gridRowEnd = `span ${Math.ceil( (item.clientHeight + rowGap) / (rowHeight + rowGap) )}`; if($(item).hasClass('visible') == false) { $(item).addClass('visible'); } }); grid.removeAttribute("style"); $('.infinite-scroll-spinner').fadeOut('normal', function() { $(this).remove(); }); }); } else { $(amani_grid).imagesLoaded(function() { $(amani_grid_item).addClass('visible'); }); $('.infinite-scroll-spinner').fadeOut('normal', function() { $(this).remove(); }); } } // When images loaded we show items $('.featured-posts').imagesLoaded(function() { $('.featured-posts .grid-item').addClass('visible'); }); // Slideshow var amani_slideshow = (function() { function amani_slideshow(element, options) { var _ = this; _.settings = $.extend($.fn.amani_slideshow.defaults, options); _.el = element; _.$element = $(element); _.$photos = _.$element.children(); _.count = _.$photos.length; _.init(); } amani_slideshow.prototype.init = function() { var _ = this; if(_.$element.find('.slideshow-paginator').length < 1) { _.$element.append('<nav class="slideshow-paginator" />'); for (var i = 0; i < _.count; i++) { _.$element.find('.slideshow-paginator').append('<span/>'); } _.$element.find('.slideshow-paginator span:first-child').addClass('current'); _.$element.find('.grid-item:first-child').addClass('current'); _.$element.find('.slideshow-paginator').on('slide_switch', 'span', function() { _.$element.find('.slideshow-paginator span').removeClass('current'); $(this).addClass('current'); var slide_switch = $(this).index(); _.$photos.removeClass('current'); _.$photos.eq(slide_switch).addClass('current'); }); _.$element.find('.slideshow-paginator').on('click', 'span', function() { $(this).trigger('slide_switch'); }); _.$element.data('interval', _.settings.interval); _.play(); _.autoPlayPause(); } } amani_slideshow.prototype.play = function() { var _ = this; if(_.$element.data('stopped') != 1) { var $paginator_current = _.$element.find('.slideshow-paginator span.current'); var $paginator_next = $paginator_current.next(); if($paginator_next.length > 0) { $paginator_next.trigger('slide_switch'); } else { _.$element.find('.slideshow-paginator span:first-child').trigger('slide_switch'); } setTimeout(function() { _.play(); }, _.$element.data('interval')); } else { setTimeout(function() { _.play(); }, _.$element.data('interval')); } }; amani_slideshow.prototype.autoPlayPause = function() { var _ = this; _.$element.on({ mouseenter: function(){ _.$element.data('stopped', 1); }, mouseleave: function(){ _.$element.data('stopped', 0); } }); }; $.fn.amani_slideshow = function(options) { var instance; instance = this.data('amani_slideshow'); if (!instance) { return this.each(function() { return $(this).data('amani_slideshow', new amani_slideshow(this,options)); }); } if (options === true) return instance; if ($.type(options) === 'string') instance[options](); return this; }; $.fn.amani_slideshow.defaults = { interval: 5000, }; }).call(this); // Init amani_init(); $('.top_featured_layout-slideshow .featured-top').amani_slideshow({ interval: 5000 }); document.addEventListener('theme-reinit', function() { amani_init(); $('.top_featured_layout-slideshow .featured-top').amani_slideshow({ interval: 5000 }); }); $(window).resize(function() { amani_init(); }); $(window).focus(function() { amani_init(); }); });
27.218487
94
0.617063
e9207dd5ef82428751c4724502600cb262f4200c
228
swift
Swift
UserLoginDelegate.swift
ceozhu/lesson_ios_mvp
19af13dc47092639fd49a4046c0efa3d18710ed3
[ "Apache-2.0" ]
null
null
null
UserLoginDelegate.swift
ceozhu/lesson_ios_mvp
19af13dc47092639fd49a4046c0efa3d18710ed3
[ "Apache-2.0" ]
null
null
null
UserLoginDelegate.swift
ceozhu/lesson_ios_mvp
19af13dc47092639fd49a4046c0efa3d18710ed3
[ "Apache-2.0" ]
null
null
null
// // UserLoginDelegate.swift // Lesson_MVP_Demo // // Created by 朱佩 on 16/5/24. // Copyright © 2016年 Andy zhu. All rights reserved. // import Foundation protocol UserLoginDelegate { func loginByUser(model:UserModel); }
19
52
0.714912
1a4357d52dee977cfc6596753d1ab58374e8af64
1,817
py
Python
cypher.py
JCode1986/ceasar-cipher
bd6259ae8ce51ae8a9e8a7bbbaebf46d9d60c0e6
[ "MIT" ]
null
null
null
cypher.py
JCode1986/ceasar-cipher
bd6259ae8ce51ae8a9e8a7bbbaebf46d9d60c0e6
[ "MIT" ]
null
null
null
cypher.py
JCode1986/ceasar-cipher
bd6259ae8ce51ae8a9e8a7bbbaebf46d9d60c0e6
[ "MIT" ]
null
null
null
def encrypt(message, key): encrypted_message = '' for char in message: if char.isalpha(): #ord() returns an integer representing the Unicode code point of the character unicode_num = ord(char) unicode_num += key if char.isupper(): if unicode_num > ord('Z'): unicode_num -= 26 elif unicode_num < ord('A'): unicode_num += 26 elif char.islower(): if unicode_num > ord('z'): unicode_num -= 26 elif unicode_num < ord('a'): unicode_num += 26 #chr() returns a character from a string encrypted_message += chr(unicode_num) else: encrypted_message += char return encrypted_message def decrypt(encoded, key): return encrypt(encoded, -key) def encrypt_input(): e_message = input('\nEnter message to encrypt: ') e_key = int(input('\nEnter key number from 1 - 26: ')) while e_key > 26: e_key = int(input('\nEnter key number from 1 - 26: ')) return f'\nYour encrypted message is =====> {encrypt(e_message, e_key)}' def decrypt_input(): d_message = input('\nEnter message to decrypt: ') d_key = int(input('\nEnter key number from 1 - 26: ')) while d_key > 26: d_key = int(input('\nEnter key number from 1 - 26: ')) return f'\nYour decrypted message is =====> {decrypt(d_message, d_key)}' def start(): question = input('\nEncrpyt (e) or Decrypt (d) a message? ') if question == 'e': return encrypt_input() if question == 'd': return decrypt_input() # else: # start() if __name__ == "__main__": while True: print(start())
27.953846
90
0.545405