hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
463976d3c4bd3d88dd11c4b4cb82c791eb1a2969
1,845
php
PHP
profiles/contrib/social/modules/custom/social_demo/src/DemoContentInterface.php
techopsph/social_pantheon
85f6c198455715dda7e62d7f9d24d987169b0093
[ "MIT" ]
null
null
null
profiles/contrib/social/modules/custom/social_demo/src/DemoContentInterface.php
techopsph/social_pantheon
85f6c198455715dda7e62d7f9d24d987169b0093
[ "MIT" ]
29
2019-12-17T18:27:31.000Z
2022-03-24T04:33:23.000Z
profiles/contrib/social/modules/custom/social_demo/src/DemoContentInterface.php
techopsph/social_pantheon
85f6c198455715dda7e62d7f9d24d987169b0093
[ "MIT" ]
null
null
null
<?php namespace Drupal\social_demo; use Drupal\Component\Plugin\PluginInspectionInterface; use Drupal\Core\Plugin\ContainerFactoryPluginInterface; use Drupal\Core\Entity\EntityStorageInterface; /** * Interface DemoContentInterface. * * @package Drupal\social_demo */ interface DemoContentInterface extends PluginInspectionInterface, ContainerFactoryPluginInterface { /** * Returns the file name. * * @return string * The source filename where are data. */ public function getSource(); /** * Sets the used profile. * * @param string $profile * The profile. * * @return string * Void. */ public function setProfile($profile); /** * Returns the profile. * * @return string * The used demo content profile. */ public function getProfile(); /** * Returns the module name. * * @return string * The module name where is placed file with data. */ public function getModule(); /** * Creates content. * * @return array * An array with list of created entities. */ public function createContent(); /** * Removes content. */ public function removeContent(); /** * Returns quantity of created items. * * @return int * Returns quantity of created items. */ public function count(); /** * Set entity storage. * * @param \Drupal\Core\Entity\EntityStorageInterface $entity_storage * The EntityStorageInterface entity_storage. */ public function setEntityStorage(EntityStorageInterface $entity_storage); /** * Scramble it. * * @param array $data * The data array to scramble. * @param int|null $max * How many items to generate. * * @return array * An array with list of data. */ public function scrambleData(array $data, $max = NULL); }
19.62766
99
0.653659
395da64d2737979bb6ce67fa88d156d87c0efda7
6,840
rs
Rust
src/mp/poly.rs
kwantam/bellman-bignat
4188d5985d4abaf257c9ec029d6d4a7bd4e49e85
[ "MIT" ]
40
2019-12-30T11:29:51.000Z
2022-03-19T13:24:13.000Z
src/mp/poly.rs
kwantam/bellman-bignat
4188d5985d4abaf257c9ec029d6d4a7bd4e49e85
[ "MIT" ]
4
2020-02-12T21:59:11.000Z
2021-03-02T08:47:22.000Z
src/mp/poly.rs
kwantam/bellman-bignat
4188d5985d4abaf257c9ec029d6d4a7bd4e49e85
[ "MIT" ]
17
2020-01-13T05:13:33.000Z
2022-03-28T20:46:09.000Z
use sapling_crypto::bellman::pairing::ff::Field; use sapling_crypto::bellman::pairing::Engine; use sapling_crypto::bellman::{ConstraintSystem, LinearCombination, SynthesisError}; use std::cmp::max; use std::fmt::{self, Debug, Formatter}; use OptionExt; pub struct Polynomial<E: Engine> { pub coefficients: Vec<LinearCombination<E>>, pub values: Option<Vec<E::Fr>>, } impl<E: Engine> Debug for Polynomial<E> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.debug_struct("Polynomial") .field("values", &self.values) .finish() } } impl<E: Engine> Polynomial<E> { pub fn evaluate_at(&self, x: E::Fr) -> Option<E::Fr> { self.values.as_ref().map(|vs| { let mut v = E::Fr::one(); let mut acc = E::Fr::zero(); for coeff in vs { let mut t = coeff.clone(); t.mul_assign(&v); acc.add_assign(&t); v.mul_assign(&x); } acc }) } pub fn alloc_product<CS: ConstraintSystem<E>>( &self, mut cs: CS, other: &Self, ) -> Result<Polynomial<E>, SynthesisError> { let n_product_coeffs = self.coefficients.len() + other.coefficients.len() - 1; let values = self.values.as_ref().and_then(|self_vs| { other.values.as_ref().map(|other_vs| { let mut values: Vec<E::Fr> = std::iter::repeat_with(E::Fr::zero) .take(n_product_coeffs) .collect(); for (self_i, self_v) in self_vs.iter().enumerate() { for (other_i, other_v) in other_vs.iter().enumerate() { let mut v = self_v.clone(); v.mul_assign(other_v); values[self_i + other_i].add_assign(&v); } } values }) }); let coefficients = (0..n_product_coeffs) .map(|i| { Ok(LinearCombination::zero() + cs.alloc(|| format!("prod {}", i), || Ok(values.grab()?[i].clone()))?) }) .collect::<Result<Vec<LinearCombination<E>>, SynthesisError>>()?; let product = Polynomial { coefficients, values, }; let one = E::Fr::one(); let mut x = E::Fr::zero(); for _ in 1..(n_product_coeffs + 1) { x.add_assign(&one); cs.enforce( || format!("pointwise product @ {}", x), |lc| { let mut i = E::Fr::one(); self.coefficients.iter().fold(lc, |lc, c| { let r = lc + (i, c); i.mul_assign(&x); r }) }, |lc| { let mut i = E::Fr::one(); other.coefficients.iter().fold(lc, |lc, c| { let r = lc + (i, c); i.mul_assign(&x); r }) }, |lc| { let mut i = E::Fr::one(); product.coefficients.iter().fold(lc, |lc, c| { let r = lc + (i, c); i.mul_assign(&x); r }) }, ) } Ok(product) } pub fn sum(&self, other: &Self) -> Self { let n_coeffs = max(self.coefficients.len(), other.coefficients.len()); let values = self.values.as_ref().and_then(|self_vs| { other.values.as_ref().map(|other_vs| { (0..n_coeffs) .map(|i| { let mut s = E::Fr::zero(); if i < self_vs.len() { s.add_assign(&self_vs[i]); } if i < other_vs.len() { s.add_assign(&other_vs[i]); } s }) .collect() }) }); let coefficients = (0..n_coeffs) .map(|i| { let mut lc = LinearCombination::zero(); if i < self.coefficients.len() { lc = lc + &self.coefficients[i]; } if i < other.coefficients.len() { lc = lc + &other.coefficients[i]; } lc }) .collect(); Polynomial { coefficients, values, } } } #[cfg(test)] mod tests { use super::*; use crate::util::convert::usize_to_f; use sapling_crypto::bellman::pairing::bn256::{Bn256, Fr}; use sapling_crypto::bellman::Circuit; use sapling_crypto::circuit::test::TestConstraintSystem; pub struct PolynomialMultiplier<E: Engine> { pub a: Vec<E::Fr>, pub b: Vec<E::Fr>, } impl<E: Engine> Circuit<E> for PolynomialMultiplier<E> { fn synthesize<CS: ConstraintSystem<E>>(self, cs: &mut CS) -> Result<(), SynthesisError> { let a = Polynomial { coefficients: self .a .iter() .enumerate() .map(|(i, x)| { Ok(LinearCombination::zero() + cs.alloc(|| format!("coeff_a {}", i), || Ok(*x))?) }) .collect::<Result<Vec<LinearCombination<E>>, SynthesisError>>()?, values: Some(self.a), }; let b = Polynomial { coefficients: self .b .iter() .enumerate() .map(|(i, x)| { Ok(LinearCombination::zero() + cs.alloc(|| format!("coeff_b {}", i), || Ok(*x))?) }) .collect::<Result<Vec<LinearCombination<E>>, SynthesisError>>()?, values: Some(self.b), }; let _prod = Polynomial::from(a) .alloc_product(cs.namespace(|| "product"), &Polynomial::from(b))?; Ok(()) } } #[test] fn test_circuit() { let mut cs = TestConstraintSystem::<Bn256>::new(); let circuit = PolynomialMultiplier { a: [1, 1, 1].iter().map(|i| usize_to_f::<Fr>(*i)).collect(), b: [1, 1].iter().map(|i| usize_to_f::<Fr>(*i)).collect(), }; circuit.synthesize(&mut cs).expect("synthesis failed"); if let Some(token) = cs.which_is_unsatisfied() { eprintln!("Error: {} is unsatisfied", token); } } }
34.029851
97
0.423246
e66c922be954821a1152e808ef675fa9aee2db1f
339
swift
Swift
Source/Collection+Payload.swift
smirnovaleksei/NRequest
3f463e7f8c2f27f6b76437328fa1ebe5966e2dc8
[ "MIT" ]
null
null
null
Source/Collection+Payload.swift
smirnovaleksei/NRequest
3f463e7f8c2f27f6b76437328fa1ebe5966e2dc8
[ "MIT" ]
null
null
null
Source/Collection+Payload.swift
smirnovaleksei/NRequest
3f463e7f8c2f27f6b76437328fa1ebe5966e2dc8
[ "MIT" ]
2
2021-09-09T11:34:19.000Z
2021-12-09T12:25:01.000Z
import Foundation public extension Collection { func throwIfEmpty<T: Error>(_ error: T) throws -> Self { if isEmpty { throw error } return self } func throwIfEmpty() throws -> Self { if isEmpty { throw DecodingError.brokenResponse } return self } }
18.833333
60
0.548673
33e17122debacbb3ef564b48dbee96f5d7c8c502
804
c
C
pyhand/kinematics/ring_prox_index_inter_side_1.c
jsupancic/libhand-public
da9b92fa5440d06fdd4ba72c2327c50c88a1d469
[ "CC-BY-3.0" ]
19
2015-11-28T03:49:10.000Z
2021-04-12T13:19:26.000Z
pyhand/kinematics/ring_prox_index_inter_side_1.c
jsupancic/libhand-public
da9b92fa5440d06fdd4ba72c2327c50c88a1d469
[ "CC-BY-3.0" ]
4
2015-12-24T08:53:10.000Z
2017-11-08T10:58:16.000Z
pyhand/kinematics/ring_prox_index_inter_side_1.c
jsupancic/libhand-public
da9b92fa5440d06fdd4ba72c2327c50c88a1d469
[ "CC-BY-3.0" ]
7
2015-12-16T05:27:22.000Z
2020-08-24T07:59:29.000Z
/****************************************************************************** * Code generated with sympy 0.7.6 * * * * See http://www.sympy.org/ for more information. * * * * This file is part of 'project' * ******************************************************************************/ #include "ring_prox_index_inter_side_1.h" #include <math.h> double ring_prox_index_inter_side_1() { double ring_prox_index_inter_side_1_result; ring_prox_index_inter_side_1_result = 0; return ring_prox_index_inter_side_1_result; }
44.666667
80
0.353234
257388fd0bb2e56c7df84ef1505aadc32bef2ebf
1,520
cs
C#
Scripts/DisplayTrainInfo.cs
KevinWu57/Learning-by-Commnication
4187aa3e0fa49fea1e2bd96b4bacec357ac7ec2f
[ "MIT" ]
null
null
null
Scripts/DisplayTrainInfo.cs
KevinWu57/Learning-by-Commnication
4187aa3e0fa49fea1e2bd96b4bacec357ac7ec2f
[ "MIT" ]
null
null
null
Scripts/DisplayTrainInfo.cs
KevinWu57/Learning-by-Commnication
4187aa3e0fa49fea1e2bd96b4bacec357ac7ec2f
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor.Animations; using UnityEngine.UI; // Display training information, including object selected and animationclip played public class DisplayTrainInfo : MonoBehaviour { public Animator kinectAnimator; public Animator leapAnimator; public Text displayArea; public EnvSetup envSetup; public AgentController agentCtrl; private AnimatorController kinectCtrl; private AnimatorController leapCtrl; private AnimationClip kinectClip; private AnimationClip leapClip; void LateUpdate() { if(envSetup.isTraining && agentCtrl.useBody) { kinectCtrl = kinectAnimator.runtimeAnimatorController as AnimatorController; leapCtrl = leapAnimator.runtimeAnimatorController as AnimatorController; NavObj.ObjType currentType = GameObject.FindObjectOfType<AgentController>().CurrentObjType; string objInfo = $"The object type is {currentType.ToString()}"; kinectClip = kinectCtrl.layers[0].stateMachine.defaultState.motion as AnimationClip; leapClip = leapCtrl.layers[0].stateMachine.defaultState.motion as AnimationClip; string kinectInfo = $"The Kinect clip is {kinectClip.name}"; string leapInfo = $"The Leap clip is {leapClip.name}"; displayArea.text = string.Join("\n",new string[]{objInfo,kinectInfo,leapInfo}); } } }
38
104
0.703289
d2d5199f4763a521b5e09eb7e3425d5ac6c894e0
5,739
rs
Rust
src/in_game/game_area.rs
lights0123/asteroids_3d
b5486d1552487076b6495dbd994116bc6968fae1
[ "MIT" ]
3
2021-04-28T01:19:47.000Z
2021-09-21T00:33:41.000Z
src/in_game/game_area.rs
lights0123/asteroids_3d
b5486d1552487076b6495dbd994116bc6968fae1
[ "MIT" ]
null
null
null
src/in_game/game_area.rs
lights0123/asteroids_3d
b5486d1552487076b6495dbd994116bc6968fae1
[ "MIT" ]
2
2021-04-27T18:04:01.000Z
2021-04-28T01:19:57.000Z
use std::collections::HashMap; use bevy::prelude::*; use bevy_rapier3d::physics::InteractionPairFilters; use bevy_rapier3d::rapier::dynamics::RigidBodyBuilder; use bevy_rapier3d::rapier::geometry::ColliderBuilder; use crate::in_game::TiedToGame; use crate::physics::OneWayPlatformHook; pub struct GameAreaPlugin<T>(pub T); impl<T: crate::util::StateType> Plugin for GameAreaPlugin<T> { fn build(&self, app: &mut AppBuilder) { app.add_system_set(SystemSet::on_enter(self.0.clone()).with_system(spawn.system())); } } pub struct GameAreaBound; #[derive(Copy, Clone)] enum Axis { X, Y, Z, } impl Axis { fn set_translation(self, mut trans: Vec3, value: f32) -> Vec3 { match self { Axis::X => trans.x = value, Axis::Y => trans.y = value, Axis::Z => trans.z = value, } trans } fn get_sizes(major: Self, minor: Self, x: f32, y: f32, z: f32) -> Option<(f32, f32, f32)> { use self::Axis::{X, Y, Z}; match (major, minor) { (X, Y) => Some((x, y, z)), (X, Z) => Some((x, z, y)), (Y, X) => Some((y, x, z)), (Y, Z) => Some((y, z, x)), (Z, X) => Some((z, x, y)), (Z, Y) => Some((z, y, x)), _ => None, } } fn get_tertiary(major: Self, minor: Self) -> Option<Axis> { use self::Axis::{X, Y, Z}; match (major, minor) { (X, Y) | (Y, X) => Some(Z), (X, Z) | (Z, X) => Some(Y), (Z, Y) | (Y, Z) => Some(X), _ => None, } } fn get_sign(major: Self, minor: Self) -> Option<f32> { use self::Axis::{X, Y, Z}; match (major, minor) { (X, Y) => Some(1.), (X, Z) => Some(1.), (Y, X) => Some(-1.), (Y, Z) => Some(1.), (Z, X) => Some(-1.), (Z, Y) => Some(-1.), _ => None, } } } pub const WIDTH: f32 = 100.; pub const HEIGHT: f32 = 100.; pub const LENGTH: f32 = 100.; fn spawn( mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>, mut materials: ResMut<Assets<StandardMaterial>>, mut filters: ResMut<InteractionPairFilters>, ) { let lines_every = 10.; let minor_color = materials.add(StandardMaterial { base_color: Color::rgb(0., 0.6, 0.6), unlit: true, ..Default::default() }); let major_color = materials.add(StandardMaterial { base_color: Color::rgb(0., 1., 1.), emissive: Color::rgb(0., 1., 1.), unlit: true, ..Default::default() }); let mut platforms = HashMap::new(); let mut handle_plane = |major_axis: Axis, minor_axis: Axis| { let (major, minor, tertiary) = Axis::get_sizes(major_axis, minor_axis, WIDTH, LENGTH, HEIGHT).unwrap(); let tertiary_axis = Axis::get_tertiary(major_axis, minor_axis).unwrap(); let lines = (major / lines_every) as i32; let mesh = { let size = minor_axis .set_translation(major_axis.set_translation(Default::default(), 0.1), minor); meshes.add(Mesh::from(shape::Box::new(size.x, size.y, size.z))) }; for i in 1..lines { for side in [-1., 1.].iter().copied() { commands .spawn_bundle(PbrBundle { mesh: mesh.clone(), material: minor_color.clone(), transform: Transform::from_translation(tertiary_axis.set_translation( major_axis.set_translation( Default::default(), i as f32 * (major / lines_every) - (major / 2.), ), minor / 2. * side, )), ..Default::default() }) .insert(TiedToGame); } } for lr_side in [-1., 1.].iter().copied() { for side in [-1., 1.].iter().copied() { commands .spawn_bundle(PbrBundle { mesh: mesh.clone(), material: major_color.clone(), transform: Transform::from_translation(tertiary_axis.set_translation( major_axis.set_translation(Default::default(), WIDTH / 2. * lr_side), LENGTH / 2. * side, )), ..Default::default() }) .insert(TiedToGame); } } let plane = minor_axis .set_translation(major_axis.set_translation(Default::default(), major), minor); let plane_offset = tertiary_axis.set_translation(Default::default(), tertiary / 2.) * Axis::get_sign(major_axis, minor_axis).unwrap(); let plane_id = commands .spawn() .insert(RigidBodyBuilder::new_static()) .insert( ColliderBuilder::cuboid(plane.x, plane.y, plane.z) .translation(plane_offset.x, plane_offset.y, plane_offset.z) .modify_solver_contacts(true), ) .insert(TiedToGame) .insert(GameAreaBound) .id(); platforms.insert(plane_id.to_bits(), (-plane_offset).normalize().into()); }; handle_plane(Axis::X, Axis::Y); handle_plane(Axis::X, Axis::Z); handle_plane(Axis::Y, Axis::X); handle_plane(Axis::Y, Axis::Z); handle_plane(Axis::Z, Axis::X); handle_plane(Axis::Z, Axis::Y); filters.hook = Some(Box::new(OneWayPlatformHook { platforms })); }
34.993902
97
0.496951
a36b52c4bc867469aa37260207f59baafe6e3864
10,193
java
Java
src/main/java/org/apache/commons/compress/harmony/pack200/AttributeDefinitionBands.java
andrebrait/commons-compress
2f8fdc2723fcdfe78ef0daf9528b9904c142f759
[ "Apache-2.0" ]
1
2022-03-16T13:50:26.000Z
2022-03-16T13:50:26.000Z
src/main/java/org/apache/commons/compress/harmony/pack200/AttributeDefinitionBands.java
andrebrait/commons-compress
2f8fdc2723fcdfe78ef0daf9528b9904c142f759
[ "Apache-2.0" ]
null
null
null
src/main/java/org/apache/commons/compress/harmony/pack200/AttributeDefinitionBands.java
andrebrait/commons-compress
2f8fdc2723fcdfe78ef0daf9528b9904c142f759
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.compress.harmony.pack200; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.objectweb.asm.Attribute; /** * Attribute Definition bands define how any unknown attributes should be read by the decompressor. */ public class AttributeDefinitionBands extends BandSet { public static final int CONTEXT_CLASS = 0; public static final int CONTEXT_CODE = 3; public static final int CONTEXT_FIELD = 1; public static final int CONTEXT_METHOD = 2; private final List classAttributeLayouts = new ArrayList(); private final List methodAttributeLayouts = new ArrayList(); private final List fieldAttributeLayouts = new ArrayList(); private final List codeAttributeLayouts = new ArrayList(); private final List attributeDefinitions = new ArrayList(); private final CpBands cpBands; private final Segment segment; public AttributeDefinitionBands(final Segment segment, final int effort, final Attribute[] attributePrototypes) { super(effort, segment.getSegmentHeader()); this.cpBands = segment.getCpBands(); this.segment = segment; final Map classLayouts = new HashMap(); final Map methodLayouts = new HashMap(); final Map fieldLayouts = new HashMap(); final Map codeLayouts = new HashMap(); for (Attribute attributePrototype : attributePrototypes) { final NewAttribute newAttribute = (NewAttribute) attributePrototype; if (!(newAttribute instanceof NewAttribute.ErrorAttribute) && !(newAttribute instanceof NewAttribute.PassAttribute) && !(newAttribute instanceof NewAttribute.StripAttribute)) { if (newAttribute.isContextClass()) { classLayouts.put(newAttribute.type, newAttribute.getLayout()); } if (newAttribute.isContextMethod()) { methodLayouts.put(newAttribute.type, newAttribute.getLayout()); } if (newAttribute.isContextField()) { fieldLayouts.put(newAttribute.type, newAttribute.getLayout()); } if (newAttribute.isContextCode()) { codeLayouts.put(newAttribute.type, newAttribute.getLayout()); } } } if (classLayouts.size() > 7) { segmentHeader.setHave_class_flags_hi(true); } if (methodLayouts.size() > 6) { segmentHeader.setHave_method_flags_hi(true); } if (fieldLayouts.size() > 10) { segmentHeader.setHave_field_flags_hi(true); } if (codeLayouts.size() > 15) { segmentHeader.setHave_code_flags_hi(true); } int[] availableClassIndices = {25, 26, 27, 28, 29, 30, 31}; if (classLayouts.size() > 7) { availableClassIndices = addHighIndices(availableClassIndices); } addAttributeDefinitions(classLayouts, availableClassIndices, CONTEXT_CLASS); int[] availableMethodIndices = {26, 27, 28, 29, 30, 31}; if (methodAttributeLayouts.size() > 6) { availableMethodIndices = addHighIndices(availableMethodIndices); } addAttributeDefinitions(methodLayouts, availableMethodIndices, CONTEXT_METHOD); int[] availableFieldIndices = {18, 23, 24, 25, 26, 27, 28, 29, 30, 31}; if (fieldAttributeLayouts.size() > 10) { availableFieldIndices = addHighIndices(availableFieldIndices); } addAttributeDefinitions(fieldLayouts, availableFieldIndices, CONTEXT_FIELD); int[] availableCodeIndices = {17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}; if (codeAttributeLayouts.size() > 15) { availableCodeIndices = addHighIndices(availableCodeIndices); } addAttributeDefinitions(codeLayouts, availableCodeIndices, CONTEXT_CODE); } /** * All input classes for the segment have now been read in, so this method is called so that this class can * calculate/complete anything it could not do while classes were being read. */ public void finaliseBands() { addSyntheticDefinitions(); segmentHeader.setAttribute_definition_count(attributeDefinitions.size()); } @Override public void pack(final OutputStream out) throws IOException, Pack200Exception { PackingUtils.log("Writing attribute definition bands..."); final int[] attributeDefinitionHeader = new int[attributeDefinitions.size()]; final int[] attributeDefinitionName = new int[attributeDefinitions.size()]; final int[] attributeDefinitionLayout = new int[attributeDefinitions.size()]; for (int i = 0; i < attributeDefinitionLayout.length; i++) { final AttributeDefinition def = (AttributeDefinition) attributeDefinitions.get(i); attributeDefinitionHeader[i] = def.contextType | (def.index + 1 << 2); attributeDefinitionName[i] = def.name.getIndex(); attributeDefinitionLayout[i] = def.layout.getIndex(); } byte[] encodedBand = encodeBandInt("attributeDefinitionHeader", attributeDefinitionHeader, Codec.BYTE1); out.write(encodedBand); PackingUtils.log("Wrote " + encodedBand.length + " bytes from attributeDefinitionHeader[" + attributeDefinitionHeader.length + "]"); encodedBand = encodeBandInt("attributeDefinitionName", attributeDefinitionName, Codec.UNSIGNED5); out.write(encodedBand); PackingUtils.log("Wrote " + encodedBand.length + " bytes from attributeDefinitionName[" + attributeDefinitionName.length + "]"); encodedBand = encodeBandInt("attributeDefinitionLayout", attributeDefinitionLayout, Codec.UNSIGNED5); out.write(encodedBand); PackingUtils.log("Wrote " + encodedBand.length + " bytes from attributeDefinitionLayout[" + attributeDefinitionLayout.length + "]"); } private void addSyntheticDefinitions() { final boolean anySytheticClasses = segment.getClassBands().isAnySyntheticClasses(); final boolean anySyntheticMethods = segment.getClassBands().isAnySyntheticMethods(); final boolean anySyntheticFields = segment.getClassBands().isAnySyntheticFields(); if (anySytheticClasses || anySyntheticMethods || anySyntheticFields) { final CPUTF8 syntheticUTF = cpBands.getCPUtf8("Synthetic"); final CPUTF8 emptyUTF = cpBands.getCPUtf8(""); if (anySytheticClasses) { attributeDefinitions.add(new AttributeDefinition(12, CONTEXT_CLASS, syntheticUTF, emptyUTF)); } if (anySyntheticMethods) { attributeDefinitions.add(new AttributeDefinition(12, CONTEXT_METHOD, syntheticUTF, emptyUTF)); } if (anySyntheticFields) { attributeDefinitions.add(new AttributeDefinition(12, CONTEXT_FIELD, syntheticUTF, emptyUTF)); } } } private int[] addHighIndices(final int[] availableIndices) { final int[] temp = new int[availableIndices.length + 32]; System.arraycopy(availableIndices, 0, temp, 0, availableIndices.length); int j = 32; for (int i = availableIndices.length; i < temp.length; i++) { temp[i] = j; j++; } return temp; } private void addAttributeDefinitions(final Map layouts, final int[] availableIndices, final int contextType) { final int i = 0; for (Object element : layouts.keySet()) { final String name = (String) element; final String layout = (String) layouts.get(name); final int index = availableIndices[i]; final AttributeDefinition definition = new AttributeDefinition(index, contextType, cpBands.getCPUtf8(name), cpBands.getCPUtf8(layout)); attributeDefinitions.add(definition); switch (contextType) { case CONTEXT_CLASS: classAttributeLayouts.add(definition); break; case CONTEXT_METHOD: methodAttributeLayouts.add(definition); break; case CONTEXT_FIELD: fieldAttributeLayouts.add(definition); break; case CONTEXT_CODE: codeAttributeLayouts.add(definition); } } } public List getClassAttributeLayouts() { return classAttributeLayouts; } public List getMethodAttributeLayouts() { return methodAttributeLayouts; } public List getFieldAttributeLayouts() { return fieldAttributeLayouts; } public List getCodeAttributeLayouts() { return codeAttributeLayouts; } public static class AttributeDefinition { public int index; public int contextType; public CPUTF8 name; public CPUTF8 layout; public AttributeDefinition(final int index, final int contextType, final CPUTF8 name, final CPUTF8 layout) { this.index = index; this.contextType = contextType; this.name = name; this.layout = layout; } } }
43.374468
119
0.656725
da8695ec62413d54bad82367bd163ba7532c89e7
1,231
php
PHP
Controller/Stoke.php
bono-cms/Stokes
4c4c880011f894483c56ae1a34b9721912eac86d
[ "CC-BY-3.0" ]
null
null
null
Controller/Stoke.php
bono-cms/Stokes
4c4c880011f894483c56ae1a34b9721912eac86d
[ "CC-BY-3.0" ]
null
null
null
Controller/Stoke.php
bono-cms/Stokes
4c4c880011f894483c56ae1a34b9721912eac86d
[ "CC-BY-3.0" ]
null
null
null
<?php /** * This file is part of the Bono CMS * * Copyright (c) No Global State Lab * * For the full copyright and license information, please view * the license file that was distributed with this source code. */ namespace Stokes\Controller; use Site\Controller\AbstractController; final class Stoke extends AbstractController { /** * Lists all stokes * * @param integer $page * @return string */ public function listAction($page = 1) { } /** * Views a stoke * * @param string $id * @return string */ public function indexAction($id) { $sm = $this->getModuleService('stokeManager'); $stoke = $sm->fetchById($id, false); if ($stoke !== false) { $this->loadSitePlugins(); // Append a breadcrumbs $this->view->getBreadcrumbBag()->addOne($stoke->getName()); return $this->view->render('stoke-single', array( 'stoke' => $stoke, 'page' => $stoke, 'languages' => $sm->getSwitchUrls($id) )); } else { return false; } } }
21.982143
72
0.514216
1a6a6003465fbfb5e697c15a4f14ad0159061461
578
cs
C#
Plugins/Logger/LoggerViewModel.cs
stu43005/KanColleViewer
1fb56728fff408456bf5f0766ba6dedf92af9d3a
[ "MIT" ]
null
null
null
Plugins/Logger/LoggerViewModel.cs
stu43005/KanColleViewer
1fb56728fff408456bf5f0766ba6dedf92af9d3a
[ "MIT" ]
null
null
null
Plugins/Logger/LoggerViewModel.cs
stu43005/KanColleViewer
1fb56728fff408456bf5f0766ba6dedf92af9d3a
[ "MIT" ]
null
null
null
using Livet; using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Reactive.Linq; using System.Windows; namespace Logger { public class LoggerViewModel : ViewModel { #region Loggers 変更通知プロパティ private ObservableCollection<LoggerBase> _Loggers; public ObservableCollection<LoggerBase> Loggers { get { return this._Loggers; } set { if (this._Loggers != value) { this._Loggers = value; this.RaisePropertyChanged(); } } } #endregion public LoggerViewModel() { } } }
15.621622
52
0.702422
e47e42b0963012bed231f6e71d0f28869a917984
63
rs
Rust
src/memory/mod.rs
NotGyro/voxelgame
1798af4380ba72262deba571cce6b39614fafe34
[ "MIT" ]
null
null
null
src/memory/mod.rs
NotGyro/voxelgame
1798af4380ba72262deba571cce6b39614fafe34
[ "MIT" ]
null
null
null
src/memory/mod.rs
NotGyro/voxelgame
1798af4380ba72262deba571cce6b39614fafe34
[ "MIT" ]
1
2018-12-16T00:40:13.000Z
2018-12-16T00:40:13.000Z
//! Memory management types. pub mod allocator; pub mod pool;
12.6
28
0.730159
18cde2e7bc62ab282117a82dab8e8fad38dce3b2
4,158
swift
Swift
Twitter/NotificationViewController.swift
kesongxie/CodePath-Week4-Twitter
97b234e37f45ba9e7e6292a6adfa728a668aaf11
[ "Apache-2.0" ]
7
2017-09-28T16:47:16.000Z
2019-09-01T17:49:00.000Z
Twitter/NotificationViewController.swift
kesongxie/CodePath-Week4-Twitter
97b234e37f45ba9e7e6292a6adfa728a668aaf11
[ "Apache-2.0" ]
1
2017-02-28T06:41:02.000Z
2017-03-05T21:36:25.000Z
Twitter/NotificationViewController.swift
kesongxie/CodePath-Week4-5-Twitter
97b234e37f45ba9e7e6292a6adfa728a668aaf11
[ "Apache-2.0" ]
null
null
null
// // NotificationViewController.swift // Twitter // // Created by Xie kesong on 2/18/17. // Copyright © 2017 ___KesongXie___. All rights reserved. // import UIKit fileprivate let reuseIden = "TweetCell" fileprivate let tweetCellNibName = "TweetTableViewCell" fileprivate let notificationSectionHeaderReuseIden = "NotificationSectionHeader" class NotificationViewController: UIViewController { @IBOutlet weak var tableView: UITableView!{ didSet{ //use xib for reuse cell self.tableView.register(UINib(nibName: tweetCellNibName, bundle: Bundle.main), forCellReuseIdentifier: reuseIden) self.tableView.delegate = self self.tableView.dataSource = self self.tableView.estimatedRowHeight = self.tableView.rowHeight self.tableView.rowHeight = UITableViewAutomaticDimension } } @IBOutlet weak var footerLoadingView: UIView! var tweets: [Tweet]?{ didSet{ self.footerLoadingView.isHidden = true self.tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() TwitterClient.getMentionedTimeLine { (tweets, error) in if let tweets = tweets{ self.tweets = tweets } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) App.postStatusBarShouldUpdateNotification(style: .default) self.navigationController?.isNavigationBarHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let iden = segue.identifier{ if iden == SegueIdentifier.showTweetDetail{ guard let tweetDetailVC = segue.destination as? TweetDetailViewController else{ return } guard let selectedIndexPath = sender as? IndexPath else{ return } guard let selectedTweet = self.tweets?[selectedIndexPath.row] else{ return } tweetDetailVC.tweet = selectedTweet } } } } extension NotificationViewController: UITableViewDelegate, UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.tweets?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIden, for: indexPath) as! TweetTableViewCell cell.tweet = self.tweets![indexPath.row] cell.delegate = self return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.performSegue(withIdentifier: SegueIdentifier.showTweetDetail, sender: indexPath) } } extension NotificationViewController: TweetTableViewCellDelegate{ func mediaImageViewTapped(cell: TweetTableViewCell, image: UIImage?, tweet: Tweet) { if let previewDetailVC = App.mainStoryBoard.instantiateViewController(withIdentifier: StorybordIdentifier.PhotoPreviewViewControllerIden) as? PhotoPreviewViewController{ previewDetailVC.tweet = tweet previewDetailVC.image = image self.present(previewDetailVC, animated: true, completion: nil) } } func profileImageViewTapped(cell: TweetTableViewCell, tweet: Tweet) { if let profileVC = App.mainStoryBoard.instantiateViewController(withIdentifier: StorybordIdentifier.ProfileTableViewControllerIden) as? ProfileTableViewController{ profileVC.isPresented = true profileVC.user = tweet.user self.navigationController?.pushViewController(profileVC, animated: true) } } }
34.65
177
0.659933
c9e32b278c9cfd9cf07a9a13ac048107d8a698f4
966
tsx
TypeScript
shared-module/src/components/ExerciseList/PageBox.tsx
rage/secret-project-331
3c78c02f2f1d2e4539522e73c3065ae8866604e3
[ "Apache-2.0" ]
6
2021-09-23T05:28:58.000Z
2022-03-11T09:25:05.000Z
shared-module/src/components/ExerciseList/PageBox.tsx
rage/secret-project-331
3c78c02f2f1d2e4539522e73c3065ae8866604e3
[ "Apache-2.0" ]
232
2021-07-09T07:13:31.000Z
2022-03-31T13:35:09.000Z
shared-module/src/components/ExerciseList/PageBox.tsx
rage/secret-project-331
3c78c02f2f1d2e4539522e73c3065ae8866604e3
[ "Apache-2.0" ]
null
null
null
import styled from "@emotion/styled" import React from "react" import { baseTheme } from "../../styles" const Wrapper = styled.div` border-radius: 10px; position: relative; width: 100%; ` const PageBoxRow = styled.div` position: relative; padding: 0.6em 1em; list-style-type: none; color: ${baseTheme.colors.neutral[100]}; text-decoration: none; border-radius: 2px; background: ${baseTheme.colors.grey[800]}; span { vertical-align: top; font-size: clamp(16px, 1vw, 18px); display: inline-block; width: 75%; margin: 0.4em 0 0.4em 0.2em; text-transform: uppercase; } ` export interface PageBoxExtraProps { pageTitle: string } export type PageBoxProps = React.HTMLAttributes<HTMLDivElement> & PageBoxExtraProps const PageBox: React.FC<PageBoxProps> = (props) => { return ( <Wrapper> <PageBoxRow> <span>{props.pageTitle}</span> </PageBoxRow> </Wrapper> ) } export default PageBox
20.125
83
0.670807
fa35dd16f796e2efc6d61495c26e22b135919be9
406
cpp
C++
src/techniques/lrel.cpp
shibii/nn
2022ec423c3bfe179997630d6ba705aeaabdd918
[ "MIT" ]
1
2020-11-17T14:25:28.000Z
2020-11-17T14:25:28.000Z
src/techniques/lrel.cpp
shibii/nn
2022ec423c3bfe179997630d6ba705aeaabdd918
[ "MIT" ]
null
null
null
src/techniques/lrel.cpp
shibii/nn
2022ec423c3bfe179997630d6ba705aeaabdd918
[ "MIT" ]
null
null
null
#include "lrel.hpp" namespace nn { LReL::LReL(float leak) : leak_(leak) {} void LReL::forward(Feed &f) { input_ = f.signal; f.signal = (input_ > 0.f) * input_ + (input_ <= 0.f) * input_ * leak_; } void LReL::backward(Feed &f) { f.signal = (input_ > 0.f) * f.signal + (input_ <= 0.f) * f.signal * leak_; } template <class Archive> void LReL::serialize(Archive &ar) { ar(leak_); } } // namespace nn
25.375
76
0.618227
75341b0b321650935c53afdbe3a07c5bdf44b6b9
2,276
css
CSS
ispinner.css
simformsolutions/ispinner
a788e727760a1958868ac4e3fa0d18a473ca9e67
[ "MIT" ]
2
2020-03-02T05:48:06.000Z
2020-04-21T03:53:31.000Z
ispinner.css
simformsolutions/ispinner
a788e727760a1958868ac4e3fa0d18a473ca9e67
[ "MIT" ]
null
null
null
ispinner.css
simformsolutions/ispinner
a788e727760a1958868ac4e3fa0d18a473ca9e67
[ "MIT" ]
1
2020-07-16T08:40:30.000Z
2020-07-16T08:40:30.000Z
.ispinner { position: relative; width: 20px; height: 20px; } .ispinner .ispinner-blade { position: absolute; top: 37%; left: 44.5%; width: 10%; height: 25%; background-color: #8e8e93; border-radius: 50%/20%; animation: iSpinnerBlade 1s linear infinite; will-change: opacity; } .ispinner .ispinner-blade:nth-child(1) { transform: rotate(30deg) translate(0, -150%); animation-delay: -1.6666666667s; } .ispinner .ispinner-blade:nth-child(2) { transform: rotate(60deg) translate(0, -150%); animation-delay: -1.5833333333s; } .ispinner .ispinner-blade:nth-child(3) { transform: rotate(90deg) translate(0, -150%); animation-delay: -1.5s; } .ispinner .ispinner-blade:nth-child(4) { transform: rotate(120deg) translate(0, -150%); animation-delay: -1.4166666667s; } .ispinner .ispinner-blade:nth-child(5) { transform: rotate(150deg) translate(0, -150%); animation-delay: -1.3333333333s; } .ispinner .ispinner-blade:nth-child(6) { transform: rotate(180deg) translate(0, -150%); animation-delay: -1.25s; } .ispinner .ispinner-blade:nth-child(7) { transform: rotate(210deg) translate(0, -150%); animation-delay: -1.1666666667s; } .ispinner .ispinner-blade:nth-child(8) { transform: rotate(240deg) translate(0, -150%); animation-delay: -1.0833333333s; } .ispinner .ispinner-blade:nth-child(9) { transform: rotate(270deg) translate(0, -150%); animation-delay: -1s; } .ispinner .ispinner-blade:nth-child(10) { transform: rotate(300deg) translate(0, -150%); animation-delay: -0.9166666667s; } .ispinner .ispinner-blade:nth-child(11) { transform: rotate(330deg) translate(0, -150%); animation-delay: -0.8333333333s; } .ispinner .ispinner-blade:nth-child(12) { transform: rotate(360deg) translate(0, -150%); animation-delay: -0.75s; } .ispinner.ispinner-large { width: 35px; height: 35px; } .ispinner.ispinner-large .ispinner-blade { width: 8.5714285714%; height: 25.7142857143%; border-radius: 50%/16.67%; } @keyframes iSpinnerBlade { 0% { opacity: 0.85; } 50% { opacity: 0.25; } 100% { opacity: 0.25; } }
34.484848
52
0.627417
3bbbc4928484cf3f8fdad4c067f8e7fbcaae6b8f
189
sql
SQL
TicTacToe/TicTacToe/Pre-Deployment/01_Create_Database.sql
AlexeyBuryanov/TicTacToe
9707ab6200f4ba9220c2416cd03a2192dad3ab1d
[ "MIT" ]
2
2019-04-07T22:28:36.000Z
2022-02-16T11:16:03.000Z
TicTacToe/TicTacToe/Pre-Deployment/01_Create_Database.sql
AlexeyBuryanov/TicTacToe
9707ab6200f4ba9220c2416cd03a2192dad3ab1d
[ "MIT" ]
null
null
null
TicTacToe/TicTacToe/Pre-Deployment/01_Create_Database.sql
AlexeyBuryanov/TicTacToe
9707ab6200f4ba9220c2416cd03a2192dad3ab1d
[ "MIT" ]
1
2021-01-28T22:26:28.000Z
2021-01-28T22:26:28.000Z
IF DB_ID(N'TicTacToe') IS NOT NULL BEGIN PRINT(N'Создание БД TicTacToe: БД уже существует!'); END ELSE BEGIN CREATE DATABASE TicTacToe; PRINT(N'Создание БД TicTacToe: успешно.'); END GO
27
53
0.756614
0bea08fea6a8f0565d9d6751eb64595c0f53d32d
1,991
kt
Kotlin
vsrecyclerview/src/main/java/com/wshtaits/vsrecyclerview/adapter/itemsadapters/base/ItemsAdapter.kt
wshtaits/VsRecyclerView
23b0749cd1c21993ba2987a49e9fc38ca9872e2e
[ "Apache-2.0" ]
11
2019-09-13T13:58:57.000Z
2021-06-19T00:19:37.000Z
vsrecyclerview/src/main/java/com/wshtaits/vsrecyclerview/adapter/itemsadapters/base/ItemsAdapter.kt
wshtaits/VsRecyclerView
23b0749cd1c21993ba2987a49e9fc38ca9872e2e
[ "Apache-2.0" ]
1
2019-10-15T10:51:38.000Z
2019-10-23T08:50:07.000Z
vsrecyclerview/src/main/java/com/wshtaits/vsrecyclerview/adapter/itemsadapters/base/ItemsAdapter.kt
wshtaits/VsRecyclerView
23b0749cd1c21993ba2987a49e9fc38ca9872e2e
[ "Apache-2.0" ]
4
2019-09-13T13:58:59.000Z
2021-01-30T15:16:29.000Z
/* * Copyright (c) 2019 Shtaits Valeriy. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wshtaits.vsrecyclerview.adapter.itemsadapters.base import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.recyclerview.widget.RecyclerView abstract class ItemsAdapter<in AdaptableData> { val viewType by lazy { hashCode() } private val itemViewFactory: ItemViewFactory constructor(@LayoutRes layoutResId: Int) { itemViewFactory = ItemViewFactory(layoutResId) } constructor(itemViewFactoryFunction: (parent: ViewGroup) -> View) { itemViewFactory = ItemViewFactory(itemViewFactoryFunction) } internal fun createViewHolder(parent: ViewGroup): ItemViewHolder { val itemView = itemViewFactory.createItemView(parent) val itemViewHolder = ItemViewHolder(itemView) itemViewHolder.onCreateViewHolder() return itemViewHolder } internal fun createAdapterItems(adaptableDataCollection: Collection<AdaptableData>): List<AdapterItem<*>> = adaptableDataCollection.map { adaptableData -> AdapterItem(adaptableData, this) } internal fun createAdapterItem(data: AdaptableData): AdapterItem<*> = AdapterItem(data, this) open fun getItemId(data: AdaptableData): Long = RecyclerView.NO_ID open fun ItemViewHolder.onCreateViewHolder() { /* stub */ } open fun ItemViewHolder.onBindViewHolder(data: AdaptableData) { /* stub */ } }
36.2
111
0.748368
a476d6bf60d89dd75e8124d353fb1642a2736e89
2,323
php
PHP
src/DescriptionFileMethod.php
event-engine/php-code-generator-cartridge-event-engine
35a2c6e76eb77581479a3e37a2003bfd946239cd
[ "MIT" ]
1
2020-08-15T08:48:39.000Z
2020-08-15T08:48:39.000Z
src/DescriptionFileMethod.php
event-engine/php-code-generator-cartridge-event-engine
35a2c6e76eb77581479a3e37a2003bfd946239cd
[ "MIT" ]
1
2020-10-02T06:17:44.000Z
2020-10-02T06:17:44.000Z
src/DescriptionFileMethod.php
event-engine/php-code-generator-cartridge-event-engine
35a2c6e76eb77581479a3e37a2003bfd946239cd
[ "MIT" ]
null
null
null
<?php /** * @see https://github.com/event-engine/php-code-generator-cartridge-event-engine for the canonical source repository * @copyright https://github.com/event-engine/php-code-generator-cartridge-event-engine/blob/master/COPYRIGHT.md * @license https://github.com/event-engine/php-code-generator-cartridge-event-engine/blob/master/LICENSE.md MIT License */ declare(strict_types=1); namespace EventEngine\CodeGenerator\Cartridge\EventEngine; use EventEngine\CodeGenerator\Cartridge\EventEngine\Code\DescriptionFileMethod as CodeDescriptionFileMethod; use OpenCodeModeling\CodeAst\NodeVisitor\ClassImplements; use OpenCodeModeling\CodeAst\NodeVisitor\ClassMethod; use OpenCodeModeling\CodeAst\NodeVisitor\NamespaceUse; use PhpParser\NodeTraverser; use PhpParser\Parser; use PhpParser\PrettyPrinterAbstract; final class DescriptionFileMethod { /** * @var Parser **/ private $parser; /** * @var PrettyPrinterAbstract */ private $printer; public function __construct(Parser $parser, PrettyPrinterAbstract $printer) { $this->parser = $parser; $this->printer = $printer; } public function __invoke(string $code): string { $ast = $this->parser->parse($code); $traverser = new NodeTraverser(); $traverser->addVisitor( new NamespaceUse( 'EventEngine\EventEngine', 'EventEngine\EventEngineDescription', 'EventEngine\JsonSchema\JsonSchema', 'EventEngine\JsonSchema\JsonSchemaArray' ) ); $traverser->addVisitor( new ClassImplements( 'EventEngineDescription' ) ); $traverser->addVisitor(new ClassMethod(CodeDescriptionFileMethod::generate())); return $this->printer->prettyPrintFile($traverser->traverse($ast)); } public static function workflowComponentDescription( Parser $parser, PrettyPrinterAbstract $printer, string $inputCode, string $output ): \OpenCodeModeling\CodeGenerator\Workflow\Description { return new \OpenCodeModeling\CodeGenerator\Workflow\ComponentDescriptionWithSlot( new self($parser, $printer), $output, $inputCode ); } }
30.973333
123
0.672837
0df188aae7677ccd000910d28b2bc58f63bcec9c
492
cs
C#
Assets/_Project/Scripts/General/SpawnPoint.cs
WagnerTB/SimplePirateGame
ec195bede589c5baed32cfa6f16ee91720305694
[ "MIT" ]
null
null
null
Assets/_Project/Scripts/General/SpawnPoint.cs
WagnerTB/SimplePirateGame
ec195bede589c5baed32cfa6f16ee91720305694
[ "MIT" ]
null
null
null
Assets/_Project/Scripts/General/SpawnPoint.cs
WagnerTB/SimplePirateGame
ec195bede589c5baed32cfa6f16ee91720305694
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnPoint : MonoBehaviour { public float size; public Vector3 RequestPosition() { var point = UnityEngine.Random.insideUnitSphere * size; var pos = transform.position + point; pos.y = 0; return pos; } private void OnDrawGizmosSelected() { Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, size); } }
20.5
63
0.654472
dbc8312d5b74dc348462f42bd9c80a129c03a86f
997
php
PHP
src/Models/MenuItemLink.php
oddvalue/backpack-menus
1b8122ee2295a1bf60d90a72b584575c2d8751f6
[ "MIT" ]
null
null
null
src/Models/MenuItemLink.php
oddvalue/backpack-menus
1b8122ee2295a1bf60d90a72b584575c2d8751f6
[ "MIT" ]
1
2020-10-21T16:15:50.000Z
2020-10-21T16:15:50.000Z
src/Models/MenuItemLink.php
oddvalue/backpack-menus
1b8122ee2295a1bf60d90a72b584575c2d8751f6
[ "MIT" ]
null
null
null
<?php namespace Oddvalue\BackpackMenus; use Oddvalue\LinkBuilder\Link; class MenuItemLink extends Link { /** * Get the link href for $this->model * * @param array $options * @return string */ public function href(array $options = []) : string { switch ($this->model->type) { case 'external_link': return $this->model->link; break; case 'internal_link': return is_null($this->model->link) ? '#' : url($this->model->link); break; default: if (! $this->model->menuable) { return ''; } return $this->model->menuable->getLinkGenerator()->href(); } } /** * Get the link text for $this->model * * @param array $options * @return string */ public function label(array $options = []) : string { return $this->model->name; } }
22.155556
83
0.489468
a102f9f5ddcf189b9b91d2bff9169b3be19ca3c8
419
swift
Swift
ITPS/ITPS/Profile/Controller/AboutViewController.swift
iWeslie/ITPS
22b9f8884b589d3d1ec2daf7a87d8ddb6dbb05e5
[ "Apache-2.0" ]
null
null
null
ITPS/ITPS/Profile/Controller/AboutViewController.swift
iWeslie/ITPS
22b9f8884b589d3d1ec2daf7a87d8ddb6dbb05e5
[ "Apache-2.0" ]
null
null
null
ITPS/ITPS/Profile/Controller/AboutViewController.swift
iWeslie/ITPS
22b9f8884b589d3d1ec2daf7a87d8ddb6dbb05e5
[ "Apache-2.0" ]
null
null
null
// // AboutViewController.swift // ITPS // // Created by Weslie on 2018/5/9. // Copyright © 2018 Weslie. All rights reserved. // import UIKit class AboutViewController: UIViewController { @IBOutlet weak var versionLbl: UILabel! @IBOutlet weak var versionSmallLbl: UILabel! override func viewDidLoad() { super.viewDidLoad() versionLbl.text = "V\(localVersion)" } }
17.458333
49
0.651551
c6e362bf6a246f7a2ad3404554bd7be6976605a3
3,102
py
Python
torch_glow/tests/nodes/trig_ops_test.py
YaronBenAtar/glow
a13706a4239fa7eaf059c670dc573e3eb0768f86
[ "Apache-2.0" ]
2,838
2018-05-02T16:57:22.000Z
2022-03-31T14:35:26.000Z
torch_glow/tests/nodes/trig_ops_test.py
YaronBenAtar/glow
a13706a4239fa7eaf059c670dc573e3eb0768f86
[ "Apache-2.0" ]
4,149
2018-05-02T17:50:14.000Z
2022-03-31T23:56:43.000Z
torch_glow/tests/nodes/trig_ops_test.py
LaudateCorpus1/glow-1
cda5383b1609ebad1a3631ca77b41b8a863443d4
[ "Apache-2.0" ]
685
2018-05-02T16:54:09.000Z
2022-03-24T01:12:24.000Z
# Copyright (c) Glow Contributors. See CONTRIBUTORS file. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import torch from tests import utils class SimpleCosModule(torch.nn.Module): def __init__(self): super(SimpleCosModule, self).__init__() def forward(self, a): return torch.cos(a + a) class SimpleSinModule(torch.nn.Module): def __init__(self): super(SimpleSinModule, self).__init__() def forward(self, a): return torch.sin(a + a) class SimpleACosModule(torch.nn.Module): def __init__(self): super(SimpleACosModule, self).__init__() def forward(self, a): return torch.acos(a + a) class SimpleASinModule(torch.nn.Module): def __init__(self): super(SimpleASinModule, self).__init__() def forward(self, a): return torch.asin(a + a) class SimpleATanModule(torch.nn.Module): def __init__(self): super(SimpleATanModule, self).__init__() def forward(self, a): return torch.atan(a + a) class TestCos(utils.TorchGlowTestCase): def test_cos(self, skip_to_glow=False): # Ensures range is in [-2*pi, 2*pi] x = 4 * np.pi * (torch.rand(2, 3, 4) - 0.5) utils.compare_tracing_methods( SimpleCosModule(), x, fusible_ops={"aten::cos"}, skip_to_glow=skip_to_glow ) class TestSin(utils.TorchGlowTestCase): def test_sin(self, skip_to_glow=False): # Ensures range is in [-2*pi, 2*pi] x = 4 * np.pi * (torch.rand(2, 3, 4) - 0.5) utils.compare_tracing_methods( SimpleSinModule(), x, fusible_ops={"aten::sin"}, skip_to_glow=skip_to_glow ) class TestACos(utils.TorchGlowTestCase): def test_acos(self, skip_to_glow=False): x = torch.rand(2, 3, 4) - 0.5 # Ensures range is in [-1,1] utils.compare_tracing_methods( SimpleACosModule(), x, fusible_ops={"aten::acos"}, skip_to_glow=skip_to_glow ) class TestASin(utils.TorchGlowTestCase): def test_asin(self, skip_to_glow=False): x = torch.rand(2, 3, 4) - 0.5 # Ensures range is in [-1,1] utils.compare_tracing_methods( SimpleASinModule(), x, fusible_ops={"aten::asin"}, skip_to_glow=skip_to_glow ) class TestATan(utils.TorchGlowTestCase): def test_atan(self, skip_to_glow=False): x = torch.randn(2, 3, 4) utils.compare_tracing_methods( SimpleATanModule(), x, fusible_ops={"aten::atan"}, skip_to_glow=skip_to_glow )
30.411765
88
0.670535
2558f8796fe277b379c33e5807f6b5acc773912d
2,525
cs
C#
src/old/MapManager.cs
kesac/gw2lam
e2cee3a27c7c43b4ce32f1a8de7105f4b62e8003
[ "MIT" ]
null
null
null
src/old/MapManager.cs
kesac/gw2lam
e2cee3a27c7c43b4ce32f1a8de7105f4b62e8003
[ "MIT" ]
null
null
null
src/old/MapManager.cs
kesac/gw2lam
e2cee3a27c7c43b4ce32f1a8de7105f4b62e8003
[ "MIT" ]
null
null
null
using System; using System.Net; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Turtlesort.Glam.Old { public class MapDataOld { public string map_name { get; set; } } public class APIResponseOld { public Dictionary<uint, MapDataOld> maps { get; set; } } public class MapManagerOld { private const string MAP_DATA_FILE = "maps.json"; private const string MAP_DATA_API_V1 = "http://api.guildwars2.com/v1/maps.json"; private const string MAP_DATA_API_V2 = "http://api.guildwars2.com/v2/maps/"; private Dictionary<uint, MapDataOld> mapData; public MapManagerOld() { this.mapData = new Dictionary<uint, MapDataOld>(); } /// <summary> /// <para> /// Initializes MapManager's ID-to-name look-up table for maps from /// the 'maps.json' file. ///</para> ///<para> /// If the file does not already exist in the same folder as the /// executable, the file will be downloaded using GW2's V1 API. ///</para> /// </summary> public void InitializeLocalCache() { string rawData; if (!File.Exists(MAP_DATA_FILE)) // Download maps.json if it doesn't exist { WebClient client = new WebClient(); rawData = client.DownloadString(MAP_DATA_API_V1); File.WriteAllText(MAP_DATA_FILE, rawData); } else { using (StreamReader streamReader = new StreamReader(MAP_DATA_FILE, Encoding.UTF8)) { rawData = streamReader.ReadToEnd(); } } APIResponseOld response = JsonConvert.DeserializeObject<APIResponseOld>(rawData); this.mapData = response.maps; } public string GetName(uint id) { if (this.mapData.ContainsKey(id)) { return this.mapData[id].map_name; } else { // try to use the API return null; } } public bool IsValidID(uint id) { return this.mapData.ContainsKey(id) || false; // try to use api here } } }
28.055556
99
0.527129
cdae64f0f374ae0ab0a3f6d3e3d51254ab5c34fa
2,213
cs
C#
Engine/Errors/SimObjectErrorManager.cs
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
Engine/Errors/SimObjectErrorManager.cs
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
Engine/Errors/SimObjectErrorManager.cs
AnomalousMedical/Engine
a19e21f597bd277e4ca17e0e5f3f89577f2307bb
[ "MIT" ]
null
null
null
using Logging; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Engine { /// <summary> /// This is a repository for errors that occur when loading, you can call this from your factory or sim objects /// to report errors to this repository then a client program could choose to display them to help with debugging. /// /// The lifecycle of the errors in this class must be handled by the client program. E.g. you must call Clear when /// loading a scene (or other object that could have errors you want to look for) and then check the HasErrors /// to display a message or handle the error. /// </summary> public static class SimObjectErrorManager { private static LinkedList<SimObjectError> errors = new LinkedList<SimObjectError>(); /// <summary> /// Clear all errors in the repository. /// </summary> public static void Clear() { errors.Clear(); } /// <summary> /// Add an error to the repository. /// </summary> /// <param name="error">The error to add.</param> public static void AddError(SimObjectError error) { errors.AddLast(error); } public static void AddAndLogError(SimObjectError error, LogLevel logLevel = LogLevel.Warning) { AddError(error); Log.Default.sendMessage("Error creating {0} named '{1}' in SimObject '{2}'. Reason: {3}", logLevel, error.Subsystem, error.Type, error.ElementName, error.SimObject, error.Message); } /// <summary> /// True if there are errors in the repository. /// </summary> public static bool HasErrors { get { return errors.First != null; } } /// <summary> /// An enumerator over all the errors. /// </summary> public static IEnumerable<SimObjectError> Errors { get { return errors; } } } }
32.544118
193
0.568459
e716b8213629236bbc03247003241aff29d0b7a4
3,308
go
Go
dbops/db.go
authetic-x/GoProxyPoll
133c54257cd157aff0157ec802508e16e4660c6c
[ "MIT" ]
2
2020-06-11T08:02:36.000Z
2020-06-11T11:18:46.000Z
dbops/db.go
authetic-x/GoProxyPoll
133c54257cd157aff0157ec802508e16e4660c6c
[ "MIT" ]
null
null
null
dbops/db.go
authetic-x/GoProxyPoll
133c54257cd157aff0157ec802508e16e4660c6c
[ "MIT" ]
null
null
null
package dbops import ( "GoProxyPoll/GoProxyPoll/defs" "database/sql" "errors" "log" "math/rand" "time" ) func AddIp(ip *defs.Ip) error { stmtIns, err := dbConn.Prepare(`INSERT INTO proxypoll (ip, protocol, score) VALUES (?, ?, ?)`) if err != nil { return err } _, err = stmtIns.Exec(ip.Data, ip.Type, MAX_SCORE) if err != nil { return err } defer stmtIns.Close() return nil } func NotExist(ip *defs.Ip) (bool, error) { stmtOut, err := dbConn.Prepare(`SELECT id FROM proxypoll WHERE ip = ?`) if err != nil { return false, err } var id int err = stmtOut.QueryRow(ip.Data).Scan(&id) if err == sql.ErrNoRows { return true, nil } if err != nil { return false, err } defer stmtOut.Close() return false, nil } func DeleteIp(ip *defs.Ip) error { stmtDel, err := dbConn.Prepare(`DELETE FROM proxypoll WHERE ip = ?`) if err != nil { return err } _, err = stmtDel.Exec(ip.Data) if err != nil { return err } defer stmtDel.Close() return nil } func UpdateIp(ip *defs.Ip, score int) error { stmtUp, err := dbConn.Prepare(`UPDATE proxypoll SET score = ? WHERE ip = ?`) if err != nil { return err } _, err = stmtUp.Exec(score, ip.Data) if err != nil { return err } defer stmtUp.Close() return nil } func Decrease(ip *defs.Ip) error { stmtOut, err := dbConn.Prepare(`SELECT score FROM proxypoll WHERE ip = ?`) if err != nil { return err } var score int err = stmtOut.QueryRow(ip.Data).Scan(&score) if err != nil { return nil } if score == MIN_SCORE { err = DeleteIp(ip) } else { err = UpdateIp(ip, score-1) } defer stmtOut.Close() return err } func Count() (int, error) { stmtOut, err := dbConn.Prepare(`SELECT count(*) FROM proxypoll`) if err != nil { return 0, err } var cnt int err = stmtOut.QueryRow().Scan(&cnt) if err != nil { return 0, err } defer stmtOut.Close() return cnt, nil } func Random() (*defs.Ip, error) { stmtOut, err := dbConn.Prepare(`SELECT ip, protocol FROM proxypoll WHERE score = ?`) if err != nil { return nil, err } rows, err := stmtOut.Query(MAX_SCORE) if err != nil { return nil, err } var ips []*defs.Ip if columns, _ := rows.Columns(); len(columns) == 0 { stmtOut, err = dbConn.Prepare(`SELECT ip, protocol FROM proxypoll`) if err != nil { return nil, err } rows, err = stmtOut.Query() if err != nil { return nil, err } if columns, _ := rows.Columns(); len(columns) == 0 { err = errors.New("There is no proxy in database.") return nil, err } } var cnt int for rows.Next() { var ip, protocol string if err = rows.Scan(&ip, &protocol); err != nil { return nil, err } c := &defs.Ip{Data:ip, Type:protocol} ips = append(ips, c) cnt++ } defer stmtOut.Close() rand.Seed(time.Now().UnixNano()) log.Println(cnt) num := rand.Intn(cnt) return ips[num], nil } func AllIps() ([]*defs.Ip, error) { stmtOut, err := dbConn.Prepare(`SELECT ip, protocol FROM proxypoll`) if err != nil { return nil, err } var ips []*defs.Ip rows, err := stmtOut.Query() if err != nil { return nil, err } for rows.Next() { var ip, protocol string if err = rows.Scan(&ip, &protocol); err != nil { return nil, err } c := &defs.Ip{Data:ip, Type:protocol} ips = append(ips, c) } defer stmtOut.Close() return ips, nil }
19.690476
85
0.626663
4f8c3c03d2dc921695356bff063effbfca92e436
911
kt
Kotlin
tmp/arrays/classVarargGetSetEvaluationOrder.kt
vitekkor/bbfgradle
b4ec701a7a3b7523db97631fa0ed6484149ca9cd
[ "Apache-2.0" ]
45,293
2015-01-01T06:23:46.000Z
2022-03-31T21:55:51.000Z
compiler/testData/codegen/box/increment/classVarargGetSetEvaluationOrder.kt
Seantheprogrammer93/kotlin
f7aabf03f89bdd39d9847572cf9e0051ea42c247
[ "ECL-2.0", "Apache-2.0" ]
3,386
2015-01-12T13:28:50.000Z
2022-03-31T17:48:15.000Z
compiler/testData/codegen/box/increment/classVarargGetSetEvaluationOrder.kt
Seantheprogrammer93/kotlin
f7aabf03f89bdd39d9847572cf9e0051ea42c247
[ "ECL-2.0", "Apache-2.0" ]
6,351
2015-01-03T12:30:09.000Z
2022-03-31T20:46:54.000Z
var log = "" fun logged(value: String) = value.also { log += value } object A { var x = "" var gets = "" var sets = "" operator fun get(vararg va: String): String { for (s in va) { gets += s } log += "get;" return x } operator fun set(vararg va: String, value: String) { for (s in va) { sets += s } log += "set;" x = value } } operator fun String.inc() = this + logged("inc;") fun box(): String { A.x = "start;" val xx = A[logged("1;"), logged("2;"), logged("3;")]++ if (xx != "start;") return "Failed xx: $xx" if (A.x != "start;inc;") return "Failed A.x: ${A.x}" if (A.gets != "1;2;3;") return "Failed A.gets: ${A.gets}" if (A.sets != "1;2;3;") return "Failed A.sets: ${A.sets}" if (log != "1;2;3;get;inc;set;") return "Failed log: $log" return "OK" }
22.775
62
0.473106
a9f0d89a2822f5693e2c3b44564f6604a6d630a1
4,748
lua
Lua
example/game/gems.lua
samuelwbaird/letter-moonshine
71e7531474dc5b1259d5b872af2e122335725748
[ "MIT" ]
1
2020-05-23T14:23:51.000Z
2020-05-23T14:23:51.000Z
example/game/gems.lua
samuelwbaird/letter-moonshine
71e7531474dc5b1259d5b872af2e122335725748
[ "MIT" ]
null
null
null
example/game/gems.lua
samuelwbaird/letter-moonshine
71e7531474dc5b1259d5b872af2e122335725748
[ "MIT" ]
null
null
null
-- a child node managing the draggable gems -- copyright 2016 Samuel Baird MIT Licence local class = require('core.class') local array = require('core.array') local app_node = require('lt.app_node') local display_geom = require('lt.display_geom') local tween = require('lt.tween') return class.derive(app_node, function (gems) function gems:prepare() self.player_gems = array() self.ai_gems = array() end function gems:begin() local x_offset = (app.screen.width - 440) / 2 if x_offset < 32 then x_offset = 32 end for gem = 1, 3 do local y_position = app.screen.height * 0.5 + (gem - 2) * 64 local player_gem = self:add_gem(x_offset, y_position, 'blue', x_offset - 80, 120 + gem * 10) self.player_gems:add(player_gem) local ai_gem = self:add_gem(app.screen.width - x_offset, y_position, 'green', app.screen.width - x_offset + 80, 125 + gem * 10) self.ai_gems:add(ai_gem) end self.drag_touch_area = self:add_touch_area_rect(self.view, 0, 0, app.screen.width, app.screen.height) self.drag_touch_area.enabled = false self.dragging_gem = nil end function gems:make_interactive(tiles, on_select) local dragging_gem = nil -- pick up a gem self.drag_touch_area.on_touch_begin = function (touch_area) for _, gem in ipairs(self.player_gems) do if not gem.tile then local x, y, width, height = gem:bounds(self.view) if display_geom.rect_contains_point(x, y, width, height, touch_area.touch_position[1], touch_area.touch_position[2]) then dragging_gem = gem end end end if dragging_gem then dragging_gem:send_to_front() self:tween(dragging_gem.shadow, tween.easing.ease_out(10), { x = 4 }) self:tween(dragging_gem.sprite, tween.easing.ease_out(10), { y = -5 }) dragging_gem.start = { dragging_gem.x, dragging_gem.y } end end -- move it self.drag_touch_area.on_touch_move = function (touch_area) if dragging_gem and touch_area.move_distance then dragging_gem.x = dragging_gem.start[1] + touch_area.drag_distance[1] dragging_gem.y = dragging_gem.start[2] + touch_area.drag_distance[2] end end -- drop it self.drag_touch_area.on_touch_end = function (touch_area) if dragging_gem then -- check the tiles and the on select callback local selected_tile = nil for _, tile in ipairs(tiles) do if display_geom.point_distance(tile.x, tile.y, dragging_gem.x, dragging_gem.y) < 30 then selected_tile = tile end end self:tween(dragging_gem.shadow, tween.easing.ease_out(10), { x = 2 }) self:tween(dragging_gem.sprite, tween.easing.ease_out(10), { y = 0 }) if selected_tile then self:tween(dragging_gem, tween.easing.ease_out(10), { x = selected_tile.x, y = selected_tile.y, }) dragging_gem.tile = selected_tile selected_tile.gem = dragging_gem self.drag_touch_area.enabled = false on_select(selected_tile) else self:tween(dragging_gem, tween.easing.ease_out(10), { x = dragging_gem.start[1], y = dragging_gem.start[2], }) end dragging_gem = nil end end self.drag_touch_area.enabled = true end function gems:all_gems_used() for _, gem in ipairs(self.player_gems) do if not gem.tile then return false end end for _, gem in ipairs(self.ai_gems) do if not gem.tile then return false end end return true end function gems:end_interactive() self.drag_touch_area.enabled = false end function gems:ai_move(tile, on_complete) local next_gem = nil for _, gem in ipairs(self.ai_gems) do if not gem.tile then next_gem = gem break end end next_gem.tile = tile tile.gem = next_gem -- pick it up next_gem:send_to_front() self:tween(next_gem.shadow, tween.easing.ease_out(10), { x = 4 }) self:tween(next_gem.sprite, tween.easing.ease_out(10), { y = -5 }) self:tween(next_gem, tween.easing.ease_inout(60), { x = tile.x, y = tile.y, }, on_complete) self.dispatch:delay(55, function () self:tween(next_gem.shadow, tween.easing.ease_out(10), { x = 2 }) self:tween(next_gem.sprite, tween.easing.ease_out(10), { y = 0 }) end) end function gems:add_gem(x, y, color, tween_from_x, delay) local gem = self.view:add_display_list({ x = tween_from_x, y = y, color = color, visible = false, tile = nil, }) gem.shadow = gem:add_image('gem_shadow', { x = 2, y = 2, scale = 0.85, alpha = 0.75, }) gem.sprite = gem:add_image('gem_' .. color, { scale = 0.75, }) self.dispatch:delay(delay, function () gem.visible = true self:tween(gem, tween.easing.ease_out(20), { x = x, }) end) return gem end end)
26.087912
130
0.670809
21c00131ecb90f886e94b3056a22449cd761c8c2
177
js
JavaScript
src/step-runner/steps/step.js
getndazn/kopytko-packager
003671d2a1a62b16d27b3a4c08ef7860ca13d082
[ "MIT" ]
2
2021-10-05T22:46:12.000Z
2021-10-08T10:50:40.000Z
src/step-runner/steps/step.js
getndazn/kopytko-packager
003671d2a1a62b16d27b3a4c08ef7860ca13d082
[ "MIT" ]
29
2021-09-21T13:07:46.000Z
2022-03-28T07:24:35.000Z
src/step-runner/steps/step.js
getndazn/kopytko-packager
003671d2a1a62b16d27b3a4c08ef7860ca13d082
[ "MIT" ]
null
null
null
module.exports = class Step { static TITLE = '<Step title>'; logger; constructor(logger) { this.logger = logger; } async run(config) {} // eslint-disable-line }
16.090909
45
0.632768
ed0850b120d136099eb11ef0e0604f883f2aea41
4,079
c
C
src/convert.c
anonymokata/01B0DE0C-6805-4CAD-A3FB-8F34F8EBA3B9
4726d9888358d565458511101e3a3eaab73089ca
[ "MIT" ]
null
null
null
src/convert.c
anonymokata/01B0DE0C-6805-4CAD-A3FB-8F34F8EBA3B9
4726d9888358d565458511101e3a3eaab73089ca
[ "MIT" ]
null
null
null
src/convert.c
anonymokata/01B0DE0C-6805-4CAD-A3FB-8F34F8EBA3B9
4726d9888358d565458511101e3a3eaab73089ca
[ "MIT" ]
null
null
null
#include "convert.h" arabicRomanPair roman_arabic_lookup[] = { { 3, ROMAN_III, sizeof(ROMAN_III) - 1}, { 2, ROMAN_II , sizeof(ROMAN_II) - 1 }, { 4, ROMAN_IV , sizeof(ROMAN_IV) - 1 }, { 9, ROMAN_IX , sizeof(ROMAN_IX) - 1 }, { 40, ROMAN_XL , sizeof(ROMAN_XL) - 1 }, { 90, ROMAN_XC , sizeof(ROMAN_XC) - 1 }, { 400, ROMAN_CD , sizeof(ROMAN_CD) - 1 }, { 900, ROMAN_CM , sizeof(ROMAN_CM) - 1 }, { 1, ROMAN_I , sizeof(ROMAN_I) - 1 }, { 5, ROMAN_V , sizeof(ROMAN_V) - 1 }, { 10, ROMAN_X , sizeof(ROMAN_X) - 1 }, { 50, ROMAN_L , sizeof(ROMAN_L) - 1 }, { 100, ROMAN_C , sizeof(ROMAN_C) - 1 }, { 500, ROMAN_D , sizeof(ROMAN_D) - 1 }, {1000, ROMAN_M , sizeof(ROMAN_M) - 1 } }; arabicRomanPair* lastRomanArabicLookupEntry = &roman_arabic_lookup[sizeof(roman_arabic_lookup) / sizeof(arabicRomanPair) - 1]; arabicRomanPair arabic_roman_lookup[] = { { 1, ROMAN_I , sizeof(ROMAN_I) - 1 }, { 2, ROMAN_II , sizeof(ROMAN_II) - 1 }, { 3, ROMAN_III, sizeof(ROMAN_III) - 1}, { 4, ROMAN_IV , sizeof(ROMAN_IV) - 1 }, { 5, ROMAN_V , sizeof(ROMAN_V) - 1 }, { 9, ROMAN_IX , sizeof(ROMAN_IX) - 1 }, { 10, ROMAN_X , sizeof(ROMAN_X) - 1 }, { 40, ROMAN_XL , sizeof(ROMAN_XL) - 1 }, { 50, ROMAN_L , sizeof(ROMAN_L) - 1 }, { 90, ROMAN_XC , sizeof(ROMAN_XC) - 1 }, { 100, ROMAN_C , sizeof(ROMAN_C) - 1 }, { 400, ROMAN_CD , sizeof(ROMAN_CD) - 1 }, { 500, ROMAN_D , sizeof(ROMAN_D) - 1 }, { 900, ROMAN_CM , sizeof(ROMAN_CM) - 1 }, {1000, ROMAN_M , sizeof(ROMAN_M) - 1 } }; arabicRomanPair* lastArabicRomanLookupEntry = &arabic_roman_lookup[sizeof(roman_arabic_lookup) / sizeof(arabicRomanPair) - 1]; #define romanNumeralComponentIsFound() strncmp(position_in_roman_numeral, pair->roman, pair->romanLength) == 0 #define charactersRemainInRomanNumeral() strlen(position_in_roman_numeral) != 0 #define notPastEndOfLookupTable() pair <= lastRomanArabicLookupEntry #define advanceToNextPositionInRomanNumeral() position_in_roman_numeral += pair->romanLength int convertRomanToArabic(char* romanNumeral) { char* position_in_roman_numeral = romanNumeral; int accumulator = 0; while( charactersRemainInRomanNumeral() ) { arabicRomanPair* pair = roman_arabic_lookup; while( notPastEndOfLookupTable() ) { if(romanNumeralComponentIsFound()) { accumulator += pair->arabic; break; } pair++; } advanceToNextPositionInRomanNumeral(); } return accumulator; } #define arabicValueNotDepleted() arabic_value > 0 #define exactMatchToArabicValue() pair->arabic == arabic_value #define tableEntryExceedsArabicValue() pair->arabic > arabic_value #define lastTableEntryIsLessOrEqualToArabicValue() pair == lastArabicRomanLookupEntry && pair->arabic <= arabic_value #define arabicValueAndTableEntriesRemain() pair <= lastArabicRomanLookupEntry && arabic_value > 0 char* convertArabicToRoman(int arabic_number, char *romanNumeral){ int arabic_value = arabic_number; while(arabicValueNotDepleted()) { arabicRomanPair* pair = arabic_roman_lookup; do { if(lastTableEntryIsLessOrEqualToArabicValue()) { strcat(romanNumeral, pair->roman); arabic_value -= pair->arabic; break; } if(tableEntryExceedsArabicValue()) { strcat(romanNumeral, (pair - 1)->roman); arabic_value -= (pair - 1)->arabic; break; } else if (exactMatchToArabicValue()) { strcat(romanNumeral, pair->roman); arabic_value -= pair->arabic; break; } pair++; } while(arabicValueAndTableEntriesRemain()); } return romanNumeral; }
38.121495
118
0.596225
1a93a45836b8df1fca7065ed06d9139482582af9
1,192
py
Python
day01/main.py
justinjhendrick/advent_of_code_2020
2b9bb15efef26d1c7a211ac2770159f4a12f9658
[ "MIT" ]
null
null
null
day01/main.py
justinjhendrick/advent_of_code_2020
2b9bb15efef26d1c7a211ac2770159f4a12f9658
[ "MIT" ]
null
null
null
day01/main.py
justinjhendrick/advent_of_code_2020
2b9bb15efef26d1c7a211ac2770159f4a12f9658
[ "MIT" ]
null
null
null
import sys ''' https://adventofcode.com/2020/day/1 ''' def parse(args): input_nums = [] with open(args[1], mode='r') as f: for line in f.readlines(): input_nums.append(int(line.strip())) return input_nums def find2(input_nums, target): ''' Find 2 numbers (assumed positive ints) in input_nums that sum to target. Return their product ''' search_for = set() for v in input_nums: if v > target: continue if v in search_for: return (target - v) * v search_for.add(target - v) return None def find3(input_nums, target): ''' Find 3 numbers (assumed positive ints) in input_nums that sum to target. Return their product ''' for v in input_nums: if v > target: continue result = find2(input_nums, target - v) if result is not None: return v * result return None def main(args): input_nums = parse(args) print("part one: {}".format(find2(input_nums, 2020))) print("part two: {}".format(find3(input_nums, 2020))) # part one: 842016 # part two: 9199664 if __name__ == '__main__': main(sys.argv)
23.372549
97
0.594799
43e43e62ab407e10af3b1f667854a55023307b15
1,570
ts
TypeScript
unit-test/dal/git/GetLastCompatibleMergeBaseRev.test.ts
jeffb4/teamcity-vscode-extension
029d3babdfe81464cc0295a687305532186dc7da
[ "MIT" ]
29
2017-09-21T07:20:48.000Z
2021-11-08T09:50:14.000Z
unit-test/dal/git/GetLastCompatibleMergeBaseRev.test.ts
jeffb4/teamcity-vscode-extension
029d3babdfe81464cc0295a687305532186dc7da
[ "MIT" ]
19
2017-09-18T15:37:58.000Z
2022-02-26T01:28:43.000Z
unit-test/dal/git/GetLastCompatibleMergeBaseRev.test.ts
jeffb4/teamcity-vscode-extension
029d3babdfe81464cc0295a687305532186dc7da
[ "MIT" ]
5
2018-04-02T10:32:18.000Z
2022-03-18T20:01:00.000Z
import "reflect-metadata"; const rmock = require("mock-require"); rmock("vscode", { }); import {anyString, instance, mock, when} from "ts-mockito"; import {CpProxy} from "../../../src/bll/moduleproxies/cp-proxy"; import * as assert from "assert"; import {GetLastCompatibleMergeBaseRev} from "../../../src/dal/git/GetLastCompatibleMergeBaseRev"; import {GetRemoteBranchName} from "../../../src/dal/git/GetRemoteBranchName"; suite("GetLastCompatibleMergeBaseRev", () => { const workSpaceRootPath = "myWorkSpaceRootPath"; const gitPath = "myGitPath"; let cpMock: CpProxy; let cpSpy: CpProxy; let theCommand: GetLastCompatibleMergeBaseRev; function reinitMocks() { cpMock = mock(CpProxy); cpSpy = instance(cpMock); const getRemoteBranchNameMock: GetRemoteBranchName = mock(GetRemoteBranchName); const getRemoteBranchNameSpy = instance(getRemoteBranchNameMock); theCommand = new GetLastCompatibleMergeBaseRev(workSpaceRootPath, gitPath, cpSpy, getRemoteBranchNameSpy); } test("should verify simple example", function (done) { reinitMocks(); const testResult = {stdout: "7fedeef81835e6ba6388d68ecbe31ece16437402", stderr: ""}; const expectedRev = "7fedeef81835e6ba6388d68ecbe31ece16437402"; when(cpMock.execAsync(anyString())).thenReturn(Promise.resolve(testResult)); theCommand.execute().then((result: string) => { assert.equal(result, expectedRev); done(); }).catch((err) => { done(err); }); }); });
38.292683
114
0.679618
df9ba3f299359373e73ffa779fbb2b8141f589f8
353
cs
C#
src/Mynt.Core/Models/Ticker.cs
taned-singlow/bottrade
54161e930ef0f123ca8d39cd3ecb4239ff3332f9
[ "BSD-3-Clause" ]
217
2017-11-02T12:41:52.000Z
2022-03-28T02:32:14.000Z
src/Mynt.Core/Models/Ticker.cs
taned-singlow/bottrade
54161e930ef0f123ca8d39cd3ecb4239ff3332f9
[ "BSD-3-Clause" ]
44
2017-12-05T20:26:08.000Z
2021-11-22T01:46:49.000Z
src/Mynt.Core/Models/Ticker.cs
taned-singlow/bottrade
54161e930ef0f123ca8d39cd3ecb4239ff3332f9
[ "BSD-3-Clause" ]
158
2017-11-13T07:24:27.000Z
2022-03-28T13:38:48.000Z
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mynt.Core.Models { public class Ticker { public decimal Bid { get; set; } public decimal Ask { get; set; } public decimal Last { get; set; } public decimal Volume { get; set; } } }
20.764706
43
0.643059
ffaabc239febf12908dd889da7a615b393e490c9
135
py
Python
contests/atcoder/abc065/a.py
conao3/coder
2cdb610fec013da88a3470d460108e8a9b462445
[ "CC0-1.0" ]
null
null
null
contests/atcoder/abc065/a.py
conao3/coder
2cdb610fec013da88a3470d460108e8a9b462445
[ "CC0-1.0" ]
null
null
null
contests/atcoder/abc065/a.py
conao3/coder
2cdb610fec013da88a3470d460108e8a9b462445
[ "CC0-1.0" ]
null
null
null
x, a, b = map(int, input().split()) if b <= a: print('delicious') elif b - a <= x: print('safe') else: print('dangerous')
15
35
0.525926
b0355df4d0557ea6b1c0005b55eca16851ac4de6
2,592
py
Python
app/upload_service.py
LowerSilesians/geo-geschenk
aee75d9a3d5fc6653a5c918530ab3ddfa0723926
[ "MIT" ]
1
2016-03-11T12:33:47.000Z
2016-03-11T12:33:47.000Z
app/upload_service.py
LowerSilesians/geo-geschenk
aee75d9a3d5fc6653a5c918530ab3ddfa0723926
[ "MIT" ]
null
null
null
app/upload_service.py
LowerSilesians/geo-geschenk
aee75d9a3d5fc6653a5c918530ab3ddfa0723926
[ "MIT" ]
null
null
null
from geosquizzy.squizzy import GeoSquizzy from pymongo import MongoClient import json from utils import get_data class UploadService: def __init__(self, request=None, session=None, url=None): self.data = self.__get__file(request=request, url=url) self.file_raw = self.__read__data__(data=self.data) self.file = self.__decode_file__(file=self.file_raw) self.mongo = MongoDBService(port=27017, url='localhost', db='test') self.mongo.save_doc(name=session, doc=self.file) self.geojson = GeoJSONService(geojson_doc_type="FeatureCollection", data=self.file) @staticmethod def __get__file(**kwargs): file = kwargs.get('request', None) if file is not None: return kwargs['request'].files['file'] else: return get_data(url=kwargs['url']) @staticmethod def __read__data__(data=None): return data.read() @staticmethod def __decode_file__(file=None): return file.decode('utf-8') def response(self): return self.geojson.get_data() class GeoJSONService: def __init__(self, geojson_doc_type=None, data=None): self.geo_squizzy = GeoSquizzy(geojson_doc_type=geojson_doc_type) self.geo_squizzy.geo_structure.start(geojson=data, is_doc=True) @staticmethod def __update_mongo__(key=None): key['keys'] = [x for x in key['keys'] if x != 'features'] return key def get_data(self): # we have to adjust keys to mongoDB features query return [self.__update_mongo__(key=x) for x in self.geo_squizzy.geo_structure.tree.get_all_leafs_paths()] class MongoDBService: def __init__(self, port=None, url=None, db=None, collection=None): self.client = MongoClient(url, port) self.db = self.client[db] if not (collection is None): self.collection = self.db[collection] def create_collection(self, name=None): return self.db[name] def convert_into_object(self, string=None): return json.loads(string) def make_search_query(self, query=None): query = {str.join('.', x['keys'][::-1]): x.get('search') for x in query if x.get('search', None) is not None} return self.__search__(query=query) def save_doc(self, name=None, doc=None): collection = self.create_collection(name=name) mongo_data = self.convert_into_object(string=doc) [collection.insert_one(x) for x in mongo_data['features']] def __search__(self, query=None): res = self.collection.find(query) return res
34.56
117
0.668981
6d6b069b4f58610fb40984ce75102a2e4b087c9c
1,647
tsx
TypeScript
client/src/App.tsx
saswatamcode/graphQLChat
9b5779a4e5ccf4d5d83d7aa8549904e2ea239ba0
[ "MIT" ]
7
2021-03-03T18:26:30.000Z
2022-03-25T09:47:17.000Z
client/src/App.tsx
saswatamcode/graphQLChat
9b5779a4e5ccf4d5d83d7aa8549904e2ea239ba0
[ "MIT" ]
null
null
null
client/src/App.tsx
saswatamcode/graphQLChat
9b5779a4e5ccf4d5d83d7aa8549904e2ea239ba0
[ "MIT" ]
null
null
null
import { ApolloClient, InMemoryCache } from "@apollo/client"; import { ApolloProvider } from "@apollo/client"; import { WebSocketLink } from "@apollo/client/link/ws"; import { split, HttpLink } from "@apollo/client"; import { getMainDefinition } from "@apollo/client/utilities"; import Chats from "./Chats"; import SendMessage from "./SendMessage"; import { useState } from "react"; const wsLink = new WebSocketLink({ uri: "ws://localhost:9000/subscriptions", options: { reconnect: true, }, }); const httpLink = new HttpLink({ uri: "http://localhost:9000/graphql", credentials: "include", }); const link = split( ({ query }) => { const definition = getMainDefinition(query); return ( definition.kind === "OperationDefinition" && definition.operation === "subscription" ); }, wsLink, httpLink ); const client = new ApolloClient({ link, cache: new InMemoryCache(), }); const App = () => { const [name, setName] = useState<string>(""); const [entered, setEntered] = useState<boolean>(false); return ( <ApolloProvider client={client}> <div className="App"> {!entered && ( <div> <input type="text" id="name" value={name} onChange={(e) => setName(e.target.value)} ></input> <button onClick={() => setEntered(true)}>Enter chat</button> </div> )} {name !== "" && entered && ( <div> <Chats /> <SendMessage name={name} /> </div> )} </div> </ApolloProvider> ); }; export default App;
23.528571
72
0.568913
69d28d5af8f9bfe414eb608612edf13cf6bc4aea
9,680
lua
Lua
Languages/Portuguese.lua
scotty007/trAInsported
e0ed49e73ffd447ba1024c8f08bcc0fb24bf3cdb
[ "WTFPL" ]
101
2015-01-06T17:26:45.000Z
2022-02-10T15:17:34.000Z
Languages/Portuguese.lua
scotty007/trAInsported
e0ed49e73ffd447ba1024c8f08bcc0fb24bf3cdb
[ "WTFPL" ]
32
2015-01-03T10:54:49.000Z
2021-08-31T12:48:37.000Z
Languages/Portuguese.lua
scotty007/trAInsported
e0ed49e73ffd447ba1024c8f08bcc0fb24bf3cdb
[ "WTFPL" ]
35
2015-02-21T10:19:56.000Z
2022-02-09T21:36:23.000Z
-- Language file for trAInsported. Make a copy of this to translate into your own language. -- Please don't change the order of the entries in this file. LNG.menu_mode_name = {} LNG.menu_mode_tooltip = {} LNG.menu_time_name = {} LNG.menu_time_tooltip = {} LNG.menu_region_name = {} LNG.menu_region_tooltip = {} LNG.load_generation = {} ------------------------------------------------- -- Menu: ------------------------------------------------- LNG.menu_live = [[Ao vivo]] LNG.menu_live_tooltip = [[Assista partidas online ao vivo!]] LNG.menu_tutorial = [[Tutoriais]] LNG.menu_tutorial_tooltip = [[Conheça o jogo!]] LNG.menu_challenge = [[Desafios]] LNG.menu_challenge_tooltip = [[Complete os mapas de desafio! Obtenha mais mapas online no website do jogo.]] LNG.menu_compete = [[Competir]] LNG.menu_compete_tooltip = [[Configure um jogo de teste para seu AI]] LNG.menu_random = [[Aleatório]] LNG.menu_random_tooltip = [[Inicie um jogo aleatório em um mapa aleatório usando AIs aleatórias de sua pasta 'AI']] LNG.menu_settings = [[Configurações]] LNG.menu_settings_tooltip = [[Mudar o idioma, resolução etc.]] LNG.menu_exit = [[Sair]] LNG.menu_return = [[Voltar]] LNG.menu_return_to_main_menu_tooltip = [[Volte ao menu principal]] LNG.menu_choose_ai = [[Escolhas as AIs para a partida:]] LNG.menu_choose_ai_tooltip = [[Selcionar esta AI para a partida?]] LNG.menu_choose_dimensions = [[Largura e Altura:]] LNG.menu_choose_dimensions_tooltip1 = [[Selecionar largura]] LNG.menu_choose_dimensions_tooltip2 = [[Selecionar altura]] LNG.menu_choose_timemode = [[Tempo e modo:]] LNG.menu_time_name[1] = [[Dia]] LNG.menu_time_name[2] = [[Hora do rush]] LNG.menu_time_tooltip[1] = [[Configuração normal, qunatidade média de passageiros]] LNG.menu_time_tooltip[2] = [[Mais VIPs!]] LNG.menu_mode_name[1] = [[Limite de Tempo]] LNG.menu_mode_name[2] = [[Passageiros]] LNG.menu_mode_tooltip[1] = [[Transporte a maior quantidade de passageiros em um determinado período de tempo.]] LNG.menu_mode_tooltip[2] = [[Quantidade fixa de passageiros. Você tem que tentar transportar mais que qualquer outro AI.]] LNG.menu_choose_region = [[Região:]] LNG.menu_region_name[1] = [[Rural]] LNG.menu_region_name[2] = [[Urbana]] LNG.menu_region_tooltip[1] = [[Cenário aldeia pacata.]] LNG.menu_region_tooltip[2] = [[O dobro de passageiros que o cenário rural tem.]] LNG.menu_start = [[Começar]] LNG.menu_start_tooltip = [[Comece a partida com essas configurações]] LNG.menu_main_server = [[Servidor principal]] LNG.menu_main_server_tooltip = [[Conecte-se ao servidor principal. Você deve estar conectado à internet!]] LNG.menu_local_server = [[Servidor local]] LNG.menu_local_server_tooltip = [[Conecte-se a um servidor rodando nesta máquina.]] -- Settings menu: LNG.menu_settings_resolution = [[Tamanho da tela:]] LNG.menu_resolution_tooltip = [[Defina uma nova resolução de tela]] LNG.menu_settings_options = [[Opções:]] LNG.menu_clouds_on = [[Nuvens: On]] LNG.menu_clouds_off = [[Nuvens: Off]] LNG.menu_clouds_on_tooltip = [[Clique para habilitar a renderização das nuvens.]] LNG.menu_clouds_off_tooltip = [[Clique para desabilitar a renderização das nuvens.]] LNG.menu_settings_language = [[Idioma:]] LNG.menu_settings_language_tooltip1 = [[Clique para alterar o idioma do jogo para]] -- before lang name LNG.menu_settings_language_tooltip2 = [[]] -- after lang name -- Menu errors: LNG.menu_err_min_ai = [[Você precisa escolher pelo menos um AI!]] LNG.menu_err_dimensions = [[Dimensões do mapa inválidas!]] LNG.menu_err_mode = [[Modo de jogo inválido!]] LNG.menu_err_time = [[Tempo de jogo inválido!]] LNG.menu_err_resolution = [[Falha ao definir a resolução!]] ------------------------------------------------- -- INGAME: ------------------------------------------------- -- Fast forward message: LNG.fast_forward = [[AVANÇO RÁPIDO PARA ENTRAR NO SERVIDOR]] -------------------------------------------------------------------------------------- LNG.confirm_leave = [[Deixar a partida atual e voltar ao menu?]] LNG.open_folder = [[Abrir Pasta]] LNG.open_folder_tooltip = [[Abre a pasta: AI_FOLDER_DIRECTORY]] -- AI_FOLDER_DIRECTORY will be replaced by the game with the correct directory. LNG.reload = [[Recarregar]] LNG.reload_confirm = [[Recarregar as AIs?]] LNG.reload_tooltip = [[Recarrega os scripts de AI e reinicia o round.]] LNG.disconnect = [[Desconectar]] LNG.end_match = [[Fim da Partida]] LNG.speed_up = [[Acelera a partida]] LNG.slow_down = [[Desacelera a partida]] LNG.pause = [[Pausa a partida]] LNG.by = [[por]] LNG.transported = [[Transportado]] -- the following three strings are for the string "X of Y passengers" LNG.transported1 = [[]] -- before X LNG.transported2 = [[ de ]] -- between X and Y LNG.transported3 = [[ passageiros]] -- after Y LNG.round_ends = [[Round termina em]] LNG.seconds = [[seg]] LNG.minutes = [[min]] LNG.hours = [[h]] LNG.days = [[dias]] LNG.end_of_match = [[A partida acabou!]] LNG.live_match = [[PARTIDA AO VIVO]] LNG.lost_connection = [[CONEXÃO PERDIDA]] ------------------------------------------------- -- LOADING SCREEN: ------------------------------------------------- LNG.load_new_map = [[Novo Mapa]] LNG.load_map_size = [[Tamanho: ]] LNG.load_map_time = [[Tempo: ]] LNG.load_map_mode_time = [[Modo: Tempo do round: ]] LNG.load_map_mode_passengers = [[Modo: Transporte suficiente de passageiros]] LNG.load_generating_map = [[Gerando o mapa]] LNG.load_rendering_map = [[Renderizando o mapa]] LNG.load_connecting = [[Conectando]] LNG.load_failed = [[Falha!]] -- leave ["rails"] etc, just translate the right part of the equal sign: LNG.load_generation["rails"] = [[Trilhos]] LNG.load_generation["houses"] = [[Casas]] LNG.load_generation["hotspots"] = [[Hotspots]] ------------------------------------------------- -- ROUND END STATISTICS: ------------------------------------------------- -- The round statistics here are placed together using these strings as base. Some have versions in plural and in singular forms. If there's no difference in your language, please just copy the one version into both strings - do NOT delete the singular form! -- In these strings, _AINAME_ and _NUMBER_ will be replaced by the appropriate values, so make sure to include them! LNG.stat_most_picked_up_title = [[Hospitalidade]] LNG.stat_most_picked_up = [[AI _AINAME_ pegou _NUMBER_ passageiros.]] LNG.stat_most_picked_up_sing = [[AI _AINAME_ pegou _NUMBER_ passageiros.]] LNG.stat_most_trains_title = [[Fleetus Maximus]] LNG.stat_most_trains = [[AI _AINAME_ possuiu _NUMBER_ trens.]] LNG.stat_most_trains_sing = [[AI _AINAME_ possuiu _NUMBER_ trens]] LNG.stat_most_transported_title = [[Ganhou seu pagamento]] LNG.stat_most_transported = [[AI _AINAME_ trouxe _NUMBER_ passageiros para seus destinos.]] LNG.stat_most_transported_sing = [[AI _AINAME_ trouxe _NUMBER_ passageiro para seu destino.]] LNG.stat_most_normal_transported_title = [[Socialista]] LNG.stat_most_normal_transported = [[AI _AINAME_ trouxe _NUMBER_ passageiros não VIPs para seus destinos.]] LNG.stat_most_normal_transported_sing = [[AI _AINAME_ trouxe _NUMBER_ passageiro não VIP para seu destino.]] LNG.stat_dropped_title = [[Get lost...]] LNG.stat_dropped = [[AI _AINAME_ deixou _NUMBER_ passageiros onde eles não queriam ir.]] LNG.stat_dropped_sing = [[AI _AINAME_ deixou _NUMBER_ passageiro onde ele/ela não queria ir.]] LNG.stat_most_money_title = [[Capitalista]] LNG.stat_most_money = [[AI _AINAME_ ganhou _NUMBER_ créditos.]] -- Some of the following can take up to three arguments: _NUMBER_, _AINAME_ and _TRAINNAME_: LNG.stat_tr_most_picked_up_title = [[Abelhinha ocupada!]] LNG.stat_tr_most_picked_up = [[_TRAINNAME_ [_AINAME_] pegou mais passageiros que qualquer outro trem.]] LNG.stat_tr_most_transported_title = [[Lar doce Lar]] LNG.stat_tr_most_transported = [[_TRAINNAME_ [_AINAME_] trouxe mais passageiros para seus destinos que qualquer outro trem.]] LNG.stat_tr_dropped_title = [[Por que você não anda?]] LNG.stat_tr_dropped = [[_TRAINNAME_ [_AINAME_] deixou _NUMBER_ passageiros no meio do nada!]] LNG.stat_tr_dropped_sing = [[_TRAINNAME_ [_AINAME_] deixou _NUMBER_ passageiro no meio do nada!]] LNG.stat_tr_blocked_title = [[A linha está ocupada...]] LNG.stat_tr_blocked = [[_TRAINNAME_ [_AINAME_] foi bloqueada por um total de _NUMBER_ segundos.]] ------------------------------------------------- -- MESSAGE BOX: ------------------------------------------------- LNG.exit_confirm = [[Tem certeza que quer sair?]] LNG.confirm_resolution = [[Manter esta nova resolução?]] LNG.agree = [[Sim]] LNG.disagree = [[Não]] LNG.cancel = [[Cancelar]] ------------------------------------------------- -- ERRORS: ------------------------------------------------- LNG.err_already_generating_map = [[Um mapa já está sendo gerado! Aguarde o processo terminar...]] LNG.err_wait_for_rendering = [[Aguarde a renderização terminar...]] LNG.err_rendering = [[Algo errado aconteceu em um segmento ao gerar o mapa. Desculpe por isso, por favor, reinicie o jogo e tente novamente.]] LNG.err_already_connecting = [[Tentativa de estabelecer conexão já está em andamento.]] LNG.error_header = [[Oh não, houve um erro!]] LNG.error_steps = [[Se você está atualmente trabalhando em seu próprio mapa de desafio, isso pode ter sido causado pelo seu desafio. Você pode obter ajuda nos fóruns: http://www.indiedb.com/games/trainsported/forum Se isso não foi causado por seu próprio código, você pode relatar o erro na página de issues: https://github.com/Germanunkol/trAInsported/issues Pressione 'c' para copiar a mensagem de erro para o clipboard. Pressione 'o' para abrir a página de issues no GitHub. Pressione 'esc' para fechar. ]] LNG.error_copied = [[Copiado!]]
46.538462
258
0.704545
1f65dd7dcb9e21b94252279a6b7c7890524602ac
736
swift
Swift
Sources/main.swift
iachievedit/MQTTClient
9290d9b3af87620f11c1d65bc3d995de12af3ef0
[ "MIT" ]
3
2016-06-07T11:58:13.000Z
2017-02-10T09:49:52.000Z
Sources/main.swift
iachievedit/MQTTClient
9290d9b3af87620f11c1d65bc3d995de12af3ef0
[ "MIT" ]
null
null
null
Sources/main.swift
iachievedit/MQTTClient
9290d9b3af87620f11c1d65bc3d995de12af3ef0
[ "MIT" ]
null
null
null
// // Copyright 2016 iAchieved.it LLC // // MIT License (https://opensource.org/licenses/MIT) // import swiftlog import Glibc guard Process.arguments.count == 2 else { print("Usage: MQTTClient temperature, where -20 <= temperature <= 50") exit(-1) } let temperature = Process.arguments[1] slogLevel = .Verbose SLogVerbose("Changing temperature on http://test.mosquitto.org/gauge/ to \(temperature)") let client = Client(clientId:"temperature") client.host = "test.mosquitto.org" client.port = 1883 guard client.connect() else { SLogError("Unable to connect to test.mosquitto.org") exit(-1) } let _ = client.publish(topic:"temp/random", withString:temperature) let _ = client.disconnect() select(0, nil, nil, nil, nil)
21.647059
89
0.720109
5ae81461b0fa3ef3e2dc2bff98511a58db22bb43
3,639
cs
C#
src/SKIT.FlurlHttpClient.ByteDance.MicroApp/Extensions/ByteDanceMicroAppClientEventExtensions.cs
lucio-c/DotNetCore.SKIT.FlurlHttpClient.ByteDance
fa3ff5d6b3630c197c25e39b5ab02ee8490ba870
[ "MIT" ]
11
2021-08-24T08:15:45.000Z
2022-03-17T11:57:09.000Z
src/SKIT.FlurlHttpClient.ByteDance.MicroApp/Extensions/ByteDanceMicroAppClientEventExtensions.cs
lucio-c/DotNetCore.SKIT.FlurlHttpClient.ByteDance
fa3ff5d6b3630c197c25e39b5ab02ee8490ba870
[ "MIT" ]
5
2021-12-09T08:28:58.000Z
2022-01-06T02:11:32.000Z
src/SKIT.FlurlHttpClient.ByteDance.MicroApp/Extensions/ByteDanceMicroAppClientEventExtensions.cs
lucio-c/DotNetCore.SKIT.FlurlHttpClient.ByteDance
fa3ff5d6b3630c197c25e39b5ab02ee8490ba870
[ "MIT" ]
8
2021-09-13T13:14:23.000Z
2022-03-19T17:16:54.000Z
using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; namespace SKIT.FlurlHttpClient.ByteDance.MicroApp { /// <summary> /// 为 <see cref="ByteDanceMicroAppClient"/> 提供回调通知事件的扩展方法。 /// </summary> public static class ByteDanceMicroAppClientEventExtensions { public static TEvent DeserializeEventFromJson<TEvent>(this ByteDanceMicroAppClient client, string callbackJson) where TEvent : ByteDanceMicroAppEvent, ByteDanceMicroAppEvent.Serialization.IJsonSerializable { if (client == null) throw new ArgumentNullException(nameof(client)); if (string.IsNullOrEmpty(callbackJson)) throw new ArgumentNullException(callbackJson); try { return client.JsonSerializer.Deserialize<TEvent>(callbackJson); } catch (Exception ex) { throw new Exceptions.ByteDanceMicroAppEventSerializationException("Deserialize event failed. Please see the `InnerException` for more details.", ex); } } public static TEvent DeserializeEventFromXml<TEvent>(this ByteDanceMicroAppClient client, string callbackXml) where TEvent : ByteDanceMicroAppEvent, ByteDanceMicroAppEvent.Serialization.IXmlSerializable { if (client == null) throw new ArgumentNullException(nameof(client)); if (string.IsNullOrEmpty(callbackXml)) throw new ArgumentNullException(callbackXml); try { using var reader = new StringReader(callbackXml); XmlSerializer xmlSerializer = new XmlSerializer(typeof(TEvent), new XmlRootAttribute("xml")); return (TEvent)xmlSerializer.Deserialize(reader)!; } catch (Exception ex) { throw new Exceptions.ByteDanceMicroAppEventSerializationException("Deserialize event failed. Please see the `InnerException` for more details.", ex); } } /// <summary> /// <para>验证回调通知事件签名。</para> /// <para>REF: https://microapp.bytedance.com/docs/zh-CN/mini-app/develop/component/message-push-customer-service </para> /// </summary> /// <param name="client"></param> /// <param name="callbackTimestamp">头条回调通知中的 timestamp 字段。</param> /// <param name="callbackNonce">头条回调通知中的 nonce 字段。</param> /// <param name="callbackMessage">头条回调通知中的 msg 字段。</param> /// <param name="callbackSignature">头条回调通知中的 signature 字段。</param> /// <returns></returns> public static bool VerifyEventSignatureForEcho(this ByteDanceMicroAppClient client, string callbackTimestamp, string callbackNonce, string callbackMessage, string callbackSignature) { if (client == null) throw new ArgumentNullException(nameof(client)); if (callbackTimestamp == null) throw new ArgumentNullException(nameof(callbackTimestamp)); if (callbackNonce == null) throw new ArgumentNullException(nameof(callbackNonce)); if (callbackMessage == null) throw new ArgumentNullException(nameof(callbackMessage)); if (callbackSignature == null) throw new ArgumentNullException(nameof(callbackSignature)); ISet<string> set = new SortedSet<string>(StringComparer.Ordinal) { client.Credentials.PushToken!, callbackTimestamp, callbackNonce, callbackMessage }; string sign = Utilities.SHA1Utility.Hash(string.Concat(set)); return string.Equals(sign, callbackSignature, StringComparison.OrdinalIgnoreCase); } } }
50.541667
189
0.672712
df7a990ab9fcd960057b20f951cce786d9db68d1
1,551
cs
C#
Scoring Report/Scoring/Sections/SectionOther.cs
jyu78749/CyberPatriot-Scoring-Report
9bc56acfcd580d19aa3db4cf3261f0f9d87ff31e
[ "MIT" ]
null
null
null
Scoring Report/Scoring/Sections/SectionOther.cs
jyu78749/CyberPatriot-Scoring-Report
9bc56acfcd580d19aa3db4cf3261f0f9d87ff31e
[ "MIT" ]
null
null
null
Scoring Report/Scoring/Sections/SectionOther.cs
jyu78749/CyberPatriot-Scoring-Report
9bc56acfcd580d19aa3db4cf3261f0f9d87ff31e
[ "MIT" ]
null
null
null
using Scoring_Report.Configuration; using Scoring_Report.Configuration.SecOptions; using System.Collections.Generic; using System.IO; namespace Scoring_Report.Scoring.Sections { public class SectionOther : ISection { public ESectionType Type => ESectionType.Other; public string Header => "Other"; public static RegistryComboBox RemoteDesktopStatus = null; public int MaxScore() { int max = 0; if (RemoteDesktopStatus.IsScored) max++; return max; } public SectionDetails GetScore() { SectionDetails details = new SectionDetails(0, new List<string>(), this); if (RemoteDesktopStatus.IsScored) { object sectionValue = RegistryManager.GetValue(RemoteDesktopStatus.Key, RemoteDesktopStatus.ValueName); if (sectionValue != null) { int value = (int)sectionValue; if (value == RemoteDesktopStatus.SelectedIndex) { details.Points++; details.Output.Add(ConfigurationManager.Translate("RemoteDesktop", RemoteDesktopStatus.SelectedItem)); } } } return details; } public void Load(BinaryReader reader) { // Load remote desktop info RemoteDesktopStatus = new RegistryComboBox(); RemoteDesktopStatus.Parse(reader); } } }
28.2
126
0.56931
643fdc5b03d98a6f42860a5ec2e0f518085f53ae
3,158
py
Python
starcraft/api.py
zzzanderw/SC2-MMR-Tracking
be8f5474e63996beebb0cb6df52903d836c67677
[ "MIT" ]
4
2018-11-24T22:41:55.000Z
2019-05-13T07:14:15.000Z
starcraft/api.py
captainGeech42/SC2-MMR-Tracking
be8f5474e63996beebb0cb6df52903d836c67677
[ "MIT" ]
10
2017-12-03T18:48:12.000Z
2017-12-12T17:52:47.000Z
starcraft/api.py
captainGeech42/SC2-MMR-Tracking
be8f5474e63996beebb0cb6df52903d836c67677
[ "MIT" ]
null
null
null
import requests from exceptions import RequestError from log import Log from .ladder import Ladder from .player import Player class API: @staticmethod def get_current_season_id(params: dict) -> int: r = requests.get("https://us.api.battle.net/data/sc2/season/current", params) if r.status_code != 200: raise RequestError(r, "{} returned error code {}, exiting...".format(r.url, r.status_code)) return r.json()["id"] @staticmethod def get_all_ladders(region_code: str, max_league_id: int, season_id: int, params: dict) -> """List of ladders""": ladders = [] for league_id in range(max_league_id + 1): try: r = requests.get("https://{}.api.battle.net/data/sc2/league/{}/201/0/{}".format(region_code, season_id, league_id), params) if r.status_code != 200: raise RequestError(r, "{} returned error code {}, skipping...".format(r.url, r.status_code)) Log.write_log_message("League {} Status: {}".format(league_id, r.status_code)) json = r.json() for tier in json["tier"]: division = tier["id"] + 1 min_mmr = tier["min_rating"] max_mmr = tier["max_rating"] for ladder in tier["division"]: ladder_id = ladder["ladder_id"] obj = Ladder(region_code, ladder_id, league_id, division, min_mmr, max_mmr) ladders.append(obj) except RequestError as e: Log.write_log_message(e.__str__(), True) return ladders @staticmethod def get_players_in_ladder(region_code: str, ladder: Ladder, params: dict) -> """List of players""": players = [] r = requests.get("https://{}.api.battle.net/data/sc2/ladder/{}".format(region_code, ladder.id), params) if r.status_code != 200: raise RequestError(r, "{} returned error code {}, skipping...".format(r.url, r.status_code)) json = r.json() for player in json["team"]: try: bnet = player["member"][0]["character_link"]["battle_tag"] mmr = player["rating"] games_played = player["member"][0]["played_race_count"][0]["count"] race = player["member"][0]["played_race_count"][0]["race"] found_player = False for p_obj in players: if p_obj.battletag == bnet: p_obj.add_race(race, ladder.league_id, ladder.division, games_played, mmr) found_player = True if not found_player: obj = Player(bnet, region_code) # ladder.division + 1 is due to API having d1 be 0, d2 be 1, etc. obj.add_race(race, ladder.league_id, ladder.division, games_played, mmr) players.append(obj) except KeyError: continue return players
47.134328
119
0.537999
3f5305de5c2210ba28a149e33561b4b328903d47
2,374
php
PHP
application/consoleboard/controller/Configmag_function.php
tyutjohn/QzxyWebsite
2efda16fb482ca6ea149bd0cf78a00d609d9dde2
[ "Apache-2.0" ]
null
null
null
application/consoleboard/controller/Configmag_function.php
tyutjohn/QzxyWebsite
2efda16fb482ca6ea149bd0cf78a00d609d9dde2
[ "Apache-2.0" ]
null
null
null
application/consoleboard/controller/Configmag_function.php
tyutjohn/QzxyWebsite
2efda16fb482ca6ea149bd0cf78a00d609d9dde2
[ "Apache-2.0" ]
1
2019-12-03T10:23:33.000Z
2019-12-03T10:23:33.000Z
<?php /** * [Starsriver] (C)2014-2099. * This is NOT a freeware, follows Apache2.0 licence * * Author: 张宇 * Email: starsriver@yahoo.com * CreateDate: 2018-03-24 * */ namespace app\consoleboard\controller; use think\Controller; use app\Qhelp; use think\Db; class Configmag_function extends Controller{ static function saveconf($data){ $name = htmlspecialchars(Qhelp::dss($data['name']),ENT_QUOTES); $rd = Db::query("select * from qzlit_config where `name` ='".$name."'"); if (empty($rd)) { return Qhelp::json_en(['Stat' => 'error', 'Message' => '数据无法映射,请刷新页面重试']); } if ($rd[0]['issolid']) { return Qhelp::json_en(['Stat' => 'error', 'Message' => '系统变量不可修改']); } if ($rd[0]['data'] == htmlspecialchars($data['data'],ENT_QUOTES)) { return 0; } if (in_array($rd[0]['data'], ['on', 'off']) && !in_array($data['data'], ['on', 'off'])) { return Qhelp::json_en(['Stat' => 'error', 'Message' => '数据类型映射错误,请刷新页面重试']); } Db::execute("update qzlit_config set `data` = '".htmlspecialchars(Qhelp::dss($data['data']),ENT_QUOTES)."' where `name`='".$name."'"); return Qhelp::json_en([ 'Stat' => 'OK', 'Message' => '已将 <b>"'.$name.'"</b> 设置为 <b>"'.htmlspecialchars($data['data'],ENT_QUOTES).'</b>"' ]); } static function resetconf($data){ $name = htmlspecialchars(Qhelp::dss($data['name']),ENT_QUOTES); $rd = Db::query("select * from qzlit_config where `name` ='".$name."'"); if (empty($rd)) { return Qhelp::json_en(['Stat' => 'error', 'Message' => '数据无法映射,请刷新页面重试']); } if ($rd[0]['issolid']) { return Qhelp::json_en(['Stat' => 'error', 'Message' => '固定变量不可修改']); } Db::execute("update qzlit_config set `data` = '".Qhelp::dss($rd[0]['df'])."' where `name` ='".$name."'"); return Qhelp::json_en([ 'Stat' => 'OK', 'Message' => $name.' 》 值已恢复默认', 'Data' => htmlspecialchars_decode($rd[0]['df']), ]); } }
38.918033
147
0.471356
e260da34f49612b9b5adcae02024d770834cf3d5
3,417
py
Python
test/from_bytes_c.py
patrick-nicholson/cyavro
a5c4db363f6514ddd011660565f6b6b79a0067c4
[ "BSD-3-Clause" ]
13
2015-12-02T20:26:37.000Z
2016-11-01T20:34:05.000Z
test/from_bytes_c.py
patrick-nicholson/cyavro
a5c4db363f6514ddd011660565f6b6b79a0067c4
[ "BSD-3-Clause" ]
11
2015-12-02T20:39:36.000Z
2016-10-11T23:40:59.000Z
test/from_bytes_c.py
MaxPoint/cyavro
a5c4db363f6514ddd011660565f6b6b79a0067c4
[ "BSD-3-Clause" ]
8
2015-12-08T17:31:11.000Z
2016-09-14T22:08:51.000Z
# Copyright (c) 2015 MaxPoint Interactive, Inc. # # 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 copyright holder nor the names of its contributors may be used to endorse or promote # products derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Tests the `reader_from_bytes_c` cython exposed function """ import io import os import tempfile import numpy as np import pandas as pd import pandas.util.testing as pdt import cyavro import pyximport pyximport.install() from cyavro import test_utils avroschema = """ {"type": "record", "name": "from_bytes_test", "fields":[ {"name": "id", "type": "int"}, {"name": "name", "type": "string"} ] } """ def prepare_file(fpath): tmpdir = tempfile.gettempdir() fpath = os.path.join(fpath) writer = cyavro.AvroWriter(fpath, 'null', avroschema) ids = np.random.randint(100, size=10) ids = np.arange(10) names = pdt.rands_array(10, 10) df_write = pd.DataFrame({"id": ids, "name": names}) df_write = cyavro.prepare_pandas_df_for_write(df_write, avroschema, copy=False) writer.write(df_write) writer.close() return df_write, fpath def test_from_bytes(): df_write, fpath = prepare_file('from_bytes_data.avro') reader = test_utils.get_reader(fpath) reader.init_buffers() df_read = pd.DataFrame(reader.read_chunk()) pdt.assert_frame_equal(df_write, df_read) reader.close() def test_from_bytes_python(): df_write, fpath = prepare_file('from_bytes_data_py.avro') with open(fpath, 'rb') as fo: data = fo.read() reader = cyavro.AvroReader() reader.init_bytes(data) reader.init_reader() reader.init_buffers() df_read = pd.DataFrame(reader.read_chunk()) pdt.assert_frame_equal(df_write, df_read) reader.close() def test_from_byesio(): df_write, fpath = prepare_file('from_bytes_data_py.avro') with open(fpath, 'rb') as fo: data = fo.read() bytesIO = io.BytesIO(data) df_read = cyavro.read_avro_bytesio_as_dataframe(bytesIO) pdt.assert_frame_equal(df_write, df_read)
32.542857
120
0.72432
2832a1504ba4ec5b9393351d6888a57b639357d5
1,451
lua
Lua
test/functional/lua/ffi_spec.lua
fgclue/dke
b6bdb12d4499e98355af112bc15fd4c6a11bf29b
[ "Vim" ]
null
null
null
test/functional/lua/ffi_spec.lua
fgclue/dke
b6bdb12d4499e98355af112bc15fd4c6a11bf29b
[ "Vim" ]
null
null
null
test/functional/lua/ffi_spec.lua
fgclue/dke
b6bdb12d4499e98355af112bc15fd4c6a11bf29b
[ "Vim" ]
null
null
null
local helpers = require('test.functional.helpers')(after_each) local eq = helpers.eq local exec_lua = helpers.exec_lua local clear = helpers.clear before_each(clear) describe('ffi.cdef', function() it('can use dke core functions', function() if not exec_lua("return pcall(require, 'ffi')") then pending('missing LuaJIT FFI') end eq(12, exec_lua[[ local ffi = require('ffi') ffi.cdef('int curwin_col_off(void);') vim.cmd('set number numberwidth=4 signcolumn=yes:4') return ffi.C.curwin_col_off() ]]) eq(20, exec_lua[=[ local ffi = require('ffi') ffi.cdef[[ typedef unsigned char char_u; typedef struct window_S win_T; typedef struct {} stl_hlrec_t; typedef struct {} StlClickRecord; typedef struct {} Error; win_T *find_window_by_handle(int Window, Error *err); int build_stl_str_hl( win_T *wp, char_u *out, size_t outlen, char_u *fmt, int use_sandbox, char_u fillchar, int maxwidth, stl_hlrec_t **hltab, StlClickRecord **tabtab ); ]] return ffi.C.build_stl_str_hl( ffi.C.find_window_by_handle(0, ffi.new('Error')), ffi.new('char_u[1024]'), 1024, ffi.cast('char_u*', 'StatusLineOfLength20'), 0, 0, 0, nil, nil ) ]=]) end) end)
23.031746
62
0.576154
1698a6bddf658115df9fbe6fc828206bea01a3fe
3,511
lua
Lua
test-common.lua
zerebubuth/ClearTables
2ad941d226cfb441aebaa7a40514dd469f51d77a
[ "MIT" ]
25
2016-07-08T05:44:54.000Z
2019-10-11T21:14:05.000Z
test-common.lua
zerebubuth/ClearTables
2ad941d226cfb441aebaa7a40514dd469f51d77a
[ "MIT" ]
62
2016-07-08T08:05:41.000Z
2018-04-14T11:12:04.000Z
test-common.lua
zerebubuth/ClearTables
2ad941d226cfb441aebaa7a40514dd469f51d77a
[ "MIT" ]
7
2016-09-28T15:19:47.000Z
2019-10-11T11:14:27.000Z
--[[ This file is part of ClearTables @author Paul Norman <penorman@mac.com> @copyright 2015-2016 Paul Norman, MIT license ]]-- require ("common") print("common.lua tests") print("TESTING: oneway") assert(oneway(nil) == nil, "test failed: oneway(nil) == nil") assert(oneway('-1') == 'reverse', "test failed: oneway('-1') == 'reverse'") assert(oneway('no') == 'false', "test failed: oneway('no') == 'false'") assert(oneway('false') == 'false', "test failed: oneway('false') == 'false'") assert(oneway('yes') == 'true', "test failed: oneway('yes') == 'true'") assert(oneway('foo') == 'true', "test failed: oneway('foo') == 'true'") print("TESTING: layer") assert(layer(nil) == "0", "test failed: nil") assert(layer("0") == "0", "test failed: 0") assert(layer("-1") == "-1", "test failed: -1") assert(layer("1") == "1", "test failed: 1") assert(layer("1.5") == "0", "test failed: 1.5") assert(layer("foo") == "0", "test failed: text") assert(layer("f1") == "0", "test failed: char num") assert(layer("1f") == "0", "test failed: num char") print("TESTING: access") assert(access(nil) == nil, "test failed: nil") assert(access("foo") == nil, "test failed: unknown") assert(access("yes") == "yes", "test failed: yes") assert(access("private") == "no", "test failed: private") assert(access("no") == "no", "test failed: no") assert(access("permissive") == "yes", "test failed: permissive") assert(access("delivery") == "partial", "test failed: delivery") assert(access("designated") == "yes", "test failed: designated") assert(access("destination") == "partial", "test failed: destination") assert(access("customers") == "partial", "test failed: customers") print("TESTING: height") assert(height(nil) == nil, "test failed: nil") assert(height("foo") == nil, "test failed: unknown") assert(height("5") == "5", "test failed: 1 digit") assert(height("56") == "56", "test failed: multi-digit") assert(height("5.6") == "5.6", "test failed: decimal") assert(height("5e6") == nil, "test failed: number with text") assert(height("10000000000") == nil, "test failed: overflow") print("TESTING: names") assert(names(nil) == nil, "test failed: nil") assert(names({}) == nil, "test failed: empty") assert(names({foo="bar"}) == nil, "test failed: non-names") assert(names({["name:foo"]="bar"}) == '"foo"=>"bar"', "test failed: one lang") local name1 = names({["name:aa"]="foo", ["name:zz"]="bar"}) assert(name1 == '"aa"=>"foo","zz"=>"bar"' or name1 == '"zz"=>"bar","aa"=>"foo"', "test failed: two langs") -- Language filtering assert(names({["name:foo:baz"]="bar"}) == nil, "test failed: one filtered lang with :") assert(names({["name:foo1"]="bar"}) == nil, "test failed: one filtered lang with number") assert(names({["name:prefix"]="bar"}) == nil, "test failed: one filtered lang with prefix") assert(names({["name:genitive"]="bar"}) == nil, "test failed: one filtered lang with genitive") assert(names({["name:etymology"]="bar"}) == nil, "test failed: one filtered lang with etymology") assert(names({["name:botanical"]="bar"}) == nil, "test failed: one filtered lang with botanical") assert(names({["name:left"]="bar"}) == nil, "test failed: one filtered lang with left") assert(names({["name:right"]="bar"}) == nil, "test failed: one filtered lang with right") assert(names({["name:foo"]="bar", ["name:foo1"]="baz"}) == '"foo"=>"bar"', "test failed: one filtered lang with non-filtered")
51.632353
126
0.614925
f0530eef4f6cf266448e9986f142d03e3219ab0c
35,598
lua
Lua
Util/Util.lua
deepstay/PersoLootRoll
be3b91422fad75822f3e8f69fbec5345fa5f090d
[ "MIT" ]
null
null
null
Util/Util.lua
deepstay/PersoLootRoll
be3b91422fad75822f3e8f69fbec5345fa5f090d
[ "MIT" ]
null
null
null
Util/Util.lua
deepstay/PersoLootRoll
be3b91422fad75822f3e8f69fbec5345fa5f090d
[ "MIT" ]
null
null
null
local Name, Addon = ... local Unit = Addon.Unit local Self = Addon.Util ------------------------------------------------------- -- WoW -- ------------------------------------------------------- -- More than this much percent of players in the group must be from -- one guild/community for it to be considered a guild/community group Self.GROUP_THRESHOLD = 0.50 -- Interaction distances Self.INTERACT_INSPECT = 1 -- 28 yards Self.INTERACT_TRADE = 2 -- 11.11 yards Self.INTERACT_DUEL = 3 -- 9.9 yards Self.INTERACT_FOLLOW = 4 -- 28 yards -- Expansions Self.EXP_CLASSIC = 1 Self.EXP_BC = 2 Self.EXP_WOTLK = 3 Self.EXP_CATA = 4 Self.EXP_MOP = 5 Self.EXP_WOD = 6 Self.EXP_LEGION = 7 Self.EXP_BFA = 8 Self.EXP_NEXT = 9 Self.EXP_LEVELS = {60, 70, 80, 85, 90, 100, 110, 120, 130, 140} -- Check if the current group is a guild group function Self.IsGuildGroup(guild) if not IsInGroup() or guild == "" then return false end local n, guilds = GetNumGroupMembers(), Self.Tbl() for i=1,n do local g = Unit.GuildName(GetRaidRosterInfo(i)) if g then guilds[g] = (guilds[g] or 0) + 1 if (not guild or g == guild) and guilds[g] / n > Self.GROUP_THRESHOLD then Self.TblRelease(guilds) return g end end end Self.TblRelease(guilds) end -- Check if the current group is a community group function Self.IsCommunityGroup(commId) if not IsInGroup() or not Self.TblFirstWhere(C_Club.GetSubscribedClubs(), "clubType", Enum.ClubType.Character, "clubId", commId) then return false end local n, comms = GetNumGroupMembers(), Self.Tbl() for i=1,n do local c = Unit.CommonClubs(GetRaidRosterInfo(i)) for _,clubId in pairs(c) do comms[clubId] = (comms[clubId] or 0) + 1 if (not commId or commId == clubId) and comms[clubId] / n >= Self.GROUP_THRESHOLD then Self.TblRelease(comms, c) return clubId end end Self.TblRelease(c) end Self.TblRelease(comms) end -- Get a list of guild ranks function Self.GetGuildRanks() local t, i, name = Self.Tbl(), 1, GuildControlGetRankName(1) while not Self.StrIsEmpty(name) do t[i] = name i, name = i + 1, GuildControlGetRankName(i + 1) end return t end function Self.GetClubRanks(clubId) local info = C_Club.GetClubInfo(clubId) if not info then return elseif info.clubType == Enum.ClubType.Guild then return Self.GetGuildRanks() else return Self.TblFlip(Enum.ClubRoleIdentifier) end end -- Get the expansion for the current instance function Self.GetInstanceExp() if IsInInstance() then local mapID = C_Map.GetBestMapForUnit("player") return mapID and Self.INSTANCES[EJ_GetInstanceForMap(mapID)] or nil end end -- Check if the legacy loot mode is active function Self.IsLegacyLoot() if IsInInstance() and GetLootMethod() == "personalloot" then local iExp = Self.GetInstanceExp() local pExp = Self.TblFindFn(Self.EXP_LEVELS, function (v) return v >= UnitLevel("player") end, true) return iExp and pExp and iExp < pExp - 1 end end -- Check if currently in a timewalking dungeon function Self.IsTimewalking() return Self.In(select(3, GetInstanceInfo()), 24, 33) end function Self.GetNumDroppedItems() local difficulty, _, maxPlayers = select(3, GetInstanceInfo()) if difficulty == DIFFICULTY_DUNGEON_CHALLENGE then -- In M+ we get 2 items at the end of the dungeon, +1 if in time, +0.4 per keystone level above 15 local _, level, _, onTime = C_ChallengeMode.GetCompletionInfo(); return 2 + (onTime and 1 or 0) + (level > 15 and math.ceil(0.4 * (level - 15)) or 0) else -- Normally we get about 1 item per 5 players in the group local players = GetNumGroupMembers() if Self.IsLegacyLoot() then players = Self.In(difficulty, DIFFICULTY_RAID_LFR, DIFFICULTY_PRIMARYRAID_LFR, DIFFICULTY_PRIMARYRAID_NORMAL, DIFFICULTY_PRIMARYRAID_HEROIC) and 20 or maxPlayers end return math.ceil(players / 5) end end -- Get hidden tooltip for scanning function Self.GetHiddenTooltip() if not Self.hiddenTooltip then Self.hiddenTooltip = CreateFrame("GameTooltip", Addon.ABBR .. "_HiddenTooltip", nil, "GameTooltipTemplate") Self.hiddenTooltip:SetOwner(UIParent, "ANCHOR_NONE") end return Self.hiddenTooltip end -- Fill a tooltip and scan it line by line function Self.ScanTooltip(fn, linkOrbag, slot, ...) local tooltip = Self.GetHiddenTooltip() tooltip:ClearLines() if not slot then tooltip:SetHyperlink(linkOrbag) else tooltip:SetBagItem(linkOrbag, slot) end local lines = tooltip:NumLines() for i=2, lines do local line = _G[Addon.ABBR .."_HiddenTooltipTextLeft" .. i]:GetText() if line then local a, b, c = fn(i, line, lines, ...) if a ~= nil then return a, b, c end end end end -- Get the correct bag position, if it exists (e.g. 1, 31 -> 2, 1) function Self.GetBagPosition(bag, slot) local numSlots = GetContainerNumSlots(bag) if bag < 0 or bag > NUM_BAG_SLOTS or not numSlots or numSlots == 0 then return nil, nil elseif slot > numSlots then return Self.GetBagPosition(bag + 1, slot - numSlots) else return bag, slot end end ------------------------------------------------------- -- General -- ------------------------------------------------------- -- Check if two values are equal function Self.Equals(a, b) return a == b end -- Compare two values, returns -1 for a < b, 0 for a == b and 1 for a > b function Self.Compare(a, b) return a == b and 0 or a == nil and 1 or b == nil and -1 or a > b and 1 or -1 end -- Create an iterator function Self.Iter(from, to, step) local i = from or 0 return function (steps, reset) i = (reset and (from or 0) or i) + (step or 1) * (steps or 1) return (not to or i <= to) and i or nil end end -- Return val if it's not nil, default otherwise function Self.Default(val, default) if val ~= nil then return val else return default end end -- Return a when cond is true, b otherwise function Self.Check(cond, a, b) if cond then return a else return b end end -- Iterate tables or parameter lists local Fn = function (t, i) i = (i or 0) + 1 if i > #t then Self.TblReleaseTmp(t) else local v = t[i] return i, Self.Check(v == Self.TBL_EMPTY, nil, v) end end function Self.Each(...) if ... and type(...) == "table" then return next, ... elseif select("#", ...) == 0 then return Self.FnNoop else return Fn, Self.TblTmp(...) end end function Self.IEach(...) if ... and type(...) == "table" then return Fn, ... else return Self.Each(...) end end -- Shortcut for val == x or val == y or ... function Self.In(val, ...) for i,v in Self.Each(...) do if v == val then return true end end return false end -- Shortcut for val == a and b or val == c and d or ... function Self.Select(val, ...) local n = select("#", ...) for i=1, n - n % 2, 2 do local a, b = select(i, ...) if val == a then return b end end if n % 2 == 1 then return select(n, ...) end end ------------------------------------------------------- -- Table -- ------------------------------------------------------- -- Create a table that tracks the highest numerical index and offers count+newIndex fields and Add function function Self.TblCounter(t) t = t or {} local count = 0 setmetatable(t, { __index = function (t, k) return k == "count" and count or k == "nextIndex" and count+1 or k == "Add" and function (v) t[count+1] = v return count end or rawget(t, k) end, __newindex = function (t, k, v) if v ~= nil and type(k) == "number" and k > count then count = k end rawset(t, k, v) end }) return t end -- REUSABLE TABLES: Store unused tables in a cache to reuse them later -- A cache for temp tables Self.tblPool = {} Self.tblPoolSize = 10 -- For when we need an empty table as noop or special marking Self.TBL_EMPTY = {} -- Get a table (newly created or from the cache), and fill it with values function Self.Tbl(...) local t = tremove(Self.tblPool) or {} for i=1, select("#", ...) do t[i] = select(i, ...) end return t end -- Get a table (newly created or from the cache), and fill it with key/value pairs function Self.TblHash(...) local t = tremove(Self.tblPool) or {} for i=1, select("#", ...), 2 do t[select(i, ...)] = select(i + 1, ...) end return t end -- Add one or more tables to the cache, first parameter can define a recursive depth function Self.TblRelease(...) local depth = type(...) ~= "table" and (type(...) == "number" and max(0, (...)) or ... and Self.tblPoolSize) or 0 for i=1, select("#", ...) do local t = select(i, ...) if type(t) == "table" and t ~= Self.TBL_EMPTY then if #Self.tblPool < Self.tblPoolSize then tinsert(Self.tblPool, t) if depth > 0 then for _,v in pairs(t) do if type(v) == "table" then Self.TblRelease(depth - 1, v) end end end wipe(t) setmetatable(t, nil) else break end end end end -- TEMPORARY TABLES: Tables that are automatically released after certain operations (such as loops) function Self.TblTmp(...) local t = tremove(Self.tblPool) or {} for i=1, select("#", ...) do local v = select(i, ...) t[i] = v == nil and Self.TBL_EMPTY or v end return setmetatable(t, Self.TBL_EMPTY) end function Self.TblHashTmp(...) return setmetatable(Self.TblHash(...), Self.TBL_EMPTY) end function Self.TblIsTmp(t) return getmetatable(t) == Self.TBL_EMPTY end function Self.TblReleaseTmp(...) for i=1, select("#", ...) do local t = select(i, ...) if type(t) == "table" and Self.TblIsTmp(t) then Self.TblRelease(t) end end end -- GET/SET -- Get a value from a table function Self.TblGet(t, ...) local n = select("#", ...) if n == 1 then if type(...) == "table" then return Self.TblGet(t, unpack(...)) elseif type(...) == "string" and (...):find("%.") then return Self.TblGet(t, ("."):split(...)) end end for i=1,n do if t ~= nil then t = t[select(i, ...)] end end return t end -- Set a value on a table function Self.TblSet(t, ...) local n = select("#", ...) - 1 local val = select(n + 1, ...) if n == 1 then if type(...) == "table" then return Self.TblSet(t, unpack((...)), val) elseif type(...) == "string" and (...):find("%.") then return Self.TblSet(t, ("."):split((...)), val) end end local u = t for i=1,n do local k = select(i, ...) if i == n then u[k] = val else if u[k] == nil then u[k] = {} end u = u[k] end end return t end -- Get a random key from the table function Self.TblRandomKey(t) local keys = Self.TblKeys(t) local r = #keys > 0 and keys[math.random(#keys)] or nil Self.TblRelease(keys) return r end -- Get a random entry from the table function Self.TblRandom(t) local key = Self.TblRandomKey(t) return key and t[key] end -- Get table keys function Self.TblKeys(t) local u = Self.Tbl() for i,v in pairs(t) do tinsert(u, i) end return u end -- Get table values as continuously indexed list function Self.TblValues(t) local u = Self.Tbl() for i,v in pairs(t) do tinsert(u, v) end return u end -- Turn a table into a continuously indexed list (in-place) function Self.TblList(t) local k, n, i, v = 1, Self.TblCount(t), next(t, nil) while i do local nextI, nextV = next(t, i) if type(i) ~= "number" or i >= k then if i ~= k then for j=k, n do if t[j] == nil then k, t[j], t[i] = j, v break end end end k = k + 1 end i, v = nextI, nextV end return t end -- Check if the table is a continuesly indexed list function Self.TblIsList(t) return #t == Self.TblCount(t) end -- SUB function Self.TblSub(t, s, e) return {unpack(t, s or 1, e)} end function Self.TblHead(t, n) return Self.TblSub(t, 1, n or 1) end function Self.TblTail(t, n) return Self.TblSub(t, #t - (n or 1)) end function Self.TblSplice(t, s, e, u) return Self.TblMerge(Self.TblHead(t, s), u or {}, Self.TblSub(#t, e)) end -- ITERATE -- Good old FoldLeft function Self.TblFoldL(t, fn, u, index, ...) fn, u = Self.Fn(fn), u or Self.Tbl() for i,v in pairs(t) do if index then u = fn(u, v, i, ...) else u = fn(u, v, ...) end end return u end -- Iterate through a table function Self.TblIter(t, fn, ...) fn = Self.Fn(fn) for i,v in pairs(t) do fn(v, i, ...) end return t end -- Call a function on every table entry function Self.TblCall(t, fn, val, index, ...) for i,v in pairs(t) do local f = Self.Fn(fn, v) if val then if index then f(v, i, ...) else f(v, ...) end else if index then f(i, ...) else f(...) end end end end -- COUNT, SUM, MULTIPLY, MIN, MAX function Self.TblCount(t) return Self.TblFoldL(t, Self.FnInc, 0) end function Self.TblSum(t) return Self.TblFoldL(t, Self.FnAdd, 0) end function Self.TblMul(t) return Self.TblFoldL(t, Self.FnMul, 1) end function Self.TblMin(t, start) return Self.TblFoldL(t, math.min, start or select(2, next(t))) end function Self.TblMax(t, start) return Self.TblFoldL(t, math.max, start or select(2, next(t))) end -- Count the # of occurences of given value(s) function Self.TblCountOnly(t, ...) local n = 0 for i,v in pairs(t) do if Self.In(v, ...) then n = n + 1 end end return n end -- Count the # of occurences of everything except given value(s) function Self.TblCountExcept(t, ...) local n = 0 for i,v in pairs(t) do if not Self.In(v, ...) then n = n + 1 end end return n end -- Count the # of tables that have given key/val pairs function Self.TblCountWhere(t, ...) local n = 0 for i,u in pairs(t) do if Self.TblFindWhere(u, ...) then n = n + 1 end end return n end -- Count using a function function Self.TblCountFn(t, fn, ...) local n, fn = 0, Self.Fn(fn) for i,v in pairs(t) do n = n + fn(v, ...) end return n end -- SEARCH -- Search for something in a table and return the index function Self.TblSearch(t, fn, ...) fn = Self.Fn(fn) or Self.FnId for i,v in pairs(t) do if fn(v, i, ...) then return i end end end -- Check if one table is contained within the other function Self.TblContains(t, u, deep) if t == u then return true elseif (t == nil) ~= (u == nil) then return false end for i,v in pairs(u) do if deep and type(t[i]) == "table" and type(v) == "table" then if not Self.TblContains(t[i], v, true) then return false end elseif t[i] ~= v then return false end end return true end -- Check if two tables are equal function Self.TblEquals(a, b, deep) return type(a) == "table" and type(b) == "table" and Self.TblContains(a, b, deep) and Self.TblContains(b, a, deep) end -- Check if a table matches the given key-value pairs function Self.TblMatches(t, ...) for i=1, select("#", ...), 2 do local key, val = select(i, ...) local v = Self.TblGet(t, key) if v == nil or val ~= nil and v ~= val then return false end end return true end -- Check a table's existence and content function Self.TblIsFilled(t) return t and next(t) and t or nil end -- Find a value in a table function Self.TblFind(t, val) for i,v in pairs(t) do if v == val then return i, v end end end -- Find a set of key/value pairs in a table function Self.TblFindWhere(t, ...) local isTbl, tbl, deep = type(...) == "table", ... for i,v in pairs(t) do if isTbl and Self.TblContains(v, tbl, deep) or not isTbl and Self.TblMatches(v, ...) then return i, v end end end -- Find the first element matching a fn function Self.TblFindFn(t, fn, val, index, ...) for i,v in pairs(t) do local f, r = Self.Fn(fn, v) if val then if index then r = f(v, i, ...) else r = f(v, ...) end else if index then r = f(i, ...) else r = f(...) end end if r then return i, v end end end -- Find the first element (optinally matching a fn) function Self.TblFirst(t, fn, val, index, ...) if not fn then return select(2, next(t)) else return select(2, Self.TblFindFn(t, fn, val, index, ...)) end end -- Find the first set of key/value pairs in a table function Self.TblFirstWhere(t, ...) return select(2, Self.TblFindWhere(t, ...)) end -- FILTER -- Filter by a function function Self.TblFilter(t, fn, index, k, ...) fn = Self.Fn(fn) or Self.FnId if not k and Self.TblIsList(t) then for i=#t,1,-1 do if index and not fn(t[i], i, ...) or not index and not fn(t[i], ...) then tremove(t, i) end end else for i,v in pairs(t) do if index and not fn(v, i, ...) or not index and not fn(v, ...) then Self.TblRemove(t, i, k) end end end return t end -- Pick specific keys from a table function Self.TblSelect(t, ...) for i,v in pairs(t) do if not Util.In(i, ...) then t[i] = nil end end return t end -- Omit specific keys from a table function Self.TblUnselect(t, ...) for i,v in Self.Each(...) do t[v] = nil end return t end -- Filter by a value function Self.TblOnly(t, val, k) return Self.TblFilter(t, Self.Equals, false, k, val) end -- Filter by not being a value local Fn = function (v, val) return v ~= val end function Self.TblExcept(t, val, k) return Self.TblFilter(t, Fn, false, k, val) end -- Filter by a set of key/value pairs in a table function Self.TblWhere(t, k, ...) return Self.TblFilter(t, Self.TblMatches, false, k, ...) end -- Filter by not having a set of key/value pairs in a table local Fn = function (...) return not Self.TblMatches(...) end function Self.TblExceptWhere(t, k, ...) return Self.TblFilter(t, Fn, false, k, ...) end -- COPY -- Copy a table and optionally apply a function to every entry function Self.TblCopy(t, fn, index, ...) local fn, u = Self.Fn(fn), Self.Tbl() for i,v in pairs(t) do if fn then if index then u[i] = fn(v, i, ...) else u[i] = fn(v, ...) end else u[i] = v end end return u end -- Filter by a function function Self.TblCopyFilter(t, fn, k, ...) fn = Self.Fn(fn) or Self.FnId local u = Self.Tbl() for i,v in pairs(t) do if fn(v, i, ...) then Self.TblInsert(u, i, v, k) end end return u end -- Pick specific keys from a table function Self.TblCopySelect(t, ...) local u = Self.Tbl() for i,v in Self.Each(...) do u[v] = t[v] end return u end -- Omit specific keys from a table function Self.TblCopyUnselect(t, ...) local u, isTbl = Self.Tbl(), type(...) == "table" for i,v in pairs(t) do if not Util.In(i, ...) then u[i] = v end end return u end -- Filter by a value function Self.TblCopyOnly(t, val, k) local u = Self.Tbl() for i,v in pairs(t) do if v == val then Self.TblInsert(u, i, v, k) end end return u end -- Filter by not being a value function Self.TblCopyExcept(t, val, k) local u = Self.Tbl() for i,v in pairs(t) do if v ~= val then Self.TblInsert(u, i, v, k) end end return u end -- Filter by a set of key/value pairs in a table function Self.TblCopyWhere(t, k, ...) local u = Self.Tbl() for i,v in pairs(t) do if Self.TblFindWhere(u, ...) then Self.TblInsert(u, i, v, k) end end return u end -- Filter by not having a set of key/value pairs in a table function Self.TblCopyExceptWhere(t, k, ...) local u = Self.Tbl() for i,v in pairs(t) do if not Self.TblFindWhere(u, ...) then Self.TblInsert(u, i, v, k) end end return u end -- MAP -- Change table values by applying a function function Self.TblMap(t, fn, index, ...) fn = Self.Fn(fn) for i,v in pairs(t) do if index then t[i] = fn(v, i, ...) else t[i] = fn(v, ...) end end return t end -- Change table keys by applying a function function Self.TblMapKeys(t, fn, value, ...) fn = Self.Fn(fn) local u = Self.Tbl() for i,v in pairs(t) do if value then u[fn(i, v, ...)] = v else u[fn(i, ...)] = v end end return u end -- Change table values by extracting a key function Self.TblPluck(t, k) for i,v in pairs(t) do t[i] = v[k] end return t end -- Flip table keys and values function Self.TblFlip(t, val, ...) local u = Self.Tbl() for i,v in pairs(t) do if type(val) == "function" then u[v] = val(v, i, ...) elseif val ~= nil then u[v] = val else u[v] = i end end return u end -- GROUP -- Group table entries by funciton function Self.TblGroup(t, fn) fn = Self.Fn(fn) or Self.FnId local u = Self.Tbl() for i,v in pairs(t) do i = fn(v, i) u[i] = u[i] or Self.Tbl() tinsert(u[i], v) end return u end -- Group table entries by key function Self.TblGroupBy(t, k) fn = Self.Fn(fn) or Self.FnId local u = Self.Tbl() for i,v in pairs(t) do i = v[k] u[i] = u[i] or Self.Tbl() tinsert(u[i], v) end return u end -- Group the keys with the same values function Self.TblGroupKeys(t) local u = Self.Tbl() for i,v in pairs(t) do u[v] = u[v] or Self.Tbl() tinsert(u[v], i) end return u end -- SET -- Make sure all table entries are unique function Self.TblUnique(t, k) local u = Self.Tbl() for i,v in pairs(t) do if u[v] ~= nil then Self.TblRemove(t, i, k) else u[v] = true end end Self.TblRelease(u) return t end -- Substract the given tables from the table function Self.TblDiff(t, ...) local k = select(select("#", ...), ...) == true for i,v in pairs(t) do for i=1, select("#", ...) - (k and 1 or 0) do if Self.In(v, (select(i, ...))) then Self.TblRemove(t, i, k) break end end end return t end -- Intersect the table with given tables function Self.TblIntersect(t, ...) local k = select(select("#", ...), ...) == true for i,v in pairs(t) do for i=1, select("#", ...) - (k and 1 or 0) do if not Self.In(v, (select(i, ...))) then Self.TblRemove(t, i, k) break end end end return t end -- Check if the intersection of the given tables is not empty function Self.TblIntersects(t, ...) for i,v in pairs(t) do local found = true for i=1, select("#", ...) do if not Self.In(v, (select(i, ...))) then found = false break end end if found then return true end end return false end -- CHANGE function Self.TblInsert(t, i, v, k) if k or type(i) ~= "number" then t[i] = v else tinsert(t, v) end end function Self.TblRemove(t, i, k) if k or type(i) ~= "number" then t[i] = nil else tremove(t, i) end end function Self.TblPush(t, v) tinsert(t, v) return t end function Self.TblPop(t) return tremove(t) end function Self.TblDrop(t) tremove(t) return t end function Self.TblShift(t) return tremove(t, 1) end function Self.TblUnshift(t, v) tinsert(t, 1, v) return t end -- Rotate by l (l>0: left, l<0: right) function Self.TblRotate(t, l) l = l or 1 for i=1, math.abs(l) do if l < 0 then tinsert(t, 1, tremove(t)) else tinsert(t, tremove(t, 1)) end end return t end -- Sort a table local Fn = function (a, b) return a > b end function Self.TblSort(t, fn) fn = fn == true and Fn or Self.Fn(fn) or nil table.sort(t, fn) return t end -- Sort a table of tables by given table keys and default values local Fn = function (a, b) return Self.Compare(b, a) end function Self.TblSortBy(t, ...) local args = type(...) == "table" and (...) or {...} return Self.TblSort(t, function (a, b) for i=1, #args, 3 do local key, default, fn = args[i], args[i+1], args[i+2] fn = fn == true and Fn or Self.Fn(fn) or Self.Compare local cmp = fn(a and a[key] or default, b and b[key] or default) if cmp ~= 0 then return cmp == -1 end end end) end -- Merge two or more tables function Self.TblMerge(t, ...) t = t or Self.Tbl() for i=1,select("#", ...) do local tbl, j = (select(i, ...)), 1 if tbl then for k,v in pairs(tbl) do if k == j then tinsert(t, v) else t[k] = v end j = j + 1 end end end return t end -- OTHER -- Convert the table into tuples of n function Self.TblTuple(t, n) local u, n, r = Self.Tbl(), n or 2 for i,v in pairs(t) do if not r or #r == n then r = Self.Tbl() tinsert(u, r) end tinsert(r, v) end return u end -- This just looks nicer when chaining function Self.TblUnpack(t, fn) fn = Self.Fn(fn) or Self.FnId return fn(unpack(t)) end -- Flatten a list of tables by one dimension local Fn = function (u, v) return Self.TblMerge(u, v) end function Self.TblFlatten(t) return Self.TblFoldL(t, Fn, Self.Tbl()) end -- Wipe multiple tables at once function Self.TblWipe(...) for i=1,select("#", ...) do wipe((select(i, ...))) end return ... end -- Join a table of strings function Self.TblConcat(t, del) return table.concat(t, del) end -- Use Blizzard's inspect tool function Self.TblInspect(t) UIParentLoadAddOn("Blizzard_DebugTools") DisplayTableInspectorWindow(t) end ------------------------------------------------------- -- String -- ------------------------------------------------------- function Self.IsStr(str) return type(str) == "string" end function Self.StrStartsWith(str, str2) return Self.IsStr(str) and str:sub(1, str2:len()) == str2 end function Self.StrEndsWith(str, str2) return Self.IsStr(str) and str:sub(-str2:len()) == str2 end function Self.StrIsEmpty(str) return not Self.IsStr(str) or str == "" end function Self.StrWrap(str, before, after) if Self.StrIsEmpty(str) then return "" end return (before or " ") .. str .. (after or before or " ") end function Self.StrPrefix(str, prefix) return Self.StrWrap(str, prefix, "") end function Self.StrPostfix(str, postfix) return Self.StrWrap(str, "", postfix) end -- Split string on delimiter function Self.StrSplit(str, del) return Self.Tbl(del:split(str)) end -- Uppercase first char function Self.StrUcFirst(str) return str:sub(1, 1):upper() .. str:sub(2) end -- Lowercase first char function Self.StrLcFirst(str) return str:sub(1, 1):lower() .. str:sub(2) end -- Check if string is a number function Self.StrIsNumber(str, leadingZero) return tonumber(str) and (leadingZero or not Self.StrStartsWith(str, "0")) end -- Get abbreviation of given length function Self.StrAbbr(str, length) return str:len() <= length and str or str:sub(1, length) .. "..." end function Self.StrColor(r, g, b, a) return ("%.2x%.2x%.2x%.2x"):format((a or 1) * 255, (r or 1) * 255, (g or 1) * 255, (b or 1) * 255) end function Self.StrReplace(str, from, len, sub) from, len, sub = from or 1, len or str:len(), sub or "" local to = from < 0 and str:len() + from + len + 1 or from + len return str:sub(1, from - 1) .. sub .. str:sub(to) end function Self.StrToCamelCase(str, del) local s = "" for v in str:gmatch("[^" .. (del or "%p%s") .. "]+") do s = s .. Self.StrUcFirst(v:lower()) end return Self.StrLcFirst(s) end function Self.StrFromCamelCase(str, del, case) local s = str:gsub("%u", (del or " ") .. "%1") return case == true and s:upper() or case == false and s:lower() or s end ------------------------------------------------------- -- Number -- ------------------------------------------------------- -- Rounds a number function Self.NumRound(num, p) p = math.pow(10, p or 0) return floor(num * p + .5) / p end -- Check if num is in interval (exclusive or inclusive) function Self.NumBetween(num, a, b) return num > a and num < b end function Self.NumIn(num, a, b) return num >= a and num <= b end function Self.NumToHex(num, minLength) return ("%." .. (minLength or 1) .. "x"):format(num) end ------------------------------------------------------- -- Boolean -- ------------------------------------------------------- function Self.Bool(v) return not not v end -- True if an uneven # of inputs are true function Self.BoolXOR(...) local n = 0 for _,v in Self.Each(...) do if v then n = n + 1 end end return n % 2 == 1 end ------------------------------------------------------- -- Function -- ------------------------------------------------------- function Self.Fn(fn, obj) return type(fn) == "string" and (obj and obj[fn] or _G[fn]) or fn end function Self.FnId(...) return ... end function Self.FnTrue() return true end function Self.FnFalse() return false end function Self.FnZero() return 0 end function Self.FnNoop() end -- Some math function Self.FnInc(i) return i+1 end function Self.FnDec(i) return i-1 end function Self.FnAdd(a, b) return a+b end function Self.FnSub(a, b) return a-b end function Self.FnMul(a, b) return a*b end function Self.FnDiv(a, b) return a/b end -- MODIFY -- Throttle a function, so it is executed at most every n seconds function Self.FnThrottle(fn, n, leading) local Fn, timer, called Fn = function (...) if not timer then if leading then fn(...) end timer = Addon:ScheduleTimer(function (...) timer = nil if not leading then fn(...) end if called then called = nil Fn(...) end end, n, ...) else called = true end end return Fn end -- Debounce a function, so it is executed only n seconds after the last call function Self.FnDebounce(fn, n, leading) local timer, called return function (...) if not timer then if leading then fn(...) end timer = Addon:ScheduleTimer(function (...) timer = nil if not leading or called then called = nil fn(...) end end, n, ...) else called = true Addon:ExtendTimerTo(timer, n) end end end ------------------------------------------------------- -- Other -- ------------------------------------------------------- -- Safecall local xpcall = xpcall local function errorhandler(err) return geterrorhandler()(err) end local function CreateDispatcher(argCount) local code = [[ local xpcall, eh = ... local method, ARGS local function call() return method(ARGS) end local function dispatch(func, ...) method = func if not method then return end ARGS = ... return xpcall(call, eh) end return dispatch ]] local ARGS = {} for i = 1, argCount do ARGS[i] = "arg"..i end code = code:gsub("ARGS", table.concat(ARGS, ", ")) return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler) end local Dispatchers = setmetatable({}, {__index=function(self, argCount) local dispatcher = CreateDispatcher(argCount) rawset(self, argCount, dispatcher) return dispatcher end}) Dispatchers[0] = function(func) return xpcall(func, errorhandler) end function Self.Safecall(func, ...) return Dispatchers[select("#", ...)](func, ...) end -- Get string representation values for dumping function Self.ToString(val, depth) depth = depth or 3 local t = type(val) if t == "nil" then return "nil" elseif t == "table" then if depth == 0 then return "{...}" else local j = 1 return Self.TblFoldL(val, function (s, v, i) if s ~= "{" then s = s .. ", " end if i ~= j then s = s .. i .. " = " end j = j + 1 return s .. Self.ToString(v, depth-1) end, "{", true) .. "}" end elseif t == "boolean" then return val and "true" or "false" elseif t == "function" then return "(fn)" elseif t == "string" then return '"' .. val .. '"' else return val end end -- Dump all given values function Self.Dump(...) for i=1,select("#", ...) do print(Self.ToString((select(i, ...)))) end end -- Stacktrace function Self.Trace() local s = Self(debugstack(2)).Split("\n").Except("")() print("------------------------- Trace -------------------------") for i,v in pairs(s) do print(i .. ": " .. v) end print("---------------------------------------------------------") end -- Enable chain-calling Self.C = {v = nil, k = nil} local Fn = function (...) local c, k, v = Self.C, rawget(Self.C, "k"), rawget(Self.C, "v") local t = type(v) local pre = t == "table" and "Tbl" or t == "string" and "Str" or t == "number" and "Num" or t == "boolean" and "Bool" or t == "function" and "Fn" or "" c.v = (Self[pre .. k] or Self[k])(v, ...) return c end setmetatable(Self.C, { __index = function (c, k) c.k = Self.StrUcFirst(k) return Fn end, __call = function (c, i) local v = rawget(c, "v") if i ~= nil then return v[i] else return v end end }) setmetatable(Self, { __call = function (_, v) Self.C.v = v Self.C.k = nil return Self.C end })
26.388436
173
0.556042
45c946aab8cef40615bbfb44b25050359a9090fb
4,507
py
Python
ocr_attribute_extraction/attribute_name.py
DAVEisZERO/IW276WS21-P19
ab9e829174ad2c7ce7b88526e25355b395abdda7
[ "MIT" ]
null
null
null
ocr_attribute_extraction/attribute_name.py
DAVEisZERO/IW276WS21-P19
ab9e829174ad2c7ce7b88526e25355b395abdda7
[ "MIT" ]
null
null
null
ocr_attribute_extraction/attribute_name.py
DAVEisZERO/IW276WS21-P19
ab9e829174ad2c7ce7b88526e25355b395abdda7
[ "MIT" ]
null
null
null
from enum import Enum, auto class Colors(Enum): Black = 'Color-Black' Blue = 'Color-Blue' Brown = 'Color-Brown' Green = 'Color-Green' Grey = 'Color-Grey' Orange = 'Color-Orange' Pink = 'Color-Pink' Purple = 'Color-Purple' Red = 'Color-Red' White = 'Color-White' Yellow = 'Color-Yellow' Mixture = 'Color-Mixture' Other = 'Color-Other' class AttributeName(Enum): Gender_Female = 'Gender-Female' UpperBody_Length_Short = 'UpperBody-Length-Short' UpperBody_Color_Black = 'UpperBody-Color-Black' UpperBody_Color_Blue = 'UpperBody-Color-Blue' UpperBody_Color_Brown = 'UpperBody-Color-Brown' UpperBody_Color_Green = 'UpperBody-Color-Green' UpperBody_Color_Grey = 'UpperBody-Color-Grey' UpperBody_Color_Orange = 'UpperBody-Color-Orange' UpperBody_Color_Pink = 'UpperBody-Color-Pink' UpperBody_Color_Purple = 'UpperBody-Color-Purple' UpperBody_Color_Red = 'UpperBody-Color-Red' UpperBody_Color_White = 'UpperBody-Color-White' UpperBody_Color_Yellow = 'UpperBody-Color-Yellow' UpperBody_Color_Mixture = 'UpperBody-Color-Mixture' UpperBody_Color_Other = 'UpperBody-Color-Other' LowerBody_Length_Short = 'LowerBody-Length-Short' LowerBody_Color_Black = 'LowerBody-Color-Black' LowerBody_Color_Blue = 'LowerBody-Color-Blue' LowerBody_Color_Brown = 'LowerBody-Color-Brown' LowerBody_Color_Green = 'LowerBody-Color-Green' LowerBody_Color_Grey = 'LowerBody-Color-Grey' LowerBody_Color_Orange = 'LowerBody-Color-Orange' LowerBody_Color_Pink = 'LowerBody-Color-Pink' LowerBody_Color_Purple = 'LowerBody-Color-Purple' LowerBody_Color_Red = 'LowerBody-Color-Red' LowerBody_Color_White = 'LowerBody-Color-White' LowerBody_Color_Yellow = 'LowerBody-Color-Yellow' LowerBody_Color_Mixture = 'LowerBody-Color-Mixture' LowerBody_Color_Other = 'LowerBody-Color-Other' Accessory_Backpack = 'Accessory-Backpack' upper_body_part_to_color = { AttributeName.UpperBody_Color_Black: Colors.Black, AttributeName.UpperBody_Color_Blue: Colors.Blue, AttributeName.UpperBody_Color_Brown: Colors.Brown, AttributeName.UpperBody_Color_Green: Colors.Green, AttributeName.UpperBody_Color_Grey: Colors.Grey, AttributeName.UpperBody_Color_Orange: Colors.Orange, AttributeName.UpperBody_Color_Pink: Colors.Pink, AttributeName.UpperBody_Color_Purple: Colors.Purple, AttributeName.UpperBody_Color_Red: Colors.Red, AttributeName.UpperBody_Color_White: Colors.White, AttributeName.UpperBody_Color_Yellow: Colors.Yellow, AttributeName.UpperBody_Color_Mixture: Colors.Mixture, AttributeName.UpperBody_Color_Other: Colors.Other, } lower_body_part_to_color = { AttributeName.LowerBody_Color_Black: Colors.Black, AttributeName.LowerBody_Color_Blue: Colors.Blue, AttributeName.LowerBody_Color_Brown: Colors.Brown, AttributeName.LowerBody_Color_Green: Colors.Green, AttributeName.LowerBody_Color_Grey: Colors.Grey, AttributeName.LowerBody_Color_Orange: Colors.Orange, AttributeName.LowerBody_Color_Pink: Colors.Pink, AttributeName.LowerBody_Color_Purple: Colors.Purple, AttributeName.LowerBody_Color_Red: Colors.Red, AttributeName.LowerBody_Color_White: Colors.White, AttributeName.LowerBody_Color_Yellow: Colors.Yellow, AttributeName.LowerBody_Color_Mixture: Colors.Mixture, AttributeName.LowerBody_Color_Other: Colors.Other, } class Part(Enum): UpperBody = "Part_UpperBody" LowerBody = "Part_LowerBody" Backpack = "Part_Backpack" attribute_keyword_lookup = { "Gender_Female": ["she", "her", "women", "girl"], "Gender_Male": ["he", "male", 'man'], Part.UpperBody.value: ['suit', "shirt", "t-shirt", "top"], Part.LowerBody.value: ['jeans', 'pant', 'pants', 'trousers', 'shorts'], Part.Backpack.value: ['backpack', 'bag'], "Length_Short": ['short', 'shorts', "shirt", "t-shirt", 'sleeveless'], "Length_Long": ['long', 'sleeves', 'trousers'], Colors.Black.value: ["black", "dark"], Colors.Blue.value: ["blue"], Colors.Brown.value: ["brown"], Colors.Green.value: ["green"], Colors.Grey.value: ["grey", "gray"], Colors.Orange.value: ["orange"], Colors.Pink.value: ["pink"], Colors.Purple.value: ["purple"], Colors.Red.value: ["red"], Colors.White.value: ["white", "light"], Colors.Yellow.value: ["yellow"], Colors.Mixture.value: ["mixture"], Colors.Other.value: ["other", "rainbow"], }
38.194915
75
0.728866
c3bddb363b575c123f3bf3bf50c1e9dbc07b5589
1,579
kt
Kotlin
src/test/kotlin/no/nav/syfo/testhelper/mock/IsproxyMock.kt
navikt/syfobehandlendeenhet
1ffaad9607453887c7c103f3a2bc23951a6a77b1
[ "MIT" ]
null
null
null
src/test/kotlin/no/nav/syfo/testhelper/mock/IsproxyMock.kt
navikt/syfobehandlendeenhet
1ffaad9607453887c7c103f3a2bc23951a6a77b1
[ "MIT" ]
4
2021-09-08T10:28:32.000Z
2022-01-26T12:52:28.000Z
src/test/kotlin/no/nav/syfo/testhelper/mock/IsproxyMock.kt
navikt/syfobehandlendeenhet
1ffaad9607453887c7c103f3a2bc23951a6a77b1
[ "MIT" ]
null
null
null
package no.nav.syfo.testhelper.mock import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* import io.ktor.server.engine.* import io.ktor.server.netty.* import no.nav.syfo.application.api.installContentNegotiation import no.nav.syfo.client.norg.NorgClient import no.nav.syfo.client.norg.domain.Enhetsstatus import no.nav.syfo.client.norg.domain.NorgEnhet import no.nav.syfo.testhelper.* const val ENHET_NR = "0101" const val ENHET_NAVN = "Enhet" fun generateNorgEnhet(): NorgEnhet { return NorgEnhet( enhetNr = ENHET_NR, navn = ENHET_NAVN, status = Enhetsstatus.AKTIV.formattedName, aktiveringsdato = null, antallRessurser = null, enhetId = null, kanalstrategi = null, nedleggelsesdato = null, oppgavebehandler = null, orgNivaa = null, orgNrTilKommunaltNavKontor = null, organisasjonsnummer = null, sosialeTjenester = null, type = null, underAvviklingDato = null, underEtableringDato = null, versjon = null, ) } class IsproxyMock { private val port = getRandomPort() val url = "http://localhost:$port" val norg2Response = listOf( generateNorgEnhet(), ) val name = "isproxy" val server: NettyApplicationEngine = embeddedServer( factory = Netty, port = port ) { installContentNegotiation() routing { post(NorgClient.ARBEIDSFORDELING_BESTMATCH_PATH) { call.respond(norg2Response) } } } }
26.316667
62
0.651045
b76c0abbec955fb31dd7399d6fe7d7236d9f9869
1,002
cs
C#
Unity-TrackIR-Plugin-DLL-master/NPConstants.cs
nash8350/GazePlusMouse
77efbfeb8f06175e39c9efd2e85be7b855095963
[ "Apache-2.0" ]
115
2017-07-19T19:09:50.000Z
2022-03-19T10:42:53.000Z
Unity-TrackIR-Plugin-DLL-master/NPConstants.cs
nash8350/GazePlusMouse
77efbfeb8f06175e39c9efd2e85be7b855095963
[ "Apache-2.0" ]
78
2017-07-23T23:13:07.000Z
2022-03-28T16:00:16.000Z
Unity-TrackIR-Plugin-DLL-master/NPConstants.cs
nash8350/GazePlusMouse
77efbfeb8f06175e39c9efd2e85be7b855095963
[ "Apache-2.0" ]
25
2017-09-08T14:44:32.000Z
2022-03-18T22:42:11.000Z
namespace TrackIRUnity { internal static class NPConstants { public const int NPQUERYVERSION = 1040; public const int NPVERSIONMAJOR = 1; public const int NPVERSIONMINOR = 2; public const int NPControl = 8; public const ushort NPRoll = (ushort) 1; public const ushort NPPitch = (ushort) 2; public const ushort NPYaw = (ushort) 4; public const ushort NPX = (ushort) 16; public const ushort NPY = (ushort) 32; public const ushort NPZ = (ushort) 64; public const ushort NPRawX = (ushort) 128; public const ushort NPRawY = (ushort) 256; public const ushort NPRawZ = (ushort) 512; public const ushort NPDeltaX = (ushort) 1024; public const ushort NPDeltaY = (ushort) 2048; public const ushort NPDeltaZ = (ushort) 4096; public const ushort NPSmoothX = (ushort) 8192; public const ushort NPSmoothY = (ushort) 16384; public const ushort NPSmoothZ = (ushort) 32768; public const ushort NP_DEVELOPER_ID = (ushort) 20430; } }
37.111111
57
0.691617
a35343051e2546da03398ef2c70cd6a8b5465a4d
297
ps1
PowerShell
data/scripts/DemoScripts-SQL2016/Get-Member_ExposeMethods.ps1
nimda-md/MAG-Azure-Automation
c656a549b207b1e8c61721fa9a074ceed13b1355
[ "MIT" ]
25
2018-10-18T18:31:33.000Z
2021-06-03T09:43:41.000Z
data/scripts/DemoScripts-SQL2016/Get-Member_ExposeMethods.ps1
aktapaz/0026-azure-automation-plus-dsc-lab
91663075ac55172f6c099ded98963cee5af7ad22
[ "MIT" ]
26
2019-03-04T14:00:10.000Z
2021-12-26T22:52:40.000Z
data/scripts/DemoScripts-SQL2016/Get-Member_ExposeMethods.ps1
aktapaz/0026-azure-automation-plus-dsc-lab
91663075ac55172f6c099ded98963cee5af7ad22
[ "MIT" ]
7
2019-02-27T05:57:33.000Z
2022-01-14T14:26:30.000Z
Import-Module SQLPS $ServerName = "Pansatywin7" #"PankajWin7" $InstanceName = "Default" #"Default" $ConnectionString = "SQLSERVER:\SQL\"+$ServerName+"\"+$InstanceName+"\Databases" dir $ConnectionString | %{$_.EnumBackupSets()} #dir $ConnectionString | %{$_.EnumBackupSets()} |Get-Member
33
80
0.707071
6b055f1bd2864175c01e1ba68ecb466ed2d31673
61
lua
Lua
remove fog.lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
70
2021-02-09T17:21:32.000Z
2022-03-28T12:41:42.000Z
remove fog.lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
4
2021-08-19T22:05:58.000Z
2022-03-19T18:58:01.000Z
remove fog.lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
325
2021-02-26T22:23:41.000Z
2022-03-31T19:36:12.000Z
game.Lighting.FogEnd = 100000 game.Lighting.FogStart = 100000
30.5
31
0.819672
9891e1f0f62d81208aefaa528be33679eab94b27
2,945
swift
Swift
SVG.playground/Sources/UIColor+CSS.swift
zhangxigithub/SVGCanvas
d45dcf626b8f7d40f429a22f0bc89395601560f8
[ "Apache-2.0" ]
1
2017-02-22T06:22:35.000Z
2017-02-22T06:22:35.000Z
SVG.playground/Sources/UIColor+CSS.swift
zhangxigithub/SVGCanvas
d45dcf626b8f7d40f429a22f0bc89395601560f8
[ "Apache-2.0" ]
null
null
null
SVG.playground/Sources/UIColor+CSS.swift
zhangxigithub/SVGCanvas
d45dcf626b8f7d40f429a22f0bc89395601560f8
[ "Apache-2.0" ]
null
null
null
import UIKit public extension UIColor { public convenience init(css:String) { if css.hasPrefix("#") == true { self.init(hexString:css) } else if css.hasPrefix("rgb(") == true { self.init(hexString:css) } else if css.hasPrefix("rgba(") == true { self.init(hexString:css) } else if css.hasPrefix("hsl(") == true { //unsppourtted self.init(red: 0, green:0,blue: 0,alpha: 1) } else if css.hasPrefix("hsla(") == true { //unsppourtted self.init(red: 0, green:0,blue: 0,alpha: 1) }else if let hex = UIColor.colorWithKey(css) { self.init(hexString:hex) }else { self.init(red: 0, green:0,blue: 0,alpha: 1) } } class func colorWithKey(key:String) -> String? { //http://www.w3school.com.cn/cssref/css_colors.asp //http://www.computerhope.com/htmcolor.htm //http://www.zhangxinxu.com/wordpress/2015/07/know-css1-css3-color/ let dict = [ "transparent":"#00000000", "red":"#FF0000", "black":"#000000", "orange":"#FFA500"]; return dict[key] } public convenience init(rgb r:Int,g:Int,b:Int) { self.init(red: CGFloat(r)/CGFloat(255.0), green: CGFloat(g)/CGFloat(255.0),blue: CGFloat(b)/CGFloat(255.0),alpha: 1) } public convenience init(rgba r:Int,g:Int,b:Int,a:Float) { self.init(red: CGFloat(r)/CGFloat(255.0), green: CGFloat(g)/CGFloat(255.0),blue: CGFloat(b)/CGFloat(255.0),alpha: CGFloat(a)) } public convenience init(hexString: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 var color = hexString if color.hasPrefix("#") == true { color = color.substringFromIndex(color.startIndex.advancedBy(1)) } var hex:UInt64 = 0 if NSScanner(string: color).scanHexLongLong(&hex) { if color.characters.count == 6 { red = CGFloat((hex & 0x8FF0000) >> 16) / 255.0 green = CGFloat((hex & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hex & 0x0000FF) / 255.0 }else if color.characters.count == 8 { red = CGFloat((hex & 0xFF000000) >> 24) / 255.0 green = CGFloat((hex & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hex & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hex & 0x000000FF) / 255.0 } }else { } self.init(red:red, green:green, blue:blue, alpha:alpha) } }
28.872549
133
0.487606
a4634792c47d0378be7cf48a6ff92e7aaa8928d0
4,907
php
PHP
resources/views/jabatan/jabatan.blade.php
glennluc/FP-PBKK
b192b604561b660bbe9eda3e48f62d230d9dcb8a
[ "MIT" ]
null
null
null
resources/views/jabatan/jabatan.blade.php
glennluc/FP-PBKK
b192b604561b660bbe9eda3e48f62d230d9dcb8a
[ "MIT" ]
null
null
null
resources/views/jabatan/jabatan.blade.php
glennluc/FP-PBKK
b192b604561b660bbe9eda3e48f62d230d9dcb8a
[ "MIT" ]
null
null
null
@extends('layouts.template') @section('content') <header class="blue accent-3 relative"> <div class="container-fluid text-white"> <div class="row p-t-b-10 "> <div class="col"> <h4> <i class="icon-database"></i> Jabatan </h4> </div> </div> <div class="row justify-content-between"> <ul class="nav nav-material nav-material-white responsive-tab" id="v-pills-tab" role="tablist"> <li> <a class="nav-link active" id="v-pills-all-tab" data-toggle="pill" href="{{ URL('admin/get-jabatan')}}" role="tab" aria-controls="v-pills-all"><i class="icon icon-home2"></i>Manage Jabatan</a> </li> <li class="float-right"> <a class="nav-link" href="{{ URL('admin/create-jabatan')}}" ><i class="icon icon-plus-circle"></i>Tambah Jabatan</a> </li> </ul> </div> </div> </header> <div class="container-fluid animatedParent animateOnce"> <div class="tab-content my-3" id="v-pills-tabContent"> <div class="tab-pane animated fadeInUpShort show active" id="v-pills-all" role="tabpanel" aria-labelledby="v-pills-all-tab"> <div class="row my-3"> <div class="col-md-12"> <div class="card r-0 shadow"> <div class="table-responsive"> <form> <table class="table table-striped table-hover r-0"> <thead> <tr class="no-b"> <th style="width: 30px"> <div class="custom-control custom-checkbox"> <input type="checkbox" id="checkedAll" class="custom-control-input"><label class="custom-control-label" for="checkedAll"></label> </div> </th> <th>No</th> <th>ID Jabatan</th> <th>Nama Jabatan</th> <th>Parent Jabatan</th> <th>Keterangan</th> <th></th> </tr> </thead> <tbody> <?php $no = 1; foreach ($jabatan as $row) { ?> <tr> <td> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input checkSingle" id="user_id_1" required><label class="custom-control-label" for="user_id_1"></label> </div> </td> <td>{{$no++}}</td> <td>{{$row->id_jabatan}}</td> <td><span class="r-3 badge badge-success ">{{$row->nama_jabatan}}</span></td> <td>{{$row->parent_jabatan}}</td> <td>{{$row->keterangan}}</td> <td> <!-- <a href="panel-page-profile.html"><i class="icon-eye mr-3"></i></a> --> <a href="{{URL('admin/edit-jabatan/'.$row->id_jabatan)}}"><i class="icon-pencil mr-3"></i></a> <a href="{{URL('admin/delete-jabatan/'.$row->id_jabatan)}}"><i class="icon-trash"></i></a> </td> </tr> <?php } ?> </tbody> </table> </form> </div> </div> </div> </div> @endsection
55.761364
142
0.316487
834a969a714745434cebf8195b92f8d12ebd8098
1,823
tsx
TypeScript
ionic-react/src/pages/SpeakerList.tsx
ferhhan/next
e34f699fa9901840df2fcba4bd2205d8a8d311db
[ "MIT" ]
null
null
null
ionic-react/src/pages/SpeakerList.tsx
ferhhan/next
e34f699fa9901840df2fcba4bd2205d8a8d311db
[ "MIT" ]
50
2020-03-14T21:34:02.000Z
2022-03-02T06:54:49.000Z
ionic-react/src/pages/SpeakerList.tsx
ferhhan/next
e34f699fa9901840df2fcba4bd2205d8a8d311db
[ "MIT" ]
null
null
null
import React from 'react'; import { IonHeader, IonToolbar, IonTitle, IonContent, IonPage, IonButtons, IonMenuButton, IonList, IonGrid, IonRow, IonCol } from '@ionic/react'; import SpeakerItem from '../components/SpeakerItem'; import { Speaker } from '../models/Speaker'; import { Session } from '../models/Session'; import { connect } from '../data/connect'; import * as selectors from '../data/selectors'; import './SpeakerList.scss'; interface OwnProps { }; interface StateProps { speakers: Speaker[]; speakerSessions: { [key: number]: Session[] }; }; interface DispatchProps { }; interface SpeakerListProps extends OwnProps, StateProps, DispatchProps { }; const SpeakerList: React.FC<SpeakerListProps> = ({ speakers, speakerSessions }) => { return ( <IonPage id="speaker-list"> <IonHeader> <IonToolbar> <IonButtons slot="start"> <IonMenuButton /> </IonButtons> <IonTitle>Speakers</IonTitle> </IonToolbar> </IonHeader> <IonContent className={`outer-content`}> <IonList> <IonGrid fixed> <IonRow align-items-stretch> {speakers.map(speaker => ( <IonCol size="12" size-md="6" key={speaker.id}> <SpeakerItem key={speaker.id} speaker={speaker} sessions={speakerSessions[speaker.id]} /> </IonCol> ))} </IonRow> </IonGrid> </IonList> </IonContent> </IonPage> ); }; export default connect<OwnProps, StateProps, DispatchProps>({ mapStateToProps: (state) => ({ speakers: selectors.getSpeakers(state), speakerSessions: selectors.getSpeakerSessions(state) }), component: React.memo(SpeakerList) });
29.885246
145
0.598464
6df03ab05e93e6d00afc633c30ab04a3f7981d1a
154
h
C
LLToolbox/Frameworks/LLToolbox.framework/Headers/NSDictionary+LLTool.h
LOLITA0164/LLToolbox
5cd71053c3ec0998c6f148f6fb7cbdeda116decd
[ "MIT" ]
null
null
null
LLToolbox/Frameworks/LLToolbox.framework/Headers/NSDictionary+LLTool.h
LOLITA0164/LLToolbox
5cd71053c3ec0998c6f148f6fb7cbdeda116decd
[ "MIT" ]
null
null
null
LLToolbox/Frameworks/LLToolbox.framework/Headers/NSDictionary+LLTool.h
LOLITA0164/LLToolbox
5cd71053c3ec0998c6f148f6fb7cbdeda116decd
[ "MIT" ]
null
null
null
#import <Foundation/Foundation.h> @interface NSDictionary (LLTool) /// 获取数据 -(id)objectForKeyNotNull:(id)key; /// 转换为字符串 -(NSString*)toString; @end
11
33
0.707792
251c3df686dcec3aaf2367193348e2dbbaf88d92
1,297
sh
Shell
android/n6/apt_upgrade_to_n6.sh
Goral64/AIS-utils
5eff75d40184565589b079e6253c25318bdaa0a2
[ "Apache-2.0" ]
null
null
null
android/n6/apt_upgrade_to_n6.sh
Goral64/AIS-utils
5eff75d40184565589b079e6253c25318bdaa0a2
[ "Apache-2.0" ]
null
null
null
android/n6/apt_upgrade_to_n6.sh
Goral64/AIS-utils
5eff75d40184565589b079e6253c25318bdaa0a2
[ "Apache-2.0" ]
null
null
null
# TODO switch this repo to stable echo " " echo "Change repo" echo "# The AI-Speaker beta repository:" > /data/data/pl.sviete.dom/files/usr/etc/apt/sources.list echo "deb [trusted=yes] https://powiedz.co/apt dom-dev beta" >> /data/data/pl.sviete.dom/files/usr/etc/apt/sources.list # apt install libacl apt install -y clang apt install -y ldc apt install apt apt upgrade -y apt install libusb pm2 delete ftp pm2 start busybox --name ftp --output /dev/null --error /dev/null --restart-delay=150000 -- tcpsvd -vE 0.0.0.0 1024 busybox ftpd -w /sdcard apt remove python rm -rf python3.7 apt install python apt remove nodejs apt install nodejs-lts pip install ais-dom pip install bcrypt==3.1.7 pip install sqlalchemy==1.3.19 pip install --upgrade pip # PRO only... apt install postgresql pip install psycopg2 mkdir -p $PREFIX/var/lib/postgresql initdb $PREFIX/var/lib/postgresql # start db pg_ctl -D $PREFIX/var/lib/postgresql start # create user ais with pass dom createuser --superuser --pwprompt ais # create database ha createdb ha # open ha database psql ha # stop server pg_ctl -D $PREFIX/var/lib/postgresql stop # start db from pm2 pm2 start postgres --name db --output /dev/null --error /dev/null --restart-delay=150000 -- -D /data/data/pl.sviete.dom/files/usr/var/lib/postgresql
24.942308
150
0.745567
dda87d3b6147d9a163eb382ab589022f123aec8e
5,402
java
Java
rebro/src/java/weka/gui/knowledgeflow/StepTreeLeafDetails.java
Benn-Co/refactored-broccoli
75e5f02dbeb824b10bf2b47175b186085f424b64
[ "MIT" ]
null
null
null
rebro/src/java/weka/gui/knowledgeflow/StepTreeLeafDetails.java
Benn-Co/refactored-broccoli
75e5f02dbeb824b10bf2b47175b186085f424b64
[ "MIT" ]
null
null
null
rebro/src/java/weka/gui/knowledgeflow/StepTreeLeafDetails.java
Benn-Co/refactored-broccoli
75e5f02dbeb824b10bf2b47175b186085f424b64
[ "MIT" ]
null
null
null
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * StepTreeLeafDetails.java * Copyright (C) 2015 University of Waikato, Hamilton, New Zealand * */ package weka.gui.knowledgeflow; import weka.core.Utils; import weka.core.WekaPackageClassLoaderManager; import weka.knowledgeflow.StepManagerImpl; import weka.knowledgeflow.steps.KFStep; import weka.knowledgeflow.steps.Step; import weka.knowledgeflow.steps.WekaAlgorithmWrapper; import javax.swing.Icon; import java.io.Serializable; import java.lang.annotation.Annotation; /** * Maintains information about a step in the {@code StepTree} - e.g. tool tip * text, wrapped algorithm name (in the case of a {@code WekaAlgorithmWrapper}. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision: $ */ public class StepTreeLeafDetails implements Serializable { /** * For serialization */ private static final long serialVersionUID = 6347861816716877761L; /** Class of the step stored at this leaf */ protected Class m_stepClazz; /** The name of the algorithm wrapped by a WekaAlgorithmWrapper step */ protected String m_wrappedWekaAlgoName = ""; /** * the label (usually derived from the qualified name or wrapped algorithm) * for the leaf */ protected String m_leafLabel = ""; /** icon to display at the leaf (scaled appropriately) */ protected transient Icon m_scaledIcon = null; /** tool tip text to display */ protected String m_toolTipText = null; /** If a tool tip text is set, whether to show it or not */ protected boolean m_showTipText = true; /** * Constructor * * @param step the step to wrap in this {@code StepTreeLeafDetails} instance */ public StepTreeLeafDetails(Object step) { this(step, true); } /** * Constructor * * @param step the step to wrap in this {@code StepTreeLeafDetails} instance * @param showTipText true if the tool tip text should be shown for this * instance */ public StepTreeLeafDetails(Object step, boolean showTipText) { m_stepClazz = step.getClass(); Annotation[] annotations = m_stepClazz.getAnnotations(); for (Annotation a : annotations) { if (a instanceof KFStep) { m_leafLabel = ((KFStep) a).name(); if (showTipText) { m_toolTipText = ((KFStep) a).toolTipText(); } break; } } if (step instanceof Step) { m_leafLabel = ((Step) step).getName(); } if (step instanceof WekaAlgorithmWrapper) { m_wrappedWekaAlgoName = ((WekaAlgorithmWrapper) step).getWrappedAlgorithm().getClass() .getCanonicalName(); } if (showTipText) { String globalInfo = Utils.getGlobalInfo(step, false); if (globalInfo != null) { m_toolTipText = globalInfo; } } m_scaledIcon = StepVisual.scaleIcon(StepVisual.iconForStep((Step) step), 0.33); } /** * Set whether to show tip text or not * * @param show true to show tip text */ public void setShowTipTexts(boolean show) { m_showTipText = show; } /** * Get the tool tip for this leaf * * @return the tool tip */ public String getToolTipText() { return m_showTipText ? m_toolTipText : null; } /** * Returns the leaf label * * @return the leaf label */ @Override public String toString() { return m_leafLabel; } /** * Gets the icon for this bean * * @return the icon for this bean */ protected Icon getIcon() { return m_scaledIcon; } /** * Returns true if this leaf represents a wrapped Weka algorithm (i.e. filter, * classifier, clusterer etc.). * * @return true if this leaf represents a wrapped algorithm */ public boolean isWrappedAlgorithm() { return m_wrappedWekaAlgoName != null && m_wrappedWekaAlgoName.length() > 0; } /** * Instantiate the step at this leaf and return it wrapped in a StepVisual * * @return a StepVisual instance wrapping a copy of the step at this leaf * @throws Exception if a problem occurs */ public StepVisual instantiateStep() throws Exception { Step step = null; step = /* * (Step) Beans.instantiate(this.getClass().getClassLoader(), * m_stepClazz.getCanonicalName()); */ (Step) m_stepClazz.newInstance(); StepManagerImpl manager = new StepManagerImpl(step); if (step instanceof WekaAlgorithmWrapper) { Object algo = // Beans.instantiate(this.getClass().getClassLoader(), // m_wrappedWekaAlgoName); WekaPackageClassLoaderManager.objectForName(m_wrappedWekaAlgoName); ((WekaAlgorithmWrapper) step).setWrappedAlgorithm(algo); } StepVisual visual = StepVisual.createVisual(manager); return visual; } }
27.282828
80
0.676231
20d1a07fd6b83557d0f2bc6d1cefacee4b2f0441
575
py
Python
source/python/SkillTree.py
JoHyukJun/algorithm-analysis
3eda22ce0eeb52490702206d73c04cff1eb3e72d
[ "Apache-2.0" ]
null
null
null
source/python/SkillTree.py
JoHyukJun/algorithm-analysis
3eda22ce0eeb52490702206d73c04cff1eb3e72d
[ "Apache-2.0" ]
null
null
null
source/python/SkillTree.py
JoHyukJun/algorithm-analysis
3eda22ce0eeb52490702206d73c04cff1eb3e72d
[ "Apache-2.0" ]
null
null
null
''' main.py Created by Jo Hyuk Jun on 2020 Copyright © 2020 Jo Hyuk Jun. All rights reserved. ''' def solution(skill, skill_trees): answer = 0 skill_stack = list(skill) for v in skill_trees: tmp = [] is_ok = True cur_skill = list(v) for i in range(len(cur_skill)): if cur_skill[i] in skill_stack: tmp.append(cur_skill[i]) if tmp != skill_stack[:len(tmp)]: is_ok = False break if is_ok: answer += 1 return answer
17.424242
54
0.514783
ae28237935854c3b5186a1f32ff14011b3407c0a
750
cs
C#
src/Giger/Filters/ColorMatrixFilterEffect.cs
bendetat/chvart
7149233955654aa53c2cae91963299d17893a4a3
[ "MIT" ]
1
2015-10-05T08:11:48.000Z
2015-10-05T08:11:48.000Z
src/Giger/Filters/ColorMatrixFilterEffect.cs
bendetat/chvart
7149233955654aa53c2cae91963299d17893a4a3
[ "MIT" ]
14
2015-09-04T09:06:18.000Z
2016-07-26T15:08:12.000Z
src/Giger/Filters/ColorMatrixFilterEffect.cs
bendetat/chvart
7149233955654aa53c2cae91963299d17893a4a3
[ "MIT" ]
null
null
null
using System.Xml; using Giger.Plumbing; namespace Giger.Filters { public class ColorMatrixFilterEffect : FilterEffect<ColorMatrixFilterEffect> { public ColorMatrixFilterEffect(double[] matrix, string filterInput, string resultName) : base(filterInput, resultName) { SetAttr("values", matrix.ToMatrix(4, 5).ToString()); } public ColorMatrixFilterEffect(string matrix, string filterInput, string resultName) : base(filterInput, resultName) { SetAttr("values", matrix.ToMatrix(4, 5).ToString()); } protected override XmlNode GetXmlNode(XmlDocument doc) { return doc.CreateSvgElement("feColorMatrix"); } } }
30
94
0.64
dde6a21db3655f1bc726374c7ff5e86144b99219
765
java
Java
src/main/java/com/github/appreciated/apexcharts/config/Theme.java
yurili8/apexcharts-flow
4cc29394bf45bab81fcdd439bed910987ecc2a16
[ "Apache-2.0" ]
38
2019-05-01T19:47:47.000Z
2022-03-20T11:26:04.000Z
src/main/java/com/github/appreciated/apexcharts/config/Theme.java
yurili8/apexcharts-flow
4cc29394bf45bab81fcdd439bed910987ecc2a16
[ "Apache-2.0" ]
111
2019-04-27T13:56:01.000Z
2022-02-28T11:37:11.000Z
src/main/java/com/github/appreciated/apexcharts/config/Theme.java
yurili8/apexcharts-flow
4cc29394bf45bab81fcdd439bed910987ecc2a16
[ "Apache-2.0" ]
34
2019-06-07T09:51:43.000Z
2022-01-23T18:57:45.000Z
package com.github.appreciated.apexcharts.config; import com.github.appreciated.apexcharts.config.theme.Mode; import com.github.appreciated.apexcharts.config.theme.Monochrome; public class Theme { private Mode mode; private String palette; private Monochrome monochrome; public Theme() { } public Mode getMode() { return mode; } public String getPalette() { return palette; } public Monochrome getMonochrome() { return monochrome; } public void setMode(Mode mode) { this.mode = mode; } public void setPalette(String palette) { this.palette = palette; } public void setMonochrome(Monochrome monochrome) { this.monochrome = monochrome; } }
19.125
65
0.656209
bea25471b331cfe986cb4f2e460dbef4033a7e01
2,667
kt
Kotlin
shared/src/main/kotlin/me/saket/press/shared/sync/git/PlatformFile.kt
federicoviceconti/press
fe8de073b3b86f5c33ac5760be03456949095205
[ "Apache-2.0" ]
null
null
null
shared/src/main/kotlin/me/saket/press/shared/sync/git/PlatformFile.kt
federicoviceconti/press
fe8de073b3b86f5c33ac5760be03456949095205
[ "Apache-2.0" ]
null
null
null
shared/src/main/kotlin/me/saket/press/shared/sync/git/PlatformFile.kt
federicoviceconti/press
fe8de073b3b86f5c33ac5760be03456949095205
[ "Apache-2.0" ]
null
null
null
package me.saket.press.shared.sync.git import okio.buffer import okio.sink import okio.source import java.io.File as JavaFile actual class PlatformFile constructor(private val delegate: JavaFile) : File { actual constructor(parentPath: String, name: String) : this(JavaFile(parentPath, name)) actual constructor(path: String) : this(JavaFile(path)) override val path: String get() = delegate.path override val name: String get() = delegate.name override val exists: Boolean get() = delegate.exists() override val parent: File? get() = delegate.parentFile?.let(::PlatformFile) override val isDirectory: Boolean get() = delegate.isDirectory override fun write(input: String) { delegate.sink().buffer().use { it.writeUtf8(input) } } override fun read(): String { delegate.source().buffer().use { return it.readUtf8() } } override fun copy(name: String, recursively: Boolean): File { check(exists) check(delegate.parent != null) check(recursively) { "todo non-recursive copy" } val targetDelegate = JavaFile(delegate.parent, name) val copied = delegate.copyRecursively(target = targetDelegate, overwrite = true) check(copied) { "Couldn't copy file ($this) to $name" } return PlatformFile(targetDelegate) } override fun renameTo(newFile: File): File { check(this.path != newFile.path) check(this.exists) { "$path doesn't exist" } val renamedFile = File(newFile.path).apply { check(!exists) if (!parent!!.exists) parent!!.makeDirectory(recursively = true) } val renamed = delegate.renameTo(JavaFile(renamedFile.path)) check(renamed) { "Couldn't rename ($this) to $newFile" } return renamedFile } override fun makeDirectory(recursively: Boolean) { if (recursively) { delegate.mkdirs() } else { delegate.mkdir() } } override fun delete(recursively: Boolean) { check(exists) { "$name does not exist: $path" } if (recursively) { delegate.deleteRecursively() } else { check(delegate.delete()) { "Failed to delete file: $this" } } } private fun JavaFile.deleteRecursively() { if (isDirectory) { for (child in listFiles()!!) { child.deleteRecursively() } } check(delete()) { "Failed to delete file: $this" } } override fun children(): List<File> { check(exists) check(delegate.isDirectory) val children = delegate.listFiles() ?: error("Can't print children. Exists? $exists. Path: $path") return children.map { PlatformFile(it) } } override fun toString(): String { return "${delegate.name} (${delegate.path})" } }
28.98913
102
0.666667
d00efe6af0f1f098435207007496ec9c0ad7b9e3
498
rb
Ruby
app/models/reservation.rb
RokoVarano/hotel_services_backend
1fae1b123558053997c0b2a9b7f842c014f1b253
[ "MIT" ]
null
null
null
app/models/reservation.rb
RokoVarano/hotel_services_backend
1fae1b123558053997c0b2a9b7f842c014f1b253
[ "MIT" ]
74
2021-11-17T19:52:17.000Z
2021-12-02T16:11:50.000Z
app/models/reservation.rb
RokoVarano/hotel_services_backend
1fae1b123558053997c0b2a9b7f842c014f1b253
[ "MIT" ]
null
null
null
class Reservation < ApplicationRecord belongs_to :user belongs_to :service validates :date, presence: true validates :city, presence: true def as_json(_options = {}) service = Service.find(service_id) { reservation_id: id, service_name: service.name, service_description: service.description, image_url: service.image_url, date: { day: date.day, month: date.month, year: date.year }, city: city } end end
19.92
47
0.63253
ccca0eafed6ebfd66b74899095a42c09fc823803
2,024
h
C
src/DenseSLAM/PrecomputedDepthProvider.h
Hansry/DenseSLAM-Global-Consistency-h
8ed653eaae9821dd262b90218e5e8fa60ec6b814
[ "BSD-3-Clause" ]
5
2019-11-14T03:18:38.000Z
2022-02-21T07:43:47.000Z
src/DenseSLAM/PrecomputedDepthProvider.h
Hansry/DenseSLAM-Global-Consistency-h
8ed653eaae9821dd262b90218e5e8fa60ec6b814
[ "BSD-3-Clause" ]
4
2019-11-09T05:20:52.000Z
2021-02-02T22:18:11.000Z
src/DenseSLAM/PrecomputedDepthProvider.h
Hansry/DenseSLAM-Global-Consistency-h
8ed653eaae9821dd262b90218e5e8fa60ec6b814
[ "BSD-3-Clause" ]
null
null
null
#ifndef DENSESLAM_PRECOMPUTEDDEPTHPROVIDER_H #define DENSESLAM_PRECOMPUTEDDEPTHPROVIDER_H #include <string> #include "DepthProvider.h" #include "Input.h" /// \brief 视差图和深度图都是从本地读取的,并不是通过双目进行实时的视差图计算 namespace SparsetoDense { extern const std::string kDispNetName; extern const std::string kPrecomputedElas; /// \brief Reads precomputed disparity (default) or depth maps from a folder. /// The depth maps are expected to be grayscale, and in short 16-bit or float 32-bit format. class PrecomputedDepthProvider : public DepthProvider { public: PrecomputedDepthProvider( Input *input, const std::string &folder, const std::string &fname_format, bool input_is_depth, float min_depth_m, float max_depth_m) : DepthProvider(input_is_depth, min_depth_m, max_depth_m), input_(input), folder_(folder), fname_format_(fname_format) {} PrecomputedDepthProvider(const PrecomputedDepthProvider&) = delete; PrecomputedDepthProvider(PrecomputedDepthProvider&&) = delete; PrecomputedDepthProvider& operator=(const PrecomputedDepthProvider&) = delete; PrecomputedDepthProvider& operator=(PrecomputedDepthProvider&&) = delete; ~PrecomputedDepthProvider() override = default; /// \brief Loads the precomputed depth map for the specified frame into 'out_depth'. void GetDepth(int frame_idx, StereoCalibration& calibration, cv::Mat1s& out_depth, float scale) override; void GetDepth(double frame_idx, StereoCalibration& calibration, cv::Mat1s& out_depth, float scale) override; protected: /// \brief Reads a disparity or depth (depending on the data). template<typename T> void ReadPrecomputed(T frame_idx, cv::Mat &out) const; private: Input *input_; std::string folder_; /// \brief The printf-style format of the frame filenames, such as "frame-%04d.png" for frames /// which are called "frame-0000.png"-"frame-9999.png". std::string fname_format_; }; } // namespace SparsetoDense #endif //DENSESLAM_PRECOMPUTEDDEPTHPROVIDER_H
34.305085
110
0.755435
c61166bbe9054a3dc8ecb9198b0e0d8641a16942
2,782
swift
Swift
anagram.playground/Contents.swift
risinggalaxy/swift-challenges
e2c979a4e0c011fe3efe6c5c08e5a14f87a6d1e6
[ "MIT" ]
null
null
null
anagram.playground/Contents.swift
risinggalaxy/swift-challenges
e2c979a4e0c011fe3efe6c5c08e5a14f87a6d1e6
[ "MIT" ]
null
null
null
anagram.playground/Contents.swift
risinggalaxy/swift-challenges
e2c979a4e0c011fe3efe6c5c08e5a14f87a6d1e6
[ "MIT" ]
null
null
null
import Foundation import XCTest // Challenge: Given two strings, write an algorithm to detect whether one word is an anagram of the other. // An anagram is a word that can be made by changing the order of the letters in another word. // // For example: // tar => rat // state => taste class Anagram { func simpleSolution( _ a: String, _ b: String) -> Bool { let start = Date() let resA = a.lowercased().sorted() let resB = b.lowercased().sorted() let end = Date() let component = Calendar.current.dateComponents([.nanosecond], from: start, to: end) let milliSeconds = Double(component.nanosecond! / 1000000) print("simpleSolution Runtime : \(milliSeconds) ") return resA == resB } func complexSolution( _ a: String, _ b: String ) -> Bool { let start = Date() guard a.count == b.count else { return false } let aChars = Array(a.lowercased()) let bChars = Array(b.lowercased()) var hashMap = [Character: Bool]() var found: Bool = false for c in aChars { hashMap[c] = true } for c in bChars { if hashMap[c] != nil { found = true continue } else { found = false break } } let end = Date() let component = Calendar.current.dateComponents([.nanosecond], from: start, to: end) let milliSeconds = Double(component.nanosecond! / 1000000) print("complexSolution Runtime : \(milliSeconds) ") return !found ? false : true } } class TestAnagram: XCTestCase { var sut: Anagram! override func setUp() { super.setUp() sut = Anagram() } override func tearDown() { sut = nil super.tearDown() } func testSimpleSimpleSolutionShouldPass() { let result = sut.simpleSolution("night", "thing") XCTAssertTrue(result) } func testSimpleSimpleSolutionReturnsFalse() { let result = sut.simpleSolution("tight", "thing") XCTAssertFalse(result) } func testSimpleComplexSolutionShouldPass() { let result = sut.complexSolution("night", "thing") XCTAssertTrue(result) } func testSimpleComplexSolutionReturnsFalse() { let result = sut.complexSolution("tight", "thing") XCTAssertFalse(result) } } class TestObservation: NSObject, XCTestObservation { func testCase(_ testCase: XCTestCase, didRecord issue: XCTIssue) { assertionFailure(issue.description) } } let testObservation = TestObservation() XCTestObservationCenter.shared.addTestObserver(testObservation) XCTestSuite.default.run()
28.680412
106
0.601006
d317aca80fc9da14328e478bcce8ffec22f5590d
4,859
cs
C#
DataTools/Graphs/Graph/Graph.cs
D15190304050/CSharpConsole2017
f85d9a3dcac2f6532f18694ced6ada1bd5be7d8b
[ "MIT" ]
2
2018-10-09T07:08:58.000Z
2021-05-12T10:23:17.000Z
DataTools/Graphs/Graph/Graph.cs
D15190304050/CSharpConsole2017
f85d9a3dcac2f6532f18694ced6ada1bd5be7d8b
[ "MIT" ]
null
null
null
DataTools/Graphs/Graph/Graph.cs
D15190304050/CSharpConsole2017
f85d9a3dcac2f6532f18694ced6ada1bd5be7d8b
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataTools.Graphs.UndirectedGraph { using Collections; public class Graph { // Adjacency lists. private LinkedList<int>[] adjacent; /// <summary> /// Create a V-vertex graph with no edges. /// </summary> /// <param name="V"></param> public Graph(int V) { this.V = V; E = 0; // Create array of lists. adjacent = new LinkedList<int>[V]; // Initialize all lists to empty. for (int v = 0; v < V; v++) adjacent[v] = new LinkedList<int>(); } /// <summary> /// Read a graph from a file. /// </summary> /// <param name="fullFileName"></param> public Graph(string fullFileName) { // Read complete content from file. string text = System.IO.File.ReadAllText(fullFileName); // Split content into individual strings. string[] numberString = System.Text.RegularExpressions.Regex.Split(text, "\\s+"); // Convert numberString into numbers. int[] numbers = new int[numberString.Length]; for (int i = 0; i < numberString.Length; i++) numbers[i] = int.Parse(numberString[i]); // Get V and E from numbers[]. V = numbers[0]; // To distinguish from this.E and make it easy to add edge to this graph in the following procedure.. int E = numbers[1]; if (V < 0 || E < 0) throw new ArgumentOutOfRangeException("Number of vertex or edges must be non-negative."); // Create array of adjacency lists. adjacent = new LinkedList<int>[V]; // Initialize all adjacency lists to empty. for (int v = 0; v < V; v++) adjacent[v] = new LinkedList<int>(); // Add edges from numbers[]. for (int i = 1; i <= E; i++) AddEdge(numbers[2 * i], numbers[2 * i + 1]); } public Graph(Graph G) : this(G.V) { E = G.E; // Reverse so that adjacency list is in same order as original. for (int v = 0; v < V; v++) { Stack<int> reverse = new Stack<int>(); foreach (int w in G.adjacent[v]) reverse.Push(w); foreach (int w in reverse) adjacent[v].AddFirst(w); } } /// <summary> /// Number of vertices. /// </summary> public int V { get; private set; } /// <summary> /// Number of edges. /// </summary> public int E { get; private set; } /// <summary> /// Add edge v-w to this graph. /// </summary> /// <param name="v"></param> /// <param name="w"></param> public void AddEdge(int v, int w) { // Add w to v's list. adjacent[v].AddFirst(w); // Add v to w's list. adjacent[w].AddFirst(v); // Increase the edgd count. E++; } /// <summary> /// Vertices adjacent to v. /// </summary> /// <param name="v"></param> /// <returns></returns> public IEnumerable<int> Adjacent(int v) { ValidateVertex(v); return adjacent[v]; } /// <summary> /// Returns the degree of vertex. /// </summary> /// <param name="v"></param> /// <returns></returns> public int Degree(int v) { ValidateVertex(v); return adjacent[v].Size; } /// <summary> /// Throw an ArgumentOutOfRangeException unless 0 &le; v &lt; V /// </summary> /// <param name="v"></param> private void ValidateVertex(int v) { if (v < 0 || v >= V) throw new ArgumentOutOfRangeException("Vertex " + v + " is not between 0 and " + (V - 1)); } /// <summary> /// String representation. /// </summary> /// <returns></returns> public override string ToString() { // Use StringBuilder to accelerate the processing. StringBuilder s = new StringBuilder(); s.Append(V).Append(" vertices ").Append(E).Append(" edges\n"); for (int v = 0; v < V; v++) { s.Append(v).Append(": "); foreach (int w in Adjacent(v)) s.Append(w).Append(" "); s.Append("\n"); } return s.ToString(); } } }
29.271084
113
0.471085
57f282f3ec9b11b18bb0d8e2bcfb5ef5d4561afe
3,138
php
PHP
src/Config/system.php
mmrtonmoybd/Bagisto-Sslcommerz-Payment-Gateway
d428bde8e52ab100a4870e699611164e248e4919
[ "MIT" ]
null
null
null
src/Config/system.php
mmrtonmoybd/Bagisto-Sslcommerz-Payment-Gateway
d428bde8e52ab100a4870e699611164e248e4919
[ "MIT" ]
null
null
null
src/Config/system.php
mmrtonmoybd/Bagisto-Sslcommerz-Payment-Gateway
d428bde8e52ab100a4870e699611164e248e4919
[ "MIT" ]
null
null
null
<?php return [ [ 'key' => 'sales.paymentmethods.sslcommerz', 'name' => 'admin::app.admin.system.sslcommerz', 'sort' => 5, 'fields' => [ [ 'name' => 'title', 'title' => 'admin::app.admin.system.title', 'type' => 'text', 'validation' => 'required', 'channel_based' => false, 'locale_based' => true, ], [ 'name' => 'description', 'title' => 'admin::app.admin.system.description', 'type' => 'textarea', 'channel_based' => false, 'locale_based' => true, ], [ 'name' => 'sslcommerz_store_id', 'title' => 'admin::app.admin.system.sslcommerz-store-id', 'type' => 'text', 'validation' => 'required', 'channel_based' => false, 'locale_based' => true, ], [ 'name' => 'sslcommerz_store_password', 'title' => 'admin::app.admin.system.sslcommerz-store-password', 'type' => 'text', 'validation' => 'required', 'channel_based' => false, 'locale_based' => true, ], [ 'name' => 'sandbox', 'title' => 'admin::app.admin.system.sandbox', 'type' => 'boolean', 'validation' => 'required', 'channel_based' => false, 'locale_based' => true, ], [ 'name' => 'sslcommerz_connect_from_localhost', 'title' => 'admin::app.admin.system.sslcommerz-connect-from-localhost', 'type' => 'boolean', 'validation' => 'required', 'channel_based' => false, 'locale_based' => true, ], [ 'name' => 'active', 'title' => 'admin::app.admin.system.status', 'type' => 'boolean', 'validation' => 'required', 'channel_based' => false, 'locale_based' => true, ], [ 'name' => 'sort', 'title' => 'admin::app.admin.system.sort_order', 'type' => 'select', 'options' => [ [ 'title' => '1', 'value' => 1, ], [ 'title' => '2', 'value' => 2, ], [ 'title' => '3', 'value' => 3, ], [ 'title' => '4', 'value' => 4, ], ], ] ] ] ];
36.917647
95
0.321224
c8dc6bb7fc6e35608c2ccdc17e0dc5c48ef9e005
1,615
kt
Kotlin
ontrack-ui/src/test/java/net/nemerosa/ontrack/boot/ProjectSearchProviderIT.kt
pavelerofeev/ontrack
a71e281890e831fc56d4eb26ee68ed59bd157f2f
[ "MIT" ]
null
null
null
ontrack-ui/src/test/java/net/nemerosa/ontrack/boot/ProjectSearchProviderIT.kt
pavelerofeev/ontrack
a71e281890e831fc56d4eb26ee68ed59bd157f2f
[ "MIT" ]
null
null
null
ontrack-ui/src/test/java/net/nemerosa/ontrack/boot/ProjectSearchProviderIT.kt
pavelerofeev/ontrack
a71e281890e831fc56d4eb26ee68ed59bd157f2f
[ "MIT" ]
null
null
null
package net.nemerosa.ontrack.boot import net.nemerosa.ontrack.it.AbstractDSLTestSupport import net.nemerosa.ontrack.model.structure.NameDescription import net.nemerosa.ontrack.test.TestUtils.uid import org.junit.Test import org.springframework.beans.factory.annotation.Autowired import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertTrue class ProjectSearchProviderIT : AbstractDSLTestSupport() { @Autowired private lateinit var projectSearchProvider: ProjectSearchProvider @Test fun `Project search by exact name`() { val project = project {} val results = projectSearchProvider.search(project.name) val result = results.find { it.title == "Project ${project.name}" } assertNotNull(result) } @Test fun `Project search by short token does not return any result`() { val prefix = uid("PP") // Creates three projects with the same prefix (1..3).map { doCreateProject(NameDescription.nd(uid(prefix), "")) } // Search with short prefix (<=3) does not return anything val results = projectSearchProvider.search("PP") assertTrue(results.isEmpty(), "No result") } @Test fun `Project search by content`() { val prefix = uid("PP") // Creates three projects with the same prefix (1..3).map { doCreateProject(NameDescription.nd(uid(prefix), "")) } // Search with short prefix (<=3) does not return anything val results = projectSearchProvider.search(prefix) assertEquals(3, results.size) } }
34.361702
75
0.68483
47da871e06f6ac07fefca61fbe6be670a23b35e2
1,976
swift
Swift
TyokinshiAI_JPHACKS2018/ViewController3.swift
jphacks/SP_1801
fcd6e1ce88f69d9f0e2d83889532ced5f72f07c7
[ "MIT" ]
1
2018-10-21T03:36:48.000Z
2018-10-21T03:36:48.000Z
TyokinshiAI_JPHACKS2018/ViewController3.swift
jphacks/SP_1801
fcd6e1ce88f69d9f0e2d83889532ced5f72f07c7
[ "MIT" ]
null
null
null
TyokinshiAI_JPHACKS2018/ViewController3.swift
jphacks/SP_1801
fcd6e1ce88f69d9f0e2d83889532ced5f72f07c7
[ "MIT" ]
null
null
null
// // ViewController3.swift // TyokinshiAI_JPHACKS2018 // // Created by 中井崚日 on 2018/10/20. // Copyright © 2018年 中井崚日. All rights reserved. // import Foundation import UIKit class ViewController3: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var pickerView: UIPickerView! @IBOutlet weak var Label_tyokingaku: UILabel! var vc2_save = 0 // 選択肢 let dataList = ["0", "50", "100", "200", "300", "400", "500"] override func viewDidLoad() { super.viewDidLoad() // Delegate設定 pickerView.delegate = self pickerView.dataSource = self } // UIPickerViewの列の数 func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } // UIPickerViewの行数、リストの数 func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return dataList.count } // UIPickerViewの最初の表示 func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return dataList[row] } var picker_value_save = "" // UIPickerViewのRowが選択された時の挙動 func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { print(dataList[row]) Label_tyokingaku.text = dataList[row] picker_value_save = dataList[row] } /*数値を別の画面の変数に引き継ぐ*/ // Segue 準備 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { //if (segue.identifier == "undoViewController2.1") { // SecondViewControllerをインスタンス化 let mainVc: ViewController2 = (segue.destination as? ViewController2)! // 値を渡す mainVc.myStr = Int(picker_value_save)! + vc2_save //} } }
25.662338
87
0.589069
bb881d7c7fc2f4bd41929f4b83564e36d1db9657
1,673
cs
C#
src/dotnetCampus.Ipc/Utils/Extensions/LoggerExtensions.cs
dotnet-campus/dotnetCampus.Ipc
da543d3483cdecbeb3efcd7080150b17d92de8fa
[ "MIT" ]
75
2020-10-08T22:30:28.000Z
2022-02-26T00:53:00.000Z
src/dotnetCampus.Ipc/Utils/Extensions/LoggerExtensions.cs
dotnet-campus/dotnetCampus.Ipc
da543d3483cdecbeb3efcd7080150b17d92de8fa
[ "MIT" ]
9
2020-10-20T12:28:52.000Z
2022-03-16T08:33:13.000Z
src/dotnetCampus.Ipc/Utils/Extensions/LoggerExtensions.cs
dotnet-campus/dotnetCampus.Ipc
da543d3483cdecbeb3efcd7080150b17d92de8fa
[ "MIT" ]
7
2021-09-26T01:50:32.000Z
2022-02-17T01:06:59.000Z
using System; using dotnetCampus.Ipc.Utils.Logging; namespace dotnetCampus.Ipc.Utils.Extensions { internal static class LoggerExtensions { public static void Trace(this ILogger? logger, string message) { logger?.Log(LogLevel.Trace, default, 0, null, (s, e) => message); } public static void Debug(this ILogger? logger, string message) { logger?.Log(LogLevel.Debug, default, 0, null, (s, e) => message); } public static void Information(this ILogger? logger, string message) { logger?.Log(LogLevel.Information, default, 0, null, (s, e) => message); } public static void Warning(this ILogger? logger, string message) { if (logger is null) { System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:hh:mm:ss.fff}] [IPC] [Warning] {message}"); } else { logger?.Log(LogLevel.Warning, default, 0, null, (s, e) => message); } } public static void Error(this ILogger? logger, string message) { if (logger is null) { System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:hh:mm:ss.fff}] [IPC] [Error] {message}"); } else { logger?.Log(LogLevel.Error, default, 0, null, (s, e) => message); } } public static void Error(this ILogger? logger, Exception exception, string? message = null) { logger?.Log(LogLevel.Error, default, 0, exception, (s, e) => message ?? ""); } } }
30.981481
111
0.534369
5675d549a5154d328d19098e4bdce569eb1b60c6
2,117
rs
Rust
examples/cursor_grab.rs
fnune/tao
cbd4cdbeb8a36bf1dbc64ce2e10a55fe3ce6b5b4
[ "Apache-2.0" ]
null
null
null
examples/cursor_grab.rs
fnune/tao
cbd4cdbeb8a36bf1dbc64ce2e10a55fe3ce6b5b4
[ "Apache-2.0" ]
null
null
null
examples/cursor_grab.rs
fnune/tao
cbd4cdbeb8a36bf1dbc64ce2e10a55fe3ce6b5b4
[ "Apache-2.0" ]
null
null
null
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 use simple_logger::SimpleLogger; use tao::{ event::{DeviceEvent, ElementState, Event, KeyEvent, WindowEvent}, event_loop::{ControlFlow, EventLoop}, keyboard::{Key, ModifiersState}, window::WindowBuilder, }; #[allow(clippy::single_match)] fn main() { SimpleLogger::new().init().unwrap(); let event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("Super Cursor Grab'n'Hide Simulator 9000") .build(&event_loop) .unwrap(); let mut modifiers = ModifiersState::default(); event_loop.run(move |event, _, control_flow| { *control_flow = ControlFlow::Wait; match event { Event::WindowEvent { event, .. } => match event { WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit, WindowEvent::KeyboardInput { event: KeyEvent { logical_key: key, state: ElementState::Released, .. }, .. } => { // WARNING: Consider using `key_without_modifers()` if available on your platform. // See the `key_binding` example match key { Key::Escape => *control_flow = ControlFlow::Exit, Key::Character(ch) => match ch.to_lowercase().as_str() { "g" => window.set_cursor_grab(!modifiers.shift_key()).unwrap(), "h" => window.set_cursor_visible(modifiers.shift_key()), _ => (), }, _ => (), } } WindowEvent::ModifiersChanged(m) => modifiers = m, _ => (), }, Event::DeviceEvent { event, .. } => match event { DeviceEvent::MouseMotion { delta } => println!("mouse moved: {:?}", delta), DeviceEvent::Button { button, state } => match state { ElementState::Pressed => println!("mouse button {} pressed", button), ElementState::Released => println!("mouse button {} released", button), }, _ => (), }, _ => (), } }); }
32.075758
92
0.569674
dfae6b4e4a8711995f850547ea9e032a6cab9094
566
cs
C#
MvcDocumentation/DaisyDocumentationController.cs
heneryville/Daisy
bc53a1809ad6046e05f4e3f1ccf417583d0a7b5d
[ "MIT" ]
4
2018-01-02T12:33:39.000Z
2021-02-25T02:55:45.000Z
MvcDocumentation/DaisyDocumentationController.cs
heneryville/Daisy
bc53a1809ad6046e05f4e3f1ccf417583d0a7b5d
[ "MIT" ]
null
null
null
MvcDocumentation/DaisyDocumentationController.cs
heneryville/Daisy
bc53a1809ad6046e05f4e3f1ccf417583d0a7b5d
[ "MIT" ]
1
2021-07-27T11:19:43.000Z
2021-07-27T11:19:43.000Z
namespace Ancestry.Daisy.Documentation.MVC { using System.Collections.Generic; using System.IO; using System.Web.Mvc; using Ancestry.Daisy.Statements; using RazorEngine.Templating; public class DaisyDocumentationController : Controller { public ActionResult Index() { var model = (DaisyDocumentationViewModel)this.RouteData.DataTokens["docSet"]; return new CompiledRazorView("Ancestry.Daisy.Documentation.MVC.Views.DaisyDocumentation.Index.cshtml", model); } } }
28.3
123
0.673145
c98c8319a3f4c9086ed82fe08c3b905677735a01
201
tsx
TypeScript
packages/fluentui/docs/src/examples/components/Pill/State/PillExampleDisabled.tsx
hetanthakkar1/fluentui
fb53fd67729d8236e0681d74322717f6974c8b72
[ "MIT" ]
7,194
2016-07-21T19:41:05.000Z
2020-03-20T11:30:44.000Z
packages/fluentui/docs/src/examples/components/Pill/State/PillExampleDisabled.tsx
hetanthakkar1/fluentui
fb53fd67729d8236e0681d74322717f6974c8b72
[ "MIT" ]
10,472
2016-07-21T22:56:20.000Z
2020-03-20T19:50:35.000Z
packages/fluentui/docs/src/examples/components/Pill/State/PillExampleDisabled.tsx
hetanthakkar1/fluentui
fb53fd67729d8236e0681d74322717f6974c8b72
[ "MIT" ]
1,664
2016-07-22T03:30:48.000Z
2020-03-19T05:23:44.000Z
import * as React from 'react'; import { Pill } from '@fluentui/react-northstar'; const PillExampleDisabled = () => <Pill disabled>This is a disabled Pill</Pill>; export default PillExampleDisabled;
28.714286
80
0.741294
ba06e76e074af08194b819f045e2c0a9b1d19ad0
5,812
go
Go
scheme/bitrix24/contact.go
vilamslep/bx24sync
b08d2d7df40867cc2b9efd2961e257532b1a8aa4
[ "MIT" ]
null
null
null
scheme/bitrix24/contact.go
vilamslep/bx24sync
b08d2d7df40867cc2b9efd2961e257532b1a8aa4
[ "MIT" ]
null
null
null
scheme/bitrix24/contact.go
vilamslep/bx24sync
b08d2d7df40867cc2b9efd2961e257532b1a8aa4
[ "MIT" ]
null
null
null
package bitrix24 import ( "bytes" "encoding/json" "fmt" "io" "strings" "unicode" "github.com/vilamslep/bx24sync/scheme/bitrix24/converter" "github.com/vilamslep/bx24sync/scheme/sql" ) const ( findContact = "crm.contact.list" addContact = "crm.contact.add" updateContact = "crm.contact.update" ) type Contact struct { Id string `json:"ORIGIN_ID"` Name string `json:"NAME"` SecondName string `json:"SECOND_NAME"` LastName string `json:"LAST_NAME"` Birthday string `json:"BIRTHDATE"` Gender converter.Gender `json:"UF_CRM_1587720922"` ConnectionWay converter.ConnectionWay `json:"UF_CRM_1612972723496"` ThereIsContract bool `json:"UF_CRM_1584964931121"` SendAds bool `json:"UF_CRM_1584970848775"` NotSendAds bool `json:"UF_CRM_1636547489168"` IsInternetClient bool `json:"UF_CRM_1585077731269"` IsOfflineClient bool `json:"UF_CRM_1585077757363"` IsClinicClient bool `json:"UF_CRM_1585077767559"` DiscountClinicService uint8 `json:"UF_CRM_1587720973"` DiscountMedicalThings uint8 `json:"UF_CRM_1587720952"` DiscountRayban uint8 `json:"UF_CRM_1587720989"` Phone []converter.ContactData `json:"PHONE"` Email []converter.ContactData `json:"EMAIL"` } func (s *Contact) transforName(val string) { //length onlyNameAndLastName, fullName := 2, 3 val = removeNumbers(val) pathName := strings.Split(val, " ") length := len(pathName) if length >= fullName { s.LastName, s.Name, s.SecondName = pathName[0], pathName[1], pathName[2] } else if length == onlyNameAndLastName { s.LastName, s.Name = pathName[0], pathName[1] } else { s.Name = val } } func (c *Contact) Json() ([]byte, error) { return json.Marshal(c) } func NewContactFromJson(raw []byte) (contact Contact, err error) { err = json.Unmarshal(raw, &contact) return contact, err } func (c Contact) Find(restUrl string) (response BitrixRestResponseFind, err error) { if restUrl[len(restUrl)-1:] == "/" { restUrl = restUrl[:len(restUrl)-1] } url := fmt.Sprintf("%s/%s?filter[ORIGIN_ID]=%s", restUrl, findContact, c.Id) if res, err := ExecReq("GET", url, nil); err == nil { return checkResponseFind(res) } else { return response, err } } func (c Contact) Add(restUrl string) (response BitrixRestResponseAdd, err error) { if restUrl[len(restUrl)-1:] == "/" { restUrl = restUrl[:len(restUrl)-1] } url := fmt.Sprintf("%s/%s", restUrl, addContact) rd, err := c.getReader() if err != nil { return response, err } if res, err := ExecReq("POST", url, rd); err == nil { return checkResponseAdd(res) } else { return response, err } } // for cleaning contact data at first need to get id entity // array should be such as // [ // "$entityId" => { // "VALUE_TYPE" => "WORK", // "VALUE" => "", // "TYPE_ID" => "PHONE" // } // ] func (c Contact) Update(restUrl string, id string) (response BitrixRestResponseUpdate, err error) { if restUrl[len(restUrl)-1:] == "/" { restUrl = restUrl[:len(restUrl)-1] } url := fmt.Sprintf("%s/%s?id=%s", restUrl, updateContact, id) rd, err := c.getReader() if err != nil { return response, err } if res, err := ExecReq("POST", url, rd); err == nil { return checkResponseUpdate(res) } else { return response, err } } func (c Contact) getReader() (rd io.Reader, err error) { data := make(map[string]Contact) data["fields"] = c if content, err := json.Marshal(data); err == nil { return bytes.NewReader(content), err } else { return rd, err } } func removeNumbers(val string) (res string) { for _, ch := range val { if !unicode.IsNumber(ch) { res += string(ch) } } return res } func GetContactsFromRaw(reader io.Reader) (data [][]byte, err error) { content, err := io.ReadAll(reader) if err != nil { return data, err } raw := make([]map[string]string, 0) err = json.Unmarshal(content, &raw) if err != nil { return } for _, v := range raw { rwClient, err := json.Marshal(v) if err != nil { return data, err } client := sql.Client{} json.Unmarshal(rwClient, &client) if err != nil { return data, err } contact := newContactFromClient(client) if result, err := contact.Json(); err == nil { data = append(data, result) } else { return data, err } } return data, err } func newContactFromClient(client sql.Client) Contact { c := Contact{} offset := 2000 c.Id = client.OriginId c.Birthday = converter.SubtractionYearsOffset(client.Birthday, offset, "02.01.2006") c.transforName(client.Name) c.DiscountMedicalThings = converter.String(client.DiscountMedicalThings).Uint8() c.DiscountRayban = converter.String(client.DiscountRayban).Uint8() c.DiscountClinicService = converter.String(client.DiscountClinicService).Uint8() c.Gender = converter.String(client.Gender).GenderCode() c.ConnectionWay = converter.String(client.ConnectionWay).ConnectionWay() c.ThereIsContract = converter.String(client.ThereIsContract).BinaryTrue() c.IsOfflineClient = converter.String(client.IsOfflineClient).BinaryTrue() c.IsInternetClient = converter.String(client.IsInternetClient).BinaryTrue() c.SendAds = converter.String(client.SendAds).BinaryTrue() c.IsClinicClient = converter.String(client.IsClinicClient).BinaryTrue() c.Phone = converter.String(client.Phone).ContactDataSlice(";", "WORK", "PHONE") c.Email = converter.String(client.Email).ContactDataSlice(";", "WORK", "EMAIL") return c }
26.298643
99
0.640227
79c56efada8996ee14c5c9c5e2e67fa01b109de2
594
php
PHP
src/Targets.php
integer-net/callback-proxy
044046774a329a37ddc2039ed3130e8a59c35d36
[ "MIT" ]
null
null
null
src/Targets.php
integer-net/callback-proxy
044046774a329a37ddc2039ed3130e8a59c35d36
[ "MIT" ]
4
2018-10-30T14:04:33.000Z
2019-03-12T09:18:11.000Z
src/Targets.php
integer-net/callback-proxy
044046774a329a37ddc2039ed3130e8a59c35d36
[ "MIT" ]
null
null
null
<?php declare(strict_types=1); namespace IntegerNet\CallbackProxy; /** * @method \ArrayIterator getInnerIterator() */ class Targets extends \IteratorIterator { public function __construct(Target ...$targets) { parent::__construct(new \ArrayIterator($targets)); } public function current(): Target { return parent::current(); } public static function fromConfig(array $config): self { return new self( ...array_map( [Target::class, 'fromConfig'], $config ) ); } }
18.5625
58
0.577441
da74c8b6ac896557838d9658ca5f266f0b04051c
228
php
PHP
app/Schedule/Tasks/UpdateDailyTop10.php
ddechant/Gazelle
87e0776747250e19f179e0ef7d3c0a808ccb7d44
[ "Unlicense" ]
169
2018-10-10T00:57:15.000Z
2022-03-18T11:10:03.000Z
app/Schedule/Tasks/UpdateDailyTop10.php
ddechant/Gazelle
87e0776747250e19f179e0ef7d3c0a808ccb7d44
[ "Unlicense" ]
130
2018-10-29T16:46:17.000Z
2022-03-14T07:33:32.000Z
app/Schedule/Tasks/UpdateDailyTop10.php
ddechant/Gazelle
87e0776747250e19f179e0ef7d3c0a808ccb7d44
[ "Unlicense" ]
78
2018-11-02T15:13:24.000Z
2022-03-07T16:51:52.000Z
<?php namespace Gazelle\Schedule\Tasks; class UpdateDailyTop10 extends \Gazelle\Schedule\Task { public function run() { $this->processed = (new \Gazelle\Manager\Torrent)->storeTop10('Daily', 'day', 1); } }
19
89
0.666667
48be36a8fdc20940d2bf0a8b1b21da7d86abb122
2,609
dart
Dart
lib/Models/TopPodcast.dart
besemuna/flutter_podcast_app_uikit
674ba62ca1716eb5968d8cca854118b3063856ea
[ "MIT" ]
null
null
null
lib/Models/TopPodcast.dart
besemuna/flutter_podcast_app_uikit
674ba62ca1716eb5968d8cca854118b3063856ea
[ "MIT" ]
null
null
null
lib/Models/TopPodcast.dart
besemuna/flutter_podcast_app_uikit
674ba62ca1716eb5968d8cca854118b3063856ea
[ "MIT" ]
null
null
null
class PlayListDeep { String date; String title; String secondary; String time; PlayListDeep({this.date, this.title, this.secondary, this.time}); } class TopPodcast { String picture; String title; String secondary; bool favorite; List<PlayListDeep> playlist; TopPodcast( {this.picture, this.title, this.secondary, this.favorite, this.playlist}); } List<PlayListDeep> detailedPlaylist = [ PlayListDeep( date: "NOV 26, 2019", title: "10 Best Books of 2019", secondary: "On a special episode of the podcast", time: "1:14:32", ), PlayListDeep( date: "NOV 22, 2019", title: "The Authorized Life of the Iron Lady", secondary: "Charles Moore discusses the final ", time: "1:09:21", ), PlayListDeep( date: "NOV 15, 2019", title: "Revisiting Baldwin vs. Buckley", secondary: "Charles Moore discusses the final ", time: "1:09:21", ), ]; List<TopPodcast> topPodcastsHome = [ TopPodcast( picture: "assets/images/one.png", title: "The Book Review", secondary: "The New York Times", favorite: false, playlist: detailedPlaylist, ), TopPodcast( picture: "assets/images/two.png", title: "The New Yorker: Fiction", secondary: "The New Yorker", favorite: true, playlist: detailedPlaylist, ), ]; List<TopPodcast> topPodcasts = [ TopPodcast( picture: "assets/images/four.png", title: "The Guardian Books", secondary: "The Guardian", favorite: false, playlist: detailedPlaylist, ), TopPodcast( picture: "assets/images/one.png", title: "The Book Review", secondary: "The New York Times", favorite: false, playlist: detailedPlaylist, ), TopPodcast( picture: "assets/images/five.png", title: "All the Books!", secondary: "Book Riot", favorite: true, playlist: detailedPlaylist, ), TopPodcast( picture: "assets/images/six.png", title: "Audio Book Club", secondary: "Slate Magazine", favorite: false, playlist: detailedPlaylist, ), TopPodcast( picture: "assets/images/two.png", title: "The New Yorker: Fiction", secondary: "The New Yorker", favorite: true, playlist: detailedPlaylist, ), TopPodcast( picture: "assets/images/seven.png", title: "Books Of Your Life of malley", secondary: "Elizabeth Khuri Chandler", favorite: false, playlist: detailedPlaylist, ), TopPodcast( picture: "assets/images/eight.png", title: "Book Fight", secondary: "Mike Ingram and Tom McAllister", favorite: false, playlist: detailedPlaylist, ), ];
23.718182
80
0.654274
5d5ffc218e19de99143de9f6b15e26d5adb6ca41
1,148
swift
Swift
Routine/CoreLayer/Network/Models/BaseResponseModels.swift
cmuphobk/routine
9c029a16fc1356936c2bfbf73939e088af0bda19
[ "MIT" ]
null
null
null
Routine/CoreLayer/Network/Models/BaseResponseModels.swift
cmuphobk/routine
9c029a16fc1356936c2bfbf73939e088af0bda19
[ "MIT" ]
null
null
null
Routine/CoreLayer/Network/Models/BaseResponseModels.swift
cmuphobk/routine
9c029a16fc1356936c2bfbf73939e088af0bda19
[ "MIT" ]
null
null
null
import Foundation protocol DataArrayContainer { associatedtype Item var dataArray: [Item]? { get set } } struct DefaultModel: Codable { var response: String enum CodingKeys: String, CodingKey { case response } } class ArrayModel <T: Codable>: Codable, DataArrayContainer { typealias Item = T var dataArray: [Item]? init() {} required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.dataArray = try container.decode([T].self, forKey: .dataArray) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.dataArray, forKey: CodingKeys.dataArray) } enum CodingKeys: String, CodingKey { case dataArray = "result" } } protocol Entity { var identifier: String { get set } } struct IdModel: Codable, Entity { var identifier: String enum CodingKeys: String, CodingKey { case identifier = "id" } }
19.793103
75
0.609756
46c77a6723b4ffebad971f8cf90bcdee21c51251
1,001
py
Python
ATLAS.py
smhooten/MRI-Learn
6aaf7759020597adfc104ef279b08f378eb2c388
[ "MIT" ]
null
null
null
ATLAS.py
smhooten/MRI-Learn
6aaf7759020597adfc104ef279b08f378eb2c388
[ "MIT" ]
null
null
null
ATLAS.py
smhooten/MRI-Learn
6aaf7759020597adfc104ef279b08f378eb2c388
[ "MIT" ]
null
null
null
import numpy as np import nibabel as nib from nilearn import datasets class ATLAS(): def __init__(self): self.dataset_files = datasets.fetch_atlas_harvard_oxford('cort-maxprob-thr25-2mm') self.mask_img = nib.load(self.dataset_files.maps) def Print_ROIs(self): for (i,lab) in enumerate(self.dataset_files.labels): print(i,lab) def Mask(self, selectors): lens = len(selectors) if lens == 1: mask_sel = self.mask_img.get_fdata()==selectors else: mask_sel = np.zeros(self.mask_img.get_fdata().shape) for sel in selectors: mask_sel = np.logical_or(mask_sel,(self.mask_img.get_fdata()==sel)) masker = np.zeros(self.mask_img.get_fdata().shape) masker[mask_sel]=1 mask_return = nib.Nifti1Image(masker,self.mask_img.affine) return mask_return def Mask_3D(self, selector): mask = self.mask_img.get_fdata()==selector return mask
30.333333
90
0.639361
c9f90a150ee7e744ebb26d50ba34b90c8ada2d4e
948
tsx
TypeScript
src/components/App/App.tsx
codewaseem/timer-app
fd24c2485b4ce88dd85ce651f04d9db3f68911e4
[ "MIT" ]
null
null
null
src/components/App/App.tsx
codewaseem/timer-app
fd24c2485b4ce88dd85ce651f04d9db3f68911e4
[ "MIT" ]
null
null
null
src/components/App/App.tsx
codewaseem/timer-app
fd24c2485b4ce88dd85ce651f04d9db3f68911e4
[ "MIT" ]
null
null
null
import React, { ReactNode, useState, useEffect } from "react"; import { ThemeProvider } from "emotion-theming"; import theme from "~/theme"; import { setCSSVariables } from "../../utils/styles"; /** * This component exists to provide a reusable application wrapper for use in Gatsby API's, testing, etc. */ const App = ({ element }: { element: ReactNode }) => { const [themeName, setThemeName] = useState<keyof typeof theme>("light"); const [currentTheme, setTheme] = useState(theme[themeName]); const toggleTheme = () => { if (themeName === "light") { setTheme(theme.dark); setThemeName("dark"); } else { setTheme(theme.light); setThemeName("light"); } }; useEffect(() => { setCSSVariables(currentTheme.colors); }); return ( <ThemeProvider theme={{ ...currentTheme, toggleTheme, }} > {element} </ThemeProvider> ); }; export default App;
23.121951
105
0.616034
b755fae74c436939a563f178a7d1bb9e6675d203
1,106
cpp
C++
Source/src/Json Parser/DataTypeHandlers/JsonObject.cpp
codenameone-akshat/LittleJsonReader
2a28219ef494d4d3a02961d74fb90fa4829a14c5
[ "MIT" ]
null
null
null
Source/src/Json Parser/DataTypeHandlers/JsonObject.cpp
codenameone-akshat/LittleJsonReader
2a28219ef494d4d3a02961d74fb90fa4829a14c5
[ "MIT" ]
null
null
null
Source/src/Json Parser/DataTypeHandlers/JsonObject.cpp
codenameone-akshat/LittleJsonReader
2a28219ef494d4d3a02961d74fb90fa4829a14c5
[ "MIT" ]
null
null
null
#include "JsonObjectItem.h" JsonReader::JsonItem * JsonReader::JsonObjectItem::GetValue() { return this; } JsonReader::JsonItem * JsonReader::JsonObjectItem::GetFirstChild() { it = m_value.begin(); return *it; } JsonReader::JsonItem * JsonReader::JsonObjectItem::GetNextChild() { std::vector<JsonItem*>::iterator end = m_value.end()-1; if (it != end) { ++it; return *it; } else return *it; } JsonReader::JsonItem * JsonReader::JsonObjectItem::AddChild(JsonItem* jsonItem) { m_value.push_back(jsonItem); return jsonItem; } JsonReader::JsonItem * JsonReader::JsonObjectItem::GetChildAt(int index) { if (index <= m_value.size() - 1) { return m_value.at(index); } else return nullptr; } int JsonReader::JsonObjectItem::asInt() { return 0; } double JsonReader::JsonObjectItem::asDouble() { return 0.0; } bool JsonReader::JsonObjectItem::asBool() { return false; } std::string JsonReader::JsonObjectItem::asString() { return std::string(); } int JsonReader::JsonObjectItem::size() { return m_value.size(); }
16.757576
80
0.664557
a393bd64f3a18321623c65c76d3bfd736693c225
406
java
Java
dubbo-common/src/test/java/com/apache/freeze/research/SPI/JavaSPITest.java
jooyu/incubator-dubbo
87564924fd6bf0c02d4d56134af19dd58881b29b
[ "Apache-2.0" ]
null
null
null
dubbo-common/src/test/java/com/apache/freeze/research/SPI/JavaSPITest.java
jooyu/incubator-dubbo
87564924fd6bf0c02d4d56134af19dd58881b29b
[ "Apache-2.0" ]
null
null
null
dubbo-common/src/test/java/com/apache/freeze/research/SPI/JavaSPITest.java
jooyu/incubator-dubbo
87564924fd6bf0c02d4d56134af19dd58881b29b
[ "Apache-2.0" ]
null
null
null
package com.apache.freeze.research.SPI; import com.apache.dubbo.freeze.research.SPI.Robot; import org.junit.Test; import java.util.ServiceLoader; public class JavaSPITest { @Test public void sayHello() throws Exception { ServiceLoader<Robot> serviceLoader = ServiceLoader.load(Robot.class); System.out.println("Java SPI"); serviceLoader.forEach(Robot::sayHello); } }
25.375
77
0.721675
55373e214ebbf5610dc476987a1700a8b0be6e7b
4,371
swift
Swift
FoodTracker/FoodTracker/CloudTrackerAPI.swift
abear247/CloudTracker
59c06a2b36a3ea8ae68075cb376d9fb08baa826e
[ "AML" ]
null
null
null
FoodTracker/FoodTracker/CloudTrackerAPI.swift
abear247/CloudTracker
59c06a2b36a3ea8ae68075cb376d9fb08baa826e
[ "AML" ]
null
null
null
FoodTracker/FoodTracker/CloudTrackerAPI.swift
abear247/CloudTracker
59c06a2b36a3ea8ae68075cb376d9fb08baa826e
[ "AML" ]
null
null
null
// // CloudTrackerAPI.swift // FoodTracker // // Created by Alex Bearinger on 2017-02-13. // Copyright © 2017 Apple Inc. All rights reserved. // import UIKit class CloudTrackerAPI: NSObject { public func postRequest(postData : [String:String], completion: @escaping ([String:[String:String]]) -> Void) { guard let postJSON = try? JSONSerialization.data(withJSONObject: postData, options: []) else { print("could not serialize json") return } let req = NSMutableURLRequest(url: URL(string:"http://159.203.243.24:8000/signup")!) req.httpBody = postJSON req.httpMethod = "POST" req.addValue("application/json", forHTTPHeaderField: "Content-Type") let task = URLSession.shared.dataTask(with: req as URLRequest) { (data, resp, err) in guard let data = data else { print("no data returned from server \(err)") return } guard let resp = resp as? HTTPURLResponse else { print("no response returned from server \(err)") return } guard let rawJSON = try? JSONSerialization.jsonObject(with: data, options: []) else { print("data returned is not json, or not valid") return } guard resp.statusCode == 200 else { // handle error print("an error occurred") return } completion(rawJSON as! [String : [String : String]]) } task.resume() } func post(data: [String: AnyObject], toEndpoint: String, completion: @escaping (Data?, NSError?)->(Void)){ guard let postJSON = try? JSONSerialization.data(withJSONObject: data, options: []) else { print("could not serialize json") return } print(postJSON) let string = toEndpoint let req = NSMutableURLRequest(url: URL(string:"http://159.203.243.24:8000/\(string)")!) print("http://159.203.243.24:8000/\(string)") req.httpBody = postJSON req.httpMethod = "POST" req.addValue("application/json", forHTTPHeaderField: "Content-Type") let task = URLSession.shared.dataTask(with: req as URLRequest) { (data, resp, err) in guard let data = data else { print("no data returned from server \(err)") return } guard let resp = resp as? HTTPURLResponse else { print("no response returned from server \(err)") return } guard resp.statusCode == 200 else { // handle error print("an error occurred") return } completion(data,err as NSError?) } task.resume() } func saveMeal(meal: Meal, completion: @escaping (NSError?)->(Void)){ let upload = meal let req = NSMutableURLRequest(url: URL(string:"http://159.203.243.24:8000/users/me/meals/:id/photo")!) guard let photo = upload.photo else{ return } guard let data = UIImagePNGRepresentation(photo) else{ return } req.httpBody = data req.httpMethod = "POST" req.addValue("application/json", forHTTPHeaderField: "Content-Type") let task = URLSession.shared.dataTask(with: req as URLRequest) { (data, resp, err) in guard let data = data else { print("no data returned from server \(err)") return } guard let resp = resp as? HTTPURLResponse else { print("no response returned from server \(err)") return } guard resp.statusCode == 200 else { // handle error print("an error occurred") return } completion(err as NSError?) } task.resume() // /users/me/meals/:id/photo } }
31.673913
115
0.505376
ed948c7219f77066a0b2680eb5cd694297e2de8a
6,519
kt
Kotlin
jvm/execution/src/test/kotlin/ExecutionTest.kt
laplab/ballista
4d53121ded76dd38092d1e8db99796657bc1d82a
[ "Apache-2.0" ]
1
2020-08-18T07:03:15.000Z
2020-08-18T07:03:15.000Z
jvm/execution/src/test/kotlin/ExecutionTest.kt
Dyqer/ballista
4f40ab73a07e6dcdabf2f7af154e9dac0021ccb5
[ "Apache-2.0" ]
null
null
null
jvm/execution/src/test/kotlin/ExecutionTest.kt
Dyqer/ballista
4f40ab73a07e6dcdabf2f7af154e9dac0021ccb5
[ "Apache-2.0" ]
1
2020-08-25T09:15:22.000Z
2020-08-25T09:15:22.000Z
// Copyright 2020 Andy Grove // // 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 org.ballistacompute.execution import java.io.File import kotlin.test.assertEquals import org.apache.arrow.vector.types.pojo.ArrowType import org.ballistacompute.datasource.InMemoryDataSource import org.ballistacompute.datatypes.ArrowTypes import org.ballistacompute.datatypes.Field import org.ballistacompute.datatypes.Schema import org.ballistacompute.fuzzer.Fuzzer import org.ballistacompute.logical.* import org.junit.Test import org.junit.jupiter.api.TestInstance @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ExecutionTest { val dir = "../testdata" val employeeCsv = File(dir, "employee.csv").absolutePath @Test fun `employees in CO using DataFrame`() { // Create a context val ctx = ExecutionContext(mapOf()) // Construct a query using the DataFrame API val df = ctx.csv(employeeCsv) .filter(col("state") eq lit("CO")) .project(listOf(col("id"), col("first_name"), col("last_name"))) val batches = ctx.execute(df).asSequence().toList() assertEquals(1, batches.size) val batch = batches.first() assertEquals("2,Gregg,Langford\n" + "3,John,Travis\n", batch.toCSV()) } @Test fun `employees in CA using SQL`() { // Create a context val ctx = ExecutionContext(mapOf()) val employee = ctx.csv(employeeCsv) ctx.register("employee", employee) // Construct a query using the DataFrame API val df = ctx.sql("SELECT id, first_name, last_name FROM employee WHERE state = 'CA'") val batches = ctx.execute(df).asSequence().toList() assertEquals(1, batches.size) val batch = batches.first() assertEquals("1,Bill,Hopkins\n", batch.toCSV()) } @Test fun `aggregate query`() { // Create a context val ctx = ExecutionContext(mapOf()) // construct a query using the DataFrame API val df = ctx.csv(employeeCsv) .aggregate( listOf(col("state")), listOf(Max(cast(col("salary"), ArrowType.Int(32, true))))) val batches = ctx.execute(df).asSequence().toList() assertEquals(1, batches.size) val batch = batches.first() val expected = "CO,11500\n" + "CA,12000\n" + ",11500\n" assertEquals(expected, batch.toCSV()) } @Test fun `bonuses in CA using SQL and DataFrame`() { // Create a context val ctx = ExecutionContext(mapOf()) // construct a query using the DataFrame API val caEmployees = ctx.csv(employeeCsv) .filter(col("state") eq lit("CA")) .project(listOf(col("id"), col("first_name"), col("last_name"), col("salary"))) // register the DataFrame as a table ctx.register("ca_employees", caEmployees) // Construct a query using the DataFrame API val df = ctx.sql("SELECT id, first_name, last_name, salary FROM ca_employees") // val df = ctx.sql("SELECT id, first_name, last_name, salary * 0.1 AS bonus FROM ca_employees") val batches = ctx.execute(df).asSequence().toList() assertEquals(1, batches.size) val batch = batches.first() assertEquals("1,Bill,Hopkins,12000\n", batch.toCSV()) } @Test fun `min max sum float`() { val schema = Schema(listOf(Field("a", ArrowTypes.StringType), Field("b", ArrowTypes.FloatType))) // val batch = Fuzzer().createRecordBatch(schema, 1024) val input = Fuzzer() .createRecordBatch( schema, listOf(listOf("a", "a", "b", "b"), listOf(1.0f, 2.0f, 4.0f, 3.0f))) val dataSource = InMemoryDataSource(schema, listOf(input)) val ctx = ExecutionContext(mapOf()) val logicalPlan = DataFrameImpl(Scan("", dataSource, listOf())) .aggregate(listOf(col("a")), listOf(Min(col("b")), Max(col("b")), Sum(col("b")))) .logicalPlan() val batches = ctx.execute(logicalPlan).asSequence().toList() assertEquals(1, batches.size) val batch = batches.first() assertEquals("a,1.0,2.0,3.0\n" + "b,3.0,4.0,7.0\n", batch.toCSV()) } @Test fun `float math`() { val schema = Schema(listOf(Field("a", ArrowTypes.FloatType), Field("b", ArrowTypes.FloatType))) // val batch = Fuzzer().createRecordBatch(schema, 1024) val input = Fuzzer() .createRecordBatch( schema, listOf(listOf(1.0f, 2.0f, 4.0f, 3.0f), listOf(11.0f, 22.0f, 44.0f, 33.0f))) val dataSource = InMemoryDataSource(schema, listOf(input)) val ctx = ExecutionContext(mapOf()) val logicalPlan = DataFrameImpl(Scan("", dataSource, listOf())) .project( listOf( Add(col("a"), col("b")), Subtract(col("a"), col("b")), Multiply(col("a"), col("b")), Divide(col("a"), col("b")))) .logicalPlan() val batches = ctx.execute(logicalPlan).asSequence().toList() assertEquals(1, batches.size) val batch = batches.first() assertEquals( "12.0,-10.0,11.0,0.09090909\n" + "24.0,-20.0,44.0,0.09090909\n" + "48.0,-40.0,176.0,0.09090909\n" + "36.0,-30.0,99.0,0.09090909\n", batch.toCSV()) } @Test fun `boolean expressions`() { val schema = Schema(listOf(Field("a", ArrowTypes.BooleanType), Field("b", ArrowTypes.BooleanType))) val input = Fuzzer() .createRecordBatch( schema, listOf(listOf(false, false, true, true), listOf(false, true, false, true))) val dataSource = InMemoryDataSource(schema, listOf(input)) val ctx = ExecutionContext(mapOf()) val logicalPlan = DataFrameImpl(Scan("", dataSource, listOf())) .project(listOf(And(col("a"), col("b")), Or(col("a"), col("b")))) .logicalPlan() val batches = ctx.execute(logicalPlan).asSequence().toList() assertEquals(1, batches.size) val batch = batches.first() assertEquals("false,false\n" + "false,true\n" + "false,true\n" + "true,true\n", batch.toCSV()) } }
32.432836
100
0.637674
46ca3ea07dc062c32443674db4689ddf04f76df1
3,530
py
Python
examples/red-pitaya/oscillo/python/oscillo.py
Koheron/koheron-sdk
82b732635f1adf5dd0b04b9290b589c1fc091f29
[ "MIT" ]
77
2016-09-20T18:44:14.000Z
2022-03-30T16:04:09.000Z
examples/red-pitaya/oscillo/python/oscillo.py
rsarwar87/koheron-sdk
02c35bf3c1c29f1029fad18b881dbd193efac5a7
[ "MIT" ]
101
2016-09-05T15:44:25.000Z
2022-03-29T09:22:09.000Z
examples/red-pitaya/oscillo/python/oscillo.py
rsarwar87/koheron-sdk
02c35bf3c1c29f1029fad18b881dbd193efac5a7
[ "MIT" ]
34
2016-12-12T07:21:57.000Z
2022-01-12T21:00:52.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import math import numpy as np from koheron import command class Oscillo(object): def __init__(self, client): self.client = client self.wfm_size = 8192 self.sampling_rate = 125e6 self.t = np.arange(self.wfm_size)/self.sampling_rate self.dac = np.zeros((2, self.wfm_size)) self.adc = np.zeros((2, self.wfm_size)) self.spectrum = np.zeros((2, int(self.wfm_size / 2))) self.avg_spectrum = np.zeros((2, int(self.wfm_size / 2))) @command() def set_dac_periods(self, period0, period1): ''' Select the periods played on each address generator ex: self.set_dac_periods(8192, 4096) ''' pass @command() def set_num_average_min(self, num_average_min): ''' Set the minimum of averages that will be computed on the FPGA The effective number of averages is >= num_average_min. ''' pass @command() def set_average_period(self, average_period): ''' Set the period of the averaging module and reset the module. ''' self.period = average_period @command() def set_average(self, is_average): ''' is_average = True enables averaging. ''' pass @command() def get_num_average(self, channel): ''' Get the number of averages corresponding to the last acquisition. ''' num_average = self.client.recv_uint32() return num_average @command() def get_decimated_data(self, decim_factor, index_low, index_high): decimated_data = self.client.recv_vector(dtype='float32') return decimated_data def get_adc(self): self.adc = np.reshape(self.get_decimated_data(1, 0, self.wfm_size), (2, self.wfm_size)) def get_spectrum(self): fft_adc = np.fft.fft(self.adc, axis=1) self.spectrum = fft_adc[:, 0:self.wfm_size / 2] def get_avg_spectrum(self, n_avg=1): self.avg_spectrum = np.zeros((2, int(self.wfm_size / 2))) for i in range(n_avg): self.get_adc() fft_adc = np.abs(np.fft.fft(self.adc, axis=1)) self.avg_spectrum += fft_adc[:, 0:int(self.wfm_size / 2)] self.avg_spectrum /= n_avg @command() def reset_acquisition(self): pass @command(funcname='reset') def reset_dac(self): pass def reset(self): self.reset_dac() # Modulation def set_dac(self, channels=[0,1]): """ Write the BRAM corresponding on the selected channels (dac0 or dac1) with the array stored in self.dac[channel,:]. ex: self.set_dac(channel=[0]) """ @command(classname='Modulation') def set_dac_buffer(self, channel, arr): pass for channel in channels: data = np.int16(16384 * (self.dac[channel,:])) set_dac_buffer(self, channel, np.uint32(data[1::2] + data[::2] * 65536)) @command(classname='Modulation') def get_modulation_status(self): return self.client.recv_tuple('IIffffff') @command(classname='Modulation') def set_waveform_type(self, channel, wfm_type): pass @command(classname='Modulation') def set_dac_amplitude(self, channel, amplitude_value): pass @command(classname='Modulation') def set_dac_frequency(self, channel, frequency_value): pass @command(classname='Modulation') def set_dac_offset(self, channel, frequency_value): pass
30.431034
95
0.625496
c6b414d1c14f98b42e46c5db548f74f885a8acc9
4,307
css
CSS
public/css/style.css
tagawa/Mobile-Checker
5a2e2a7d67fe19a703009440ad0d821540ece683
[ "MIT" ]
null
null
null
public/css/style.css
tagawa/Mobile-Checker
5a2e2a7d67fe19a703009440ad0d821540ece683
[ "MIT" ]
null
null
null
public/css/style.css
tagawa/Mobile-Checker
5a2e2a7d67fe19a703009440ad0d821540ece683
[ "MIT" ]
null
null
null
/* TODO : use full path of elements */ html, body{ margin: 0px; padding: 0px; outline: 0px; height: 100%; background-color: #ecf0f1; font-family: Open Sans; } /* DEFAULT view */ #home{ height: 100%; padding: 0px; } .navbar-default { background-image: none; background-color: #384047; box-shadow: none; border-radius: 0px; border: 0px; padding-top: 15px; text-align: center; margin-bottom: 0px; } #home > header { padding: 0px; padding-top: 50px; font-size: 20px; font-weight: 400; text-align: center; color: #FCFCFB; } #home > header > form { padding: 0px; } .device-selector { margin-left: 0px; padding: 15px; background-image: none; background-color: transparent; border: 0px; box-shadow: none; border-radius: 2px; color: #7E8A94; text-shadow:none; font-size: 18px; font-weight: 300; } .device-selector img{ margin-bottom: 20px; } .device-selector:hover { background-color: transparent; color: #7E8A94; transition:0.2s; } .btn-default:active, .btn-default.active { background-image: none; box-shadow: none; background-color: #eee; text-shadow:none; color: #7E8A94; --box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.2); } .btn-group { padding-left: 0px; padding-right: 0px; background-color: white; border: 1px solid rgba(0, 0, 0, 0.2); border-radius: 2px; } .btn-group .btn + .btn{ margin-left: 0px; } #home > header > form > div > #url { height: 50px; width: 100%; padding: 5px; margin: 0px; margin-top: 5px; border-left: 0px solid #eee; border-right: 0px solid #eee; border-top: 0px solid #eee; border-bottom: 0px solid #eee; border-radius: 2px; border: 1px solid rgba(0, 0, 0, 0.2); background-color: #fcfcfb; font-size: 18px; font-weight: 300; color: #666; --box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.2); } #home > header > form > div > button { height: 50px; width: 100%; margin-top: 5px; border-left: 0px; border-right: 0px; border-top: 0px; border-bottom: 0px; border-radius: 3px; color: #FFF; font-weight: 300; font-size: 22px; background-color: #334d5c; border: 2px solid #334d5c; font-family: Open Sans; } #home > header > form > div > button:hover { transition:0.3s; background-color: #ecf0f1; border: 2px solid #334d5c; color: #334d5c; } #home > header > form > div > button > span { } #home > header #options { margin-top: 30px; } #home > header > #options > #options-title { margin-top: 0px; font-weight: 700; font-size: 18px; text-align: left; color: #7E8A94; } #main-title { font-family: Bitter; font-size: 50px; font-weight: 700; color: #384047; text-align: center; margin-top: 30px; margin-bottom: 30px; } #slogan { font-size: 20px; font-weight: 300; color: #384047; text-align: left; margin-top: 40px; } footer { background-color: #ecf0f1; padding-top: 30px; padding-bottom: 30px; text-align: center; } footer p { color: #384047; padding-top: 10px; font-weight: 300; } footer a { } footer img{ text-align: center; } .border { margin-top: 50px; border-bottom: 1px solid #bdc3c7; } #donation-link{ background-color: #FF5E5E; padding: 10px; border-radius: 5px; color: white; } #infos { margin-top: 50px; padding-bottom: 0px; background-color: #384047; background-color: #ecf0f1; font-size: 18px; font-weight: 300; } #infos h2 { font-family: Open Sans; font-weight: 400; color: #7E8A94; font-size: 22px; } /* MOBILE device view */ @media screen and (max-width: 990px) { #github-banner { visibility: hidden; } #overview { visibility: hidden; } #report > .navbar-fixed-top > div > h3 { visibility: hidden; } #main-title { font-size: 32px; } #slogan { font-size: 20px; } #home header { padding-top: 20px; } #home > header > form > div > #url { margin-top: 40px; } #home > header > form > div > button { margin-top: 20px; } .device-selector { width: 100%; } .border { margin-top: 40px; } #home > header > form > div > button { margin-top: 5px; } #home > header > form > div > #url { margin-top: 10px; } }
17.579592
51
0.609241
f44020301b281dd4230b810584809750ecf316e3
972
tsx
TypeScript
frontend/src/app/components/Layout.tsx
MariusArhaug/JAMDb
0cb3d750887db19015ba3c357d85fcf557c3d624
[ "Apache-2.0" ]
null
null
null
frontend/src/app/components/Layout.tsx
MariusArhaug/JAMDb
0cb3d750887db19015ba3c357d85fcf557c3d624
[ "Apache-2.0" ]
null
null
null
frontend/src/app/components/Layout.tsx
MariusArhaug/JAMDb
0cb3d750887db19015ba3c357d85fcf557c3d624
[ "Apache-2.0" ]
1
2021-11-03T12:44:31.000Z
2021-11-03T12:44:31.000Z
import React, { ReactNode } from 'react' import NavBar from './Navbar' import { Footer } from './Footer' /** * Layout wrapper */ export function Layout({ children }: { children: ReactNode }) { return ( <div> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossOrigin="anonymous" /> <div className="min-h-screen relative"> <NavBar /> <div className="flex flex-col max-w-screen-xl my-0 mx-auto px-10"> <div className="flex-grow">{children}</div> </div> <Footer /> </div> </div> ) }
32.4
123
0.546296
4bb5dc55bc874742aa5444955c9791281dc5fcd1
390
h
C
include/Texture.h
Hukunaa/CPU-Rasterizer
e56a1215750842e42cd5d933698bb94bcc859c9f
[ "MIT" ]
null
null
null
include/Texture.h
Hukunaa/CPU-Rasterizer
e56a1215750842e42cd5d933698bb94bcc859c9f
[ "MIT" ]
null
null
null
include/Texture.h
Hukunaa/CPU-Rasterizer
e56a1215750842e42cd5d933698bb94bcc859c9f
[ "MIT" ]
null
null
null
#pragma once #include <Color.h> #include <SDL.h> class Texture { public: unsigned int mui_w; unsigned int mui_h; Color* m_pixels; public: Texture(unsigned int pui_w, unsigned int pui_h); ~Texture(); Texture(const Texture& p_other); void SetPixelColor(unsigned int pui_x, unsigned int pui_y, const Color& p_c); Color & GetPixelColor(unsigned int pui_x, unsigned int pui_y); };
17.727273
78
0.735897
ad3e6d586cf4753e6a75c712418435dc4d683132
920
ps1
PowerShell
CommonTasks/Tests/Integration/22 ChocolateyPackages.Tests.ps1
edwarddijk/CommonTasks
e0a255c11636411c307778536a476bdfa01e3b18
[ "MIT" ]
null
null
null
CommonTasks/Tests/Integration/22 ChocolateyPackages.Tests.ps1
edwarddijk/CommonTasks
e0a255c11636411c307778536a476bdfa01e3b18
[ "MIT" ]
null
null
null
CommonTasks/Tests/Integration/22 ChocolateyPackages.Tests.ps1
edwarddijk/CommonTasks
e0a255c11636411c307778536a476bdfa01e3b18
[ "MIT" ]
null
null
null
Import-Module -Name $PSScriptRoot\Assets\TestHelpers.psm1 Init Describe 'ChocolateyPackages DSC Resource compiles' -Tags FunctionalQuality { It 'ChocolateyPackages Compiles' { configuration Config_ChocolateyPackages { Import-DscResource -ModuleName CommonTasks node localhost_ChocolateyPackages { ChocolateyPackages ChocolateyPackages { Package = $configurationData.Datum.Config.ChocolateyPackages.Packages } } } { Config_ChocolateyPackages -ConfigurationData $configurationData -OutputPath $env:BHBuildOutput -ErrorAction Stop } | Should -Not -Throw } It 'ChocolateyPackages should have created a mof file' { $mofFile = Get-Item -Path $env:BHBuildOutput\localhost_ChocolateyPackages.mof -ErrorAction SilentlyContinue $mofFile | Should -BeOfType System.IO.FileInfo } }
34.074074
145
0.695652
23413241bbf1c64fab417630f035c15e8f5d69a2
7,571
css
CSS
libs/bower-material-master/modules/js/progressLinear/progressLinear.min.css
thiagoaslima/fatoresApp
035395f754e209dcf03225654bcb8fa01cc4a8af
[ "MIT" ]
null
null
null
libs/bower-material-master/modules/js/progressLinear/progressLinear.min.css
thiagoaslima/fatoresApp
035395f754e209dcf03225654bcb8fa01cc4a8af
[ "MIT" ]
null
null
null
libs/bower-material-master/modules/js/progressLinear/progressLinear.min.css
thiagoaslima/fatoresApp
035395f754e209dcf03225654bcb8fa01cc4a8af
[ "MIT" ]
null
null
null
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.6.1-master-d192083 */md-progress-linear{display:block;width:100%;height:5px}md-progress-linear .md-container{overflow:hidden;position:relative;height:5px;top:5px;-webkit-transform:translate(0,5px) scale(1,0);transform:translate(0,5px) scale(1,0);transition:all .3s linear}md-progress-linear .md-container.md-ready{-webkit-transform:translate(0,0) scale(1,1);transform:translate(0,0) scale(1,1)}md-progress-linear .md-bar{height:5px;position:absolute;width:100%}md-progress-linear .md-bar1,md-progress-linear .md-bar2{transition:all .2s linear}md-progress-linear[md-mode=determinate] .md-bar1{display:none}md-progress-linear[md-mode=indeterminate] .md-bar1{-webkit-animation:indeterminate1 4s infinite linear;animation:indeterminate1 4s infinite linear}md-progress-linear[md-mode=indeterminate] .md-bar2{-webkit-animation:indeterminate2 4s infinite linear;animation:indeterminate2 4s infinite linear}md-progress-linear[md-mode=buffer] .md-container{background-color:transparent!important}md-progress-linear[md-mode=buffer] .md-dashed:before{content:"";display:block;height:5px;width:100%;margin-top:0;position:absolute;background-color:transparent;background-size:10px 10px!important;background-position:0 -23px;-webkit-animation:buffer 3s infinite linear;animation:buffer 3s infinite linear}md-progress-linear[md-mode=query] .md-bar2{-webkit-animation:query .8s infinite cubic-bezier(0.39,.575,.565,1);animation:query .8s infinite cubic-bezier(0.39,.575,.565,1)}@-webkit-keyframes indeterminate1{0%{-webkit-transform:translateX(-25%) scale(0.5,1);transform:translateX(-25%) scale(0.5,1)}10%{-webkit-transform:translateX(25%) scale(0.5,1);transform:translateX(25%) scale(0.5,1)}19.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}20%{-webkit-transform:translateX(-37.5%) scale(0.25,1);transform:translateX(-37.5%) scale(0.25,1)}30%{-webkit-transform:translateX(37.5%) scale(0.25,1);transform:translateX(37.5%) scale(0.25,1)}34.99%,36.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}37%{-webkit-transform:translateX(-37.5%) scale(0.25,1);transform:translateX(-37.5%) scale(0.25,1)}47%{-webkit-transform:translateX(20%) scale(0.25,1);transform:translateX(20%) scale(0.25,1)}52%{-webkit-transform:translateX(35%) scale(0.05,1);transform:translateX(35%) scale(0.05,1)}55%{-webkit-transform:translateX(35%) scale(0.1,1);transform:translateX(35%) scale(0.1,1)}58%{-webkit-transform:translateX(50%) scale(0.1,1);transform:translateX(50%) scale(0.1,1)}61.99%,69.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}70%{-webkit-transform:translateX(-37.5%) scale(0.25,1);transform:translateX(-37.5%) scale(0.25,1)}80%{-webkit-transform:translateX(20%) scale(0.25,1);transform:translateX(20%) scale(0.25,1)}85%{-webkit-transform:translateX(35%) scale(0.05,1);transform:translateX(35%) scale(0.05,1)}88%{-webkit-transform:translateX(35%) scale(0.1,1);transform:translateX(35%) scale(0.1,1)}91%{-webkit-transform:translateX(50%) scale(0.1,1);transform:translateX(50%) scale(0.1,1)}92.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}93%{-webkit-transform:translateX(-50%) scale(0,1);transform:translateX(-50%) scale(0,1)}100%{-webkit-transform:translateX(-25%) scale(0.5,1);transform:translateX(-25%) scale(0.5,1)}}@keyframes indeterminate1{0%{-webkit-transform:translateX(-25%) scale(0.5,1);transform:translateX(-25%) scale(0.5,1)}10%{-webkit-transform:translateX(25%) scale(0.5,1);transform:translateX(25%) scale(0.5,1)}19.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}20%{-webkit-transform:translateX(-37.5%) scale(0.25,1);transform:translateX(-37.5%) scale(0.25,1)}30%{-webkit-transform:translateX(37.5%) scale(0.25,1);transform:translateX(37.5%) scale(0.25,1)}34.99%,36.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}37%{-webkit-transform:translateX(-37.5%) scale(0.25,1);transform:translateX(-37.5%) scale(0.25,1)}47%{-webkit-transform:translateX(20%) scale(0.25,1);transform:translateX(20%) scale(0.25,1)}52%{-webkit-transform:translateX(35%) scale(0.05,1);transform:translateX(35%) scale(0.05,1)}55%{-webkit-transform:translateX(35%) scale(0.1,1);transform:translateX(35%) scale(0.1,1)}58%{-webkit-transform:translateX(50%) scale(0.1,1);transform:translateX(50%) scale(0.1,1)}61.99%,69.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}70%{-webkit-transform:translateX(-37.5%) scale(0.25,1);transform:translateX(-37.5%) scale(0.25,1)}80%{-webkit-transform:translateX(20%) scale(0.25,1);transform:translateX(20%) scale(0.25,1)}85%{-webkit-transform:translateX(35%) scale(0.05,1);transform:translateX(35%) scale(0.05,1)}88%{-webkit-transform:translateX(35%) scale(0.1,1);transform:translateX(35%) scale(0.1,1)}91%{-webkit-transform:translateX(50%) scale(0.1,1);transform:translateX(50%) scale(0.1,1)}92.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}93%{-webkit-transform:translateX(-50%) scale(0,1);transform:translateX(-50%) scale(0,1)}100%{-webkit-transform:translateX(-25%) scale(0.5,1);transform:translateX(-25%) scale(0.5,1)}}@-webkit-keyframes indeterminate2{0%,25.99%{-webkit-transform:translateX(-50%) scale(0,1);transform:translateX(-50%) scale(0,1)}28%{-webkit-transform:translateX(-37.5%) scale(0.25,1);transform:translateX(-37.5%) scale(0.25,1)}38%{-webkit-transform:translateX(37.5%) scale(0.25,1);transform:translateX(37.5%) scale(0.25,1)}42.99%,46.99%,49.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}50%{-webkit-transform:translateX(-50%) scale(0,1);transform:translateX(-50%) scale(0,1)}60%{-webkit-transform:translateX(-25%) scale(0.5,1);transform:translateX(-25%) scale(0.5,1)}70%{-webkit-transform:translateX(25%) scale(0.5,1);transform:translateX(25%) scale(0.5,1)}79.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}}@keyframes indeterminate2{0%,25.99%{-webkit-transform:translateX(-50%) scale(0,1);transform:translateX(-50%) scale(0,1)}28%{-webkit-transform:translateX(-37.5%) scale(0.25,1);transform:translateX(-37.5%) scale(0.25,1)}38%{-webkit-transform:translateX(37.5%) scale(0.25,1);transform:translateX(37.5%) scale(0.25,1)}42.99%,46.99%,49.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}50%{-webkit-transform:translateX(-50%) scale(0,1);transform:translateX(-50%) scale(0,1)}60%{-webkit-transform:translateX(-25%) scale(0.5,1);transform:translateX(-25%) scale(0.5,1)}70%{-webkit-transform:translateX(25%) scale(0.5,1);transform:translateX(25%) scale(0.5,1)}79.99%{-webkit-transform:translateX(50%) scale(0,1);transform:translateX(50%) scale(0,1)}}@-webkit-keyframes query{0%{opacity:1;-webkit-transform:translateX(35%) scale(0.3,1);transform:translateX(35%) scale(0.3,1)}100%{opacity:0;-webkit-transform:translateX(-50%) scale(0,1);transform:translateX(-50%) scale(0,1)}}@keyframes query{0%{opacity:1;-webkit-transform:translateX(35%) scale(0.3,1);transform:translateX(35%) scale(0.3,1)}100%{opacity:0;-webkit-transform:translateX(-50%) scale(0,1);transform:translateX(-50%) scale(0,1)}}@-webkit-keyframes buffer{0%{opacity:1;background-position:0 -23px}50%{opacity:0}100%{opacity:1;background-position:-200px -23px}}@keyframes buffer{0%{opacity:1;background-position:0 -23px}50%{opacity:0}100%{opacity:1;background-position:-200px -23px}}
1,261.833333
7,460
0.747457
c98f6f023c392b31977c949f478266b4af6f4930
1,090
ts
TypeScript
lib_deprecated/chunk.ts
gizak/batch
551b0653b3c53945c161275bb3e38f7b805c9159
[ "MIT" ]
null
null
null
lib_deprecated/chunk.ts
gizak/batch
551b0653b3c53945c161275bb3e38f7b805c9159
[ "MIT" ]
null
null
null
lib_deprecated/chunk.ts
gizak/batch
551b0653b3c53945c161275bb3e38f7b805c9159
[ "MIT" ]
null
null
null
export interface ItemReader extends ItemReadListener { open(chkp?: any): void close(): void readItem(): any checkpointInfo(): any } export abstract class ItemReadListener { beforeRead(): void {} afterRead(item: any): void {} onReadError(e: Error): void { throw e } } export interface ItemProcessor extends ItemProcessListener { processItem(item: any): any } export abstract class ItemProcessListener { beforeProcess(item: any): void {} afterProcess(item: any, result: any): void {} onProcessError(item: any, e: Error): void { throw e } } export interface ItemWriter extends ItemWriteListener { open(chkp?: any): void close(): void writeItem(items: any[]): void checkpointInfo(): any } export abstract class ItemWriteListener { beforeWrite(items: any[]): void {} afterWrite(items: any[]): void {} onWriteError(items: any[], e: Error): void { throw e } } export interface Chunk extends ItemReader, ItemProcessor, ItemWriter, ChunkListener {} export abstract class ChunkListener { beforeChunk(): void {} afterChunk(): void {} onError(e: Error): void { throw e } }
24.772727
86
0.722018
df77edf302f135fea73403857f075cef339069a5
11,305
cs
C#
Assets/Editor/Generated/Black/Sequence/Action/Actor/Status/SequenceActionActorGetDeath.generated.cs
Gurrimo/Luminaire
7b435d41ff69390356021111f4a56a95c2000ace
[ "MIT" ]
null
null
null
Assets/Editor/Generated/Black/Sequence/Action/Actor/Status/SequenceActionActorGetDeath.generated.cs
Gurrimo/Luminaire
7b435d41ff69390356021111f4a56a95c2000ace
[ "MIT" ]
10
2020-05-11T00:27:20.000Z
2020-05-13T06:14:09.000Z
Assets/Editor/Generated/Black/Sequence/Action/Actor/Status/SequenceActionActorGetDeath.generated.cs
youarebritish/Luminaire
7ed4632f969aac34cef8f3e258eaef9f07213055
[ "MIT" ]
3
2021-03-28T15:25:55.000Z
2021-04-07T00:46:52.000Z
//---------------------- // <auto-generated> // This file was automatically generated. Any changes to it will be lost if and when the file is regenerated. // </auto-generated> //---------------------- #pragma warning disable using System; using SQEX.Luminous.Core.Object; using System.Collections.Generic; using CodeDom = System.CodeDom; namespace Black.Sequence.Action.Actor.Status { [Serializable, CodeDom.Compiler.GeneratedCode("Luminaire", "0.1")] public partial class SequenceActionActorGetDeath : Black.Sequence.Actor.SequenceActionActorBase { new public static ObjectType ObjectType { get; private set; } private static PropertyContainer fieldProperties; [UnityEngine.SerializeReference] public SQEX.Ebony.Framework.Node.GraphTriggerInputPin in_= new SQEX.Ebony.Framework.Node.GraphTriggerInputPin(); [UnityEngine.SerializeReference] public SQEX.Ebony.Framework.Node.GraphTriggerInputPin stop_= new SQEX.Ebony.Framework.Node.GraphTriggerInputPin(); [UnityEngine.SerializeReference] public SQEX.Ebony.Framework.Node.GraphVariableInputPin inValue_= new SQEX.Ebony.Framework.Node.GraphVariableInputPin(); [UnityEngine.SerializeReference] public SQEX.Ebony.Framework.Node.GraphTriggerOutputPin out_= new SQEX.Ebony.Framework.Node.GraphTriggerOutputPin(); [UnityEngine.SerializeReference] public SQEX.Ebony.Framework.Node.GraphTriggerOutputPin death_= new SQEX.Ebony.Framework.Node.GraphTriggerOutputPin(); [UnityEngine.SerializeReference] public SQEX.Ebony.Framework.Node.GraphTriggerOutputPin allDeath_= new SQEX.Ebony.Framework.Node.GraphTriggerOutputPin(); public bool usePlayerSaveBankNumber_; public int playerSaveBankNumber_; public float deathCheckTime_; new public static void SetupObjectType() { if (ObjectType != null) { return; } var dummy = new SequenceActionActorGetDeath(); var properties = dummy.GetFieldProperties(); ObjectType = new ObjectType("Black.Sequence.Action.Actor.Status.SequenceActionActorGetDeath", 0, Black.Sequence.Action.Actor.Status.SequenceActionActorGetDeath.ObjectType, Construct, properties, 0, 800); } public override ObjectType GetObjectType() { return ObjectType; } protected override PropertyContainer GetFieldProperties() { if (fieldProperties != null) { return fieldProperties; } fieldProperties = new PropertyContainer("Black.Sequence.Action.Actor.Status.SequenceActionActorGetDeath", base.GetFieldProperties(), -1225962162, -1128391154); fieldProperties.AddIndirectlyProperty(new Property("refInPorts_", 1035088696, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 24, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("refOutPorts_", 283683627, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 40, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("triInPorts_", 291734708, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 96, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("triOutPorts_", 3107891487, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin*, MEMORY_CATEGORY_FRAMEWORK >", 112, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)4)); fieldProperties.AddIndirectlyProperty(new Property("Isolated_", 56305607, "bool", 168, 1, 1, Property.PrimitiveType.Bool, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("in_.pinName_", 3330161590, "Base.String", 192, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("in_.name_", 192292993, "Base.String", 208, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("in_.connections_", 490033121, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 224, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("in_.delayType_", 261766523, "SQEX.Ebony.Framework.Node.GraphPin.DelayType", 256, 4, 1, Property.PrimitiveType.Enum, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("in_.delayTime_", 1689218608, "float", 260, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("in_.delayMaxTime_", 1529341114, "float", 264, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("stop_.pinName_", 183528169, "Base.String", 288, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("stop_.name_", 2815449908, "Base.String", 304, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("stop_.connections_", 2986689162, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 320, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("stop_.delayType_", 2766128696, "SQEX.Ebony.Framework.Node.GraphPin.DelayType", 352, 4, 1, Property.PrimitiveType.Enum, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("stop_.delayTime_", 1614578803, "float", 356, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("stop_.delayMaxTime_", 2505467947, "float", 360, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("inValue_.pinName_", 2599123119, "Base.String", 384, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("inValue_.name_", 1668691786, "Base.String", 400, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("inValue_.connections_", 1463894344, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 416, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("inValue_.pinValueType_", 727226451, "Base.String", 448, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("out_.pinName_", 1137295951, "Base.String", 472, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("out_.name_", 2182257194, "Base.String", 488, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("out_.connections_", 2048532136, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 504, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("out_.delayType_", 124432558, "SQEX.Ebony.Framework.Node.GraphPin.DelayType", 536, 4, 1, Property.PrimitiveType.Enum, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("out_.delayTime_", 3264366185, "float", 540, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("out_.delayMaxTime_", 456551125, "float", 544, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("death_.pinName_", 2834546497, "Base.String", 568, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("death_.name_", 2256069052, "Base.String", 584, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("death_.connections_", 4078875682, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 600, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("death_.delayType_", 1512581504, "SQEX.Ebony.Framework.Node.GraphPin.DelayType", 632, 4, 1, Property.PrimitiveType.Enum, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("death_.delayTime_", 1213770987, "float", 636, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("death_.delayMaxTime_", 1656122835, "float", 640, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("allDeath_.pinName_", 2162760718, "Base.String", 664, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("allDeath_.name_", 1525282633, "Base.String", 680, 16, 1, Property.PrimitiveType.String, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("allDeath_.connections_", 2992775097, "SQEX.Ebony.Std.DynamicArray< SQEX.Ebony.Framework.Node.GraphPin* >", 696, 16, 1, Property.PrimitiveType.PointerArray, 0, (char)1)); fieldProperties.AddIndirectlyProperty(new Property("allDeath_.delayType_", 2507862691, "SQEX.Ebony.Framework.Node.GraphPin.DelayType", 728, 4, 1, Property.PrimitiveType.Enum, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("allDeath_.delayTime_", 482641096, "float", 732, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddIndirectlyProperty(new Property("allDeath_.delayMaxTime_", 4257218754, "float", 736, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); fieldProperties.AddProperty(new Property("in_", 1827225043, "SQEX.Ebony.Framework.Node.GraphTriggerInputPin", 184, 96, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddProperty(new Property("stop_", 3454812878, "SQEX.Ebony.Framework.Node.GraphTriggerInputPin", 280, 96, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddProperty(new Property("inValue_", 2850905696, "SQEX.Ebony.Framework.Node.GraphVariableInputPin", 376, 88, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddProperty(new Property("out_", 1514340864, "SQEX.Ebony.Framework.Node.GraphTriggerOutputPin", 464, 96, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddProperty(new Property("death_", 3642860374, "SQEX.Ebony.Framework.Node.GraphTriggerOutputPin", 560, 96, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddProperty(new Property("allDeath_", 2021506587, "SQEX.Ebony.Framework.Node.GraphTriggerOutputPin", 656, 96, 1, Property.PrimitiveType.ClassField, 0, (char)0)); fieldProperties.AddProperty(new Property("usePlayerSaveBankNumber_", 534537168, "bool", 752, 1, 1, Property.PrimitiveType.Bool, 0, (char)0)); fieldProperties.AddProperty(new Property("playerSaveBankNumber_", 2728010947, "Black.Save.SAVE_PLAYER", 756, 4, 1, Property.PrimitiveType.Enum, 0, (char)0)); fieldProperties.AddProperty(new Property("deathCheckTime_", 3782207907, "float", 760, 4, 1, Property.PrimitiveType.Float, 0, (char)0)); return fieldProperties; } private static BaseObject Construct() { return new SequenceActionActorGetDeath(); } } }
93.429752
241
0.75586
f4f3e74797b6d623f1b1d052ef90499a1788b70b
1,348
ts
TypeScript
src/getOptions.ts
Calvin-LL/webpack-loader-util
7be93f63ce6d0f458306fdb5101e60344e8ff721
[ "MIT" ]
1
2020-11-28T17:52:27.000Z
2020-11-28T17:52:27.000Z
src/getOptions.ts
Calvin-LL/webpack-loader-util
7be93f63ce6d0f458306fdb5101e60344e8ff721
[ "MIT" ]
196
2020-11-25T19:04:49.000Z
2022-03-24T13:09:14.000Z
src/getOptions.ts
Calvin-LL/webpack-loader-util
7be93f63ce6d0f458306fdb5101e60344e8ff721
[ "MIT" ]
null
null
null
import loaderUtils from "loader-utils"; import { loader } from "webpack"; type OPTIONS = Readonly<Record<string, any>> | null; export function getOptions<T extends Record<string, any> = any>( loadContext: loader.LoaderContext, includeQuery = true, convertStringQueryParamsToNumber = false ): T { const options = loaderUtils.getOptions(loadContext) as OPTIONS; const queryObject = includeQuery && loadContext.resourceQuery ? (loaderUtils.parseQuery(loadContext.resourceQuery) as Partial<OPTIONS>) : null; const fullOptions: Partial<OPTIONS> = { ...options, ...(includeQuery && convertStringQueryParamsToNumber ? attemptToConvertValuesToNumbers(queryObject) : queryObject), }; return fullOptions as T; } function attemptToConvertValuesToNumbers<T extends OPTIONS>(object: T): T { if (!object) return null as T; const result = { ...object } as Record<string, any>; Object.keys(result).forEach((key) => { if (isNumeric(result[key])) { result[key] = Number(result[key]); } }); return result as T; } // https://stackoverflow.com/a/175787 function isNumeric(string: any): boolean { if (typeof string !== "string") return false; // @ts-expect-error using isNaN to test string, works but typescript doesn't like return !isNaN(string) && !isNaN(parseFloat(string)); }
29.304348
83
0.70178
df61c785fecc4f01f450943be789f21f043c7660
430
cs
C#
Porter/IStemmer.cs
electronart/WordListAnalyser
0eac9661af07541685189356ff4d57e37d935cc3
[ "Apache-2.0" ]
5
2019-11-22T01:25:30.000Z
2021-07-23T15:35:56.000Z
Porter/IStemmer.cs
electronart/WordListAnalyser
0eac9661af07541685189356ff4d57e37d935cc3
[ "Apache-2.0" ]
1
2018-12-11T16:20:03.000Z
2018-12-11T16:20:03.000Z
Porter/IStemmer.cs
electronart/WordListAnalyser
0eac9661af07541685189356ff4d57e37d935cc3
[ "Apache-2.0" ]
2
2019-11-22T02:50:21.000Z
2021-07-23T15:36:02.000Z
/* * Created by SharpDevelop. * User: Tom * Date: 04/11/2015 * Time: 12:52 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; namespace WordListAnalyser2.Porter { /// <summary> /// Port of Stemmer.java interface Tom 04/11/2015 /// </summary> public interface IStemmer { void initialize(); porterData stemFile(porterData inFile, string outfilename); } }
17.2
80
0.674419
3f4d529f2c26a998b378a76fa08d807bf638ed03
272
php
PHP
src/Facades/Sendinblue.php
combindma/laravel-sendinblue
b2414aab901ba08564a8ef7eaf91712dc2ad6341
[ "MIT" ]
null
null
null
src/Facades/Sendinblue.php
combindma/laravel-sendinblue
b2414aab901ba08564a8ef7eaf91712dc2ad6341
[ "MIT" ]
2
2022-03-01T18:36:24.000Z
2022-03-01T18:51:56.000Z
src/Facades/Sendinblue.php
combindma/laravel-sendinblue
b2414aab901ba08564a8ef7eaf91712dc2ad6341
[ "MIT" ]
null
null
null
<?php namespace Combindma\Sendinblue\Facades; use Illuminate\Support\Facades\Facade; /** * @see \Combindma\Sendinblue\Sendinblue */ class Sendinblue extends Facade { protected static function getFacadeAccessor() { return 'laravel-sendinblue'; } }
16
49
0.713235
a14d12eabe1328f022afb4045597f74f83292c06
7,015
tsx
TypeScript
src/components/randomFood/RandomFood.tsx
yeukfei02/lunchPickerReactNative
0be5d5e3eab9388dee5178d842dcb14147e18810
[ "MIT" ]
11
2020-04-01T14:22:58.000Z
2021-11-12T07:40:56.000Z
src/components/randomFood/RandomFood.tsx
yeukfei02/lunchPickerReactNative
0be5d5e3eab9388dee5178d842dcb14147e18810
[ "MIT" ]
14
2020-04-01T11:43:12.000Z
2022-01-13T07:28:20.000Z
src/components/randomFood/RandomFood.tsx
yeukfei02/lunchPickerReactNative
0be5d5e3eab9388dee5178d842dcb14147e18810
[ "MIT" ]
5
2020-04-13T12:43:49.000Z
2021-10-11T06:15:47.000Z
import React, { useState, useEffect, useRef } from 'react'; import { StyleSheet, ScrollView, View, Text, RefreshControl } from 'react-native'; import { Button, Switch, FAB } from 'react-native-paper'; import { useTranslation } from 'react-i18next'; import _ from 'lodash'; import axios from 'axios'; import { getRootUrl } from '../../common/Common'; import Divider from '../divider/Divider'; import DisplayResult from '../displayResult/DisplayResult'; const ROOT_URL = getRootUrl(); const style = StyleSheet.create({ scrollViewContainer: { flex: 1, backgroundColor: '#FAFAD2', }, container: { flex: 1, marginTop: 70, justifyContent: 'flex-end', alignItems: 'flex-end', marginHorizontal: 30, }, titleStyle: { fontSize: 18, fontWeight: 'bold', }, rowContainer: { flexDirection: 'row', }, currentFoodCategoryValueStyle: { fontSize: 18, fontWeight: 'normal', }, colorPrimary: { color: '#ed1f30', }, fab: { backgroundColor: '#ed1f30', position: 'absolute', margin: 16, right: 0, bottom: 0, }, }); function RandomFood(props: any): JSX.Element { const scrollRef = useRef<ScrollView>(); const { t } = useTranslation(); const [useRandomFoodCategory, setUseRandomFoodCategory] = useState(false); const [selectedTerm, setSelectedTerm] = useState(''); const [randomFoodList, setRandomFoodList] = useState([]); const [latitude, setLatitude] = useState(0); const [longitude, setLongitude] = useState(0); const [refreshButtonClicked, setRefreshButtonClicked] = useState(false); const [resultList, setResultList] = useState([]); const [refreshing, setRefreshing] = useState(false); useEffect(() => { getRandomFoodList(); getUserCurrentLatLong(); }, []); useEffect(() => { const selectedTerm = _.sample(randomFoodList); setSelectedTerm(selectedTerm as any); if (latitude !== 0 && longitude !== 0) findRestaurantsByLatLong(useRandomFoodCategory, selectedTerm as any, latitude, longitude); }, [useRandomFoodCategory, randomFoodList, latitude, longitude]); const getRandomFoodList = async () => { const response = await axios.get(`${ROOT_URL}/category/get-categories`, { headers: { 'Content-Type': 'application/json', }, }); if (!_.isEmpty(response)) { console.log('response = ', response); if (!_.isEmpty(response.data.categories)) { const randomFoodList: any = []; response.data.categories.forEach((item: any, i: number) => { if (!_.isEmpty(item.parent_aliases)) { const parentAliases = item.parent_aliases[0]; if ( _.isEqual(parentAliases, 'food') || _.isEqual(parentAliases, 'restaurants') || _.isEqual(parentAliases, 'bars') || _.isEqual(parentAliases, 'breakfast_brunch') ) { randomFoodList.push(item); } } }); const formattedRandomFoodList = randomFoodList.map((item: any, i: number) => { return item.title; }); setRandomFoodList(formattedRandomFoodList); } } }; const getUserCurrentLatLong = () => { navigator.geolocation.getCurrentPosition((location) => { const latitude = location.coords.latitude; const longitude = location.coords.longitude; setLatitude(latitude); setLongitude(longitude); }); }; const findRestaurantsByLatLong = async ( useRandomFoodCategory: boolean, selectedTerm: string, latitude: number, longitude: number, ) => { const response = await axios.get(`${ROOT_URL}/restaurant/find-restaurants-by-lat-long`, { params: { term: useRandomFoodCategory === true ? selectedTerm : '', latitude: latitude, longitude: longitude, }, headers: { 'Content-Type': 'application/json', }, }); if (!_.isEmpty(response)) { console.log('response = ', response); setResultList(response.data.restaurants.businesses); setRefreshButtonClicked(false); } }; const handleRefresh = () => { setResultList([]); setRefreshButtonClicked(true); const selectedTerm = _.sample(randomFoodList) as any; setSelectedTerm(selectedTerm); if (latitude !== 0 && longitude !== 0) { findRestaurantsByLatLong(useRandomFoodCategory, selectedTerm, latitude, longitude); } }; const renderCurrentFoodCategory = () => { let currentFoodCategory = null; if (useRandomFoodCategory) { currentFoodCategory = ( <Text style={style.titleStyle}> {t('currentFoodCategory')} <Text style={style.currentFoodCategoryValueStyle}>{selectedTerm}</Text> </Text> ); } return currentFoodCategory; }; const renderRefreshButton = () => { let refreshButton = null; if (refreshButtonClicked === true) { refreshButton = ( <Button mode="contained" color={style.colorPrimary.color} disabled={true} onPress={handleRefresh}> {t('loading')} </Button> ); } else { refreshButton = ( <Button mode="contained" color={style.colorPrimary.color} onPress={handleRefresh}> {t('refresh')} </Button> ); } return refreshButton; }; const toggleSwitch = () => { if (!useRandomFoodCategory) setUseRandomFoodCategory(true); else setUseRandomFoodCategory(false); }; const renderDisplayResult = () => { let displayResult = null; if (!_.isEmpty(resultList)) { displayResult = ( <View> <DisplayResult navigation={props.navigation} resultList={resultList} isFavourites={false} /> <FAB style={style.fab} icon="chevron-up" onPress={() => handleFABButtonClick()} /> </View> ); } return displayResult; }; const onRefresh = () => { setRefreshing(true); getRandomFoodList(); setTimeout(() => { setRefreshing(false); }, 1000); }; const handleFABButtonClick = () => { scrollRef.current?.scrollTo({ y: 0, }); }; return ( <ScrollView ref={scrollRef} style={style.scrollViewContainer} refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#ed1f30', '#ed1f30', '#2b76f0']} /> } keyboardDismissMode="on-drag" keyboardShouldPersistTaps="always" > <View style={style.container}> {renderCurrentFoodCategory()} <Divider margin={8} /> <View style={style.rowContainer}> <Switch color={style.colorPrimary.color} value={useRandomFoodCategory} onValueChange={toggleSwitch} /> <Text style={{ marginLeft: 5, fontSize: 18, alignSelf: 'center' }}>{t('useRandomFoodCategory')}</Text> </View> <Divider margin={8} /> {renderRefreshButton()} </View> <Divider margin={5} /> {renderDisplayResult()} </ScrollView> ); } export default RandomFood;
27.61811
115
0.621525
af5d5b55129f355cafbc0b240f9d7ffd14a52862
6,072
py
Python
_apicheck/apicheck/core/openapi3.py
sundayayandele/apicheck
ab91f567d67547b92b8e94824a29dcd5993b769e
[ "Apache-2.0" ]
2
2019-05-31T09:56:59.000Z
2019-05-31T11:28:50.000Z
_apicheck/apicheck/core/openapi3.py
sundayayandele/apicheck
ab91f567d67547b92b8e94824a29dcd5993b769e
[ "Apache-2.0" ]
3
2022-02-07T03:37:37.000Z
2022-03-02T03:38:13.000Z
_apicheck/apicheck/core/openapi3.py
sundayayandele/apicheck
ab91f567d67547b92b8e94824a29dcd5993b769e
[ "Apache-2.0" ]
1
2021-07-18T15:01:22.000Z
2021-07-18T15:01:22.000Z
import json import logging from typing import Tuple, List, Dict from apicheck.core.helpers import slug, debugging from apicheck.exceptions import APICheckException from apicheck.db import APIDefinitions, APIDefinitionsCache, get_engine from .helpers import yaml_loader from .model import API, EndPointRequest, Response, ContentTypes from .dict_helpers import search_all, search, ref_resolver, transform_tree logger = logging.getLogger("apicheck") def extract_responses(method: str, content: dict) -> List[Response]: responses = [] for http_code, response_content in search(content, "responses").items(): # # Currently only extract JSON info # try: # Check end-point has json info json_content = response_content["content"]["application/json"] except KeyError: logger.info(f"Can't get JSON info") continue response_properties = search(json_content, "properties") resp = Response( http_code=http_code, content_type=ContentTypes.JSON, content=response_properties, headers={ "Content-Type": "application/json" } ) responses.append(resp) return responses def extract_endpoints(parsed_data) -> List[dict]: return search(parsed_data, "paths") def extract_methods(end_point: dict) -> Dict[str, dict]: methods = ["get", "put", "post", "patch", "delete", "trace"] for k, v in end_point.items(): if k in methods: yield k, v def extract_metadata(parsed_data: dict) -> Tuple[str, str]: metadata: dict = search(parsed_data, "info") try: api_name = slug(metadata["title"]) except KeyError: raise APICheckException("Can't get API name. Be sure definition " "file has the property 'title'") try: api_version = metadata["version"] except KeyError: raise APICheckException("Can't get API Version. Be sure definition " "file has the property 'version'") return api_name, api_version def build_api_model(str_data: str) -> API: end_points = [] end_points_append = end_points.append debug_enabled = debugging() # ------------------------------------------------------------------------- # We don't know why if debugger is enabled this code lock them. Then only # transform the complete tree when non-debug running mode # ------------------------------------------------------------------------- if not debug_enabled: parsed_data = json.loads(str_data) resolver = ref_resolver(parsed_data) parsed_data = transform_tree(parsed_data, resolver) else: parsed_data = json.loads(str_data) resolver = ref_resolver(parsed_data) logger.debug("Extracting info") for debug_counter, (end_point, end_point_info) in enumerate( extract_endpoints(parsed_data).items() ): for method, req_info in extract_methods(end_point_info): if debug_enabled: info = transform_tree(req_info, resolver) else: info = req_info # # Check request parameters # data = search(info, "properties", {"requestBody"}) req = EndPointRequest( uri=end_point, method=method, content=data, headers={}, content_type=ContentTypes.JSON, responses=extract_responses(method, info) ) end_points_append(req) if debug_enabled and debug_counter > 10: break name, version = extract_metadata(parsed_data) return API( name=name, version=version, end_points=end_points ) async def openapi3_from_db(api_id: str) -> dict: """ This function get an API Id, detect the stored definition format and call the specific format loaded. Always returns an OpenAPI3 object """ try: connection = await get_engine().connect() except Exception as e: raise APICheckException(f"Can't connect to database. Error: {e}") # ------------------------------------------------------------------------- # Try to get the loaded content form cache # ------------------------------------------------------------------------- _cached = await connection.execute( APIDefinitionsCache.select().where( APIDefinitionsCache.c.api_id == api_id ) ) try: _, api_format, cached = await _cached.fetchone() except TypeError: api_format = cached = None if not cached: # --------------------------------------------------------------------- # Getting content from original source # --------------------------------------------------------------------- c = await connection.execute( APIDefinitions.select().where( APIDefinitions.c.metadata_id == api_id ).order_by(APIDefinitions.c.id.desc()) ) try: _, api_format, _, content, _ = await c.fetchone() except TypeError: # API not found raise APICheckException(f"API '{api_id}' not found in database") else: content = cached try: logger.info("Parsing OpenAPI information") if bool(cached): parsed = json_content = json.loads(cached) else: parsed = yaml_loader(content) json_content = json.dumps(parsed) # # Save into cache # if not cached: await connection.execute( APIDefinitionsCache.insert().values( api_id=api_id, format=api_format, content=json_content )) return json_content except KeyError: raise APICheckException(f"Format '{api_format}' not supported")
29.333333
79
0.556983
69b1fc0d0c0307e8f2c464f2d0f9754c9b1ec1e9
52
sh
Shell
build.sh
jarekkozak/docker-sshtunnel
abe5e97167e04768c4502757329fc0680356a054
[ "BSD-3-Clause" ]
null
null
null
build.sh
jarekkozak/docker-sshtunnel
abe5e97167e04768c4502757329fc0680356a054
[ "BSD-3-Clause" ]
null
null
null
build.sh
jarekkozak/docker-sshtunnel
abe5e97167e04768c4502757329fc0680356a054
[ "BSD-3-Clause" ]
null
null
null
#!/bin/bash . config docker build -t $IMAGE ./src
8.666667
28
0.634615
a3084080664414502cb3e9ff505084ebdde64291
161
ts
TypeScript
packages/offix-client/src/apollo/index.ts
LakshanKarunathilake/offix
b0faaf6117d9cdff863dc833d16a4e13de91bb19
[ "Apache-2.0" ]
null
null
null
packages/offix-client/src/apollo/index.ts
LakshanKarunathilake/offix
b0faaf6117d9cdff863dc833d16a4e13de91bb19
[ "Apache-2.0" ]
null
null
null
packages/offix-client/src/apollo/index.ts
LakshanKarunathilake/offix
b0faaf6117d9cdff863dc833d16a4e13de91bb19
[ "Apache-2.0" ]
null
null
null
export * from "./ApolloOfflineClient"; export * from "./ApolloOperationSerializer"; export * from "./LinksBuilder"; export * from "./optimisticResponseHelpers";
32.2
44
0.751553
fa1d53c016e8862b1034f23a46c39111cbee4868
139
cc
C++
tests/data/test-diff-suppr/test22-suppr-removed-var-sym-v1.cc
insilications/libabigail-clr
1eb5d367686626660d3cc987b473f296b0a59152
[ "Apache-2.0" ]
3
2021-01-29T20:26:44.000Z
2021-04-28T07:49:48.000Z
tests/data/test-diff-suppr/test22-suppr-removed-var-sym-v1.cc
insilications/libabigail-clr
1eb5d367686626660d3cc987b473f296b0a59152
[ "Apache-2.0" ]
2
2021-03-07T19:31:56.000Z
2021-03-07T23:26:13.000Z
tests/data/test-diff-suppr/test22-suppr-removed-var-sym-v1.cc
insilications/libabigail-clr
1eb5d367686626660d3cc987b473f296b0a59152
[ "Apache-2.0" ]
1
2021-03-07T19:14:08.000Z
2021-03-07T19:14:08.000Z
// Compile this without debug info with: // g++ -Wall -c test22-suppr-removed-var-sym-v1.cc int global_var0 = 0; double global_var3 = 0;
23.166667
51
0.705036
48a415ddea122b6b15a2315035b6b2dc6f43f72e
1,902
dart
Dart
lib/src/mixins/batched_redraws.dart
matthewsullivan-wf/w_flux
b4c70bcb52081a24116f275f737dc0505b1575a7
[ "Apache-2.0" ]
30
2015-10-01T14:01:04.000Z
2021-12-28T19:18:07.000Z
lib/src/mixins/batched_redraws.dart
matthewsullivan-wf/w_flux
b4c70bcb52081a24116f275f737dc0505b1575a7
[ "Apache-2.0" ]
132
2015-08-25T20:35:28.000Z
2021-12-17T22:17:09.000Z
lib/src/mixins/batched_redraws.dart
matthewsullivan-wf/w_flux
b4c70bcb52081a24116f275f737dc0505b1575a7
[ "Apache-2.0" ]
25
2015-11-05T00:31:45.000Z
2021-04-12T18:00:00.000Z
library w_flux.mixins.batched_redraws; import 'dart:async'; import 'dart:html'; import 'package:react/react.dart' as react; class _RedrawScheduler implements Function { Map<BatchedRedraws, List<Function>> _components = <BatchedRedraws, List<Function>>{}; void call(BatchedRedraws component, [callback()]) { if (_components.isEmpty) { _tick(); } _components[component] ??= []; if (callback != null) _components[component].add(callback); } Future _tick() async { await window.animationFrame; // Making a copy of `_components` so we don't iterate over the map while it's potentially being mutated. var entries = _components.entries.toList(); _components.clear(); for (var entry in entries) { var component = entry.key; var callbacks = entry.value; // Skip if the component doesn't want to batch redraw if (!component.shouldBatchRedraw) { continue; } Function() chainedCallbacks; if (callbacks.isNotEmpty) { chainedCallbacks = () { callbacks.forEach((callback) { callback(); }); }; } (component as react.Component)?.setState({}, chainedCallbacks); // Waits a tick to prevent holding up the thread, allowing other scripts to execute in between each component. await Future(() {}); } } } _RedrawScheduler _scheduleRedraw = _RedrawScheduler(); /// A mixin that overrides the [Component.redraw] method of a React /// [Component] (including a [FluxComponent]) and prevents the component /// from being redrawn more than once per animation frame. /// /// Example: /// /// class MyComponent extends react.Component /// with BatchedRedraws { /// render() {...} /// } /// class BatchedRedraws { bool shouldBatchRedraw = true; void redraw([callback()]) => _scheduleRedraw(this, callback); }
26.416667
116
0.650368
f69c448ca3898f8519a24ca09ea32b8845428714
3,139
sql
SQL
migrations/sql/R__add_update_indexes.sql
bcgov/mds
6c427a66a5edb4196222607291adef8fd6677038
[ "Apache-2.0" ]
25
2018-07-09T19:04:37.000Z
2022-03-15T17:27:10.000Z
migrations/sql/R__add_update_indexes.sql
areyeslo/mds
e8c38e593e09b78e2a57009c0d003d6c4bfa32e6
[ "Apache-2.0" ]
983
2018-04-25T20:08:07.000Z
2022-03-31T21:45:20.000Z
migrations/sql/R__add_update_indexes.sql
areyeslo/mds
e8c38e593e09b78e2a57009c0d003d6c4bfa32e6
[ "Apache-2.0" ]
58
2018-05-15T22:35:50.000Z
2021-11-29T19:40:52.000Z
/** Repetable migrations to manage database indexes. Indexes are grouped by table names alphabetically. **/ /* Mine */ CREATE INDEX IF NOT EXISTS active_mine_mine_region_fkey_idx ON mine(mine_region, deleted_ind) WHERE (deleted_ind = false); CREATE INDEX IF NOT EXISTS mine_mine_name_search_idx ON mine USING gist (mine_name gist_trgm_ops); CREATE INDEX IF NOT EXISTS mine_mine_no_search_idx ON mine USING gist (mine_no gist_trgm_ops); /* Mine document */ CREATE INDEX IF NOT EXISTS mine_document_document_name_search_idx on mine_document USING gist (document_name gist_trgm_ops); /* Mine Location */ DROP INDEX IF EXISTS mine_location_lat_long_idx; DROP INDEX IF EXISTS mine_location_geom_idx; /* Mine party appt */ DROP INDEX IF EXISTS mine_party_appt_guid_idx; CREATE INDEX IF NOT EXISTS mine_party_appt_mine_guid_fkey_idx ON mine_party_appt(mine_guid); CREATE INDEX IF NOT EXISTS mine_party_appt_party_guid_fkey_idx ON mine_party_appt(party_guid); CREATE INDEX IF NOT EXISTS mine_party_appt_mine_party_appt_type_code_fkey_idx ON mine_party_appt(mine_party_appt_type_code); CREATE INDEX IF NOT EXISTS mine_party_appt_mine_guid_permit_id_fkey_idx ON mine_party_appt(mine_guid, permit_id); CREATE INDEX IF NOT EXISTS mine_party_appt_mine_tsf_guid_mine_guid_fkey_idx ON mine_party_appt(mine_tailings_storage_facility_guid,mine_guid); CREATE INDEX IF NOT EXISTS mine_party_appt_permit_id_mine_party_appt_type_code_end_date_idx ON mine_party_appt (permit_id, mine_party_appt_type_code, end_date DESC NULLS FIRST); /* Mine Type */ DROP INDEX IF EXISTS mine_type_tenure_type_code_idx; DROP INDEX IF EXISTS mine_type_tenure_type_id_idx; DROP INDEX IF EXISTS mine_type_update_timestamp_idx; CREATE INDEX IF NOT EXISTS active_mine_type_mine_tenure_type_code_fkey_idx ON mine_type(mine_tenure_type_code, active_ind) WHERE (active_ind = true); /* Party */ DROP INDEX IF EXISTS active_party_sub_division_code_fkey_idx; DROP INDEX IF EXISTS active_party_address_type_code_fkey_idx; CREATE INDEX IF NOT EXISTS active_party_party_type_code_fkey_idx ON party(party_type_code, deleted_ind) WHERE (deleted_ind = false); CREATE INDEX IF NOT EXISTS party_email_search_idx ON party USING gist (email gist_trgm_ops); CREATE INDEX IF NOT EXISTS party_first_name_search_idx ON party USING gist (first_name gist_trgm_ops); CREATE INDEX IF NOT EXISTS party_party_name_search_idx ON party USING gist (party_name gist_trgm_ops); CREATE INDEX IF NOT EXISTS party_phone_no_search_idx ON party USING gist (phone_no gist_trgm_ops); /* Permit */ CREATE INDEX IF NOT EXISTS permit_permit_status_code_fkey_idx ON permit(permit_status_code); /* Permit amendment */ CREATE INDEX IF NOT EXISTS active_permit_amendment_permit_fkey_idx ON permit_amendment(permit_id, deleted_ind) WHERE (deleted_ind = false); CREATE INDEX IF NOT EXISTS active_permit_amendment_permit_amendment_status_code_fkey_idx ON permit_amendment(permit_amendment_status_code, deleted_ind) WHERE (deleted_ind = false); CREATE INDEX IF NOT EXISTS active_permit_amendment_permit_amendment_type_code_fkey_idx ON permit_amendment(permit_amendment_type_code, deleted_ind) WHERE (deleted_ind = false);
61.54902
180
0.854731
c2dbd58e84514e087fdc4ccfd5f034c7c927fbac
462
kt
Kotlin
tmp/arrays/youTrackTests/1406.kt
vitekkor/bbfgradle
b4ec701a7a3b7523db97631fa0ed6484149ca9cd
[ "Apache-2.0" ]
1
2021-04-06T16:59:24.000Z
2021-04-06T16:59:24.000Z
tmp/arrays/youTrackTests/1406.kt
vitekkor/bbfgradle
b4ec701a7a3b7523db97631fa0ed6484149ca9cd
[ "Apache-2.0" ]
null
null
null
tmp/arrays/youTrackTests/1406.kt
vitekkor/bbfgradle
b4ec701a7a3b7523db97631fa0ed6484149ca9cd
[ "Apache-2.0" ]
11
2020-03-23T08:28:36.000Z
2022-03-22T07:04:42.000Z
// Original bug: KT-44198 package compilerBug.demo fun main(args: Array<String>) { AnonymousClassInLambda().run() } class AnonymousClassInLambda() { fun run() { val foo = listOf("hello", "world") val threads = (1..10).map { object: Runnable { override fun run() { println("foo has size ${foo.size}") } } } threads.forEach { it.run() } } }
21
55
0.495671