identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/jrm5100/fgbio/blob/master/src/main/scala/com/fulcrumgenomics/bam/CallOverlappingConsensusBases.scala
Github Open Source
Open Source
MIT
null
fgbio
jrm5100
Scala
Code
1,026
2,413
/* * The MIT License * * Copyright (c) 2022 Fulcrum Genomics * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.fulcrumgenomics.bam import com.fulcrumgenomics.FgBioDef.{FgBioEnum, FilePath, PathToBam, PathToFasta, SafelyClosable} import com.fulcrumgenomics.bam.api.{SamOrder, SamSource, SamWriter} import com.fulcrumgenomics.cmdline.{ClpGroups, FgBioTool} import com.fulcrumgenomics.commons.collection.ParIterator import com.fulcrumgenomics.commons.util.LazyLogging import com.fulcrumgenomics.commons.util.Threads.IterableThreadLocal import com.fulcrumgenomics.sopt.{arg, clp} import com.fulcrumgenomics.util.{Io, Metric, ProgressLogger} import enumeratum.EnumEntry import scala.collection.immutable @clp(group = ClpGroups.SamOrBam, description= """ |Consensus calls overlapping bases in read pairs. | |## Inputs and Outputs | |In order to correctly correct reads by template, the input BAM must be either `queryname` sorted or `query` grouped. |The sort can be done in streaming fashion with: | |``` |samtools sort -n -u in.bam | fgbio CallOverlappingConsensusBases -i /dev/stdin ... |``` | |The output sort order may be specified with `--sort-order`. If not given, then the output will be in the same |order as input. | |The reference FASTA must be given so that any existing `NM`, `UQ` and `MD` tags can be repaired. | |## Correction | |Only mapped read pairs with overlapping bases will be eligible for correction. | |Each read base from the read and its mate that map to same position in the reference will be used to create |a consensus base as follows: | |1. If the base agree, then the chosen agreement strategy (`--agreement-strategy`) will be used. |2. If the base disagree, then the chosen disagreement strategy (`--disagreement-strategy`) will be used. | |The agreement strategies are as follows: | |* Consensus: Call the consensus base and return a new base quality that is the sum of the two base qualities. |* MaxQual: Call the consensus base and return a new base quality that is the maximum of the two base qualities. |* PassThrough: Leave the bases and base qualities unchanged. | |In the context of disagreement strategies, masking a base will make the base an "N" with base quality phred-value "2". |The disagreement strategies are as follows: | |* MaskBoth: Mask both bases. |* MaskLowerQual: Mask the base with the lowest base quality, with the other base unchanged. If the base qualities | are the same, mask both bases. |* Consensus: Consensus call the base. If the base qualities are the same, mask both bases. Otherwise, call the | base with the highest base quality and return a new base quality that is the difference between the | highest and lowest base quality. | """) class CallOverlappingConsensusBases (@arg(flag='i', doc="Input SAM or BAM file of aligned reads.") val input: PathToBam, @arg(flag='o', doc="Output SAM or BAM file.") val output: PathToBam, @arg(flag='m', doc="Output metrics file.") val metrics: FilePath, @arg(flag='r', doc="Reference sequence fasta file.") val ref: PathToFasta, @arg(doc="The number of threads to use while consensus calling.") val threads: Int = 1, @arg(flag='S', doc="The sort order of the output. If not given, output will be in the same order as input if the input.") val sortOrder: Option[SamOrder] = None, @arg(doc="The strategy to consensus call when both bases agree. See the usage for more details") val agreementStrategy: AgreementStrategy = AgreementStrategy.Consensus, @arg(doc="The strategy to consensus call when both bases disagree. See the usage for more details") val disagreementStrategy: DisagreementStrategy = DisagreementStrategy.Consensus ) extends FgBioTool with LazyLogging { Io.assertReadable(input) Io.assertReadable(ref) Io.assertCanWriteFile(output) private case class ThreadData (caller: OverlappingBasesConsensusCaller = new OverlappingBasesConsensusCaller(agreementStrategy=agreementStrategy, disagreementStrategy=disagreementStrategy), templateMetric: CallOverlappingConsensusBasesMetric = CallOverlappingConsensusBasesMetric(kind=CountKind.Templates), basesMetric: CallOverlappingConsensusBasesMetric = CallOverlappingConsensusBasesMetric(kind=CountKind.Bases) ) override def execute(): Unit = { val source = SamSource(input) val outSort = sortOrder.flatMap { order => if (SamOrder(source.header).contains(order)) None else Some(order) } val writer = Bams.nmUqMdTagRegeneratingWriter(writer=SamWriter(output, source.header.clone(), sort=outSort), ref=ref) val progress = new ProgressLogger(logger) val templateIterator = Bams.templateIterator(source) val threadData = new IterableThreadLocal(() => ThreadData()) // Require queryname sorted or query grouped Bams.requireQueryGrouped(header=source.header, toolName="CallOverlappingConsensusBases") ParIterator(templateIterator, threads=threads) .map { template => val threadDatum = threadData.get() threadDatum.synchronized { // update metrics threadDatum.templateMetric.total += 1 threadDatum.basesMetric.total += template.primaryReads.map(_.length).sum // corrects val stats = threadDatum.caller.call(template) val correctedBases = stats.r1CorrectedBases + stats.r2CorrectedBases if (stats.overlappingBases > 0) { threadDatum.templateMetric.overlapping += 1 threadDatum.basesMetric.overlapping += stats.overlappingBases if (correctedBases > 0) { threadDatum.templateMetric.corrected += 1 threadDatum.basesMetric.corrected += correctedBases } } } template.allReads.foreach(progress.record) template }.toAsync(ParIterator.DefaultChunkSize * 8).foreach { template => writer ++= template.allReads } progress.logLast() source.safelyClose() writer.close() val templatesMetric = CallOverlappingConsensusBasesMetric(kind=CountKind.Templates) val basesMetric = CallOverlappingConsensusBasesMetric(kind=CountKind.Bases) threadData.foreach { datum => templatesMetric += datum.templateMetric basesMetric += datum.basesMetric } Metric.write(metrics, templatesMetric, basesMetric) } } /** Collects the the number of reads or bases that were examined, had overlap, and were corrected as part of * the [[CallOverlappingConsensusBases]] tool. * * @param kind template if the counts are per template, bases if counts are in units of bases. * @param total the total number of templates (bases) examined * @param overlapping the total number of templates (bases) that were overlapping * @param corrected the total number of templates (bases) that were corrected. */ case class CallOverlappingConsensusBasesMetric ( kind: CountKind, var total: Long = 0, var overlapping: Long = 0, var corrected: Long = 0, ) extends Metric { def +=(other: CallOverlappingConsensusBasesMetric): CallOverlappingConsensusBasesMetric = { require(this.kind == other.kind) this.total += other.total this.overlapping += other.overlapping this.corrected += other.corrected this } } sealed trait CountKind extends EnumEntry /** Enumeration for the type of counts in [[CallOverlappingConsensusBasesMetric]]. */ object CountKind extends FgBioEnum[CountKind] { case object Templates extends CountKind case object Bases extends CountKind override def values: immutable.IndexedSeq[CountKind] = findValues }
43,008
https://github.com/kp-favorite/wip/blob/master/JavaScript/DynamicLoadOfScripts.js
Github Open Source
Open Source
MIT
null
wip
kp-favorite
JavaScript
Code
79
216
// // THIS GIVES A STRANGE RECURSIVE DEFINITION OF constructors, // USE THE OTHER METHOD in DynamivLoadOfScripts2.js INSTEAD // var gizur2; if(!gizur2) gizur2 = {}; // A simple module gizur2.modules = (function () { // A private constructor function MyModule() { this._myString = ""; // a private variable } MyModule.prototype.getString = function() { return this._myString; } MyModule.prototype.setString = function(str) { this._myString = str; } return { MyModule: MyModule }; // make the module public by returning the constructors }());
30,752
https://github.com/nomantufail/jr-architecture/blob/master/app/Http/Validators/Validators/UserValidators/AddUserValidator.php
Github Open Source
Open Source
MIT
null
jr-architecture
nomantufail
PHP
Code
79
232
<?php /** * Created by PhpStorm. * User: JR Tech * Date: 3/21/2016 * Time: 9:22 AM */ namespace App\Http\Validators\Validators\UserValidators; use App\Http\Validators\Interfaces\ValidatorsInterface; class AddUserValidator extends UserValidator implements ValidatorsInterface { public function __construct($request){ parent::__construct($request); } public function CustomValidationMessages(){ return [ // ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'f_name' => 'required', 'l_name' => 'required', 'email' => 'required|email|unique:users|max:255', 'password' => 'required' ]; } }
19,387
https://github.com/BradenLinick/Dolphin/blob/master/Core/Object Arts/Dolphin/MVP/SingleSelectListBoxTest.cls
Github Open Source
Open Source
MIT
2,019
Dolphin
BradenLinick
Apex
Code
195
595
"Filed out from Dolphin Smalltalk 7"! ListBoxTest subclass: #SingleSelectListBoxTest instanceVariableNames: '' classVariableNames: '' poolDictionaries: '' classInstanceVariableNames: ''! SingleSelectListBoxTest guid: (GUID fromString: '{8e5a59a5-f500-4d07-9ea2-b1019c9302b2}')! SingleSelectListBoxTest comment: ''! !SingleSelectListBoxTest categoriesForClass!Unclassified! ! !SingleSelectListBoxTest methodsFor! testSelectionModeChange | objects | self deny: presenter view isMultiSelect. objects := self objectsToTest. presenter model addAll: objects. self assert: presenter hasSelection not. self assertIsNil: presenter selectionOrNil. "Must trigger a selection change when switching to multi-select, as otherwise observers do not know the mode change has occurred." self should: [presenter view isMultiSelect: true] trigger: #selectionChanged against: presenter. self assert: presenter hasSelection not. self assertIsNil: presenter selectionOrNil. self assert: presenter view selectionMode identicalTo: #multi. self shouldnt: [presenter view selectionMode: #toggle] trigger: #selectionChanged against: presenter. self shouldnt: [presenter view selectionMode: #multi] trigger: #selectionChanged against: presenter. self should: [presenter view isMultiSelect: false] trigger: #selectionChanged against: presenter. presenter selection: objects second. self assert: presenter view selectionsByIndex equals: #(2). self should: [presenter view getMultipleSelections] raise: Error. self should: [presenter view isMultiSelect: true] trigger: #selectionChanged against: presenter. "#115: Changing list box selection mode fails if there are selections" self assert: presenter view selectionsByIndex equals: #(2)! ! !SingleSelectListBoxTest categoriesFor: #testSelectionModeChange!public!unit tests! ! !SingleSelectListBoxTest class methodsFor! classToTest ^ListPresenter! ! !SingleSelectListBoxTest class categoriesFor: #classToTest!helpers!private! !
46,938
https://github.com/laurenceschellevisch/runelite/blob/master/runescape-client/src/main/java/class14.java
Github Open Source
Open Source
BSD-2-Clause
null
runelite
laurenceschellevisch
Java
Code
496
2,237
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; import net.runelite.rs.ScriptOpcodes; @ObfuscatedName("s") public class class14 { @ObfuscatedName("a") @ObfuscatedSignature( descriptor = "Loi;" ) static IndexedSprite field69; @ObfuscatedName("n") @ObfuscatedGetter( intValue = 1162986903 ) final int field71; @ObfuscatedName("c") final String field67; @ObfuscatedName("m") final ThreadFactory field68; @ObfuscatedName("k") final ThreadPoolExecutor field70; public class14(String var1, int var2, int var3) { this.field67 = var1; this.field71 = var2; this.field68 = new class16(this); this.field70 = this.method182(var3); } @ObfuscatedName("n") @ObfuscatedSignature( descriptor = "(II)Ljava/util/concurrent/ThreadPoolExecutor;", garbageValue = "6276176" ) final ThreadPoolExecutor method182(int var1) { return new ThreadPoolExecutor(var1, var1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue(this.field71), this.field68); } @ObfuscatedName("c") @ObfuscatedSignature( descriptor = "(Ll;I)Lx;", garbageValue = "1026683688" ) public class19 method186(class10 var1) { if (this.field70.getQueue().remainingCapacity() <= 0) { System.err.println("REST thread pool queue is empty\r\nThread pool size " + this.field70.getCorePoolSize() + " Queue capacity " + this.field71); return new class19("Queue full"); } else { class19 var2 = new class19(this.field70.submit(new class20(this, var1))); return var2; } } @ObfuscatedName("m") @ObfuscatedSignature( descriptor = "(I)V", garbageValue = "-1134604933" ) public final void method191() { try { this.field70.shutdown(); } catch (Exception var2) { System.err.println("Error shutting down RestRequestService\r\n" + var2); } } @ObfuscatedName("o") @ObfuscatedSignature( descriptor = "(ILbg;ZI)I", garbageValue = "1662089462" ) static int method185(int var0, Script var1, boolean var2) { int var3 = -1; Widget var4; if (var0 >= 2000) { var0 -= 1000; var3 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize]; var4 = class87.getWidget(var3); } else { var4 = var2 ? PacketWriter.scriptDotWidget : class9.scriptActiveWidget; } if (var0 == ScriptOpcodes.CC_SETPOSITION) { class240.Interpreter_intStackSize -= 4; var4.rawX = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize]; var4.rawY = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 1]; var4.xAlignment = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 2]; var4.yAlignment = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 3]; Actor.invalidateWidget(var4); ArchiveDiskActionHandler.client.alignWidget(var4); if (var3 != -1 && var4.type == 0) { VerticalAlignment.revalidateWidgetScroll(class139.Widget_interfaceComponents[var3 >> 16], var4, false); } return 1; } else if (var0 == ScriptOpcodes.CC_SETSIZE) { class240.Interpreter_intStackSize -= 4; var4.rawWidth = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize]; var4.rawHeight = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 1]; var4.widthAlignment = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 2]; var4.heightAlignment = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 3]; Actor.invalidateWidget(var4); ArchiveDiskActionHandler.client.alignWidget(var4); if (var3 != -1 && var4.type == 0) { VerticalAlignment.revalidateWidgetScroll(class139.Widget_interfaceComponents[var3 >> 16], var4, false); } return 1; } else if (var0 == ScriptOpcodes.CC_SETHIDE) { boolean var5 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; if (var5 != var4.isHidden) { var4.isHidden = var5; Actor.invalidateWidget(var4); } return 1; } else if (var0 == ScriptOpcodes.CC_SETNOCLICKTHROUGH) { var4.noClickThrough = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; return 1; } else if (var0 == ScriptOpcodes.CC_SETNOSCROLLTHROUGH) { var4.noScrollThrough = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; return 1; } else { return 2; } } @ObfuscatedName("b") @ObfuscatedSignature( descriptor = "(ILbg;ZI)I", garbageValue = "-1305341703" ) static int method190(int var0, Script var1, boolean var2) { Widget var3 = class87.getWidget(Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize]); if (var0 == ScriptOpcodes.IF_GETTARGETMASK) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = class138.Widget_unpackTargetMask(Decimator.getWidgetFlags(var3)); return 1; } else if (var0 != ScriptOpcodes.IF_GETOP) { if (var0 == ScriptOpcodes.IF_GETOPBASE) { if (var3.dataText == null) { Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; } else { Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = var3.dataText; } return 1; } else { return 2; } } else { int var4 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize]; --var4; if (var3.actions != null && var4 < var3.actions.length && var3.actions[var4] != null) { Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = var3.actions[var4]; } else { Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; } return 1; } } }
25,304
https://github.com/pronoy2108/SwiftBrowser/blob/master/SwiftBrowser/SettingsViews/WebSettings.xaml.cs
Github Open Source
Open Source
Unlicense
2,021
SwiftBrowser
pronoy2108
C#
Code
1,037
4,445
using System; using System.Collections.Generic; using System.Linq; using Windows.Foundation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Microsoft.Toolkit.Uwp.UI.Animations.Expressions; using System.ComponentModel; using System.Numerics; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Windows.UI.Composition; using Windows.UI.Xaml.Hosting; using Windows.UI.Xaml.Media.Imaging; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238 namespace SwiftBrowser.SettingsViews { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class WebSettings : Page { public event PropertyChangedEventHandler PropertyChanged; public WebSettings() { this.InitializeComponent(); I.IsOn = (bool)Windows.Storage.ApplicationData.Current.LocalSettings.Values["IndexDB"]; E.IsOn = (bool)Windows.Storage.ApplicationData.Current.LocalSettings.Values["Javascript"]; switch ((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["SearchEngine"]) { case "https://www.ecosia.org/search?q=": se.SelectedIndex = 0; break; case "https://www.google.com/search?q=": se.SelectedIndex = 2; break; case "https://www.bing.com/search?q=": se.SelectedIndex = 3; break; case "http://www.baidu.com/s?wd=": se.SelectedIndex = 5; break; case "https://www.yandex.com/search/?text=": se.SelectedIndex = 4; break; case "https://duckduckgo.com/?q=": se.SelectedIndex = 6; break; case "https://search.yahoo.com/search?p=": se.SelectedIndex = 7; break; case "https://en.wikipedia.org/w/index.php?search=": se.SelectedIndex = 1; break; } switch ((string)Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"]) { case "Default": UserAgent.SelectedIndex = 0; break; case "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36": UserAgent.SelectedIndex = 2; break; case "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0": UserAgent.SelectedIndex = 1; break; case "Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36": UserAgent.SelectedIndex = 3; break; case "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/69.0.3497.105 Mobile/15E148 Safari/605.1": UserAgent.SelectedIndex = 4; break; case "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/13.1058": UserAgent.SelectedIndex = 5; break; case "Mozilla/5.0 (Linux; Android 7.0; SM-T827R4 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.116 Safari/537.36": UserAgent.SelectedIndex = 6; break; case "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9": UserAgent.SelectedIndex = 7; break; case "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36": UserAgent.SelectedIndex = 8; break; case "Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36": UserAgent.SelectedIndex = 9; break; case "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1": UserAgent.SelectedIndex = 10; break; case "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/13.10586": UserAgent.SelectedIndex = 11; break; } _compositor = ElementCompositionPreview.GetElementVisual(this)?.Compositor; Setup(); } private Compositor _compositor; private List<Visual> _gearVisuals; private ScalarKeyFrameAnimation _gearMotionScalarAnimation; private double _x = 87, _y = 0d, _width = 100, _height = 100; private double _gearDimension = 87; private int _count; public int Count { get { return _count; } set { _count = value; RaisePropertyChanged(); } } private async void Setup() { var firstGearVisual = ElementCompositionPreview.GetElementVisual(FirstGear); firstGearVisual.Size = new Vector2((float)FirstGear.ActualWidth, (float)FirstGear.ActualHeight); firstGearVisual.AnchorPoint = new Vector2(0.5f, 0.5f); for (int i = Container.Children.Count - 1; i > 0; i--) { Container.Children.RemoveAt(i); } _x = 87; _y = 0d; _width = 100; _height = 100; _gearDimension = 87; Count = 1; _gearVisuals = new List<Visual>() { firstGearVisual }; var bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/Gear.png")); var image = new Image { Source = bitmapImage, Width = _width, Height = _height, RenderTransformOrigin = new Point(0.5, 0.5) }; // Set the coordinates of where the image should be Canvas.SetLeft(image, _x); Canvas.SetTop(image, _y); PerformLayoutCalculation(); // Add the gear to the container Container.Children.Add(image); // Add a gear visual to the screen var gearVisual = AddGear(image); ConfigureGearAnimation(_gearVisuals[_gearVisuals.Count - 1], _gearVisuals[_gearVisuals.Count - 2]); await Task.Delay(1000); StartGearMotor(5); } private Visual AddGear(Image gear) { // Create a visual based on the XAML object var visual = ElementCompositionPreview.GetElementVisual(gear); visual.Size = new Vector2((float)gear.ActualWidth, (float)gear.ActualHeight); visual.AnchorPoint = new Vector2(0.5f, 0.5f); _gearVisuals.Add(visual); Count++; return visual; } private void StartGearMotor(double secondsPerRotation) { // Start the first gear (the red one) if (_gearMotionScalarAnimation == null) { _gearMotionScalarAnimation = _compositor.CreateScalarKeyFrameAnimation(); var linear = _compositor.CreateLinearEasingFunction(); var startingValue = ExpressionValues.StartingValue.CreateScalarStartingValue(); _gearMotionScalarAnimation.InsertExpressionKeyFrame(0.0f, startingValue); _gearMotionScalarAnimation.InsertExpressionKeyFrame(1.0f, startingValue + 360f, linear); _gearMotionScalarAnimation.IterationBehavior = AnimationIterationBehavior.Forever; } _gearMotionScalarAnimation.Duration = TimeSpan.FromSeconds(secondsPerRotation); _gearVisuals.First().StartAnimation("RotationAngleInDegrees", _gearMotionScalarAnimation); } private void ConfigureGearAnimation(Visual currentGear, Visual previousGear) { // If rotation expression is null then create an expression of a gear rotating the opposite direction var rotateExpression = -previousGear.GetReference().RotationAngleInDegrees; // Start the animation based on the Rotation Angle in Degrees. currentGear.StartAnimation("RotationAngleInDegrees", rotateExpression); } private void PerformLayoutCalculation() { if ( ((_x + Container.Margin.Left + _width > Container.ActualWidth) && _gearDimension > 0) || (_x < Container.Margin.Left && _gearDimension < 0)) { if (_gearDimension < 0) { _y -= _gearDimension; } else { _y += _gearDimension; } _gearDimension = -_gearDimension; } else { _x += _gearDimension; } } private void RaisePropertyChanged([CallerMemberName]string property = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property)); } private void UserAgent_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox c = sender as ComboBox; switch (c.SelectedItem.ToString()) { case "Default": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Default"; break; case "Google": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"; break; case "Firefox": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0"; break; case "Android (galaxy s9)": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36"; break; case "Iphone (iphone XS chrome)": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/69.0.3497.105 Mobile/15E148 Safari/605.1"; break; case "Windows phone (lumia 950)": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/13.1058"; break; case "Tablet (samsung tab s3)": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (Linux; Android 7.0; SM-T827R4 Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.116 Safari/537.36"; break; case "Desktop (Macos safari)": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9"; break; case "Desktop (Windows 7 chrome)": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"; break; case "Desktop (chromeos chrome)": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36"; break; case "Desktop (linux firefox)": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1"; break; case "Console (xbox one)": Windows.Storage.ApplicationData.Current.LocalSettings.Values["UserAgent"] = "Mozilla/5.0 (Windows Phone 10.0; Android 4.2.1; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Mobile Safari/537.36 Edge/13.10586"; break; } } private void I_Toggled(object sender, RoutedEventArgs e) { Windows.Storage.ApplicationData.Current.LocalSettings.Values["IndexDB"] = I.IsOn; } private void E_Toggled(object sender, RoutedEventArgs e) { Windows.Storage.ApplicationData.Current.LocalSettings.Values["Javascript"] = E.IsOn; } private void Se_SelectionChanged(object sender, SelectionChangedEventArgs e) { ComboBox c = sender as ComboBox; switch (c.SelectedItem.ToString()) { case "Ecosia": Windows.Storage.ApplicationData.Current.LocalSettings.Values["SearchEngine"] = "https://www.ecosia.org/search?q="; break; case "Google": Windows.Storage.ApplicationData.Current.LocalSettings.Values["SearchEngine"] = "https://www.google.com/search?q="; break; case "Bing": Windows.Storage.ApplicationData.Current.LocalSettings.Values["SearchEngine"] = "https://www.bing.com/search?q="; break; case "Baidu": Windows.Storage.ApplicationData.Current.LocalSettings.Values["SearchEngine"] = "http://www.baidu.com/s?wd="; break; case "DuckDuckGo": Windows.Storage.ApplicationData.Current.LocalSettings.Values["SearchEngine"] = "https://duckduckgo.com/?q="; break; case "Yandex": Windows.Storage.ApplicationData.Current.LocalSettings.Values["SearchEngine"] = "https://www.yandex.com/search/?text="; break; case "Yahoo": Windows.Storage.ApplicationData.Current.LocalSettings.Values["SearchEngine"] = "https://search.yahoo.com/search?p="; break; case "Wikipedia": Windows.Storage.ApplicationData.Current.LocalSettings.Values["SearchEngine"] = "https://en.wikipedia.org/w/index.php?search="; break; } } } }
48,658
https://github.com/tsukoyumi/ouzel/blob/master/engine/input/Mouse.hpp
Github Open Source
Open Source
Unlicense
null
ouzel
tsukoyumi
C++
Code
190
574
// Ouzel by Elviss Strazdins #ifndef OUZEL_INPUT_MOUSE_HPP #define OUZEL_INPUT_MOUSE_HPP #include <bitset> #include <cstdint> #include "Controller.hpp" #include "../math/Vector.hpp" namespace ouzel::input { class Cursor; class Mouse final: public Controller { friend InputManager; public: enum class Button { none, left, // Left mouse button right, // Right mouse button middle, // Middle mouse button (three-button mouse) x1, // First extra mouse button x2, // Second extra mouse button last = x2 }; Mouse(InputManager& initInputManager, DeviceId initDeviceId); auto& getPosition() const noexcept { return position; } void setPosition(const math::Vector<float, 2>& newPosition); auto isButtonDown(Button button) const { return buttonStates.test(static_cast<std::size_t>(button)); } auto isCursorVisible() const noexcept { return cursorVisible; } void setCursorVisible(bool visible); auto isCursorLocked() const noexcept { return cursorLocked; } void setCursorLocked(bool locked); auto getCursor() const noexcept { return cursor; } void setCursor(const Cursor* newCursor); private: bool handleButtonPress(Mouse::Button button, const math::Vector<float, 2>& pos); bool handleButtonRelease(Mouse::Button button, const math::Vector<float, 2>& pos); bool handleMove(const math::Vector<float, 2>& pos); bool handleRelativeMove(const math::Vector<float, 2>& pos); bool handleScroll(const math::Vector<float, 2>& scroll, const math::Vector<float, 2>& pos); bool handleCursorLockChange(bool locked); math::Vector<float, 2> position{}; std::bitset<static_cast<std::size_t>(Button::last) + 1U> buttonStates; bool cursorVisible = true; bool cursorLocked = false; const Cursor* cursor = nullptr; }; } #endif // OUZEL_INPUT_MOUSE_HPP
25,632
https://github.com/urna/OpenBots.Server/blob/master/OpenBots.Server.ViewModel/FileObjectViewModel.cs
Github Open Source
Open Source
Apache-2.0
2,020
OpenBots.Server
urna
C#
Code
42
87
using System.IO; namespace OpenBots.Server.ViewModel { public class FileObjectViewModel { public virtual string Name { get; set; } public virtual string ContentType { get; set; } public virtual string StoragePath { get; set; } public virtual FileStream BlobStream {get; set; } } }
38,504
https://github.com/2002-feb24-net/tyler-code/blob/master/StringStuff/Program.cs
Github Open Source
Open Source
MIT
null
tyler-code
2002-feb24-net
C#
Code
138
384
using System; namespace StringStuff { class Program { static void Main(string[] args) { //Console.Read is for one character System.Console.Write("enter some text: "); String input = Console.ReadLine(); if (input.Contains("nick")) // case sentive by defuault { System.Console.WriteLine("Input contains 'nick'"); } else { System.Console.WriteLine(input); } // input.IndexOf like contains instead of returning true it returns where in the strings // instead of false Console.Write("index of '.' "); int index = input.IndexOf("."); System.Console.WriteLine(input.IndexOf(".")); //substring is with indexof System.Console.WriteLine("After the first dot"); System.Console.WriteLine(input.Substring(index + 1)); //if -1 console.write not found int length = input.Length; //how many chars //how to find how many words in a string break it up spaces int words = input.Split(' ').Length; System.Console.WriteLine(words); String[] words2 = input.Split(' '); String stringWithoutSpcaes = input.Replace(' ', '-'); System.Console.WriteLine(stringWithoutSpcaes); //ToUpper and ToLower String uperCase, lowerCase; uperCase = input.ToUpper(); lowerCase = input.ToLower(); } } }
42,983
https://github.com/itwwj/mykit-data/blob/master/mykit-data-monitor/src/main/java/io/mykit/data/monitor/mysql/io/impl/XInputStreamImpl.java
Github Open Source
Open Source
Apache-2.0
null
mykit-data
itwwj
Java
Code
892
2,200
package io.mykit.data.monitor.mysql.io.impl; import io.mykit.data.monitor.mysql.common.glossary.UnsignedLong; import io.mykit.data.monitor.mysql.common.glossary.column.BitColumn; import io.mykit.data.monitor.mysql.common.glossary.column.StringColumn; import io.mykit.data.monitor.mysql.common.util.CodecUtils; import io.mykit.data.monitor.mysql.io.ExceedLimitException; import io.mykit.data.monitor.mysql.io.XInputStream; import io.mykit.data.monitor.mysql.io.util.XSerializer; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; public class XInputStreamImpl extends InputStream implements XInputStream { private int head = 0; private int tail = 0; private final byte[] buffer; private final InputStream is; protected int readCount = 0; protected int readLimit = 0; public XInputStreamImpl(InputStream is) { this(is, 512 * 1024); } public XInputStreamImpl(InputStream is, int size) { this.is = is; this.buffer = new byte[size]; } public int readInt(int length) throws IOException { return readInt(length, true); } public long readLong(int length) throws IOException { return readLong(length, true); } public byte[] readBytes(int length) throws IOException { final byte[] r = new byte[length]; this.read(r, 0, length); return r; } public BitColumn readBit(int length) throws IOException { return readBit(length, true); } public UnsignedLong readUnsignedLong() throws IOException { final int v = this.read(); if (v < 251) return UnsignedLong.valueOf(v); else if (v == 251) return null; else if (v == 252) return UnsignedLong.valueOf(readInt(2)); else if (v == 253) return UnsignedLong.valueOf(readInt(3)); else if (v == 254) return UnsignedLong.valueOf(readLong(8)); else throw new RuntimeException("assertion failed, should NOT reach here"); } public StringColumn readLengthCodedString() throws IOException { final UnsignedLong length = readUnsignedLong(); return length == null ? null : readFixedLengthString(length.intValue()); } public StringColumn readNullTerminatedString() throws IOException { final XSerializer s = new XSerializer(128); // 128 should be OK for most schema names while (true) { final int v = this.read(); if (v == 0) break; s.writeInt(v, 1); } return StringColumn.valueOf(s.toByteArray()); } public StringColumn readFixedLengthString(final int length) throws IOException { return StringColumn.valueOf(readBytes(length)); } /** * */ public int readSignedInt(int length) throws IOException { int r = 0; for (int i = 0; i < length; ++i) { final int v = this.read(); r |= (v << (i << 3)); if ((i == length - 1) && ((v & 0x80) == 0x80)) { for (int j = length; j < 4; j++) { r |= (255 << (j << 3)); } } } return r; } public long readSignedLong(int length) throws IOException { long r = 0; for (int i = 0; i < length; ++i) { final long v = this.read(); r |= (v << (i << 3)); if ((i == length - 1) && ((v & 0x80) == 0x80)) { for (int j = length; j < 8; j++) { r |= (255 << (j << 3)); } } } return r; } public int readInt(int length, boolean littleEndian) throws IOException { int r = 0; for (int i = 0; i < length; ++i) { final int v = this.read(); if (littleEndian) { r |= (v << (i << 3)); } else { r = (r << 8) | v; } } return r; } public long readLong(int length, boolean littleEndian) throws IOException { long r = 0; for (int i = 0; i < length; ++i) { final long v = this.read(); if (littleEndian) { r |= (v << (i << 3)); } else { r = (r << 8) | v; } } return r; } public BitColumn readBit(int length, boolean littleEndian) throws IOException { byte[] bytes = readBytes((int) ((length + 7) >> 3)); if (!littleEndian) bytes = CodecUtils.toBigEndian(bytes); return BitColumn.valueOf(length, bytes); } /** * */ @Override public void close() throws IOException { this.is.close(); } public void setReadLimit(final int limit) throws IOException { this.readCount = 0; this.readLimit = limit; } @Override public int available() throws IOException { if (this.readLimit > 0) { return this.readLimit - this.readCount; } else { return this.tail - this.head + this.is.available(); } } public boolean hasMore() throws IOException { if (this.head < this.tail) return true; return this.available() > 0; } @Override public long skip(final long n) throws IOException { if (this.readLimit > 0 && (this.readCount + n) > this.readLimit) { this.readCount += doSkip(this.readLimit - this.readCount); throw new ExceedLimitException(); } else { this.readCount += doSkip(n); return n; // always skip the number of bytes specified by parameter "n" } } @Override public int read() throws IOException { if (this.readLimit > 0 && (this.readCount + 1) > this.readLimit) { throw new ExceedLimitException(); } else { if (this.head >= this.tail) doFill(); final int r = this.buffer[this.head++] & 0xFF; ++this.readCount; return r; } } @Override public int read(final byte b[], final int off, final int len) throws IOException { if (this.readLimit > 0 && (this.readCount + len) > this.readLimit) { this.readCount += doRead(b, off, this.readLimit - this.readCount); throw new ExceedLimitException(); } else { this.readCount += doRead(b, off, len); return len; // always read the number of bytes specified by parameter "len" } } /** * */ private void doFill() throws IOException { this.head = 0; this.tail = this.is.read(this.buffer, 0, this.buffer.length); if (this.tail <= 0) throw new EOFException(); } private long doSkip(final long n) throws IOException { long total = n; while (total > 0) { final int availabale = this.tail - this.head; if (availabale >= total) { this.head += total; break; } else { total -= availabale; doFill(); } } return n; } private int doRead(final byte[] b, final int off, final int len) throws IOException { int total = len; int index = off; while (total > 0) { final int available = this.tail - this.head; if (available >= total) { System.arraycopy(this.buffer, this.head, b, index, total); this.head += total; break; } else { System.arraycopy(this.buffer, this.head, b, index, available); index += available; total -= available; doFill(); } } return len; } }
45,589
https://github.com/WebDevUniandes/andfoy/blob/master/js/calc.js
Github Open Source
Open Source
MIT
null
andfoy
WebDevUniandes
JavaScript
Code
455
1,613
// Code goes here $(document).ready(function() { $("#expr").keydown(function() { get_result(this.value); }); $("#expr").keyup(function() { get_result(this.value); }); }); function get_result(expr_s) { console.log(expr_s); $("#result").val(""); var expr_node = {expr:expr_s}; try { parse_expr(expr_node); //console.log(expr_node); var result = eval_tree(expr_node); if(typeof result == 'string') { failure(); } else { console.log(result); correct(); } $("#result").val(result); } catch(e) { $("#result").val("Syntax Error!"); failure(); } } function eval_tree(tree) { if(tree.hasOwnProperty('root')) { return tree['root']; } var a; var b; if(typeof tree.left == 'object') { a = eval_tree(tree.left); } if(typeof tree.right == 'object') { b = eval_tree(tree.right); } if(tree.op == '/') { console.log(b); if(b === 0) { return "Division by zero!" } } return tree.operation(a, b); } function parse_expr(expr_node) { var num_expr = /^\s*\d+([.]\d+)?\s*$/; var paren_expr = /^\s*[(]\s*(\d|[.]|[(]|[)]|[+]|[-]|[/]|[*])+\s*[)]\s*$/; var lvl = 0; var expr_s = remove_whitespace(expr_node.expr); if (num_expr.test(expr_s)) { expr_node.root = parseFloat(expr_s); } else { if(paren_expr.test(expr_s)) { expr_s = expr_s.slice(1, expr_s.length-1); } var c = ''; var fail = false; for (var i = 0, len = expr_s.length; i < len; i++) { c = expr_s[i]; if (c == "(") { lvl += 1; } else if (c == ")") { lvl -= 1; } else { if (lvl === 0) { var op = is_operator(c); if (op[0]) { var left = expr_s.slice(0, i); var right = expr_s.slice(i + 1, expr_s.length); expr_node.left = { expr: left }; expr_node.right = { expr: right }; expr_node.operation = op[1]; expr_node.op = c; break; } } } } parse_expr(expr_node.left); parse_expr(expr_node.right); } } function failure() { $('#result' + "_output").removeClass(); $('#result' + "_output").addClass("form-group has-error has-feedback"); $('#result' + "_verification").removeClass(); $('#result' + "_verification").addClass("glyphicon glyphicon-remove form-control-feedback"); } function correct() { $('#result' + "_output").removeClass(); $('#result' + "_output").addClass("form-group has-success has-feedback"); $('#result' + "_verification").removeClass(); $('#result' + "_verification").addClass("glyphicon glyphicon-ok form-control-feedback"); } function remove_whitespace(s) { var init = false; var start = 0; var end = s.length; for (var i = 0; i < s.length; i++) { var c = s[i]; if (c != ' ') { if (!init) { start = i; init = true; } else { end = i; } } } var ret = s.slice(start, end + 1); // $('#result').val(ret); return ret; } function sum(a, b) { return a + b; } function minus(a, b) { return a - b; } function times(a, b) { return a * b; } function divide(a, b) { return a / b; } function is_operator(c) { var op = ''; var opt = false; var func = { '+': sum, '-': minus, '*': times, '/': divide }; var ops = ['+', '-', '*', '/']; for (var i = 0; i < ops.length; i++) { if (ops[i] == c) { op = c; opt = true; break; } } return [opt, func[op]]; } // 1 + 1 + (1/2) + (1/(1*2*3)) + (1/(1*2*3*4))+ (1/(1*2*3*4*5)) + (1/(1*2*3*4*5*6))+ (1/(1*2*3*4*5*6*7))+ (1/(1*2*3*4*5*6*7*8))+ (1/(1*2*3*4*5*6*7*8*9))+ (1/(1*2*3*4*5*6*7*8*9*10))+ (1/(1*2*3*4*5*6*7*8*9*10*11)) + (1/(1*2*3*4*5*6*7*8*9*10*11*12)) + (1/(1*2*3*4*5*6*7*8*9*10*11*12*13))
4,174
https://github.com/aykanatm/toybox/blob/master/toybox-server/toybox-common-lib/src/main/java/com/github/murataykanat/toybox/schema/container/CreateContainerRequest.java
Github Open Source
Open Source
MIT
2,019
toybox
aykanatm
Java
Code
53
194
package com.github.murataykanat.toybox.schema.container; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.Serializable; public class CreateContainerRequest implements Serializable { @JsonProperty("parentContainerId") private String parentContainerId; @JsonProperty("containerName") private String containerName; public String getParentContainerId() { return parentContainerId; } public void setParentContainerId(String parentContainerId) { this.parentContainerId = parentContainerId; } public String getContainerName() { return containerName; } public void setContainerName(String containerName) { this.containerName = containerName; } }
23,965
https://github.com/DenisNet/Balance-Sheet-UWP/blob/master/BalanceSheet/NavigationBar/ProfileNavigationBarMenu.cs
Github Open Source
Open Source
BSD-2-Clause
null
Balance-Sheet-UWP
DenisNet
C#
Code
133
455
using System; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using BalanceSheet.Models; using BalanceSheet.Views; namespace BalanceSheet.NavigationBar { class ProfileNavigationBarMenu : BaseNavigationBarMenu, INavigationBarMenu { //public ProfileNavigationBarMenu() //{ // //AppEnvironment.Instance.CurrentUserChanged += CurrentUserChanged; //} public string Label { get { var loader = new Windows.ApplicationModel.Resources.ResourceLoader(); return loader.GetString("SingIn"); } } void CurrentUserChanged(object sender, User e) { // Notify UI that user has changed. NotifyPropertyChanged(nameof(Image)); NotifyPropertyChanged(nameof(Symbol)); NotifyPropertyChanged(nameof(Label)); NotifyPropertyChanged(nameof(SymbolAsChar)); } public override Symbol Symbol { get { return Symbol.Contact; } } public Type TypePage { get { return typeof(SignInPage); /*return AppEnvironment.Instance.CurrentUser == null ? typeof(SignInPage) : typeof(ProfilePage); */} } public override NavigationBarPosition Position { get { return NavigationBarPosition.Bottom; } } //public override ImageSource Image //{ // get // { // if (AppEnvironment.Instance.CurrentUser?.ProfilePictureUrl == null) // { // return null; // } // return new BitmapImage(new Uri(AppEnvironment.Instance.CurrentUser.ProfilePictureUrl)); // } //} } }
24,220
https://github.com/aliyun/aliyun-openapi-java-sdk/blob/master/aliyun-java-sdk-edas/src/main/java/com/aliyuncs/edas/transform/v20170801/UpdateSwimmingLaneResponseUnmarshaller.java
Github Open Source
Open Source
Apache-2.0
2,023
aliyun-openapi-java-sdk
aliyun
Java
Code
171
974
/* * 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.aliyuncs.edas.transform.v20170801; import java.util.ArrayList; import java.util.List; import com.aliyuncs.edas.model.v20170801.UpdateSwimmingLaneResponse; import com.aliyuncs.edas.model.v20170801.UpdateSwimmingLaneResponse.Data; import com.aliyuncs.edas.model.v20170801.UpdateSwimmingLaneResponse.Data.SwimmingLaneAppRelationShip; import com.aliyuncs.transform.UnmarshallerContext; public class UpdateSwimmingLaneResponseUnmarshaller { public static UpdateSwimmingLaneResponse unmarshall(UpdateSwimmingLaneResponse updateSwimmingLaneResponse, UnmarshallerContext _ctx) { updateSwimmingLaneResponse.setRequestId(_ctx.stringValue("UpdateSwimmingLaneResponse.RequestId")); updateSwimmingLaneResponse.setCode(_ctx.integerValue("UpdateSwimmingLaneResponse.Code")); updateSwimmingLaneResponse.setMessage(_ctx.stringValue("UpdateSwimmingLaneResponse.Message")); Data data = new Data(); data.setNamespaceId(_ctx.stringValue("UpdateSwimmingLaneResponse.Data.NamespaceId")); data.setGroupId(_ctx.longValue("UpdateSwimmingLaneResponse.Data.GroupId")); data.setEntryRule(_ctx.stringValue("UpdateSwimmingLaneResponse.Data.EntryRule")); data.setTag(_ctx.stringValue("UpdateSwimmingLaneResponse.Data.Tag")); data.setName(_ctx.stringValue("UpdateSwimmingLaneResponse.Data.Name")); data.setId(_ctx.longValue("UpdateSwimmingLaneResponse.Data.Id")); List<SwimmingLaneAppRelationShip> swimmingLaneAppRelationShipList = new ArrayList<SwimmingLaneAppRelationShip>(); for (int i = 0; i < _ctx.lengthValue("UpdateSwimmingLaneResponse.Data.SwimmingLaneAppRelationShipList.Length"); i++) { SwimmingLaneAppRelationShip swimmingLaneAppRelationShip = new SwimmingLaneAppRelationShip(); swimmingLaneAppRelationShip.setAppName(_ctx.stringValue("UpdateSwimmingLaneResponse.Data.SwimmingLaneAppRelationShipList["+ i +"].AppName")); swimmingLaneAppRelationShip.setRules(_ctx.stringValue("UpdateSwimmingLaneResponse.Data.SwimmingLaneAppRelationShipList["+ i +"].Rules")); swimmingLaneAppRelationShip.setLaneId(_ctx.longValue("UpdateSwimmingLaneResponse.Data.SwimmingLaneAppRelationShipList["+ i +"].LaneId")); swimmingLaneAppRelationShip.setAppId(_ctx.stringValue("UpdateSwimmingLaneResponse.Data.SwimmingLaneAppRelationShipList["+ i +"].AppId")); swimmingLaneAppRelationShipList.add(swimmingLaneAppRelationShip); } data.setSwimmingLaneAppRelationShipList(swimmingLaneAppRelationShipList); updateSwimmingLaneResponse.setData(data); return updateSwimmingLaneResponse; } }
32,031
https://github.com/usc-isi-i2/dsbox-ta2/blob/master/python/dsbox/template/template_files/loaded/CMUacledProblemTemplate.py
Github Open Source
Open Source
MIT
2,020
dsbox-ta2
usc-isi-i2
Python
Code
262
1,357
from dsbox.template.template import DSBoxTemplate from d3m.metadata.problem import TaskKeyword from dsbox.template.template_steps import TemplateSteps from dsbox.schema import SpecializedProblem import typing import numpy as np # type: ignore class CMUacledProblemTemplate(DSBoxTemplate): # From primitives/v2019.6.7/Distil/d3m.primitives.data_transformation.encoder.DistilTextEncoder/0.1.0/pipelines/0ed6fbca-2afd-4ba6-87cd-a3234e9846c3.json def __init__(self): DSBoxTemplate.__init__(self) self.template = { "name": "CMU_acled_problem_template", "taskType": {TaskKeyword.CLASSIFICATION.name}, "taskSubtype": {TaskKeyword.BINARY.name, TaskKeyword.MULTICLASS.name}, "inputType": {"table"}, "output": "steps.13", "steps": [ { 'name': 'steps.0', 'primitives': [ { 'primitive': 'd3m.primitives.data_transformation.dataset_to_dataframe.Common', 'hyperparameters': { }, }, ], 'inputs': ['template_input'], }, { "name": "common_profiler_step", "primitives": ["d3m.primitives.schema_discovery.profiler.Common"], "inputs": ["steps.0"] }, { 'name': 'steps.1', 'primitives': [ { 'primitive': 'd3m.primitives.data_transformation.column_parser.Common', 'hyperparameters': { }, }, ], 'inputs': ['common_profiler_step'], }, { 'name': 'steps.2', 'primitives': [ { 'primitive': 'd3m.primitives.data_transformation.extract_columns_by_semantic_types.Common', 'hyperparameters': { 'semantic_types': [('https://metadata.datadrivendiscovery.org/types/Attribute',)], }, }, ], 'inputs': ['steps.1'], }, { 'name': 'steps.3', 'primitives': [ { 'primitive': 'd3m.primitives.data_transformation.extract_columns_by_semantic_types.Common', 'hyperparameters': { 'semantic_types': [('https://metadata.datadrivendiscovery.org/types/Target', 'https://metadata.datadrivendiscovery.org/types/TrueTarget')], }, }, ], 'inputs': ['steps.1'], }, { 'name': 'steps.4', 'primitives': [ { 'primitive': 'd3m.primitives.natural_language_processing.lda.Fastlvm', 'hyperparameters': { "k":[10, 100, 1000, 5000], "iters":[100, 1000, 5000], "frac":[0.001, 0.01], }, }, ], 'inputs': ['steps.2'], }, { 'name': 'steps.5', 'primitives': [ { 'primitive': 'd3m.primitives.classification.gradient_boosting.SKlearn', 'hyperparameters': { }, }, { "primitive": "d3m.primitives.classification.extra_trees.SKlearn", "hyperparameters": { 'use_semantic_types': [True], 'return_result': ['new'], 'add_index_columns': [True], 'bootstrap': ["bootstrap", "disabled"], 'max_depth': [15, 30, None], 'min_samples_leaf': [1, 2, 4], 'min_samples_split': [2, 5, 10], 'max_features': ['auto', 'sqrt'], 'n_estimators': [10, 50, 100] } }, { "primitive": "d3m.primitives.classification.xgboost_gbtree.Common", "hyperparameters": { # 'use_semantic_types': [True], # 'return_result': ['new'], 'learning_rate': [0.001, 0.1], 'max_depth': [15, 30, None], # 'min_samples_leaf': [1, 2, 4], # 'min_samples_split': [2, 5, 10], 'n_more_estimators': [10, 50, 100, 1000], 'n_estimators': [10, 50, 100, 1000] } } ], 'inputs': ['steps.4', 'step.3'], }, { 'name': 'steps.6', 'primitives': [ { 'primitive': 'd3m.primitives.data_transformation.construct_predictions.Common', 'hyperparameters': { }, }, ], 'inputs': ['steps.5', 'common_profiler_step'], }, ] }
13,995
https://github.com/ashigeru/asakusafw-legacy/blob/master/thundergate-project/asakusa-thundergate-plugin/src/main/java/com/asakusafw/compiler/bulkloader/BulkLoaderScript.java
Github Open Source
Open Source
Apache-2.0
null
asakusafw-legacy
ashigeru
Java
Code
2,648
8,535
/** * Copyright 2011-2016 Asakusa Framework Team. * * 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.asakusafw.compiler.bulkloader; import java.text.MessageFormat; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Properties; import com.asakusafw.compiler.flow.Location; import com.asakusafw.utils.collections.Lists; /** * バルクローダーの処理に関する情報。 */ public class BulkLoaderScript { private final List<ImportTable> importTargetTables; private final List<ExportTable> exportTargetTables; /** * インスタンスを生成する。 * @param importTargetTables インポート対象の情報一覧 * @param exportTargetTables エクスポート対象の情報一覧 * @throws IllegalArgumentException 引数に{@code null}が指定された場合 */ public BulkLoaderScript( List<ImportTable> importTargetTables, List<ExportTable> exportTargetTables) { if (importTargetTables == null) { throw new IllegalArgumentException("importTargetTables must not be null"); //$NON-NLS-1$ } if (exportTargetTables == null) { throw new IllegalArgumentException("exportTargetTables must not be null"); //$NON-NLS-1$ } this.importTargetTables = importTargetTables; this.exportTargetTables = exportTargetTables; } /** * インポーターの設定情報を返す。 * @return インポーターの設定情報 */ public List<ImportTable> getImportTargetTables() { return importTargetTables; } /** * エクスポーターの設定情報を返す。 * @return エクスポーターの設定情報 */ public List<ExportTable> getExportTargetTables() { return exportTargetTables; } /** * インポーターの設定情報を返す。 * @return インポーターの設定情報 */ public Properties getImporterProperties() { return ImportTable.toProperties(importTargetTables); } /** * エクスポーターの設定情報を返す。 * @return エクスポーターの設定情報 */ public Properties getExporterProperties() { return ExportTable.toProperties(exportTargetTables); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + exportTargetTables.hashCode(); result = prime * result + importTargetTables.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } BulkLoaderScript other = (BulkLoaderScript) obj; if (exportTargetTables.equals(other.exportTargetTables) == false) { return false; } if (importTargetTables.equals(other.importTargetTables) == false) { return false; } return true; } static List<String> toNames(List<? extends Table> tables) { assert tables != null; List<String> results = Lists.create(); for (Table table : tables) { results.add(table.getName()); } return results; } static String toPath(Location location) { assert location != null; return location.toPath('/'); } static Location fromPath(String path) { assert path != null; return Location.fromPath(path, '/'); } static List<String> toPaths(List<Location> locations) { assert locations != null; List<String> results = Lists.create(); for (Location location : locations) { results.add(toPath(location)); } return results; } static List<Location> fromPaths(List<String> paths) { assert paths != null; List<Location> results = Lists.create(); for (String path : paths) { results.add(fromPath(path)); } return results; } static String join(List<String> fields) { assert fields != null; if (fields.isEmpty()) { return ""; } if (fields.size() == 1) { return fields.get(0); } StringBuilder buf = new StringBuilder(); Iterator<String> iter = fields.iterator(); assert iter.hasNext(); buf.append(iter.next()); while (iter.hasNext()) { buf.append(','); buf.append(iter.next()); } return buf.toString(); } static List<String> split(String fields) { assert fields != null; if (fields.isEmpty()) { return Collections.emptyList(); } List<String> results = Lists.create(); int start = 0; while (true) { int end = fields.indexOf(',', start); if (end < 0) { break; } results.add(fields.substring(start, end)); start = end + 1; } results.add(fields.substring(start)); return results; } static String get(Properties properties, String keyName, boolean mandatory) { assert properties != null; assert keyName != null; String value = properties.getProperty(keyName); if (value == null && mandatory) { throw new IllegalArgumentException(keyName); } return value; } /** * インポートまたはエクスポート対象のテーブル情報。 */ public abstract static class Table { private final Class<?> modelClass; private final String name; private final List<String> targetColumns; /** * インスタンスを生成する。 * @param modelClass テーブルと対応づけられたモデルクラス * @param name 対象テーブルの名前 * @param targetColumns 処理対象のカラム一覧 * @throws IllegalArgumentException 引数に{@code null}が指定された場合 */ protected Table( Class<?> modelClass, String name, List<String> targetColumns) { if (modelClass == null) { throw new IllegalArgumentException( "modelClass must not be null"); //$NON-NLS-1$ } if (name == null) { throw new IllegalArgumentException( "name must not be null"); //$NON-NLS-1$ } if (targetColumns == null) { throw new IllegalArgumentException( "targetColumns must not be null"); //$NON-NLS-1$ } this.modelClass = modelClass; this.name = name; this.targetColumns = targetColumns; } /** * このテーブルの名前を返す。 * @return このテーブルの名前 */ public String getName() { return name; } /** * このテーブルに対応するモデルクラスを返す。 * @return このテーブルに対応するモデルクラス */ public Class<?> getModelClass() { return modelClass; } /** * 処理対象とするカラム名の一覧を返す。 * @return 処理対象とするカラム名の一覧 */ public List<String> getTsvColumns() { return targetColumns; } /** * このオブジェクトに対するプロパティ一覧を返す。 * @return このオブジェクトに対するプロパティ一覧 */ public abstract Properties toProperties(); } /** * インポート対象のテーブル情報。 */ public static class ImportTable extends Table { private static final String K_TARGET_TABLES = "import.target-table"; private static final String P_TSV_COLUMNS = ".target-column"; private static final String P_SEARCH_CONDITION = ".search-condition"; private static final String P_CACHE_ID = ".cache-id"; private static final String P_LOCK_TYPE = ".lock-type"; private static final String P_LOCKED_OPERATION = ".locked-operation"; private static final String P_BEAN_NAME = ".bean-name"; private static final String P_DESTINATION = ".hdfs-import-file"; private final String searchConditionOrNull; private final String cacheId; private final LockType lockType; private final LockedOperation lockedOperation; private final Location destination; /** * インスタンスを生成する。 * @param modelClass テーブルと対応づけられたモデルクラス * @param name 対象テーブルの名前 * @param targetColumns 処理対象のカラム一覧 * @param searchConditionOrNull 検索条件、利用しない場合は{@code null} * @param cacheId キャッシュID (利用しない場合は{@code null}) * @param lockType ロックの種類 * @param lockedOperation 処理対象がロックされていた際の動作 * @param destination 出力先の位置 * @throws IllegalArgumentException 引数に{@code null}が指定された場合 */ public ImportTable( Class<?> modelClass, String name, List<String> targetColumns, String searchConditionOrNull, String cacheId, LockType lockType, LockedOperation lockedOperation, Location destination) { super(modelClass, name, targetColumns); if (lockType == null) { throw new IllegalArgumentException( "lockType must not be null"); //$NON-NLS-1$ } if (lockedOperation == null) { throw new IllegalArgumentException( "lockedOperation must not be null"); //$NON-NLS-1$ } if (destination == null) { throw new IllegalArgumentException( "destination must not be null"); //$NON-NLS-1$ } this.searchConditionOrNull = searchConditionOrNull; this.cacheId = cacheId; this.lockType = lockType; this.lockedOperation = lockedOperation; this.destination = destination; } /** * 出力先の位置を返す。 * @return 出力先の位置 */ public Location getDestination() { return destination; } static Properties toProperties(List<ImportTable> list) { assert list != null; Properties properties = new Properties(); properties.setProperty(K_TARGET_TABLES, join(toNames(list))); for (ImportTable table : list) { properties.putAll(table.toProperties()); } return properties; } @Override public Properties toProperties() { String prefix = getName(); Properties p = new Properties(); p.setProperty(prefix + P_TSV_COLUMNS, join(getTsvColumns())); if (searchConditionOrNull != null) { p.setProperty(prefix + P_SEARCH_CONDITION, searchConditionOrNull); } if (cacheId != null) { p.setProperty(prefix + P_CACHE_ID, String.valueOf(cacheId)); } p.setProperty(prefix + P_LOCK_TYPE, String.valueOf(lockType.id)); p.setProperty(prefix + P_LOCKED_OPERATION, String.valueOf(lockedOperation.id)); p.setProperty(prefix + P_BEAN_NAME, String.valueOf(getModelClass().getName())); p.setProperty(prefix + P_DESTINATION, String.valueOf(toPath(destination))); return p; } /** * 指定のプロパティに対するこのクラスのインスタンス一覧を返す。 * @param properties 対象のプロパティ * @param loaderOrNull モデルをロードする際のクラスローダー * @return 対応するインスタンス一覧 * @throws IllegalArgumentException プロパティを解析できなかった場合 */ public static List<ImportTable> fromProperties( Properties properties, ClassLoader loaderOrNull) { if (properties == null) { throw new IllegalArgumentException( "properties must not be null"); //$NON-NLS-1$ } ClassLoader loader = (loaderOrNull == null) ? BulkLoaderScript.class.getClassLoader() : loaderOrNull; List<ImportTable> results = Lists.create(); for (String prefix : split(get(properties, K_TARGET_TABLES, true))) { results.add(fromProperties(properties, prefix, loader)); } return results; } private static ImportTable fromProperties( Properties p, String name, ClassLoader loader) { assert p != null; assert name != null; assert loader != null; Class<?> modelClass; try { modelClass = Class.forName( get(p, name + P_BEAN_NAME, true), false, loader); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } List<String> targetColumns = split(get(p, name + P_TSV_COLUMNS, true)); String searchConditionOrNull = get(p, name + P_SEARCH_CONDITION, false); String cacheId = get(p, name + P_CACHE_ID, false); LockType lockType = LockType.idOf(get(p, name + P_LOCK_TYPE, true)); LockedOperation lockedOperation = LockedOperation.idOf(get(p, name + P_LOCKED_OPERATION, true)); Location destination = fromPath(get(p, name + P_DESTINATION, true)); return new ImportTable( modelClass, name, targetColumns, searchConditionOrNull, cacheId, lockType, lockedOperation, destination); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getModelClass().hashCode(); result = prime * result + getName().hashCode(); result = prime * result + getTsvColumns().hashCode(); result = prime * result + destination.hashCode(); result = prime * result + lockType.hashCode(); result = prime * result + lockedOperation.hashCode(); result = prime * result + ((searchConditionOrNull == null) ? 0 : searchConditionOrNull.hashCode()); result = prime * result + ((cacheId == null) ? 0 : cacheId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ImportTable other = (ImportTable) obj; if (getModelClass() != other.getModelClass()) { return false; } if (getName().equals(other.getName()) == false) { return false; } if (getTsvColumns().equals(other.getTsvColumns()) == false) { return false; } if (destination.equals(other.destination) == false) { return false; } if (lockType != other.lockType) { return false; } if (lockedOperation != other.lockedOperation) { return false; } if (searchConditionOrNull == null) { if (other.searchConditionOrNull != null) { return false; } } else if (searchConditionOrNull.equals(other.searchConditionOrNull) == false) { return false; } if (cacheId == null) { if (other.cacheId != null) { return false; } } else if (cacheId.equals(other.cacheId) == false) { return false; } return true; } } /** * エクスポート対象のテーブル情報。 */ public static class ExportTable extends Table { private static final String K_TARGET_TABLES = "export.target-table"; private static final String P_BEAN_NAME = ".bean-name"; private static final String P_TSV_COLUMNS = ".tsv-column"; private static final String P_TARGET_COLUMNS = ".export-table-column"; private static final String P_SOURCES = ".hdfs-export-file"; private final List<String> exportColumns; private final List<Location> sources; private final DuplicateRecordErrorTable duplicateRecordError; /** * インスタンスを生成する。 * @param modelClass テーブルと対応づけられたモデルクラス * @param name 対象テーブルの名前 * @param tsvColumns 処理対象のカラム一覧 * @param exportColumns 正常エクスポート時に利用するカラム一覧 * @param duplicateRecordError ユニーク制約のエラー、不要の場合は{@code null} * @param sources 読み出し元のディレクトリ一覧 * @throws IllegalArgumentException 引数に{@code null}が指定された場合 */ public ExportTable( Class<?> modelClass, String name, List<String> tsvColumns, List<String> exportColumns, DuplicateRecordErrorTable duplicateRecordError, List<Location> sources) { super(modelClass, name, tsvColumns); this.sources = sources; this.exportColumns = exportColumns; this.duplicateRecordError = duplicateRecordError; } /** * 読み出し元のディレクトリ一覧を返す。 * @return 読み出し元のディレクトリ一覧 */ public List<Location> getSources() { return sources; } static Properties toProperties(List<ExportTable> list) { assert list != null; Properties properties = new Properties(); properties.setProperty(K_TARGET_TABLES, join(toNames(list))); for (ExportTable table : list) { properties.putAll(table.toProperties()); } return properties; } @Override public Properties toProperties() { String prefix = getName(); Properties p = new Properties(); p.setProperty(prefix + P_TSV_COLUMNS, join(getTsvColumns())); p.setProperty(prefix + P_TARGET_COLUMNS, join(exportColumns)); p.setProperty(prefix + P_BEAN_NAME, String.valueOf(getModelClass().getName())); p.setProperty(prefix + P_SOURCES, String.valueOf(join(toPaths(sources)))); if (duplicateRecordError != null) { Properties sub = duplicateRecordError.toProperties(prefix); p.putAll(sub); } return p; } /** * 指定のプロパティに対するこのクラスのインスタンス一覧を返す。 * @param properties 対象のプロパティ * @param loaderOrNull モデルをロードする際のクラスローダー * @return 対応するインスタンス一覧 * @throws IllegalArgumentException プロパティを解析できなかった場合 */ public static List<ExportTable> fromProperties( Properties properties, ClassLoader loaderOrNull) { if (properties == null) { throw new IllegalArgumentException( "properties must not be null"); //$NON-NLS-1$ } ClassLoader loader = (loaderOrNull == null) ? BulkLoaderScript.class.getClassLoader() : loaderOrNull; List<ExportTable> results = Lists.create(); for (String prefix : split(get(properties, K_TARGET_TABLES, true))) { results.add(fromProperties(properties, prefix, loader)); } return results; } private static ExportTable fromProperties( Properties p, String name, ClassLoader loader) { assert p != null; assert name != null; assert loader != null; Class<?> modelClass; try { modelClass = Class.forName( get(p, name + P_BEAN_NAME, true), false, loader); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(e); } List<String> tsvColumns = split(get(p, name + P_TSV_COLUMNS, true)); List<String> exportColumns = split(get(p, name + P_TARGET_COLUMNS, true)); List<Location> sources = fromPaths(split(get(p, name + P_SOURCES, true))); DuplicateRecordErrorTable ucError = DuplicateRecordErrorTable.fromProperties(p, name); return new ExportTable( modelClass, name, tsvColumns, exportColumns, ucError, sources); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getModelClass().hashCode(); result = prime * result + getName().hashCode(); result = prime * result + getTsvColumns().hashCode(); result = prime * result + exportColumns.hashCode(); result = prime * result + (duplicateRecordError == null ? 0 : duplicateRecordError.hashCode()); result = prime * result + sources.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ExportTable other = (ExportTable) obj; if (getModelClass() != other.getModelClass()) { return false; } if (getName().equals(other.getName()) == false) { return false; } if (getTsvColumns().equals(other.getTsvColumns()) == false) { return false; } if (exportColumns.equals(other.exportColumns) == false) { return false; } if (duplicateRecordError == null) { if (other.duplicateRecordError != null) { return false; } } else if (duplicateRecordError.equals(other.duplicateRecordError) == false) { return false; } if (sources.equals(other.sources) == false) { return false; } return true; } } /** * エクスポート時の重複レコードエラーに関する情報。 */ public static class DuplicateRecordErrorTable { private static final String P_TABLE_NAME = ".error-table"; private static final String P_TARGET_COLUMNS = ".error-table-column"; private static final String P_KEY_COLUMNS = ".key-column"; private static final String P_ERROR_CODE_COLUMN = ".error-column"; private static final String P_ERROR_CODE_VALUE = ".error-code"; private final List<String> targetColumns; private final List<String> keyColumns; private final String errorCodeColumn; private final String errorCodeValue; private final String tableName; /** * インスタンスを生成する。 * @param tableName エラー情報のテーブル名 * @param targetColumns エラー情報のカラム一覧 * @param keyColumns ユニーク制約に利用するカラムの一覧 * @param errorCodeColumn エラーコードのカラム名 * @param errorCodeValue エラーコードの値 * @throws IllegalArgumentException 引数に{@code null}が指定された場合 */ public DuplicateRecordErrorTable( String tableName, List<String> targetColumns, List<String> keyColumns, String errorCodeColumn, String errorCodeValue) { if (tableName == null) { throw new IllegalArgumentException( "tableName must not be null"); //$NON-NLS-1$ } if (targetColumns == null) { throw new IllegalArgumentException("targetColumns must not be null"); //$NON-NLS-1$ } if (keyColumns == null) { throw new IllegalArgumentException("keyColumns must not be null"); //$NON-NLS-1$ } if (errorCodeColumn == null) { throw new IllegalArgumentException("errorCodeColumn must not be null"); //$NON-NLS-1$ } if (errorCodeValue == null) { throw new IllegalArgumentException("errorCodeValue must not be null"); //$NON-NLS-1$ } this.tableName = tableName; this.targetColumns = targetColumns; this.keyColumns = keyColumns; this.errorCodeColumn = errorCodeColumn; this.errorCodeValue = errorCodeValue; } /** * このオブジェクトに対するプロパティ一覧を返す。 * @param prefix 設定項目の接頭辞 * @return このオブジェクトに対するプロパティ一覧 */ public Properties toProperties(String prefix) { if (prefix == null) { throw new IllegalArgumentException("prefix must not be null"); //$NON-NLS-1$ } Properties p = new Properties(); p.setProperty(prefix + P_TABLE_NAME, tableName); p.setProperty(prefix + P_TARGET_COLUMNS, join(targetColumns)); p.setProperty(prefix + P_KEY_COLUMNS, join(keyColumns)); p.setProperty(prefix + P_ERROR_CODE_COLUMN, errorCodeColumn); p.setProperty(prefix + P_ERROR_CODE_VALUE, errorCodeValue); return p; } static DuplicateRecordErrorTable fromProperties(Properties p, String name) { assert p != null; assert name != null; String tableName = get(p, name + P_TABLE_NAME, false); String rawTargetColumns = get(p, name + P_TARGET_COLUMNS, false); String rawKeyColumns = get(p, name + P_KEY_COLUMNS, false); String errorColumn = get(p, name + P_ERROR_CODE_COLUMN, false); String errorCode = get(p, name + P_ERROR_CODE_VALUE, false); if (tableName == null || tableName.isEmpty()) { return null; } checkProperties(name, rawTargetColumns, rawKeyColumns, errorColumn, errorCode); List<String> targetColumns = split(rawTargetColumns); List<String> keyColumns = split(rawKeyColumns); return new DuplicateRecordErrorTable( tableName, targetColumns, keyColumns, errorColumn, errorCode); } private static void checkProperties( String name, String rawTargetColumns, String rawKeyColumns, String errorColumn, String errorCode) { if (rawTargetColumns == null) { throw new IllegalArgumentException(MessageFormat.format( "{0}.{1}の指定がありません", name, P_TARGET_COLUMNS)); } if (rawKeyColumns == null) { throw new IllegalArgumentException(MessageFormat.format( "{0}.{1}の指定がありません", name, P_KEY_COLUMNS)); } if (errorColumn == null) { throw new IllegalArgumentException(MessageFormat.format( "{0}.{1}の指定がありません", name, P_ERROR_CODE_COLUMN)); } if (errorCode == null) { throw new IllegalArgumentException(MessageFormat.format( "{0}.{1}の指定がありません", name, P_ERROR_CODE_VALUE)); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + tableName.hashCode(); result = prime * result + targetColumns.hashCode(); result = prime * result + keyColumns.hashCode(); result = prime * result + errorCodeColumn.hashCode(); result = prime * result + errorCodeValue.hashCode(); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } DuplicateRecordErrorTable other = (DuplicateRecordErrorTable) obj; if (!tableName.equals(other.tableName)) { return false; } if (!targetColumns.equals(other.targetColumns)) { return false; } if (!keyColumns.equals(other.keyColumns)) { return false; } if (!errorCodeColumn.equals(other.errorCodeColumn)) { return false; } if (!errorCodeValue.equals(other.errorCodeValue)) { return false; } return true; } } /** * ロック取得のタイプ。 */ public enum LockType { /** * テーブルロック。 */ TABLE(1), /** * 行ロック。 */ ROW(2), /** * ロックしない。 */ UNLOCKED(3), ; /** * この項目の識別子。 */ public final int id; LockType(int identifier) { this.id = identifier; } static LockType idOf(String id) { assert id != null; int idNum; try { idNum = Integer.parseInt(id); } catch (NumberFormatException e) { throw new IllegalArgumentException(id); } for (LockType constant : values()) { if (constant.id == idNum) { return constant; } } throw new IllegalArgumentException(id); } } /** * 対象のレコードがロック済みの場合の取り扱い。 */ public enum LockedOperation { /** * 処理対象から外す。 */ SKIP(1), /** * ロックの有無にかかわらず処理対象とする。 */ FORCE(2), /** * エラーとする。 */ ERROR(3), ; /** * この項目の識別子。 */ public final int id; LockedOperation(int identifier) { this.id = identifier; } static LockedOperation idOf(String id) { assert id != null; int idNum; try { idNum = Integer.parseInt(id); } catch (NumberFormatException e) { throw new IllegalArgumentException(id); } for (LockedOperation constant : values()) { if (constant.id == idNum) { return constant; } } throw new IllegalArgumentException(id); } } }
3,022
https://github.com/AlexanderKlement/eisenstecken-angular-electron-public/blob/master/src/app/employee/meal/meal.component.ts
Github Open Source
Open Source
MIT
null
eisenstecken-angular-electron-public
AlexanderKlement
TypeScript
Code
272
1,059
import {Component, ComponentRef, OnInit} from '@angular/core'; import {TableDataSource} from '../../shared/components/table-builder/table-builder.datasource'; import {DefaultService, Meal} from 'eisenstecken-openapi-angular-library'; import * as moment from 'moment'; import {MatDialog} from '@angular/material/dialog'; import {ConfirmDialogComponent} from '../../shared/components/confirm-dialog/confirm-dialog.component'; import {first} from 'rxjs/operators'; import {MatSnackBar} from '@angular/material/snack-bar'; import {ActivatedRoute} from '@angular/router'; import {Observable, Subscriber} from 'rxjs'; @Component({ selector: 'app-meal', templateUrl: './meal.component.html', styleUrls: ['./meal.component.scss'] }) export class MealComponent implements OnInit { mealDataSource: TableDataSource<Meal>; eatingPlaceId: number; title = ''; public $refresh: Observable<void>; private $refreshSubscriber: Subscriber<void>; constructor(private api: DefaultService, private dialog: MatDialog, private snackBar: MatSnackBar, private route: ActivatedRoute) { } ngOnInit(): void { this.route.params.subscribe(params => { this.eatingPlaceId = parseInt(params.id, 10); if (isNaN(this.eatingPlaceId)) { console.error('EmployeeDetailComponent: Could not parse userId'); } this.api.getEatingPlacesEatingPlaceEatingPlaceIdGet(this.eatingPlaceId).pipe(first()).subscribe(eatingPlace => { this.title = 'Mahlzeiten: ' + eatingPlace.name; }); this.initMealDataSource(); }); this.initRefreshObservables(); } initRefreshObservables(): void { this.$refresh = new Observable<void>((subscriber => { this.$refreshSubscriber = subscriber; })); } onAttach(ref: ComponentRef<any>, activatedRoute: ActivatedRoute): void { this.$refreshSubscriber.next(); } private initMealDataSource(): void { this.mealDataSource = new TableDataSource( this.api, (api, filter, sortDirection, skip, limit) => api.readMealsMealGet(skip, limit, filter, undefined, this.eatingPlaceId), (dataSourceClasses) => { const rows = []; dataSourceClasses.forEach((dataSource) => { rows.push( { values: { date: moment(dataSource.date).format('DD.MM.YYYY'), // eslint-disable-next-line @typescript-eslint/naming-convention 'user.fullname': dataSource.user.fullname, }, route: () => { this.mealClicked(dataSource.id); } }); }); return rows; }, [ {name: 'date', headerName: 'Datum'}, {name: 'user.fullname', headerName: 'Angestellter'}, ], (api) => api.readMealCountMealCountGet(undefined, this.eatingPlaceId) ); this.mealDataSource.loadData(); } private mealClicked(id: number) { const dialogRef = this.dialog.open(ConfirmDialogComponent, { width: '400px', data: { title: 'Mahlzeit löschen?', text: 'Mahlzeit löschen? Diese Aktion kann nicht rückgängig gemacht werden!' } }); dialogRef.afterClosed().subscribe(result => { if (result) { this.api.deleteMealMealMealIdDelete(id).pipe(first()).subscribe(success => { if (success) { this.mealDataSource.loadData(); } else { this.snackBar.open('Mahlzeit konnte nicht gelöscht werden', 'Ok', { duration: 10000 }); } }); } }); } }
12,812
https://github.com/achraf-byte/online-education-web-aplication-laravel/blob/master/app/Models/StudentPost.php
Github Open Source
Open Source
MIT
null
online-education-web-aplication-laravel
achraf-byte
PHP
Code
26
84
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class StudentPost extends Model { protected $fillable = [ 'caption', 'image' ,'Student_id' ]; public function student (){ return $this->belongsto(student::class); } }
38,368
https://github.com/gitter-badger/e2d/blob/master/src/object/addObject.js
Github Open Source
Open Source
MIT
2,015
e2d
gitter-badger
JavaScript
Code
105
253
/** * @param {Object} options - The object's options. * @param {Object} options.pos - The object's position. * @param {int} options.pos.x - The object's X coordinate. * @param {int} options.pos.y - The object's Y coordinate. */ E2D.Scene.prototype.addObject = function(options) { var self = this; if (typeof options == "undefined") { options = { pos: { x: 0, y: 0 } }; } else { if (typeof options.pos.x != "number" || typeof options.pos.y != "number") { console.warn("Invalid position supplied. Using (0, 0) (@addObject)"); } } var obj = {}; obj.id = options.id || self.generateId(); obj.body = { pos: options.pos, }; self._objects[obj.id] = obj; return obj; };
12,261
https://github.com/FMota0/PrometheeOptimization/blob/master/caja/playground/monitor/plot-usages.r
Github Open Source
Open Source
MIT
2,021
PrometheeOptimization
FMota0
R
Code
374
1,754
#http://ggplot2.tidyverse.org/reference/#section-scales library("ggplot2") library("scales") library("data.table") library("stringi") args = commandArgs(trailingOnly=TRUE) cpu_usage_path = args[1] mem_usage_path = args[2] disk_usage_path = args[3] proctimes_path = args[4] cpu_usage = read.table(sep = ",", cpu_usage_path, header=TRUE) mem_usage = read.table(sep = ",", mem_usage_path, header=TRUE) disk_usage = read.table(sep = ",", disk_usage_path, header=TRUE) proctimes = read.table(sep = " ", proctimes_path, header=FALSE) # Cada proctime com label deve indicar o fim de o processamento desse label no script proctimes = subset(proctimes, stri_length(V2) > 0) cpu_min_TS = min(cpu_usage$TIMESTAMP) mem_min_TS = min(mem_usage$TIMESTAMP) disk_min_TS = min(disk_usage$TIMESTAMP) proctimes_min_TS = min(proctimes$V1) start_program_TS = min( c(cpu_min_TS, mem_min_TS, disk_min_TS, proctimes_min_TS) ) cpu_usage$IDLE = 100 - cpu_usage$IDLE mem_usage$TOTAL = (mem_usage$USED/mem_usage$TOTAL)*100 cpu_usage$TIMESTAMP = cpu_usage$TIMESTAMP - start_program_TS mem_usage$TIMESTAMP = mem_usage$TIMESTAMP - start_program_TS disk_usage$TIMESTAMP = disk_usage$TIMESTAMP - start_program_TS proctimes$V1 = proctimes$V1 - start_program_TS cpu_usage = cpu_usage[c("TIMESTAMP", "IDLE", "GNICE")] mem_usage = mem_usage[c("TIMESTAMP", "TOTAL", "BUFFER.CACHE")] disk_read_usage = disk_usage[c("TIMESTAMP", "KB_READ.S", "KB_WRITE.S")]#TIMESTAMP, KB/S, TYPE(READ/WRITE) disk_write_usage = disk_usage[c("TIMESTAMP", "KB_READ.S", "KB_WRITE.S")] disk_write_usage$"KB_READ.S" = disk_write_usage$"KB_WRITE.S" setnames(cpu_usage, c("TIMESTAMP", "USAGE", "TYPE")) setnames(mem_usage, c("TIMESTAMP", "USAGE", "TYPE")) setnames(disk_read_usage, c("TIMESTAMP", "MB.S", "TYPE")) setnames(disk_write_usage, c("TIMESTAMP", "MB.S", "TYPE")) cpu_usage$TYPE = 'CPU' mem_usage$TYPE = 'MEM' disk_read_usage$TYPE = 'READ' disk_write_usage$TYPE = 'WRITE' data_cpu_mem = rbind(cpu_usage, mem_usage) data_disk = rbind(disk_write_usage, disk_read_usage) data_disk$TYPE = as.character(data_disk$TYPE) data_disk$TYPE = factor(data_disk$TYPE, levels = unique(data_disk$TYPE)) data_disk$MB.S = data_disk$MB.S/1024 med_proctimes = 0 previous = 0 for(i in 1:dim(proctimes)[1]) { med_proctimes[i] = (previous + proctimes$V1[i])/2.0 previous = proctimes$V1[i] } pplot = ggplot(cpu_usage, aes(x=TIMESTAMP, y=USAGE, group=TYPE, colour=TYPE)) + geom_line(size=0.7) + xlab("TIME (s)") + ylab("USAGE (%)") + geom_vline(xintercept = proctimes$V1, linetype=2, size=0.4) + annotate("text", x = med_proctimes, y=0.0, label = proctimes$V2) + scale_colour_manual(values=c("#FF7777")) + theme_bw() + guides(fill=guide_legend(title=NULL)) + theme(legend.title=element_blank()) ggsave("usage_cpu.png", pplot, width=14) pplot = ggplot(mem_usage, aes(x=TIMESTAMP, y=USAGE, group=TYPE, colour=TYPE)) + geom_line(size=0.7) + xlab("TIME (s)") + ylab("USAGE (%)") + geom_vline(xintercept = proctimes$V1, linetype=2, size=0.4) + annotate("text", x = med_proctimes, y=0.0, label = proctimes$V2) + scale_colour_manual(values=c("#0066CC")) + theme_bw() + guides(fill=guide_legend(title=NULL)) + theme(legend.title=element_blank()) ggsave("usage_mem.png", pplot, width=14) pplot = ggplot(data_cpu_mem, aes(x=TIMESTAMP, y=USAGE, color=TYPE)) + geom_line(size=0.7) + xlab("TIME (s)") + ylab("USAGE (%)") + geom_vline(xintercept = proctimes$V1, linetype=2, size=0.4) + annotate("text", x = med_proctimes, y=0.0, label = proctimes$V2) + scale_colour_manual(values=c("#FF7777", "#0066CC")) + theme_bw() + guides(fill=guide_legend(title=NULL)) + theme(legend.title=element_blank()) ggsave("usage_cpu_mem.png", pplot, width=14) pplot = ggplot(data_disk, aes(x=TIMESTAMP, y=MB.S, color=TYPE)) + geom_line(size=0.7) + xlab("TIME (s)") + ylab("MB/S") + geom_vline(xintercept = proctimes$V1, linetype=2, size=0.4) + annotate("text", x = med_proctimes, y=-10.0, label = proctimes$V2) + scale_colour_manual(values=c("#FF7777", "#0066CC")) + theme_bw() + guides(fill=guide_legend(title=NULL)) + theme(legend.title=element_blank()) ggsave("usage_disk.png", pplot, width=14)
135
https://github.com/true-eye/polkawallet_plugin_chainx/blob/master/example/android/app/src/main/kotlin/io/polkawallet/www/example/MainActivity.kt
Github Open Source
Open Source
Apache-2.0
2,021
polkawallet_plugin_chainx
true-eye
Kotlin
Code
9
47
package io.polkawallet.www.plugin.chainx.example import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
16,616
https://github.com/Rembane/lemmingpants/blob/master/frontend/src/Components/Admin/SpeakerQueue.purs
Github Open Source
Open Source
Apache-2.0
2,018
lemmingpants
Rembane
PureScript
Code
1,127
2,824
module Components.Admin.SpeakerQueue where import Prelude import Affjax.StatusCode (StatusCode(..)) import Data.Array as A import Data.HTTP.Method (Method(..)) import Data.Lens (filtered, preview, traversed, view) import Data.Maybe (Maybe(Just, Nothing), maybe) import Data.Newtype (class Newtype) import Effect.Aff (Aff) import FormHelpers (FieldError, fieldScaffolding, isInt, isNonEmpty, setFocus) import Formless as F import Halogen as H import Halogen.HTML as HH import Halogen.HTML.Events as HE import Halogen.HTML.Properties as HP import Postgrest (createURL) import Postgrest as PG import Simple.JSON (class WriteForeign) import Types.Attendee (Attendee(..), AttendeeDB, getAttendeeByNumber) import Types.Flash as FL import Types.Speaker as S import Types.SpeakerQueue (SpeakerQueue(..), _Speakers, _Speaking) import Types.Token (Token) type State = { agendaItemId :: Int , speakerQueue :: SpeakerQueue , token :: Token , attendees :: AttendeeDB , sqHeight :: Int } data Query a = PushSQ a | PopSQ a | Formless (F.Message' Form) a | Next a | Eject a | Delete Int a | GotNewState State a type ChildQuery = F.Query' Form Aff data Message = Flash (Maybe FL.Flash) newtype Form r f = Form (r ( id :: f FieldError String Int )) derive instance newtypeForm :: Newtype (Form r f) _ component :: H.Component HH.HTML Query State Message Aff component = H.parentComponent { initialState: identity , render , eval , receiver: HE.input GotNewState } where render :: State -> H.ParentHTML Query ChildQuery Unit Aff render {attendees, speakerQueue, sqHeight} = HH.div [ HP.id_ "speakerhandling-container" ] [ HH.div [ HP.id_ "speaker-col" ] [ HH.p_ [ HH.strong_ [ HH.text "Speaking: " ] , HH.text (maybe "–" (S.visualizeSpeaker attendees) (preview (_Speakers <<< _Speaking) speakerQueue)) ] , HH.table [ HP.id_ "attendee-table" ] [ HH.thead_ [ HH.tr_ [ HH.th [ HP.class_ (HH.ClassName "id") ] [ HH.text "ID" ] , HH.th [ HP.id_ "name" ] [ HH.text "Name" ] , HH.th [ HP.class_ (HH.ClassName "numspoken") , HP.title ("Number of times spoken") ] [ HH.text "#" ] , HH.th [ HP.id_ "delcol" ] [ HH.text " " ] ] ] , HH.tbody_ (A.fromFoldable (map (\s@(S.Speaker {attendeeId, id, timesSpoken}) -> (let (SpeakerQueue {speakerAdded}) = speakerQueue in if Just s == speakerAdded then HH.tr [ HP.class_ $ HH.ClassName "speaker-added" ] else HH.tr_ ) [ HH.td [ HP.class_ (HH.ClassName "id") ] [ HH.text (show attendeeId) ] , HH.td_ [ HH.text (S.visualizeSpeaker attendees s) ] , HH.td [ HP.class_ (HH.ClassName "numspoken") ] [ HH.text (show timesSpoken) ] , HH.td_ [ HH.button [ HE.onClick (HE.input_ (Delete id)) ] [ HH.text "X" ] ] ]) (A.dropWhile (\(S.Speaker {state}) -> state == S.Active) $ view _Speakers speakerQueue))) ] ] , HH.div [ HP.id_ "speaker-button-col" ] [ HH.p_ [ HH.text ("Stack height: " <> show sqHeight) ] , HH.ul_ [ HH.li_ [ HH.button [ HE.onClick (HE.input_ PushSQ) ] [ HH.text "Push speakerqueue" ] ] , HH.li_ [ HH.button [ HE.onClick (HE.input_ PopSQ) , if sqHeight <= 1 then HP.disabled true else HP.disabled false ] [ HH.text "Pop speakerqueue" ] ] ] , HH.ul [ HP.class_ (HH.ClassName "with-top-margin") ] [ HH.li_ [ HH.button [ HE.onClick (HE.input_ Eject) ] [HH.text "Eject current speaker"] ] , HH.li_ [ HH.button [ HE.onClick (HE.input_ Next) ] [HH.text "Next speaker"] ] ] , HH.slot unit F.component { initialInputs, validators, render: renderFormless } (HE.input Formless) ] ] where proxy = F.FormProxy :: F.FormProxy Form initialInputs :: Form Record F.InputField initialInputs = F.mkInputFields proxy validators :: Form Record (F.Validation Form Aff) validators = Form { id: isInt <<< isNonEmpty } renderFormless :: F.State Form Aff -> F.HTML' Form Aff renderFormless s = HH.form [ HE.onSubmit (HE.input_ F.submit) ] [ fieldScaffolding "Speaker ID" [ HH.input [ HP.value $ F.getInput r.id s.form , HE.onValueInput $ HE.input $ F.setValidate r.id , HP.type_ HP.InputNumber , HP.required true , HP.autocomplete false , HP.id_ "id" ] ] , HH.p_ [ HH.input [ HP.type_ HP.InputSubmit , HP.value "Add speaker" ] ] ] where r = F.mkSProxies proxy eval :: Query ~> H.ParentDSL State Query ChildQuery Unit Message Aff eval = case _ of PushSQ next -> H.raise (Flash Nothing) *> H.get >>= \{agendaItemId} -> ajaxHelper "/speaker_queue" POST { agenda_item_id: agendaItemId , state: "active" } 201 "PushSQ -- ERROR! Got a HTTP response we didn't expect! See the console for more information." *> focusId *> pure next PopSQ next -> H.raise (Flash Nothing) *> H.get >>= \{speakerQueue} -> let (SpeakerQueue {id}) = speakerQueue in ajaxHelper ("/speaker_queue?id=eq." <> show id) PATCH { state: "done" } 204 "PopSQ -- ERROR! Got a HTTP response we didn't expect! See the console for more information." *> focusId *> pure next Formless m next -> H.raise (Flash Nothing) *> H.get >>= \({attendees, speakerQueue, token}) -> case m of F.Submitted formOutput -> do let form = F.unwrapOutputFields formOutput case getAttendeeByNumber form.id attendees of Nothing -> H.raise $ Flash $ Just $ FL.mkFlash ("Couldn't find attendee with number: " <> show form.id) FL.Error Just (Attendee a) -> H.liftAff (PG.emptyResponse (createURL "/speaker") token POST { speaker_queue_id: let (SpeakerQueue {id}) = speakerQueue in id , attendee_id: a.id }) >>= \{status} -> case status of StatusCode 201 -> -- The `Created` HTTP status code. H.query unit (H.action F.resetAll) $> unit StatusCode 409 -> -- We can only have a visible speaker once per speaker queue. H.raise $ Flash $ Just $ FL.mkFlash "I'm sorry, but you cannot add a speaker while it still is in the speaker queue." FL.Error _ -> H.raise $ Flash $ Just $ FL.mkFlash "SpeakerQueue.FormMsg -- ERROR! Got a HTTP response we didn't expect! See the console for more information." FL.Error pure next _ -> pure next *> focusId *> pure next Next next -> do H.raise (Flash Nothing) {speakerQueue} <- H.get case preview (_Speakers <<< traversed <<< filtered (\(S.Speaker {state}) -> state /= S.Active)) speakerQueue of Nothing -> pure unit Just (S.Speaker {id}) -> do ajaxHelper "/rpc/set_current_speaker" POST { id: id } 200 "SpeakerQueue.Next -- ERROR! Got a HTTP response we didn't expect! See the console for more information." focusId pure next Eject next -> do H.raise (Flash Nothing) {speakerQueue} <- H.get case preview (_Speakers <<< _Speaking) speakerQueue of Nothing -> pure unit Just (S.Speaker {id}) -> do ajaxHelper ("/speaker?id=eq." <> show id) PATCH { state: "done" } 204 "SpeakerQueue.Eject -- ERROR! Got a HTTP response we didn't expect! See the console for more information." focusId pure next Delete id_ next -> do H.raise (Flash Nothing) ajaxHelper ("/speaker?id=eq." <> show id_) PATCH { state: "deleted" } 204 "SpeakerQueue.Delete -- ERROR! Got a HTTP response we didn't expect! See the console for more information." focusId pure next GotNewState s next -> H.put s *> pure next focusId = H.liftEffect (setFocus "id") ajaxHelper :: forall r . WriteForeign r => String -> Method -> r -> Int -> String -> H.ParentDSL State Query ChildQuery Unit Message Aff Unit ajaxHelper partialUrl method dta code msg = do {token} <- H.get {status} <- H.liftAff $ PG.emptyResponse (createURL partialUrl) token method dta if status == StatusCode code then pure unit else H.raise $ Flash $ Just $ FL.mkFlash msg FL.Error
25,061
https://github.com/cse2016hy/cse2016hy.github.io/blob/master/code/unfolding_app_template_with_examples_0/examples/de/fhpotsdam/unfolding/examples/misc/SimpleBackgroundMapApp.java
Github Open Source
Open Source
MIT
2,022
cse2016hy.github.io
cse2016hy
Java
Code
114
356
package de.fhpotsdam.unfolding.examples.misc; import processing.core.PApplet; import de.fhpotsdam.unfolding.UnfoldingMap; import de.fhpotsdam.unfolding.geo.Location; import de.fhpotsdam.unfolding.utils.MapUtils; /** * Shows how to set the background color of the map where no tiles have been loaded yet, or where not tiles exist. * * Zoom out quickly to see the behaviour. */ public class SimpleBackgroundMapApp extends PApplet { UnfoldingMap map; public void setup() { size(800, 600, OPENGL); map = new UnfoldingMap(this, 50, 50, 700, 500); map.zoomAndPanTo(new Location(52.5f, 13.4f), 10); MapUtils.createDefaultEventDispatcher(this, map); // background color of the map map.setBackgroundColor(color(60, 70, 10)); } public void draw() { // Outer area the map gets a different color background(30, 70, 10); map.draw(); } public static void main(String[] args) { PApplet.main(new String[] { "de.fhpotsdam.unfolding.examples.SimpleBackgroundMapApp" }); } }
5,120
https://github.com/vivek2007/sharetribe/blob/master/spec/controllers/admin/communities/footer_controller_spec.rb
Github Open Source
Open Source
PostgreSQL, Ruby, ImageMagick
2,022
sharetribe
vivek2007
Ruby
Code
254
899
require 'spec_helper' describe Admin::Communities::FooterController, type: :controller do let(:community) { FactoryGirl.create(:community) } let(:plan) do { expired: false, features: { whitelabel: true, admin_email: true, footer: true } } end before(:each) do @request.host = "#{community.ident}.lvh.me" @request.env[:current_marketplace] = community @request.env[:current_plan] = plan user = create_admin_for(community) sign_in_for_spec(user) end describe "#update" do it 'works' do params = {"community" => {"footer_theme" => "light", "footer_enabled" => 1, "footer_menu_links_attributes" => {"0" => {"id" => "", "entity_type" => "for_footer", "sort_priority" => "0", "_destroy" => "false", "translation_attributes" => {"en"=>{"title"=>"ccc", "url"=>"http://example.com"}}}}, "footer_copyright" => "Sample", "social_links_attributes" => {"0" => {"id" => "", "sort_priority" => "0", "provider" => "youtube", "enabled" => "1", "url" => "hoho"}, "1" => {"id" => "", "sort_priority" => "1", "provider" => "facebook", "enabled" => "0", "url" => ""}, "2" => {"id" => "", "sort_priority" => "2", "provider" => "twitter", "enabled" => "0", "url" => ""}, "3" => {"id" => "", "sort_priority" => "3", "provider" => "instagram", "enabled" => "0", "url" => ""}, "4" => {"id" => "", "sort_priority" => "4", "provider" => "googleplus", "enabled" => "0", "url" => ""}, "5" => {"id" => "", "sort_priority" => "5", "provider" => "linkedin", "enabled" => "0", "url" => ""}, "6" => {"id" => "", "sort_priority" => "6", "provider" => "pinterest", "enabled" => "0", "url" => ""}, "7" => {"id" => "", "sort_priority" => "7", "provider" => "soundcloud", "enabled" => "0", "url" => ""} } } } expect(community.footer_menu_links.count).to eq 0 expect(community.social_links.count).to eq 0 expect(community.footer_enabled).to eq false put :update, params: params expect(community.footer_enabled).to eq true expect(community.reload.footer_menu_links.count).to eq 1 expect(community.social_links.count).to eq 8 expect(community.social_links.enabled.count).to eq 1 expect(community.social_links.first.provider).to eq 'youtube' end end end
36,506
https://github.com/BoltApp/sleet/blob/master/gateways/adyen/request_builder.go
Github Open Source
Open Source
MIT
2,022
sleet
BoltApp
Go
Code
773
3,470
package adyen import ( "fmt" "regexp" "strconv" "github.com/BoltApp/sleet" "github.com/BoltApp/sleet/common" "github.com/adyen/adyen-go-api-library/v4/src/checkout" "github.com/adyen/adyen-go-api-library/v4/src/payments" ) const ( level3Default = "NA" maxLineItemDescriptionLength = 26 maxProductCodeLength = 12 ) const ( shopperInteractionEcommerce = "Ecommerce" shopperInteractionContAuth = "ContAuth" ) const ( recurringProcessingModelCardOnFile = "CardOnFile" recurringProcessingModelSubscription = "Subscription" recurringProcessingModelUnscheduledCardOnFile = "UnscheduledCardOnFile" ) var streetNumberRegex = regexp.MustCompile(`^(\d+)\s(.*)`) // these maps are based on https://docs.adyen.com/online-payments/tokenization/create-and-use-tokens#set-parameters-to-flag-transactions var initiatorTypeToShopperInteraction = map[sleet.ProcessingInitiatorType]string{ sleet.ProcessingInitiatorTypeInitialCardOnFile: shopperInteractionEcommerce, sleet.ProcessingInitiatorTypeInitialRecurring: shopperInteractionEcommerce, sleet.ProcessingInitiatorTypeStoredCardholderInitiated: shopperInteractionContAuth, sleet.ProcessingInitiatorTypeStoredMerchantInitiated: shopperInteractionContAuth, sleet.ProcessingInitiatorTypeFollowingRecurring: shopperInteractionContAuth, } var initiatorTypeToRecurringProcessingModel = map[sleet.ProcessingInitiatorType]string{ sleet.ProcessingInitiatorTypeInitialCardOnFile: recurringProcessingModelCardOnFile, sleet.ProcessingInitiatorTypeInitialRecurring: recurringProcessingModelSubscription, sleet.ProcessingInitiatorTypeStoredCardholderInitiated: recurringProcessingModelCardOnFile, sleet.ProcessingInitiatorTypeStoredMerchantInitiated: recurringProcessingModelUnscheduledCardOnFile, sleet.ProcessingInitiatorTypeFollowingRecurring: recurringProcessingModelSubscription, } func buildAuthRequest(authRequest *sleet.AuthorizationRequest, merchantAccount string) *checkout.PaymentRequest { request := &checkout.PaymentRequest{ Amount: checkout.Amount{ Value: authRequest.Amount.Amount, Currency: authRequest.Amount.Currency, }, // Adyen requires a reference in request so this will panic if client doesn't pass it. Assuming this is good for now Reference: *authRequest.ClientTransactionReference, PaymentMethod: map[string]interface{}{ "expiryMonth": strconv.Itoa(authRequest.CreditCard.ExpirationMonth), "expiryYear": strconv.Itoa(authRequest.CreditCard.ExpirationYear), "holderName": authRequest.CreditCard.FirstName + " " + authRequest.CreditCard.LastName, "number": authRequest.CreditCard.Number, "type": "scheme", }, MerchantAccount: merchantAccount, MerchantOrderReference: authRequest.MerchantOrderReference, // https://docs.adyen.com/api-explorer/#/CheckoutService/latest/payments__reqParam_shopperReference ShopperReference: authRequest.ShopperReference, } addPaymentSpecificFields(authRequest, request) addShopperData(authRequest, request) addAddresses(authRequest, request) // overwrites the flag transactions if authRequest.ProcessingInitiator != nil { if shopperInteraction, ok := initiatorTypeToShopperInteraction[*authRequest.ProcessingInitiator]; ok { request.ShopperInteraction = shopperInteraction } if recurringProcessingModel, ok := initiatorTypeToRecurringProcessingModel[*authRequest.ProcessingInitiator]; ok { request.RecurringProcessingModel = recurringProcessingModel } } // overwrites for citiplcc if authRequest.CreditCard.Network == sleet.CreditCardNetworkCitiPLCC { request.RecurringProcessingModel = "Subscription" request.ShopperInteraction = "Ecommerce" } level3 := authRequest.Level3Data if level3 != nil { request.AdditionalData = buildLevel3Data(level3) } // Attach results of 3DS verification if performed (and not "R"ejected) if authRequest.ThreeDS != nil && authRequest.ThreeDS.PAResStatus != sleet.ThreedsStatusRejected { request.MpiData = &checkout.ThreeDSecureData{ Cavv: authRequest.ThreeDS.CAVV, CavvAlgorithm: authRequest.ThreeDS.CAVVAlgorithm, DirectoryResponse: authRequest.ThreeDS.PAResStatus, DsTransID: authRequest.ThreeDS.DSTransactionID, Eci: authRequest.ECI, ThreeDSVersion: authRequest.ThreeDS.Version, Xid: authRequest.ThreeDS.XID, } // Only pass these fields for challenge flow if !authRequest.ThreeDS.Frictionless { request.MpiData.AuthenticationResponse = authRequest.ThreeDS.PAResStatus } } return request } // addPaymentSpecificFields adds fields to the Adyen Payment request that are dependent on the payment method func addPaymentSpecificFields(authRequest *sleet.AuthorizationRequest, request *checkout.PaymentRequest) { if authRequest.Cryptogram != "" && authRequest.ECI != "" { // Apple Pay request request.MpiData = &checkout.ThreeDSecureData{ AuthenticationResponse: "Y", Cavv: authRequest.Cryptogram, DirectoryResponse: "Y", Eci: authRequest.ECI, } request.PaymentMethod["brand"] = "applepay" request.RecurringProcessingModel = "CardOnFile" request.ShopperInteraction = "Ecommerce" } else if authRequest.CreditCard.CVV != "" { // New customer credit card request request.PaymentMethod["cvc"] = authRequest.CreditCard.CVV request.ShopperInteraction = "Ecommerce" if authRequest.CreditCard.Save { // Customer opts in to saving card details request.RecurringProcessingModel = "CardOnFile" request.StorePaymentMethod = true } else { // Customer opts out of saving card details request.StorePaymentMethod = false } } else { // Existing customer credit card request request.RecurringProcessingModel = "CardOnFile" request.ShopperInteraction = "ContAuth" } } // addAddresses adds the billing address and shipping address to the Ayden Payment request if available func addAddresses(authRequest *sleet.AuthorizationRequest, request *checkout.PaymentRequest) { if authRequest.BillingAddress != nil { billingStreetNumber, billingStreetName := extractAdyenStreetFormat(common.SafeStr(authRequest.BillingAddress.StreetAddress1)) request.BillingAddress = &checkout.Address{ City: common.SafeStr(authRequest.BillingAddress.Locality), Country: common.SafeStr(authRequest.BillingAddress.CountryCode), HouseNumberOrName: billingStreetNumber, PostalCode: common.SafeStr(authRequest.BillingAddress.PostalCode), StateOrProvince: common.SafeStr(authRequest.BillingAddress.RegionCode), Street: billingStreetName, } } if authRequest.ShippingAddress != nil { shippingStreetNumber, shippingStreetName := extractAdyenStreetFormat(common.SafeStr(authRequest.ShippingAddress.StreetAddress1)) request.DeliveryAddress = &checkout.Address{ City: common.SafeStr(authRequest.ShippingAddress.Locality), Country: common.SafeStr(authRequest.ShippingAddress.CountryCode), HouseNumberOrName: shippingStreetNumber, PostalCode: common.SafeStr(authRequest.ShippingAddress.PostalCode), StateOrProvince: common.SafeStr(authRequest.ShippingAddress.RegionCode), Street: shippingStreetName, } } } // addShopperData adds the shoppers IP and email to the Ayden Payment request if available func addShopperData(authRequest *sleet.AuthorizationRequest, request *checkout.PaymentRequest) { if authRequest.Options["ShopperIP"] != nil { request.ShopperIP = authRequest.Options["ShopperIP"].(string) } if authRequest.BillingAddress.Email != nil { request.ShopperEmail = common.SafeStr(authRequest.BillingAddress.Email) } } func buildLevel3Data(level3Data *sleet.Level3Data) map[string]string { additionalData := map[string]string{ "enhancedSchemeData.customerReference": sleet.DefaultIfEmpty(level3Data.CustomerReference, level3Default), "enhancedSchemeData.destinationPostalCode": level3Data.DestinationPostalCode, "enhancedSchemeData.dutyAmount": sleet.AmountToString(&level3Data.DutyAmount), "enhancedSchemeData.freightAmount": sleet.AmountToString(&level3Data.ShippingAmount), "enhancedSchemeData.totalTaxAmount": sleet.AmountToString(&level3Data.TaxAmount), } var keyBase string for idx, lineItem := range level3Data.LineItems { // Maximum of 9 line items allowed in the request if idx == 9 { break } keyBase = fmt.Sprintf("enhancedSchemeData.itemDetailLine%d.", idx+1) // Due to issues with the credit card networks, dont send any line item if discount amount is 0 if lineItem.ItemDiscountAmount.Amount > 0 { additionalData[keyBase+"discountAmount"] = sleet.AmountToString(&lineItem.ItemDiscountAmount) } additionalData[keyBase+"commodityCode"] = lineItem.CommodityCode additionalData[keyBase+"description"] = sleet.TruncateString(lineItem.Description, maxLineItemDescriptionLength) additionalData[keyBase+"productCode"] = sleet.TruncateString(lineItem.ProductCode, maxProductCodeLength) additionalData[keyBase+"quantity"] = strconv.Itoa(int(lineItem.Quantity)) additionalData[keyBase+"totalAmount"] = sleet.AmountToString(&lineItem.TotalAmount) additionalData[keyBase+"unitOfMeasure"] = common.ConvertUnitOfMeasurementToCode(lineItem.UnitOfMeasure) additionalData[keyBase+"unitPrice"] = sleet.AmountToString(&lineItem.UnitPrice) } // Omit optional fields if they are empty addIfNonEmpty(level3Data.DestinationCountryCode, "enhancedSchemeData.destinationCountryCode", &additionalData) addIfNonEmpty(level3Data.DestinationAdminArea, "enhancedSchemeData.destinationStateProvinceCode", &additionalData) return additionalData } func buildCaptureRequest(captureRequest *sleet.CaptureRequest, merchantAccount string) *payments.ModificationRequest { request := &payments.ModificationRequest{ OriginalReference: captureRequest.TransactionReference, ModificationAmount: &payments.Amount{ Value: captureRequest.Amount.Amount, Currency: captureRequest.Amount.Currency, }, MerchantAccount: merchantAccount, } return request } func buildRefundRequest(refundRequest *sleet.RefundRequest, merchantAccount string) *payments.ModificationRequest { request := &payments.ModificationRequest{ OriginalReference: refundRequest.TransactionReference, ModificationAmount: &payments.Amount{ Value: refundRequest.Amount.Amount, Currency: refundRequest.Amount.Currency, }, MerchantAccount: merchantAccount, } return request } func buildVoidRequest(voidRequest *sleet.VoidRequest, merchantAccount string) *payments.ModificationRequest { request := &payments.ModificationRequest{ OriginalReference: voidRequest.TransactionReference, MerchantAccount: merchantAccount, } return request } func addIfNonEmpty(value string, key string, data *map[string]string) { if value != "" { (*data)[key] = value } } // extractAdyenStreetFormat extracts adyen street format from generic street address // returns (streetNumber, streetName) format // If address does not have leading street number, will return ("", street) func extractAdyenStreetFormat(streetAddress string) (string, string) { streetExtraction := streetNumberRegex.FindStringSubmatch(streetAddress) if streetExtraction == nil { return "", streetAddress } return streetExtraction[1], streetExtraction[2] }
6,346
https://github.com/runningjack/auctionsite/blob/master/app/views/pages/home.blade.php
Github Open Source
Open Source
MIT
2,015
auctionsite
runningjack
Blade
Code
832
4,333
<?php require_once("inc/init.php"); use \Illuminate\Support\Facades\DB; ?> @extends("layouts.default") @section("content") <div class="space10">&nbsp;</div> <!--<div class="dg"> <div class="col-4"> <div class="beta-banner"> <img src="<?php /*echo ASSETS_URL*/?>/uploads/images/banners/banner2.png" alt=""> <h2 class="beta-banner-layer text-right" data-animo='{ "duration" : 1000, "delay" : 100, "easing" : "easeOutSine", "template" : { "opacity" : [0, 1], "top" : [20, 20, "px"], "right" : [-300, 25, "px"] } }' >Woven</h2> <p class="beta-banner-layer text-right" data-animo='{ "duration" : 1000, "delay" : 400, "easing" : "easeOutSine", "template" : { "opacity" : [0, 1], "top" : [65, 65, "px"], "right" : [-300, 25, "px"] } }' > <br /> </p> <a class="beta-banner-layer beta-btn text-right" href="javascript:void(0)" data-animo='{ "duration" : 1000, "delay" : 300, "easing" : "easeOutSine", "template" : { "opacity" : [0, 1], "bottom" : [20, 20, "px"], "right" : [-300, 25, "px"] } }' >Shop Now</a> </div> </div> <div class="col-4"> <div class="beta-banner"> <img src="<?php /*echo ASSETS_URL*/?>/uploads/images/banners/banner3.png" alt=""> <h2 class="beta-banner-layer text-right" data-animo='{ "duration" : 1000, "delay" : 100, "easing" : "easeOutSine", "template" : { "opacity" : [0, 1], "top" : [20, 20, "px"], "right" : [-300, 25, "px"] } }' >Syringes</h2> <p class="beta-banner-layer text-right" data-animo='{ "duration" : 1000, "delay" : 400, "easing" : "easeOutSine", "template" : { "opacity" : [0, 1], "top" : [65, 65, "px"], "right" : [-300, 25, "px"] } }' > <br /> </p> <a class="beta-banner-layer beta-btn text-right" href="javascript:void(0)" data-animo='{ "duration" : 1000, "delay" : 300, "easing" : "easeOutSine", "template" : { "opacity" : [0, 1], "bottom" : [20, 20, "px"], "right" : [-300, 25, "px"] } }' >Shop Now</a> </div> </div> <div class="col-4"> <div class="beta-banner"> <img src="<?php /*echo ASSETS_URL*/?>/uploads/images/banners/banner3.png" alt=""> <h2 class="beta-banner-layer text-right" data-animo='{ "duration" : 1000, "delay" : 100, "easing" : "easeOutSine", "template" : { "opacity" : [0, 1], "top" : [20, 20, "px"], "right" : [-300, 25, "px"] } }' >Syringes</h2> <p class="beta-banner-layer text-right" data-animo='{ "duration" : 1000, "delay" : 400, "easing" : "easeOutSine", "template" : { "opacity" : [0, 1], "top" : [65, 65, "px"], "right" : [-300, 25, "px"] } }' > <br /> </p> <a class="beta-banner-layer beta-btn text-right" href="javascript:void(0)" data-animo='{ "duration" : 1000, "delay" : 300, "easing" : "easeOutSine", "template" : { "opacity" : [0, 1], "bottom" : [20, 20, "px"], "right" : [-300, 25, "px"] } }' >Shop Now</a> </div> </div> </div>--> <div class="space50">&nbsp;</div> <div class="beta-products-list"> <h4 class="wow fadeInLeft">Special Products</h4> <div class="beta-products-details"> <p class="pull-left">438 found | <a href="#">View all</a></p> <p class="pull-right"> <span class="sort-by">Sort by </span> <select name="sortproducts" class="beta-select-primary"> <option value="desc">Latest</option> <option value="popular">Popular</option> <option value="rating">Rating</option> <option value="best">Best</option> </select> </p> <div class="clearfix"></div> </div> <div class="row"> @if($specialproducts) @foreach($specialproducts as $latest) <div class="col-sm-3 wow fadeInDown"> <div class="single-item"> <div class="ribbon-wrapper"><div class="ribbon sale">Special</div></div> <div class="single-item-header"> <?php if($latest->image != ""){ if(public_path()){ $source_folder = public_path().'/uploads/images/'; $destination_folder = public_path(). '/uploads/images/'; $image_info = pathinfo(public_path().'/uploads/images/'.$latest->image); }else{ $source_folder = '/home/medicalng/public_html/uploads/images/'; $destination_folder = '/home/medicalng/public_html/uploads/images/'; $image_info = pathinfo('/home/medicalng/public_html/uploads/images/'.$latest->image); } $image_extension = strtolower($image_info["extension"]); //image extension $image_name_only = strtolower($image_info["filename"]);//file name only, no extension $img2 = \Image::make($source_folder.$latest->image); $img2->resize(262,311); $imgName = $image_name_only."-262x311".".".$image_extension; $img2->save($destination_folder."thumbs/".$imgName); echo "<a href='".url()."/product/details/".$latest->id."'><img src='".url()."/uploads/images/thumbs/".$imgName."' style='width:262px !important; height:311px !important'></a>"; }?> </div> <div class="single-item-body"> <p class="single-item-title">{{$latest->title}}</p> <p class="single-item-price"> <span class="beta-comp beta-sales-price"> &#8358;{{number_format($latest->price,2,".",",")}}</span> <br> <span class="beta-comp beta-time" data-start-date="" data-end-date="{{$latest->end_date}}" style="font-size: 12px">Closing: {{$latest->end_date}} {{$latest->end_time}} </span> <br> </p> </div> <div class="single-item-caption"> <!--<a class="add-to-cart pull-left" href="javascript:void(0)" pid="{{$latest->id}}"><i class="fa fa-shopping-cart"></i></a>--> <a class="beta-btn primary" href="{{ASSETS_URL}}/product/details/{{$latest->id}}">Bid Now <i class="fa fa-chevron-right"></i></a> <div class="clearfix"></div> </div> </div> </div> @endforeach @endif </div> </div> <!-- .beta-products-list --> <div class="space50">&nbsp;</div> <div class="beta-products-list"> <h4 class="wow fadeInLeft">New Products</h4> <div class="beta-products-details"> <div class="clearfix"></div> </div> <div class="row"> @if($newproducts) @foreach($newproducts as $latest) <div class="col-sm-3 wow fadeInDown"> <div class="single-item"> <!--<div class="ribbon-wrapper"><div class="ribbon sale">New</div></div>--> <div class="single-item-header"> <?php if($latest->image != ""){ if(public_path()){ $source_folder = public_path().'/uploads/images/'; $destination_folder = public_path(). '/uploads/images/'; $image_info = pathinfo(public_path().'/uploads/images/'.$latest->image); }else{ $source_folder = '/home/medicalng/public_html/uploads/images/'; $destination_folder = '/home/medicalng/public_html/uploads/images/'; $image_info = pathinfo('/home/medicalng/public_html/uploads/images/'.$latest->image); } $image_extension = strtolower($image_info["extension"]); //image extension $image_name_only = strtolower($image_info["filename"]);//file name only, no extension $img2 = \Image::make($source_folder.$latest->image); $img2->resize(262,311); $imgName = $image_name_only."-262x311".".".$image_extension; $img2->save($destination_folder."thumbs/".$imgName); echo "<a href='".url()."/product/details/".$latest->id."'><img src='".url()."/uploads/images/thumbs/".$imgName."' style='width:262px !important; height:311px !important'></a>"; }?> </div> <div class="single-item-body"> <p class="single-item-title">{{$latest->title}}</p> <p class="single-item-price"> <span class="beta-comp beta-sales-price"> &#8358;{{number_format($latest->price,2,".",",")}}</span> <br> <span class="beta-comp beta-time" data-start-date="" data-end-date="{{$latest->end_date}}" style="font-size: 12px">Closing: {{$latest->end_date}} {{$latest->end_time}} </span> <br> </p> </div> <div class="single-item-caption"> <!--<a class="add-to-cart pull-left" href="javascript:void(0)" pid="{{$latest->id}}"><i class="fa fa-shopping-cart"></i></a>--> <a class="beta-btn primary" href="{{ASSETS_URL}}/product/details/{{$latest->id}}">Details <i class="fa fa-chevron-right"></i></a> <div class="clearfix"></div> </div> </div> </div> @endforeach @endif </div> </div> <!-- .beta-products-list --> <div class="space50">&nbsp;</div> <div class="beta-products-list"> <h4 class="wow fadeInLeft">Featured Products</h4> <div class="beta-products-details"> <div class="clearfix"></div> </div> <div class="row"> @if($latestproducts) @foreach($latestproducts as $latest) <div class="col-sm-3 wow fadeInDown"> <div class="single-item"> <!--<div class="ribbon-wrapper"><div class="ribbon sale">New</div></div>--> <div class="single-item-header"> <?php if($latest->image != ""){ if(public_path()){ $source_folder = public_path().'/uploads/images/'; $destination_folder = public_path(). '/uploads/images/'; $image_info = pathinfo(public_path().'/uploads/images/'.$latest->image); }else{ $source_folder = '/home/medicalng/public_html/uploads/images/'; $destination_folder = '/home/medicalng/public_html/uploads/images/'; $image_info = pathinfo('/home/medicalng/public_html/uploads/images/'.$latest->image); } $image_extension = strtolower($image_info["extension"]); //image extension $image_name_only = strtolower($image_info["filename"]);//file name only, no extension $img2 = \Image::make($source_folder.$latest->image); $img2->resize(262,311); $imgName = $image_name_only."-262x311".".".$image_extension; $img2->save($destination_folder."thumbs/".$imgName); echo "<a href='".url()."/product/details/".$latest->id."'><img src='".url()."/uploads/images/thumbs/".$imgName."' style='width:262px !important; height:311px !important'></a>"; }?> </div> <div class="single-item-body"> <p class="single-item-title">{{$latest->title}}</p> <p class="single-item-price"> <span class="beta-sales-price"> Current Price: &#8358;{{number_format($latest->price,2,".",",")}}</span> </p> </div> <div class="single-item-caption"> <!--<a class="add-to-cart pull-left" href="javascript:void(0)" pid="{{$latest->id}}"><i class="fa fa-shopping-cart"></i></a>--> <a class="beta-btn primary" href="{{ASSETS_URL}}/product/details/{{$latest->id}}">Details <i class="fa fa-chevron-right"></i></a> <div class="clearfix"></div> </div> </div> </div> @endforeach @endif </div> </div> <!-- .beta-products-list --> <div class="space50">&nbsp;</div> <div class="dg"> <div class="col-4"> <div class="beta-banner"> <a href="#"><img class="h164" src="{{url()}}/img/banner9.jpg" alt=""></a> </div> </div> <div class="col-4"> <div class="beta-banner"> <a href="#"><img class="h164" src="{{url()}}/img/banner10.jpg" alt=""></a> </div> </div> <div class="col-4"> <div class="beta-banner"> <a href="#"><img class="h164" src="{{url()}}/img/banner11.jpg" alt=""></a> </div> </div> </div> @stop
17,676
https://github.com/Geonovum/respec/blob/master/src/geonovum/leafletfigures.js
Github Open Source
Open Source
W3C-20150513
2,020
respec
Geonovum
JavaScript
Code
319
1,183
/** * Module: geonovum/leafletfigures * Makes figures scalable via zoom and pan function */ import L from "../geonovum/deps/leaflet"; import easyButton from "../geonovum/deps/easy-button"; import { sub } from "../core/pubsubhub"; export const name = "geonovum/leafletfigures"; export async function run(conf, doc, cb) { sub("beforesave", addLeafletOnSave); cb(); await document.respecIsReady; processImages(); } function processImages() { Array.from( document.querySelectorAll("figure.scalable img") ).forEach(image => { const { width, height, src } = image; image.hidden = true; const div = document.createElement("div"); div.classList.add("removeOnSave"); const map = L.map(div, { maxZoom: 4, minZoom: -4, center: [0, 0], crs: L.CRS.Simple, }); const imageBounds = [[0, 0], [height, width]]; image.insertAdjacentElement("beforebegin", div); map.setView([height / 2, width / 2], 1); [ L.easyButton("fa-arrows-alt", () => window.open(src, "_blank")), L.easyButton("fa-globe", () => map.fitBounds(imageBounds)), L.imageOverlay(src, imageBounds), ].forEach(item => item.addTo(map)); map.fitBounds(imageBounds); }); } const rawProcessImages = ` function processImages() { Array.from( document.querySelectorAll("figure.scalable img") ).forEach(image => { const { width, height, src } = image; image.hidden = true; const div = document.createElement("div"); const map = L.map(div, { maxZoom: 4, minZoom: -4, center: [0, 0], crs: L.CRS.Simple, }); const imageBounds = [[0, 0], [height, width]]; image.insertAdjacentElement("beforebegin", div); map.setView([height / 2, width / 2], 1); [ L.easyButton("fa-arrows-alt", () => window.open(src, "_blank")), L.easyButton("fa-globe", () => map.fitBounds(imageBounds)), L.imageOverlay(src, imageBounds), ].forEach(item => item.addTo(map)); map.fitBounds(imageBounds); }); } `; function addLeafletOnSave(rootElem) { const doc = rootElem.ownerDocument; const head = rootElem.querySelector("head"); if (rootElem.querySelector("figure.scalable img") === null) { return; // this document doesn't need leaflet } // this script loads leaflet const leafletScript = doc.createElement("script"); leafletScript.src = "https://tools.geostandaarden.nl/respec/scripts/leaflet.js"; //Loads easy button const easyButtonScript = doc.createElement("script"); easyButtonScript.src = "https://tools.geostandaarden.nl/respec/scripts/easy-button.js"; // This script handles actually doing the work const processImagesScript = doc.createElement("script"); processImagesScript.textContent = ` ${rawProcessImages}; // Calls processImages when the document loads window.addEventListener("DOMContentLoaded", processImages); `; // add the CSS const leafletStyle = doc.createElement("link"); leafletStyle.rel = "stylesheet"; leafletStyle.href = "https://tools.geostandaarden.nl/respec/style/leaflet.css"; // add easyButton font-awesome CSS const easyButtonStyle = doc.createElement("link"); easyButtonStyle.rel = "stylesheet"; easyButtonStyle.href = "https://tools.geostandaarden.nl/respec/style/font-awesome.css"; // Finally, we add stylesheet and the scripts in order head.insertAdjacentElement("afterbegin", leafletStyle); head.insertAdjacentElement("afterbegin", easyButtonStyle); head.appendChild(leafletScript); head.appendChild(easyButtonScript); head.appendChild(processImagesScript); }
41,351
https://github.com/jjaybrown/pbnetwork-boilerplate/blob/master/application/modules/community/controllers/IndexController.php
Github Open Source
Open Source
Unlicense
2,016
pbnetwork-boilerplate
jjaybrown
PHP
Code
236
775
<?php use App\Controller as AppController; class Community_IndexController extends AppController { public function init() { parent::init(); } public function indexAction() { $recentPosts = $this->_em->getRepository("App\Entity\Community\Post")->recentActivity(); $this->view->recentPosts = $recentPosts; } public function headerAction() { $container = new Zend_Navigation( array( array( 'action' => 'index', 'controller' => 'index', 'module' => 'site', 'label' => 'Home' ), array( 'action' => 'index', 'controller' => 'index', 'module' => 'news', 'label' => 'News', 'pages' => array( array( 'action' => 'archive', 'controller' => 'index', 'module' => 'news', 'label' => 'Archive' ) ) ), array( 'action' => 'index', 'controller' => 'index', 'module' => 'event', 'label' => 'Events', 'pages' => array( array( 'action' => 'index', 'controller' => 'calendar', 'module' => 'event', 'label' => 'Calendar' ) ) ), array( 'action' => 'index', 'controller' => 'index', 'module' => 'community', 'label' => 'Community', 'active' => true, 'pages' => array( array( 'action' => 'index', 'controller' => 'index', 'module' => 'community', 'label' => 'Community Roundup' ), array( 'module' => 'forum', 'label' => 'Forums', 'pages' => array( array( 'module' => 'forum', 'controller' => 'thread', 'action' => 'view' ), array( 'module' => 'forum', 'controller' => 'post', 'action' => 'index' ) ) ), array( 'action' => 'index', 'controller' => 'groups', 'module' => 'community', 'label' => 'Groups' ), array( 'action' => 'index', 'controller' => 'competitions', 'module' => 'community', 'label' => 'Weekly Competitions' ) ) ), array( 'action' => 'index', 'controller' => 'index', 'module' => 'magazine', 'label' => 'Paintball Scene Magazine' ) ) ); \Zend_Registry::set("community_nav", $container); $this->view->navigation($container); } }
13,577
https://github.com/HIMARTONLINE/ERPJERAMODA/blob/master/app/Http/Controllers/PresenceController.php
Github Open Source
Open Source
MIT
null
ERPJERAMODA
HIMARTONLINE
PHP
Code
377
1,558
<?php namespace App\Http\Controllers; use App\Models\Presence; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\User; use File; use Response; class PresenceController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $personal = User::all(['id','serial','clave','foto','name'])->toArray(); $tiempo = date('Y-m-d H:i:s'); foreach ($personal as $key => $value) { $personal[$key]['registros'] = Presence::where('users_id', '=', $value['id'])->whereRaw("DATE_FORMAT(presences.registro, '%Y-%m-%d') = DATE_FORMAT('".$tiempo."', '%Y-%m-%d')")->count(); } $parametros = ['personal' => $personal, 'entrada' => $this->configuracion['Entrada']]; return view('presencia', compact('parametros')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function setPresence(Request $request) { try { $usuario = User::where('serial', '=', request('clave')) ->orWhere('clave', '=', request('clave')) ->first(); $limite = date("Y-m-d {$this->configuracion['Entrada']}"); $tiempo = date('Y-m-d H:i:s'); if($usuario != null) { $clase = 'neutro'; $registro = ['users_id' => $usuario->id, 'registro' => $tiempo, 'estatus' => 0]; if(Presence::where('users_id', '=', $usuario->id)->whereRaw("DATE_FORMAT(presences.registro, '%Y-%m-%d') = DATE_FORMAT('".$tiempo."', '%Y-%m-%d')")->count() == 0) { $datetime1 = new \DateTime($limite); $datetime2 = new \DateTime($tiempo); $intervalo = $datetime1->diff($datetime2); if($intervalo->invert == 0) { //Tarde $registro['estatus'] = -1; $clase = 'tarde'; } else if($intervalo->invert == 1) { //A tiempo $registro['estatus'] = 1; $clase = 'atiempo'; } } Presence::create($registro); $fecha = \DateTime::createFromFormat('Y-m-d H:i:s', $tiempo); $resultado = ['res' => true, 'id' => $usuario->id, 'nombre' => $usuario->name, 'avatar' => $usuario->foto, 'clase' => $clase, 'tiempo' => $fecha->format('H:i')]; } else { $fecha = \DateTime::createFromFormat('Y-m-d H:i:s', $tiempo); $resultado = ['res' => false, 'id' => 0, 'nombre' => 'Usuario no encontrado', 'avatar' => 'assets/images/users/avatar.jpg', 'clase' => 'fallo', 'tiempo' => $fecha->format('H:i')]; } } catch(Exception $exception) { $usuario = User::where('serial', '=', request('clave')) ->orWhere('clave', '=', request('clave')) ->first(); $resultado = ['res' => false, 'id' => $usuario->id, 'nombre' => $usuario->name, 'avatar' => $usuario->foto, 'clase' => 'fallo', 'tiempo' => date('H:i')]; } header('Content-Type: application/json'); echo json_encode($resultado); die(); } public function displayImage($filename) { $path = storage_path('app/public/images/usuarios/'.$filename); if(!File::exists($path)) { abort(404); } $file = File::get($path); $type = File::mimeType($path); $response = Response::make($file, 200); $response->header("Content-Type", $type); return $response; } public function displayImageG($filename) { $path = storage_path("app/public/img/$filename"); if(!File::exists($path)) { abort(404); } $file = File::get($path); $type = File::mimeType($path); $response = Response::make($file, 200); $response->header("Content-Type", $type); return $response; } public function token() { header('Content-Type: application/json'); echo json_encode(['_token' => csrf_token()]); die(); } public function getPersonal() { $resultado = User::all(['id','serial','clave','foto','name'])->toArray(); $tiempo = date('Y-m-d H:i:s'); foreach ($resultado as $key => $value) { $resultado[$key]['registros'] = Presence::where('users_id', '=', $value['id'])->whereRaw("DATE_FORMAT(presences.registro, '%Y-%m-%d') = DATE_FORMAT('".$tiempo."', '%Y-%m-%d')")->count(); } header('Content-Type: application/json'); echo json_encode($resultado); die(); } }
21,046
https://github.com/youyingxiang/php_cms_of/blob/master/application/admin/validate/News.php
Github Open Source
Open Source
Apache-2.0
2,018
php_cms_of
youyingxiang
PHP
Code
77
384
<?php namespace app\admin\validate; use think\Validate; class News extends Validate { protected $rule = [ 'title' => 'require|max:200', 'seo_title' => 'max:200', 'seo_des' => 'max:500', 'url_title' => 'require|max:255|unique:news', ]; protected $message = [ 'title.require' => '标题不能为空!', 'title.max' => '标题最多200个字符!', 'seo_title.max' => 'seo标题最多200个字符!', 'seo_des.max' => 'seo描述最多500个字符!', 'url_title.max' => 'url别名最多255个字符!', 'url_title.require' => '请输入url别名!', 'url_title.unique' => 'url别名已存在!', ]; protected $scene = [ 'add' => ['title','seo_title','seo_des','url_title'], 'edit' => ['title','seo_title','seo_des','url_title'], 'title' => ['title'], 'seo_title' => ['seo_title'], 'seo_des' => ['seo_des'], 'state' => ['state'], ]; }
14,352
https://github.com/azemeo/MyVideoExplorer/blob/master/SubForms/SubFormListView.Designer.cs
Github Open Source
Open Source
MIT
2,018
MyVideoExplorer
azemeo
C#
Code
300
1,304
namespace MyVideoExplorer { partial class SubFormListView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.listView = new System.Windows.Forms.ListView(); this.columnHeaderTitle = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderYear = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.toolStripMenuItemPlay = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemOpenFolder = new System.Windows.Forms.ToolStripMenuItem(); this.contextMenuStrip.SuspendLayout(); this.SuspendLayout(); // // listView // this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderTitle, this.columnHeaderYear}); this.listView.Dock = System.Windows.Forms.DockStyle.Fill; this.listView.HideSelection = false; this.listView.Location = new System.Drawing.Point(0, 0); this.listView.Name = "listView"; this.listView.Size = new System.Drawing.Size(240, 400); this.listView.TabIndex = 0; this.listView.UseCompatibleStateImageBehavior = false; this.listView.View = System.Windows.Forms.View.Details; this.listView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.listView_ColumnClick); this.listView.SelectedIndexChanged += new System.EventHandler(this.listView_SelectedIndexChanged); this.listView.DoubleClick += new System.EventHandler(this.listView_DoubleClick); this.listView.MouseClick += new System.Windows.Forms.MouseEventHandler(this.listView_MouseClick); // // columnHeaderTitle // this.columnHeaderTitle.Text = "Title"; this.columnHeaderTitle.Width = 235; // // columnHeaderYear // this.columnHeaderYear.Text = "Year"; // // contextMenuStrip // this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemPlay, this.toolStripMenuItemOpenFolder}); this.contextMenuStrip.Name = "contextMenuStrip"; this.contextMenuStrip.Size = new System.Drawing.Size(175, 60); // // toolStripMenuItemPlay // this.toolStripMenuItemPlay.Name = "toolStripMenuItemPlay"; this.toolStripMenuItemPlay.Size = new System.Drawing.Size(174, 28); this.toolStripMenuItemPlay.Text = "Play"; this.toolStripMenuItemPlay.Click += new System.EventHandler(this.toolStripMenuItemPlay_Click); // // toolStripMenuItemOpenFolder // this.toolStripMenuItemOpenFolder.Name = "toolStripMenuItemOpenFolder"; this.toolStripMenuItemOpenFolder.Size = new System.Drawing.Size(174, 28); this.toolStripMenuItemOpenFolder.Text = "Open Folder"; this.toolStripMenuItemOpenFolder.Click += new System.EventHandler(this.toolStripMenuItemOpenFolder_Click); // // SubFormListView // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.Controls.Add(this.listView); this.Name = "SubFormListView"; this.Size = new System.Drawing.Size(240, 400); this.Load += new System.EventHandler(this.SubFormListView_Load); this.contextMenuStrip.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ListView listView; private System.Windows.Forms.ColumnHeader columnHeaderTitle; private System.Windows.Forms.ColumnHeader columnHeaderYear; private System.Windows.Forms.ContextMenuStrip contextMenuStrip; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemPlay; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemOpenFolder; } }
10,079
https://github.com/JonasReich/unity-git-integration/blob/master/Assets/Plugins/git-integration/Editor/GitOverlay.cs
Github Open Source
Open Source
MIT
null
unity-git-integration
JonasReich
C#
Code
540
2,215
//------------------------------------------- // (c) 2017 - Jonas Reich //------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using EStatus = GitIntegration.Git.EStatus; namespace GitIntegration { /// <summary> /// Manages everything related to the visualization of git status + context menu entries in the project browser /// </summary> [InitializeOnLoad] public static class GitOverlay { const string ICON_FOLDER = "GitIcons/"; static Texture addedTexture, ignoredTexture, modifiedTexture, modifiedAddedTexture, movedTexture, unresolvedTexture, untrackedTexture; static string currentSelectionPath = ""; static GitOverlay() { EditorApplication.projectWindowItemOnGUI += ProjectWindowItemOnGui; EditorApplication.projectWindowChanged += delegate { Git.dirty = true; }; EditorApplication.update += Update; addedTexture = Resources.Load<Texture>(ICON_FOLDER + "added"); ignoredTexture = Resources.Load<Texture>(ICON_FOLDER + "ignored"); modifiedTexture = Resources.Load<Texture>(ICON_FOLDER + "modified"); modifiedAddedTexture = Resources.Load<Texture>(ICON_FOLDER + "modifiedAdded"); movedTexture = Resources.Load<Texture>(ICON_FOLDER + "moved"); unresolvedTexture = Resources.Load<Texture>(ICON_FOLDER + "unresolved"); untrackedTexture = Resources.Load<Texture>(ICON_FOLDER + "untracked"); } static void Update() { if (Git.dirty && Git.IsReady()) { Git.dirty = false; Git.RefreshStatus(); if (GitEditorWindow.Window) GitEditorWindow.Window.Repaint(); } if (UpdateCurrentSelectionPath()) Git.dirty = true; } static void ProjectWindowItemOnGui(string guid, Rect selectionRect) { var path = AssetDatabase.GUIDToAssetPath(guid); selectionRect.height = selectionRect.width = 16; foreach (var file in Git.files) { bool isMatchingFile = path.Contains(file.path.Replace("\"", "")); bool isMatchingFolderMetaFile = file.isMetaFile && file.isFolder && path.Contains(file.path.Replace(".meta\"", "")); if (isMatchingFile || isMatchingFolderMetaFile) { if (file.HasStatus(EStatus.Unresolved)) { GUI.DrawTexture(selectionRect, unresolvedTexture); } else if (file.HasStatus(EStatus.Untracked)) { GUI.DrawTexture(selectionRect, untrackedTexture); } else if (file.HasStatus(EStatus.Renamed)) { GUI.DrawTexture(selectionRect, movedTexture); } else if (file.HasStatus(EStatus.HasStagedChanges)) { if (file.HasStatus(EStatus.HasUnstagedChanges)) { GUI.DrawTexture(selectionRect, modifiedAddedTexture); } else { GUI.DrawTexture(selectionRect, addedTexture); } } else if (file.HasStatus(EStatus.HasUnstagedChanges)) { GUI.DrawTexture(selectionRect, modifiedTexture); } else if (file.HasStatus(EStatus.Ignored)) { GUI.DrawTexture(selectionRect, ignoredTexture); } } } } /// <summary> /// Update the currentSelectionPath member /// </summary> /// <returns> /// Has currentSelectionPath changed? /// </returns> static bool UpdateCurrentSelectionPath() { string path = (Selection.activeObject == null) ? "Assets" : AssetDatabase.GetAssetPath(Selection.activeObject.GetInstanceID()); if (currentSelectionPath == path) return false; currentSelectionPath = path; return true; } static List<Git.File> FindSelectedGitFiles(Func<Git.File, bool> conditionFunction) { List<Git.File> files = new List<Git.File>(); foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.Assets)) { var path = AssetDatabase.GetAssetPath(obj); foreach (var file in Git.files) { bool isMatchingFile = path.Contains(file.path.Replace("\"", "")); bool isMatchingFolderMetaFile = file.isMetaFile && file.isFolder && path.Contains(file.path.Replace(".meta\"", "")); if (isMatchingFile || isMatchingFolderMetaFile) { if (conditionFunction(file)) { files.Add(file); } } } } return files; } [MenuItem("Assets/Git/Add", true)] public static bool AddValidate() { return FindSelectedGitFiles(file => file.HasStatus(EStatus.HasUnstagedChanges)).Count > 0; } [MenuItem("Assets/Git/Add", false)] public static void Add() { Git.Command(Git.ECommand.Add, FindSelectedGitFiles(file => file.HasStatus(EStatus.HasUnstagedChanges))); } [MenuItem("Assets/Git/Reset", true)] public static bool ResetValidate() { return FindSelectedGitFiles(file => file.HasStatus(EStatus.HasStagedChanges)).Count > 0; } [MenuItem("Assets/Git/Reset", false)] public static void Reset() { Git.Command(Git.ECommand.Reset, FindSelectedGitFiles(file => file.HasStatus(EStatus.HasStagedChanges))); } [MenuItem("Assets/Git/Diff", true)] public static bool DiffValidate() { return FindSelectedGitFiles(file => file.HasStatus(EStatus.HasStagedChanges) || file.HasStatus(EStatus.HasUnstagedChanges)).Count > 0; } [MenuItem("Assets/Git/Diff", false)] public static void Diff() { Git.Command(Git.ECommand.Diff, FindSelectedGitFiles(file => file.HasStatus(EStatus.HasStagedChanges) || file.HasStatus(EStatus.HasUnstagedChanges))); } [MenuItem("Assets/Git/Discard", true)] public static bool DiscardValidate() { return FindSelectedGitFiles(file => file.HasStatus(EStatus.HasUnstagedChanges)).Count > 0; } [MenuItem("Assets/Git/Discard", false)] public static void Discard() { var files = FindSelectedGitFiles(file => file.HasStatus(EStatus.HasStagedChanges) || file.HasStatus(EStatus.HasUnstagedChanges)); string fileNames = ""; foreach (var file in files) fileNames += file.name + ", "; if (EditorUtility.DisplayDialog("Discard local changes?", "Are you sure you want to discard your local changes to " + fileNames + "?", "Discard", "Cancel")) Git.Command(Git.ECommand.Discard, files); } [MenuItem("Assets/Git/Info")] public static void Info() { foreach (Git.File file in FindSelectedGitFiles(file => true)) { string statusString = ""; foreach (EStatus status in Enum.GetValues(typeof(EStatus))) { if (file.HasStatus(status)) statusString += status + ", "; } Debug.Log(file.name + " status: " + statusString); } } } }
43,216
https://github.com/F-S-C/Cicerone/blob/master/docs/Server/dir_09a58e4ad679d39594142c6d9007160c.js
Github Open Source
Open Source
Apache-2.0
null
Cicerone
F-S-C
JavaScript
Code
10
80
var dir_09a58e4ad679d39594142c6d9007160c = [ [ "006e07e4f87e0fb9.php", "006e07e4f87e0fb9_8php.html", "006e07e4f87e0fb9_8php" ] ];
21,992
https://github.com/kagu/kunquat/blob/master/src/lib/init/devices/processors/Proc_noise.c
Github Open Source
Open Source
CC0-1.0
2,022
kunquat
kagu
C
Code
132
533
/* * Authors: Tomi Jylhä-Ollila, Finland 2010-2019 * Ossi Saresoja, Finland 2010 * * This file is part of Kunquat. * * CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/ * * To the extent possible under law, Kunquat Affirmers have waived all * copyright and related or neighboring rights to Kunquat. */ #include <init/devices/processors/Proc_noise.h> #include <debug/assert.h> #include <init/devices/Device_params.h> #include <init/devices/Proc_cons.h> #include <init/devices/Processor.h> #include <kunquat/limits.h> #include <memory.h> #include <player/devices/processors/Noise_state.h> #include <string/common.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> static void del_Proc_noise(Device_impl* proc_impl); Device_impl* new_Proc_noise(void) { Proc_noise* noise = memory_alloc_item(Proc_noise); if (noise == NULL) return NULL; if (!Device_impl_init(&noise->parent, del_Proc_noise)) { del_Device_impl(&noise->parent); return NULL; } noise->parent.create_pstate = new_Noise_pstate; noise->parent.get_vstate_size = Noise_vstate_get_size; noise->parent.init_vstate = Noise_vstate_init; noise->parent.render_voice = Noise_vstate_render_voice; return &noise->parent; } static void del_Proc_noise(Device_impl* dimpl) { if (dimpl == NULL) return; Proc_noise* noise = (Proc_noise*)dimpl; memory_free(noise); return; }
41,250
https://github.com/fachriagustian12/sis_pakar/blob/master/application/controllers/Diagnosa.php
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, MIT
2,021
sis_pakar
fachriagustian12
PHP
Code
158
729
<?php defined('BASEPATH') or exit('No direct script access allowed'); class Diagnosa extends CI_Controller { public function __construct() { parent::__construct(); $this->isLogin = $this->session->userdata('isLogin'); if ($this->isLogin == 0) { redirect(base_url()); } $this->id = $this->session->userdata('id'); $this->load->model('model_diagnosa'); } public function listDiagnosa() { $page['page'] = 'diagnosa'; $data['listDiagnosa'] = $this->model_diagnosa->getAll(); $this->load->view('back/template/header'); $this->load->view('back/template/sidebar'); $this->load->view('back/diagnosa', $data); $this->load->view('back/template/footer'); } public function getAlldiagnosa() { $diagnosa = $this->model_diagnosa->getAll(); echo json_encode($diagnosa); } public function diagnosaById() { $id = $this->input->post('id'); $diagnosa = $this->model_diagnosa->getById($id); $output = array( 'kode_diagnosa' => $diagnosa->kode_diagnosa, 'nama_diagnosa' => $diagnosa->nama_diagnosa, 'keterangan' => $diagnosa->keterangan ); echo json_encode($output); } public function doDiagnosa() { $operation = $this->input->post('operation'); if ($operation == "Tambah") { $data = array( 'kode_diagnosa' => $this->input->post('kode_diagnosa'), 'nama_diagnosa' => $this->input->post('nama_diagnosa'), 'keterangan' => $this->input->post('keterangan') ); $process = $this->model_diagnosa->tambah($data); } else if ($operation == "Edit") { $id = $this->input->post('id_diagnosa'); $data = array( 'kode_diagnosa' => $this->input->post('kode_diagnosa'), 'nama_diagnosa' => $this->input->post('nama_diagnosa'), 'keterangan' => $this->input->post('keterangan') ); $process = $this->model_diagnosa->edit($id, $data); } echo json_encode($process); } public function deleteDiagnosa() { $id = $this->input->post('id'); $process = $this->model_diagnosa->delete($id); echo json_encode($process); } }
814
https://github.com/marscore/hhvm/blob/master/hphp/test/slow/array_functions/531.php
Github Open Source
Open Source
Zend-2.0, PHP-3.01, MIT
2,019
hhvm
marscore
PHP
Code
54
285
<?php function f($x, $y) { var_dump($x, $y); return $x + $x + $y + 1; } <<__EntryPoint>> function main_531() { var_dump(array_reduce(array(), 'f')); var_dump(array_reduce(array(), 'f', null)); var_dump(array_reduce(array(), 'f', 0)); var_dump(array_reduce(array(), 'f', 23)); var_dump(array_reduce(array(4), 'f')); var_dump(array_reduce(array(4), 'f', null)); var_dump(array_reduce(array(4), 'f', 0)); var_dump(array_reduce(array(4), 'f', 23)); var_dump(array_reduce(array(1,2,3,4), 'f')); var_dump(array_reduce(array(1,2,3,4), 'f', null)); var_dump(array_reduce(array(1,2,3,4), 'f', 0)); var_dump(array_reduce(array(1,2,3,4), 'f', 23)); }
35,768
https://github.com/guilhermessantos/imc/blob/master/assets/stylesheets/elements/form/_inputs.scss
Github Open Source
Open Source
MIT
2,015
imc
guilhermessantos
SCSS
Code
18
59
input { background: $colorDetail; border: none; border-radius: $borderRadius; color: $colorText; height: 35px; padding: 5px 10px; width: 100%; }
4,537
https://github.com/ljcollins25/Codeground/blob/master/src/UnoApp/UnoDecompile/Uno.UI/Windows.UI.Xaml.Automation.Pee/AutomationEvents.cs
Github Open Source
Open Source
MIT
null
Codeground
ljcollins25
C#
Code
37
231
namespace Windows.UI.Xaml.Automation.Peers; public enum AutomationEvents { ToolTipOpened, ToolTipClosed, MenuOpened, MenuClosed, AutomationFocusChanged, InvokePatternOnInvoked, SelectionItemPatternOnElementAddedToSelection, SelectionItemPatternOnElementRemovedFromSelection, SelectionItemPatternOnElementSelected, SelectionPatternOnInvalidated, TextPatternOnTextSelectionChanged, TextPatternOnTextChanged, AsyncContentLoaded, PropertyChanged, StructureChanged, DragStart, DragCancel, DragComplete, DragEnter, DragLeave, Dropped, LiveRegionChanged, InputReachedTarget, InputReachedOtherElement, InputDiscarded, WindowClosed, WindowOpened, ConversionTargetChanged, TextEditTextChanged, LayoutInvalidated }
1,111
https://github.com/Jhushaw/CCCEventManager/blob/master/resources/views/showEditEvent.blade.php
Github Open Source
Open Source
MIT
null
CCCEventManager
Jhushaw
PHP
Code
235
987
<!-- View page lets admins add upcoming church events --> @extends('layouts.appmaster') @section('head','Add Events') @section('content') @if (!Session::has('User')) <script>window.location = "Login";</script> @endif @if (Session::has('User') && Session::get('Admin') == 1) <!-- action will point to the route --> <div class="blog-home2 py-5"> <div class="container"> <!-- Row --> <div class="row justify-content-center"> <div class="col-md-5 text-center"> <h4 class="my-1">Edit an Event</h3> <h6 class="subtitle font-weight-normal">Fill all fields in and save</h6> </div> </div> <div class="row mt-4"> <!-- Column --> <form> <div class="col-md-10 on-hover"> <div class="card border-0 mb-4"> <a href="#"><img class="card-img-top" src="{{ $event->getUrl()}}" alt="wrappixel kit"></a> <!--{{ $timestamp = strtotime( $event->getDate() ) }}--> <div class="date-pos bg-info-gradiant p-3 d-inline-block text-center rounded text-white position-absolute">{{ date("M", $timestamp) }}<span class="d-block">{{ date("d", $timestamp) }}</span></div> <h5 class="font-weight-medium mt-3"><p>{{ $event->getTitle()}}</p></h5> <p class="mt-2">{{ $event->getDescription()}}</p> <!-- <a href="#" class="text-decoration-none linking text-themecolor mt-2">Learn More</a> --> </div> </form> </div> <h5 align="center"><?php if (isset($msg)){ //checks if message is instantiated, if so echos message echo $msg; }?></h5> <form action="editEvent" method="POST"> <input type="hidden" name="_token" value=" <?php echo csrf_token()?>" /><br/> <input type="hidden" name="id" value="{{ $event->getID()}}" /> <div class="form-group"><input class="form-control" type="text" name="url" value="{{ $event->getUrl()}}" placeholder="Image URL"></div> <div class="form-group"><input class="form-control" type="text" name="title" value="{{ $event->getTitle()}}" placeholder="Title"></div> <div class="form-group"><input class="form-control" type="date" name="date" value="{{ $event->getDate()}}" placeholder="Date"></div> <div class="form-group"><p>Capacity:</p><input class="form-control" type="number" name="capacity" value="{{ $event->getCapacity()}}" placeholder="0"></div> <div class="form-group"><textarea rows="5" cols="50" class="form-control" name="description" placeholder="Description">{{ $event->getDescription()}}</textarea></div> <button class="btn btn-info" type="submit">Save Event</button> </form> @if($errors->count() != 0) <h5 align="center">List of Errors</h5> @foreach($errors->all() as $message) <p align="center">{{ $message }} </p><br> @endforeach @endif </div> </div> </div> <script src="assets/js/jquery.min.js"></script> <script src="assets/bootstrap/js/bootstrap.min.js"></script> @else <script>window.location = "Login";</script> @endif @endsection
10,367
https://github.com/MonashTS/tempo/blob/master/experiments/2021-04-19-PF2018-comparison/PF2018_java/ProximityForest/src/trees/ProximityForest.java
Github Open Source
Open Source
BSD-3-Clause
2,022
tempo
MonashTS
Java
Code
427
1,603
package trees; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import core.AppContext; import core.ProximityForestResult; import core.contracts.Dataset; import util.PrintUtilities; /** * * @author shifaz * @email [email protected] * */ public class ProximityForest implements Serializable{ /** * */ private static final long serialVersionUID = -1183368028217094381L; protected transient ProximityForestResult result; protected int forest_id; protected ProximityTree trees[]; public String prefix; int[] num_votes; List<Integer> max_voted_classes; public ProximityForest(int forest_id) { this.result = new ProximityForestResult(this); this.forest_id = forest_id; this.trees = new ProximityTree[AppContext.num_trees]; for (int i = 0; i < AppContext.num_trees; i++) { trees[i] = new ProximityTree(i, this); } } public void train(Dataset train_data) throws Exception { result.startTimeTrain = System.nanoTime(); for (int i = 0; i < AppContext.num_trees; i++) { trees[i].train(train_data); if (AppContext.verbosity > 0) { System.out.print(i+"."); if (AppContext.verbosity > 1) { PrintUtilities.printMemoryUsage(true); if ((i+1) % 20 == 0) { System.out.println(); } } } } result.endTimeTrain = System.nanoTime(); result.elapsedTimeTrain = result.endTimeTrain - result.startTimeTrain; if (AppContext.verbosity > 0) { System.out.print("\n"); } // System.gc(); if (AppContext.verbosity > 0) { PrintUtilities.printMemoryUsage(); } } //ASSUMES CLASS labels HAVE BEEN reordered to start from 0 and contiguous public ProximityForestResult test(Dataset test_data) throws Exception { result.startTimeTest = System.nanoTime(); num_votes = new int[test_data._get_initial_class_labels().size()]; max_voted_classes = new ArrayList<Integer>(); int predicted_class; int actual_class; int size = test_data.size(); for (int i=0; i < size; i++){ actual_class = test_data.get_class(i); predicted_class = predict(test_data.get_series(i)); if (actual_class != predicted_class){ result.errors++; }else{ result.correct++; } if (AppContext.verbosity > 0) { if (i % AppContext.print_test_progress_for_each_instances == 0) { System.out.print("*"); } } } result.endTimeTest = System.nanoTime(); result.elapsedTimeTest = result.endTimeTest - result.startTimeTest; if (AppContext.verbosity > 0) { System.out.println(); } assert test_data.size() == result.errors + result.correct; result.accuracy = ((double) result.correct) / test_data.size(); result.error_rate = 1 - result.accuracy; return result; } public Integer predict(double[] query) throws Exception { //ASSUMES CLASSES HAVE BEEN REMAPPED, start from 0 int label; int max_vote_count = -1; int temp_count = 0; for (int i = 0; i < num_votes.length; i++) { num_votes[i] = 0; } max_voted_classes.clear(); for (int i = 0; i < trees.length; i++) { label = trees[i].predict(query); num_votes[label]++; } // System.out.println("vote counting using uni dist"); for (int i = 0; i < num_votes.length; i++) { temp_count = num_votes[i]; if (temp_count > max_vote_count) { max_vote_count = temp_count; max_voted_classes.clear(); max_voted_classes.add(i); }else if (temp_count == max_vote_count) { max_voted_classes.add(i); } } int r = AppContext.getRand().nextInt(max_voted_classes.size()); //collecting some stats if (max_voted_classes.size() > 1) { this.result.majority_vote_match_count++; } return max_voted_classes.get(r); } public ProximityTree[] getTrees() { return this.trees; } public ProximityTree getTree(int i) { return this.trees[i]; } public ProximityForestResult getResultSet() { return result; } public ProximityForestResult getForestStatCollection() { result.collateResults(); return result; } public int getForestID() { return forest_id; } public void setForestID(int forest_id) { this.forest_id = forest_id; } }
37,925
https://github.com/mrnettek/VBScript/blob/master/VBScript1/Add the Contents of a Group of Text Files to an Access Database.vbs
Github Open Source
Open Source
MIT
2,020
VBScript
mrnettek
VBScript
Code
93
334
Const ForReading = 1 Const adLockOptimistic = 3 Set objConnection = CreateObject("ADODB.Connection") Set objRecordSet = CreateObject("ADODB.Recordset") Set objFSO = CreateObject("Scripting.FileSystemObject") objConnection.Open _ "Provider = Microsoft.Jet.OLEDB.4.0; " & _ "Data Source = C:\Scripts\Test.mdb" objRecordSet.Open "SELECT * FROM TextFiles" , _ objConnection, adOpenStatic, adLockOptimistic strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colFileList = objWMIService.ExecQuery _ ("ASSOCIATORS OF {Win32_Directory.Name='C:\Archive'} Where " _ & "ResultClass = CIM_DataFile") For Each objFile In colFileList Set objTextFile = objFSO.OpenTextFile(objFile.Name, ForReading) strContents = objTextFile.ReadAll objTextFile.Close objRecordSet.AddNew objRecordSet("FileName") = objFile.Name objRecordSet("FileContents") = strContents objRecordSet.Update Next objRecordSet.Close objConnection.Close
39,899
https://github.com/JIoffe/PastryEditor/blob/master/src/model/palettized-image.ts
Github Open Source
Open Source
MIT
2,021
PastryEditor
JIoffe
TypeScript
Code
10
31
export interface PalettizedImage{ width: number; height: number; indices: Uint8Array; }
3,089
https://github.com/Seachal/okhttp-RxHttp/blob/master/app/build/generated/source/kapt/debug/rxhttp/wrapper/param/ObservableErrorHandler.java
Github Open Source
Open Source
Apache-2.0
2,020
okhttp-RxHttp
Seachal
Java
Code
51
343
package rxhttp.wrapper.param; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.functions.Consumer; import io.reactivex.rxjava3.plugins.RxJavaPlugins; import rxhttp.wrapper.utils.LogUtil; /** * User: ljx * Date: 2020/4/11 * Time: 16:19 */ public abstract class ObservableErrorHandler<T> extends Observable<T> { static { Consumer<? super Throwable> errorHandler = RxJavaPlugins.getErrorHandler(); if (errorHandler == null) { /* RxJava2的一个重要的设计理念是:不吃掉任何一个异常, 即抛出的异常无人处理,便会导致程序崩溃 这就会导致一个问题,当RxJava2“downStream”取消订阅后,“upStream”仍有可能抛出异常, 这时由于已经取消订阅,“downStream”无法处理异常,此时的异常无人处理,便会导致程序崩溃 */ RxJavaPlugins.setErrorHandler(LogUtil::log); } } }
20,361
https://github.com/lsoaresesilva/lunanative/blob/master/android/LunaFramework/app/src/main/java/luna/framework/syntax/data/LuaHashMapAdapter.java
Github Open Source
Open Source
MIT
2,021
lunanative
lsoaresesilva
Java
Code
284
914
package luna.framework.syntax.data; import org.luaj.vm2.LuaFunction; import org.luaj.vm2.LuaNil; import org.luaj.vm2.LuaTable; import org.luaj.vm2.LuaValue; import org.luaj.vm2.Varargs; import luna.framework.syntax.function.LuaFunctionAdapter; import luna.framework.syntax.function.LunaFunctionAdapter; import static org.luaj.vm2.LuaValue.TBOOLEAN; import static org.luaj.vm2.LuaValue.TFUNCTION; import static org.luaj.vm2.LuaValue.TINT; import static org.luaj.vm2.LuaValue.TNIL; import static org.luaj.vm2.LuaValue.TNUMBER; import static org.luaj.vm2.LuaValue.TSTRING; import static org.luaj.vm2.LuaValue.TTABLE; /** * Created by macbookair on 27/04/17. */ public class LuaHashMapAdapter implements LunaHashMapAdapter { LuaTable luaTable; @Override public void create(Object luaTable) { if( luaTable != null && luaTable instanceof LuaTable) this.luaTable = (LuaTable)luaTable; } @Override public int size() { if( this.luaTable != null ) { int count = 0; LuaValue k = LuaValue.NIL; while ( true ) { Varargs n = luaTable.next(k); if ( (k = n.arg1()).isnil() ) break; count++; } return count; } throw new NullPointerException("An LuaTable was not passed to create() method."); } @Override public boolean containsKey(String key) { if( this.luaTable != null ) { LuaValue value = this.luaTable.get(key); if ( value != LuaValue.NIL ) return true; else return false; } throw new NullPointerException("An LuaTable was not passed to create() method."); } @Override public Object get(String key) { if(this.luaTable != null) { Object value = null; if (this.luaTable.get(key) != null || !(this.luaTable.get(key) instanceof LuaNil)) { LuaValue luaValue = this.luaTable.get(key); if (luaValue.type() == TSTRING) { value = luaValue.toString(); } else if (luaValue.type() == TINT) { value = luaValue.toint(); } else if (luaValue.type() == TNIL) { value = null; } else if (luaValue.type() == TBOOLEAN) { value = luaValue.toboolean(); }else if (luaValue.type() == TFUNCTION) { LunaFunctionAdapter luaFunction = new LuaFunctionAdapter(); luaFunction.create((LuaFunction)luaValue); value = luaFunction; } else if (luaValue.type() == TNUMBER) { value = luaValue.todouble(); } else if (luaValue.type() == TTABLE) { LunaHashMapAdapter luaHash = new LuaHashMapAdapter(); luaHash.create(luaValue); value = luaHash; } } return value; } throw new NullPointerException("An LuaTable was not passed to create() method."); } }
1,893
https://github.com/deanlinsalata/JALoP/blob/master/src/network_lib/test/test_jaln_string_utils.c
Github Open Source
Open Source
Apache-2.0
2,021
JALoP
deanlinsalata
C
Code
764
3,900
/** * @file test_jaln_string_utils.c This file contains tests for jaln_string_utils.c functions. * * @section LICENSE * * Source code in 3rd-party is licensed and owned by their respective * copyright holders. * * All other source code is copyright Tresys Technology and licensed as below. * * Copyright (c) 2012 Tresys Technology LLC, Columbia, Maryland, USA * * This software was developed by Tresys Technology LLC * with U.S. Government sponsorship. * * 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. */ #include <axl.h> #include <errno.h> #include <limits.h> #include <stdlib.h> #include <stdint.h> #include <test-dept.h> #include "jal_asprintf_internal.h" #include "jaln_string_utils.h" #define VALID_NUMERIC_STRING "65" #define NOT_VALID_NUMERIC_STRING "A" static char *longer_than_max = NULL; void setup() { jal_asprintf(&longer_than_max, "%llu0", ULLONG_MAX); } void teardown() { free(longer_than_max); longer_than_max = NULL; } void test_jaln_ascii_to_uint64_succeeds() { uint64_t out = 0; assert_true(jaln_ascii_to_uint64(VALID_NUMERIC_STRING, &out)); assert_equals(65, out); } void test_jaln_ascii_to_uint64_fails_when_not_ascii() { axl_bool ret = axl_false; uint64_t out = 0; ret = jaln_ascii_to_uint64(NOT_VALID_NUMERIC_STRING, &out); assert_false(ret); } void test_jaln_ascii_to_uint64_fails_when_string_causing_overflow() { axl_bool ret = axl_false; uint64_t out = 0; ret = jaln_ascii_to_uint64(longer_than_max, &out); assert_false(ret); } void test_jaln_ascii_to_uint64_t_succeeds() { axl_bool ret = axl_false; uint64_t out = 0; ret = jaln_ascii_to_uint64_t(VALID_NUMERIC_STRING, &out); assert_equals(axl_true, ret); assert_equals(65, out); } void test_jaln_ascii_to_uint64_t_fails_with_invalid_input() { axl_bool ret = axl_false; uint64_t out = 0; ret = jaln_ascii_to_uint64_t(NOT_VALID_NUMERIC_STRING, &out); assert_equals(axl_false, ret); } void test_jaln_ascii_to_uint64_fails_with_null_inputs() { uint64_t out = 0; assert_false(jaln_ascii_to_uint64(NULL, &out)); assert_false(jaln_ascii_to_uint64(VALID_NUMERIC_STRING, NULL)); } void test_jaln_hex_to_bin_fails_for_bad_input() { uint8_t out; assert_equals(JAL_E_INVAL, jaln_hex_to_bin('\0', &out)); assert_equals(JAL_E_INVAL, jaln_hex_to_bin('0' - 1, &out)); assert_equals(JAL_E_INVAL, jaln_hex_to_bin('9' + 1, &out)); assert_equals(JAL_E_INVAL, jaln_hex_to_bin('a' - 1, &out)); assert_equals(JAL_E_INVAL, jaln_hex_to_bin('A' - 1, &out)); assert_equals(JAL_E_INVAL, jaln_hex_to_bin('f' + 1, &out)); assert_equals(JAL_E_INVAL, jaln_hex_to_bin('F' + 1, &out)); } void test_jaln_hex_to_bin_works_for_valid_input() { uint8_t out; assert_equals(JAL_OK, jaln_hex_to_bin('0', &out)); assert_equals(0, out); assert_equals(JAL_OK, jaln_hex_to_bin('1', &out)); assert_equals(1, out); assert_equals(JAL_OK, jaln_hex_to_bin('2', &out)); assert_equals(2, out); assert_equals(JAL_OK, jaln_hex_to_bin('3', &out)); assert_equals(3, out); assert_equals(JAL_OK, jaln_hex_to_bin('4', &out)); assert_equals(4, out); assert_equals(JAL_OK, jaln_hex_to_bin('5', &out)); assert_equals(5, out); assert_equals(JAL_OK, jaln_hex_to_bin('6', &out)); assert_equals(6, out); assert_equals(JAL_OK, jaln_hex_to_bin('7', &out)); assert_equals(7, out); assert_equals(JAL_OK, jaln_hex_to_bin('8', &out)); assert_equals(8, out); assert_equals(JAL_OK, jaln_hex_to_bin('9', &out)); assert_equals(9, out); assert_equals(JAL_OK, jaln_hex_to_bin('a', &out)); assert_equals(10, out); assert_equals(JAL_OK, jaln_hex_to_bin('A', &out)); assert_equals(10, out); assert_equals(JAL_OK, jaln_hex_to_bin('b', &out)); assert_equals(11, out); assert_equals(JAL_OK, jaln_hex_to_bin('B', &out)); assert_equals(11, out); assert_equals(JAL_OK, jaln_hex_to_bin('c', &out)); assert_equals(12, out); assert_equals(JAL_OK, jaln_hex_to_bin('C', &out)); assert_equals(12, out); assert_equals(JAL_OK, jaln_hex_to_bin('d', &out)); assert_equals(13, out); assert_equals(JAL_OK, jaln_hex_to_bin('D', &out)); assert_equals(13, out); assert_equals(JAL_OK, jaln_hex_to_bin('e', &out)); assert_equals(14, out); assert_equals(JAL_OK, jaln_hex_to_bin('E', &out)); assert_equals(14, out); assert_equals(JAL_OK, jaln_hex_to_bin('f', &out)); assert_equals(15, out); assert_equals(JAL_OK, jaln_hex_to_bin('F', &out)); assert_equals(15, out); } void test_hex_str_to_buf_works_for_00() { uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_OK, jaln_hex_str_to_bin_buf("00", strlen("00"), &buf, &buf_len)); assert_equals(buf_len, 1); assert_equals(0x00, buf[0]); free(buf); } void test_hex_str_to_buf_works_for_10() { uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_OK, jaln_hex_str_to_bin_buf("10", strlen("10"), &buf, &buf_len)); assert_equals(buf_len, 1); assert_equals(0x10, buf[0]); free(buf); } void test_hex_str_to_buf_works_for_ff() { uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_OK, jaln_hex_str_to_bin_buf("ff", strlen("ff"), &buf, &buf_len)); assert_equals(buf_len, 1); assert_equals(0xff, buf[0]); free(buf); } void test_hex_str_to_buf_works_for_f0() { uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_OK, jaln_hex_str_to_bin_buf("f0", strlen("f0"), &buf, &buf_len)); assert_equals(buf_len, 1); assert_equals(0xf0, buf[0]); free(buf); } void test_hex_str_to_buf_works_for_f() { uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_OK, jaln_hex_str_to_bin_buf("f", strlen("f"), &buf, &buf_len)); assert_equals(buf_len, 1); assert_equals(0xf, buf[0]); free(buf); } void test_hex_str_to_buf_works_for_5() { uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_OK, jaln_hex_str_to_bin_buf("5", strlen("5"), &buf, &buf_len)); assert_equals(buf_len, 1); assert_equals(0x5, buf[0]); free(buf); } void test_hex_str_to_buf_works_for_0() { uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_OK, jaln_hex_str_to_bin_buf("0", strlen("0"), &buf, &buf_len)); assert_equals(buf_len, 1); assert_equals(0x0, buf[0]); free(buf); } void test_hex_str_to_buf_works_for_long_even_cnt() { const char *str = "abcd123411aaff22"; uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_OK, jaln_hex_str_to_bin_buf(str, strlen(str), &buf, &buf_len)); assert_equals(buf_len, 8); assert_equals(0xab, buf[0]); assert_equals(0xcd, buf[1]); assert_equals(0x12, buf[2]); assert_equals(0x34, buf[3]); assert_equals(0x11, buf[4]); assert_equals(0xaa, buf[5]); assert_equals(0xff, buf[6]); assert_equals(0x22, buf[7]); free(buf); } void test_hex_str_to_buf_works_for_long_even_cnt_fails_with_bad_string() { const char *str = "bcd12341z1aaff22"; uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_E_INVAL, jaln_hex_str_to_bin_buf(str, strlen(str), &buf, &buf_len)); } void test_hex_str_to_buf_works_for_long_odd_cnt() { const char *str = "abcd123411aaff223"; uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_OK, jaln_hex_str_to_bin_buf(str, strlen(str), &buf, &buf_len)); assert_equals(buf_len, 9); assert_equals(0x0a, buf[0]); assert_equals(0xbc, buf[1]); assert_equals(0xd1, buf[2]); assert_equals(0x23, buf[3]); assert_equals(0x41, buf[4]); assert_equals(0x1a, buf[5]); assert_equals(0xaf, buf[6]); assert_equals(0xf2, buf[7]); assert_equals(0x23, buf[8]); free(buf); } void test_hex_str_to_buf_works_for_long_odd_cnt_fails_with_bad_string() { const char *str = "abcd12341z1aaff22"; uint8_t *buf = NULL; uint64_t buf_len; assert_equals(JAL_E_INVAL, jaln_hex_str_to_bin_buf(str, strlen(str), &buf, &buf_len)); } void test_hex_fails_with_null_inputs() { const char *str = "abcd123411aaff223"; uint8_t *buf = NULL; uint64_t buf_len; //assert_equals(JAL_E_INVAL, jaln_hex_str_to_bin_buf(str, strlen(str), &buf, &buf_len)); assert_equals(JAL_E_INVAL, jaln_hex_str_to_bin_buf(NULL, strlen(str), &buf, &buf_len)); assert_equals(JAL_E_INVAL, jaln_hex_str_to_bin_buf(str, 0, &buf, &buf_len)); assert_equals(JAL_E_INVAL, jaln_hex_str_to_bin_buf(str, strlen(str), NULL, &buf_len)); assert_equals(JAL_E_INVAL, jaln_hex_str_to_bin_buf(str, strlen(str), &buf, NULL)); buf = (uint8_t*) 0xbadf00d; assert_equals(JAL_E_INVAL, jaln_hex_str_to_bin_buf(str, strlen(str), &buf, &buf_len)); }
8,878
https://github.com/Dython-sky/AID1908/blob/master/study/1905/month01/code/Stage5/day20/paddle/day01/04_reader_demo.py
Github Open Source
Open Source
MIT
2,020
AID1908
Dython-sky
Python
Code
56
226
# 04_reader_demo.py 实现文件的顺序读取、随机读取、批量读取 import paddle # 读取文件的生成器函数 def reader_creator(file_path): def reader(): with open(file_path) as f: lines = f.readlines() for line in lines: yield line # 生成一行数据 return reader reader = reader_creator("test.txt") shuffle_reader = paddle.reader.shuffle(reader,10) # 随机读取 batch_reader = paddle.batch(shuffle_reader,3) # 批量读取,每个批次3笔 # for data in reader(): # for data in shuffle_reader(): for data in batch_reader(): print(data,end="")
49,053
https://github.com/EngFarisAlsmawi/django-user-g11n/blob/master/tests/settings.py
Github Open Source
Open Source
MIT
2,022
django-user-g11n
EngFarisAlsmawi
Python
Code
80
479
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'user_g11n', 'tests.accounts', ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } SECRET_KEY = "secret_key_for_testing" MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'user_g11n.middleware.UserLanguageMiddleware', 'user_g11n.middleware.UserTimeZoneMiddleware', ] MIDDLEWARE = MIDDLEWARE_CLASSES ROOT_URLCONF = 'tests.urls' STATIC_URL = "/" TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ["templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] AUTH_USER_MODEL = "accounts.User" USE_I18N = True USE_L10N = True USE_TZ = True TIME_ZONE = "UTC"
35,929
https://github.com/meitu/twemproxy/blob/master/tests/test_memcache/test_gets.py
Github Open Source
Open Source
Apache-2.0
2,020
twemproxy
meitu
Python
Code
189
718
#!/usr/bin/env python #coding: utf-8 import os import sys import redis import memcache PWD = os.path.dirname(os.path.realpath(__file__)) WORKDIR = os.path.join(PWD, '../') sys.path.append(os.path.join(WORKDIR, 'lib/')) sys.path.append(os.path.join(WORKDIR, 'conf/')) from conf import * from utils import * large = int(getenv('T_LARGE', 1000)) def getconn(): host_port = '%s:%s' % (nc_servers['mc-shards']['host'], nc_servers['mc-shards']['port']) return memcache.Client([host_port]) def test_basic(): conn = getconn() conn.set('k', 'v') assert('v' == conn.get('k')) conn.set("key", "1") for i in range(10): conn.incr("key") assert(str(i+2) == conn.get('key')) conn.delete("key") assert(None == conn.get('key')) default_kv = {'kkk-%s' % i :'vvv-%s' % i for i in range(10)} def test_mget_mset(kv=default_kv): conn = getconn() conn.set_multi(kv) keys = sorted(kv.keys()) assert(conn.get_multi(keys) == kv) assert(conn.gets_multi(keys) == kv) #del conn.delete_multi(keys) #mget again vals = conn.get_multi(keys) assert({} == vals) def test_mget_mset_large(): for cnt in range(179, large, 179): #print 'test', cnt kv = {'kkk-%s' % i :'vvv-%s' % i for i in range(cnt)} test_mget_mset(kv) def test_mget_mset_key_not_exists(kv=default_kv): conn = getconn() conn.set_multi(kv) keys = kv.keys() keys2 = ['x-'+k for k in keys] keys = keys + keys2 random.shuffle(keys) for i in range(2): #mget to check vals = conn.get_multi(keys) for i, k in enumerate(keys): if k in kv: assert(kv[k] == vals[k]) else: assert(k not in vals) #del conn.delete_multi(keys) #mget again vals = conn.get_multi(keys) assert({} == vals)
13,263
https://github.com/Mizumi/gh6-narwhal/blob/master/device-server/src/main/webapp/src/assets/styles/sass/main.scss
Github Open Source
Open Source
Apache-2.0
null
gh6-narwhal
Mizumi
SCSS
Code
311
1,004
/* * Project: gh6 * Since: Oct 21, 2016 * * Copyright (c) Brandon Sanders [[email protected]], Joshua Gagen [[email protected]], * Edwin Munguia [[email protected]] and Justin Stone * * 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. */ .mainContainer { img { position: relative; width: 100%; min-height: auto; text-align: center; color: #fff; z-index: 100; background-attachment: fixed !important; background-position: center !important; -webkit-background-size: cover !important; -moz-background-size: cover !important; background-size: cover !important; -o-background-size: cover !important; background: linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)); } .darkMask { z-index: 110; width: 100%; height: 100%; //TODO: COME BACK TO THIS position: absolute; left: 0; top: 50px; background: linear-gradient(rgba(0,0,0,0.45), rgba(0,0,0,0.55)); //For Text: margin-left: auto; margin-right: auto; text-align: center; font-weight: 700; font-size: 40pt; color: #e5e9eb; h1 { font-weight: 900; font-size: 65pt; } h5 { font-weight: 100; letter-spacing: 1px; font-size: 12px; color: rgba(255,255,255,0.6); } .low-impact { font-weight: 100; color: rgba(255,255,255,0.75); } .text-shade { text-shadow: 0 2px 8px rgba(0,0,0,0.4); } .slide-up { position: relative; animation-duration: 0.5s; animation-name: slideUp; animation-fill-mode: forwards; animation-timing-function: ease; } @keyframes slideUp { from { top: 1000px; } to { top: 0; } } .navigationButtons { i { margin-top: 20px; font-size: 40px; text-shadow: 0 2px 8px rgba(0,0,0,0.4); } .btn { top: 1000px; width: 400px; margin-top: 10px; } //Bootstrap overrides will have to go here. .btn>h2 { background-color: #565656; color: transparent; background-clip: text; -webkit-background-clip: text; -moz-background-clip: text; text-shadow: 0 1px 0.8px rgba(255,255,255,0.9); font-size: 60px; } span { padding-right: 5px; font-size: 45px; } } } }
37,268
https://github.com/Newlifer/Cesium/blob/master/Cesium.Ast/Expressions.cs
Github Open Source
Open Source
MIT
null
Cesium
Newlifer
C#
Code
107
285
using System.Collections.Immutable; using Yoakke.C.Syntax; using Yoakke.Lexer; namespace Cesium.Ast; public abstract record Expression; // 6.5.1 Primary expressions public record IdentifierExpression(string Identifier) : Expression; public record ConstantExpression(IToken<CTokenType> Constant) : Expression; public record IntConstantExpression(int Constant) : Expression; public record StringConstantExpression(string ConstantContent) : Expression; // 6.5.2 Postfix operators public record SubscriptingExpression(Expression Base, Expression Index) : Expression; public record FunctionCallExpression(Expression Function, ImmutableArray<Expression>? Arguments) : Expression; // 6.5.3 Unary operators public record NegationExpression(Expression Target) : Expression; public record PrefixIncrementExpression(Expression Target) : Expression; // 6.5.5–6.5.15: Various binary operators public record BinaryOperatorExpression(Expression Left, string Operator, Expression Right) : Expression; // 6.5.16 Assignment operators public record AssignmentExpression(Expression Left, string Operator, Expression Right) : BinaryOperatorExpression(Left, Operator, Right);
26,042
https://github.com/fuchen1994/bel-admin/blob/master/src/views/components/ConditionRadio.vue
Github Open Source
Open Source
MIT
2,019
bel-admin
fuchen1994
Vue
Code
168
648
<template> <div class="condition-radio-group"> <span class="condition-radio-group__title" > {{label}} </span> <div class="condition-radio-group__options"> <Button class="condition-radio-group__options--all" size="small" :type=" !$route.query[tag] ? 'primary' : 'text' " :disabled="$route.query[tag] && readonly" @click="onChooseOption(tag)" > 全部 </Button> <Button v-for="option in data" class="condition-radio-group__options-item" :key="option.value" :type=" $route.query[tag] === String(option.value) ? 'primary' : 'text' " :disabled=" readonly && $route.query[tag] !== String(option.value) " @click="onChooseOption(tag, String(option.value))" > {{option.display_name}} </Button> </div> </div> </template> <script> /** * 公共组件 - button式radio组件 * * @author huojinzhao */ export default { name: 'ConditionRadio', props: { // 中文标识 label: { type: String, required: true, }, // queryKey tag: { type: String, required: true, }, // 高级搜索条件数据 data: { type: Array, required: true, }, // 是否禁止变更 readonly: { type: Boolean, default: false, }, }, methods: { onChooseOption(key, value) { // 重复点击无动作 if (this.$route.query[key] === value) return // 数据初始化 const { [key]: filter, ...rest } = this.$route.query const query = value ? { ...rest, [key]: value, page: 1 } : { ...rest, page: 1 } this.$router.push({ query }) }, }, } </script> <style lang="less"> @import './style/conditionRadio'; .condition-radio-group { .condition-radio-group(); } </style>
23,200
https://github.com/ziveo/ckan/blob/master/ckanext/stats/tests/__init__.py
Github Open Source
Open Source
Apache-2.0
2,020
ckan
ziveo
Python
Code
30
132
# encoding: utf-8 from ckan.tests.helpers import _get_test_app from ckan.common import config class StatsFixture(object): @classmethod def setup_class(cls): cls._original_config = config.copy() config['ckan.plugins'] = 'stats' cls.app = _get_test_app() @classmethod def teardown_class(cls): config.clear() config.update(cls._original_config)
31,182
https://github.com/greghicks01/uft/blob/master/Reusable Classes/ADODB.vbs
Github Open Source
Open Source
Apache-2.0
2,014
uft
greghicks01
VBScript
Code
446
962
'@ Copyright 2014 '@ '@ Gregory Hicks '@ Software Engineer '@ '@ Licensed under Creative Commons '@ '@ You may use or extend this work under the following conditions: '@ 1. You must include this copyright in your derived works. '@ 2. The software is made available "As-Is". '@ No liabilities accepted for your use or updates applied '@ No Warranties, implicit or implied apply to use. '@ '@ Version = $Version$ ' ' ADODB Manager Class ' ' Feature: ' Create a new database wrapper and connect with a connection string ' ' Scenario: ' Given the class is instantiated ' And we supply a valid connection sting ' Result is we connect to the database ' ' ' Feature: ' Create a new Recordset and run a query ' ' Scenario: ' Given the first test passes ' And we supply a valid record set name and SQL statement ' The record set produces a result matching the SQL statement ' ' '@ Start: Test Harness ' connectionString = "" ' SQLString = "" set testADO = newADODB REM testADO.DBConnect "" REM set rs1 = testADO.executeSQL("Set 1" , "Select * from t") REM set rs2 = testADO.executeSQL("Set 2" , "Update t set f = <value> where f = 'value'") REM do until rs1.eof REM 'process rs 1 REM loop REM do until rs2.eof REM 'process rs 2 REM loop '@ End: Test Harness function newADODB newADODB = new clsADODB end function class clsADODB static Version = $Version$ private objConnection, objRecordSets sub class_initialize on error resume next Set objConnection = CreateObject("ADODB.Connection") if err.number > 0 then Err.raise vbError + 1 on error goto 0 set objRecordSets = CreateObject("Scripting.Dictionary") end sub sub class_terminate : catch DBClose set objRecordSets = nothing set objConnection = nothing end sub private sub catch if err.number = 0 then exit sub end sub sub DBconnect ( conString ) objConnection.open conString end sub sub DBClose on error resume next for each rs in objRecordSets rs.close next objConnection.Close on error goto 0 err.clear end sub private sub newRecSet ( stringRecordSetID ) if stringRecordSetID = "" then Err.Raise vbErrorNumber + 2 : exit sub if objRecordSets.exist(stringRecordSetID) then exit sub objRecordSets.Add stringRecordSetID , CreateObject("ADODB.Recordset") end sub function executeSQL ( RecordSetID , SQLStatement ) newRecSet ( RecordSetID ) set executeSQL = objRecordSets(RecordSetID).open ( SQLStatement , objConnection ) end function property get EOF( recordID ) EOF = True if objRecordSets(RecordID).Status = 1 then EOF = objRecordSets(RecordID).EOF end property property get BOF ( recordID ) BOF = True if objRecordSets(RecordID).Status = 1 then BOF = objRecordSets(RecordID).BOF end property function moveNext ( recordID ) if not objRecordSets(RecordID).EOF and _ objRecordSets(RecordID).Status = 1 then _ objRecordSets(RecordID).moveNext end function end class
32,040
https://github.com/sanity-io/sanity/blob/master/packages/sanity/src/desk/components/confirmDeleteDialog/ConfirmDeleteDialogBody.tsx
Github Open Source
Open Source
MIT
2,023
sanity
sanity-io
TSX
Code
650
2,270
import React, {useCallback} from 'react' import { WarningOutlineIcon, DocumentsIcon, ClipboardIcon, UnknownIcon, ChevronDownIcon, } from '@sanity/icons' import {useToast, Text, Box, Button, Flex, Label, Card, Stack} from '@sanity/ui' import CopyToClipboard from 'react-copy-to-clipboard' import {ReferencePreviewLink} from './ReferencePreviewLink' import {ReferringDocuments} from './useReferringDocuments' import { OtherReferenceCount, CrossDatasetReferencesDetails, CrossDatasetReferencesSummary, Table, ChevronWrapper, DocumentIdFlex, } from './ConfirmDeleteDialogBody.styles' import {SanityDefaultPreview, useSchema} from 'sanity' type DeletionConfirmationDialogBodyProps = Required<ReferringDocuments> & { documentTitle: React.ReactNode action: string onReferenceLinkClick?: () => void } /** * The inner part of the `ConfirmDeleteDialog`. This is ran when both the * `crossDatasetReferences` and `internalReferences` are loaded. */ export function ConfirmDeleteDialogBody({ crossDatasetReferences, internalReferences, documentTitle, totalCount, action, datasetNames, hasUnknownDatasetNames, onReferenceLinkClick, }: DeletionConfirmationDialogBodyProps) { const schema = useSchema() const toast = useToast() const renderPreviewItem = useCallback( (item: any) => { const type = schema.get(item._type) if (type) { return <ReferencePreviewLink type={type} value={item} onClick={onReferenceLinkClick} /> } return ( // Padding added to match the ReferencePreviewLink styling <Box padding={2}> <SanityDefaultPreview icon={UnknownIcon} title="Preview Unavailable" subtitle={`ID: ${item._id}`} layout="default" /> </Box> ) }, [schema, onReferenceLinkClick], ) if (internalReferences?.totalCount === 0 && crossDatasetReferences?.totalCount === 0) { return ( <Text as="p"> Are you sure you want to {action} <strong>“{documentTitle}”</strong>? </Text> ) } const documentCount = crossDatasetReferences.totalCount === 1 ? '1 document' : `${crossDatasetReferences.totalCount.toLocaleString()} documents` // We do some extra checks to handle cases where you have unavailable dataset // name(s) due to permissions, both alone and in combination with known datasets // This normalizes one or more undefined dataset names to the catch-all `unavailable` const normalizedDatasetNames = [ ...datasetNames, ...(hasUnknownDatasetNames ? ['unavailable'] : []), ] const datasetsCount = normalizedDatasetNames.length === 1 ? 'another dataset' : `${normalizedDatasetNames.length} datasets` let datasetNameList = `Dataset${ normalizedDatasetNames.length === 1 ? '' : 's' }: ${normalizedDatasetNames.join(', ')}` // We only have one dataset, and it is unavailable due to permissions if (hasUnknownDatasetNames && normalizedDatasetNames.length === 1) { datasetNameList = 'Unavailable dataset' } return ( <Card> <Card padding={3} radius={2} tone="caution" marginBottom={4} flex="none"> <Flex> <Text aria-hidden="true" size={1}> <WarningOutlineIcon /> </Text> <Box flex={1} marginLeft={3}> <Text size={1}> {totalCount === 1 ? ( <>1 document refers to “{documentTitle}”</> ) : ( <> {totalCount.toLocaleString()} documents refer to “{documentTitle}” </> )} </Text> </Box> </Flex> </Card> <Box flex="none" marginBottom={4}> <Text> You may not be able to {action} “{documentTitle}” because the following documents refer to it: </Text> </Box> <Card radius={2} shadow={1} marginBottom={4} flex="auto"> <Flex direction="column"> {internalReferences.totalCount > 0 && ( <Stack as="ul" padding={2} space={3} data-testid="internal-references"> {internalReferences?.references.map((item) => ( <Box as="li" key={item._id}> {renderPreviewItem(item)} </Box> ))} {internalReferences.totalCount > internalReferences.references.length && ( <Box as="li" padding={3}> <OtherReferenceCount {...internalReferences} /> </Box> )} </Stack> )} {crossDatasetReferences.totalCount > 0 && ( <CrossDatasetReferencesDetails data-testid="cross-dataset-references" style={{ // only add the border if needed borderTop: internalReferences.totalCount > 0 ? '1px solid var(--card-shadow-outline-color)' : undefined, }} > <CrossDatasetReferencesSummary> <Card as="a" margin={2} radius={2} shadow={1} paddingY={1}> <Flex align="center" margin={2}> <Box marginLeft={3} marginRight={4}> <Text size={3}> <DocumentsIcon /> </Text> </Box> <Flex marginRight={4} direction="column"> <Box marginBottom={2}> <Text> {documentCount} in {datasetsCount} </Text> </Box> <Box> <Text title={datasetNameList} textOverflow="ellipsis" size={1} muted> {datasetNameList} </Text> </Box> </Flex> <ChevronWrapper> <Text muted> <ChevronDownIcon /> </Text> </ChevronWrapper> </Flex> </Card> </CrossDatasetReferencesSummary> <Box overflow="auto" paddingBottom={2} paddingX={2}> <Table> <thead> <tr> <th> <Label muted size={0} style={{minWidth: '5rem'}}> Project ID </Label> </th> <th> <Label muted size={0}> Dataset </Label> </th> <th> <Label muted size={0}> Document ID </Label> </th> </tr> </thead> <tbody> {crossDatasetReferences.references .filter((reference): reference is Required<typeof reference> => { return 'projectId' in reference }) .map(({projectId, datasetName, documentId}, index) => ( // eslint-disable-next-line react/no-array-index-key <tr key={`${documentId}-${index}`}> <td> <Text size={1}>{projectId}</Text> </td> <td> <Text size={1}>{datasetName || 'unavailable'}</Text> </td> <td> <DocumentIdFlex align="center" gap={2} justify="flex-end"> <Text textOverflow="ellipsis" size={1}> {documentId || 'unavailable'} </Text> {documentId && ( <CopyToClipboard text={documentId} // eslint-disable-next-line react/jsx-no-bind onCopy={() => { // TODO: this isn't visible with the dialog open toast.push({ title: 'Copied document ID to clipboard!', status: 'success', }) }} > <Button title="Copy ID to clipboard" mode="bleed" icon={ClipboardIcon} fontSize={0} /> </CopyToClipboard> )} </DocumentIdFlex> </td> </tr> ))} </tbody> </Table> <Box padding={2}> <OtherReferenceCount {...crossDatasetReferences} /> </Box> </Box> </CrossDatasetReferencesDetails> )} </Flex> </Card> <Box flex="none"> <Text> If you {action} this document, documents that refer to it will no longer be able to access it. </Text> </Box> </Card> ) }
31,703
https://github.com/sumtech/Checkbook/blob/master/Checkbook.Api/Models/Budget.cs
Github Open Source
Open Source
MIT
2,019
Checkbook
sumtech
C#
Code
226
435
// Copyright (c) Palouse Coding Conglomerate. All Rights Reserved. namespace Checkbook.Api.Models { using System.Collections.Generic; /// <summary> /// Represents a budget to which finances are being allocated for a future /// expense. /// </summary> public class Budget { /// <summary> /// Initializes a new instance of the <see cref="Budget"/> class. /// </summary> public Budget() { this.TransactionItems = new List<TransactionItem>(); } /// <summary> /// Gets or sets the unique identifier for this budget. /// </summary> public long Id { get; set; } /// <summary> /// Gets or sets the name of this budget. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the unique identifier for the category to which this /// budget is associated. /// </summary> public long CategoryId { get; set; } /// <summary> /// Gets or sets the category to which this budget is associated. /// </summary> public Category Category { get; set; } /// <summary> /// Gets or sets the unique identifier for the user to which this /// budget belongs. /// </summary> public long UserId { get; set; } /// <summary> /// Gets or sets the user to which this budgetbelongs. /// </summary> public User User { get; set; } /// <summary> /// Gets or sets the transaction items that are associated with this /// budget. /// </summary> public List<TransactionItem> TransactionItems { get; set; } } }
45,813
https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/eventgrid/Azure.ResourceManager.EventGrid/src/Generated/PartnerDestinationData.cs
Github Open Source
Open Source
LGPL-2.1-or-later, Apache-2.0, MIT, LicenseRef-scancode-generic-cla
2,023
azure-sdk-for-net
Azure
C#
Code
427
998
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using Azure.Core; using Azure.ResourceManager.EventGrid.Models; using Azure.ResourceManager.Models; namespace Azure.ResourceManager.EventGrid { /// <summary> /// A class representing the PartnerDestination data model. /// Event Grid Partner Destination. /// </summary> public partial class PartnerDestinationData : TrackedResourceData { /// <summary> Initializes a new instance of PartnerDestinationData. </summary> /// <param name="location"> The location. </param> public PartnerDestinationData(AzureLocation location) : base(location) { } /// <summary> Initializes a new instance of PartnerDestinationData. </summary> /// <param name="id"> The id. </param> /// <param name="name"> The name. </param> /// <param name="resourceType"> The resourceType. </param> /// <param name="systemData"> The systemData. </param> /// <param name="tags"> The tags. </param> /// <param name="location"> The location. </param> /// <param name="partnerRegistrationImmutableId"> The immutable Id of the corresponding partner registration. </param> /// <param name="endpointServiceContext"> Endpoint context associated with this partner destination. </param> /// <param name="expirationTimeIfNotActivatedUtc"> /// Expiration time of the partner destination. If this timer expires and the partner destination was never activated, /// the partner destination and corresponding channel are deleted. /// </param> /// <param name="provisioningState"> Provisioning state of the partner destination. </param> /// <param name="activationState"> Activation state of the partner destination. </param> /// <param name="endpointBaseUri"> Endpoint Base URL of the partner destination. </param> /// <param name="messageForActivation"> Context or helpful message that can be used during the approval process. </param> internal PartnerDestinationData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary<string, string> tags, AzureLocation location, Guid? partnerRegistrationImmutableId, string endpointServiceContext, DateTimeOffset? expirationTimeIfNotActivatedUtc, PartnerDestinationProvisioningState? provisioningState, PartnerDestinationActivationState? activationState, Uri endpointBaseUri, string messageForActivation) : base(id, name, resourceType, systemData, tags, location) { PartnerRegistrationImmutableId = partnerRegistrationImmutableId; EndpointServiceContext = endpointServiceContext; ExpirationTimeIfNotActivatedUtc = expirationTimeIfNotActivatedUtc; ProvisioningState = provisioningState; ActivationState = activationState; EndpointBaseUri = endpointBaseUri; MessageForActivation = messageForActivation; } /// <summary> The immutable Id of the corresponding partner registration. </summary> public Guid? PartnerRegistrationImmutableId { get; set; } /// <summary> Endpoint context associated with this partner destination. </summary> public string EndpointServiceContext { get; set; } /// <summary> /// Expiration time of the partner destination. If this timer expires and the partner destination was never activated, /// the partner destination and corresponding channel are deleted. /// </summary> public DateTimeOffset? ExpirationTimeIfNotActivatedUtc { get; set; } /// <summary> Provisioning state of the partner destination. </summary> public PartnerDestinationProvisioningState? ProvisioningState { get; } /// <summary> Activation state of the partner destination. </summary> public PartnerDestinationActivationState? ActivationState { get; set; } /// <summary> Endpoint Base URL of the partner destination. </summary> public Uri EndpointBaseUri { get; set; } /// <summary> Context or helpful message that can be used during the approval process. </summary> public string MessageForActivation { get; set; } } }
43,912
https://github.com/eltonchan/NetEase_Music_Flutter/blob/master/lib/routes.dart
Github Open Source
Open Source
MIT
2,022
NetEase_Music_Flutter
eltonchan
Dart
Code
39
117
import 'package:flutter/material.dart'; import './video/index.dart'; import './me/index.dart'; import './friend/index.dart'; import './account/index.dart'; final routes = { '/video': (BuildContext context) => new VideoView(), '/me': (BuildContext context) => new MeView(), '/friend': (BuildContext context) => new FriendView(), '/account': (BuildContext context) => new AccountView(), };
21,759
https://github.com/jehovahsays/MMOSOCKETHTML5JSCHAT/blob/master/examples/chat/node_modules/limitation/index.js
Github Open Source
Open Source
MIT
2,019
MMOSOCKETHTML5JSCHAT
jehovahsays
JavaScript
Code
896
2,187
/** * Kademlia DHT based rate limiter. * * Features: * - Checks are cheap in-memory operations. * - Distributes counters across many nodes, using the Kademlia DHT. * - Supports multiple limits per key. * - Configurable bursting and update scaling via `interval` option. */ 'use strict'; var events = require('events'); var util = require('util'); var P = require('bluebird'); var MemoryBackend = require('./lib/memory_backend'); var KadBackend = require('./lib/kad_backend'); /** * Limitation constructor * * @param {object} options: * - `listen`: {object} describing the local interface to listen on. Default: * `{ address: 'localhost', port: 3050 }`. If this port is used, a random * port is used instead. * - `seeds`: {[object]} describing seeds nodes, containing `port` and * `address` string properties * - `interval`: Update interval in ms. Default: 10000ms. Longer intervals * reduce load, but also increase detection latency. * - `minValue`: Drop global counters below this value. Default: 0.1. */ function Limitation(options) { events.EventEmitter(this); this._options = options = options || {}; if (options.interval === undefined) { options.interval = 10000; } // Local counters. Contain objects with `value` and `limits` properties. this._counters = {}; this._blocks = {}; this._end = false; this._globalUpdatesTimeout = null; if (!options.seeds || !options.seeds.length) { // Single-node operation this._store = new MemoryBackend(options); } else if (options.seeds && options.seeds.length) { this._store = new KadBackend(options); } } util.inherits(Limitation, events.EventEmitter); /** * Synchronous limit check * * @param {string} key * @param {number} limit * @param {number} increment, default 1 * @return {boolean}: `true` if the request rate is below the limit, `false` * if the limit is exceeded. */ Limitation.prototype.isAboveLimit = function(key, limit, increment) { var counter = this._counters[key]; if (!counter) { counter = this._counters[key] = { value: 0, limits: {}, }; } counter.value += increment || 1; counter.limits[limit] = counter.limits[limit] || Date.now(); if (this._blocks[key]) { return this._blocks[key].value > limit; } else { return false; } }; /** * Set up / connect the limiter. * @returns {P<Limitation> */ Limitation.prototype.setup = function() { var self = this; return self._store.setup() .then(function(store) { self._store = store; // Start periodic global updates self._globalUpdatesTimeout = setTimeout(function() { return self._globalUpdates(); }, self._getRandomizedInterval(0.5)); return self; }); }; Limitation.prototype.stop = function() { this._end = true; this._store.stop(); clearTimeout(this._globalUpdatesTimeout); }; /** * Randomize the configured interval slightly */ Limitation.prototype._getRandomizedInterval = function(multiplier) { var interval = this._options.interval * (multiplier || 1); return interval + (Math.random() - 0.5) * interval * 0.1; }; /** * Report local counts to the global DHT, and update local blocks. */ Limitation.prototype._globalUpdates = function() { var self = this; // Set up an empty local counter object for the next interval var lastCounters = self._counters; self._counters = {}; // New blocks. Only update these after the full iteration. var newBlocks = {}; // For each local counter, update the DHT & check for limits var errCount = 0; return P.map(Object.keys(lastCounters), function(key) { var counter = lastCounters[key]; return self._store.put(key, counter.value) .then(function(counterVal) { counterVal = self._normalizeCounter(counterVal); var minLimit = Math.min.apply(null, Object.keys(counter.limits)); // console.log('put val', counterVal, minLimit, counter.value); if (counterVal > minLimit) { newBlocks[key] = { value: counterVal, limits: counter.limits }; } }) // Ignore update errors. .catch(function() { errCount++; }); }, { concurrency: 50 }) .then(function() { return self._updateBlocks(newBlocks); }) .catch(function(err) { console.log(err.stack); }) .finally(function(err) { self.emit('blocks', self._blocks); // Schedule the next iteration if (self._end) { return; } self._globalUpdatesTimeout = setTimeout(function() { self._globalUpdates(); }, self._getRandomizedInterval()); }); }; Limitation.prototype._normalizeCounter = function(val) { val = val || 0; // Compensate for exponential decay with factor 2, and scale to 1/s rates. // Bias against false negatives by diving by 2.2 instead of 2.0. return val / 2.2 / this._options.interval * 1000; }; /** * Re-check old blocks against newBlocks and the DHT state. * * This method ensures that we keep blocking requests when the global request * rate is a bit above the limit, even if the local request rates occasionally * drops below the limit. * * @param {object} newBlocks, new blocks based on the put response from local counters. */ Limitation.prototype._updateBlocks = function(newBlocks) { var self = this; // Stop checking for old limits if they haven't been reached in the last // 600 seconds. var maxAge = Date.now() - (600 * 1000); var asyncChecks = []; var oldBlocks = this._blocks; var oldBlockKeys = Object.keys(self._blocks); // Fast handling for blocks that remain for (var i = 0; i < oldBlockKeys.length; i++) { var key = oldBlockKeys[i]; if (newBlocks[key]) { var newBlockLimits = newBlocks[key].limits; // Still blocked. See if other limits need to be added. var oldLimits = self._blocks[key].limits; var oldLimitKeys = Object.keys(oldLimits); for (var j = 0; j < oldLimitKeys.length; j++) { var limit = oldLimitKeys[j]; if (oldLimits[limit] > maxAge && !newBlockLimits[limit]) { newBlockLimits[limit] = oldLimits[limit]; } } } else { asyncChecks.push(key); } } self._blocks = newBlocks; // Async re-checks for previous blocks that didn't see any requests in the // last interval. return P.map(asyncChecks, function(key) { var block = oldBlocks[key]; // Only consider var currentLimits = Object.keys(block.limits) .filter(function(limit) { return block.limits[limit] > maxAge; }); if (!currentLimits.length) { // Nothing to do. return; } // Need to get the current value return self._store.get(key) .then(function(counterVal) { counterVal = self._normalizeCounter(counterVal); var limitObj = {}; var curTime = Date.now(); currentLimits.forEach(function(limit) { if (Number(limit) > counterVal) { limitObj[limit] = curTime; } else { limitObj[limit] = block.limits[limit]; } }); newBlocks[key] = { value: counterVal, limits: limitObj, }; }) // Ignore individual update errors. .catch(function() {}); }, { concurrency: 50 }); }; module.exports = Limitation;
15,365
https://github.com/nasedkinpv/nuxt-use-motion/blob/master/example/app/motion.config.js
Github Open Source
Open Source
MIT
2,022
nuxt-use-motion
nasedkinpv
JavaScript
Code
28
80
export default { directives: { 'slide-rotate-bottom': { initial: { y: 400, opacity: 0, rotate: 90 }, enter: { y: 0, opacity: 1, rotate: 0 } } } }
2,847
https://github.com/asac-geeks/childbook/blob/master/finalProject/src/main/java/com/example/finalProject/controller/LikesController.java
Github Open Source
Open Source
MIT
null
childbook
asac-geeks
Java
Code
116
588
package com.example.finalProject.controller; import com.example.finalProject.entity.AppUser; import com.example.finalProject.entity.Likes; import com.example.finalProject.entity.Post; import com.example.finalProject.repository.LikesRepositoy; import com.example.finalProject.repository.PostRepository; import com.example.finalProject.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.view.RedirectView; @RestController @CrossOrigin(origins= "*") public class LikesController { @Autowired LikesRepositoy likesRepositoy; @Autowired UserRepository userRepository; @Autowired PostRepository postRepository; @PostMapping("/likepost/{id}") public RedirectView addLike(@PathVariable Integer id){ try{ if((SecurityContextHolder.getContext().getAuthentication()) != null){ AppUser userDetails = userRepository.findByUserName(SecurityContextHolder.getContext().getAuthentication().getName()); Likes like = likesRepositoy.save(new Likes(userDetails,postRepository.findById(id).get())); } }catch (Exception ex){ return new RedirectView("/error?message=Used%username"); } return new RedirectView("/"); } @DeleteMapping("/deletelike/{id}") public ResponseEntity handleDeleteLike(@PathVariable Integer id) { System.out.println(id); try{ if((SecurityContextHolder.getContext().getAuthentication()) != null){ Likes likes = likesRepositoy.findById(id).get(); AppUser userDetails = userRepository.findByUserName(SecurityContextHolder.getContext().getAuthentication().getName()); if (likes != null && userDetails.getId() == likes.getAppUser().getId()){ likesRepositoy.deleteById(id); } } return new ResponseEntity("Delete",HttpStatus.OK); }catch (Exception ex){ return new ResponseEntity(HttpStatus.BAD_REQUEST); } } }
27,596
https://github.com/YutoMizutani/gohome/blob/master/app/presenter/usecase/animal_usecase.go
Github Open Source
Open Source
MIT
null
gohome
YutoMizutani
Go
Code
12
54
package usecase import "github.com/YutoMizutani/gohome/app/domain/entity" type AnimalUseCase interface { Fetch() (*entity.Animal, error) }
21,272
https://github.com/ahmeshaf/ctakes/blob/master/ctakes-gui/src/main/java/org/apache/ctakes/gui/pipeline/bit/parameter/ParameterMapper.java
Github Open Source
Open Source
Apache-2.0
2,022
ctakes
ahmeshaf
Java
Code
271
726
package org.apache.ctakes.gui.pipeline.bit.parameter; import org.apache.log4j.Logger; import org.apache.uima.fit.descriptor.ConfigurationParameter; import java.lang.reflect.Field; import java.util.*; /** * @author SPF , chip-nlp * @version %I% * @since 3/19/2017 */ final public class ParameterMapper { static private final Logger LOGGER = Logger.getLogger( "ParameterMapper" ); private ParameterMapper() { } /** * @param pipeBitClass - * @return Configuration Parameters and Field class types for the Pipe Bit and all of its parent classes */ static public Map<ConfigurationParameter, String> createParameterTypeMap( final Class<?> pipeBitClass ) { final Map<ConfigurationParameter, String> parameterMap = new HashMap<>(); final Collection<Class<?>> inheritables = new ArrayList<>(); final Class<?>[] interfaces = pipeBitClass.getInterfaces(); if ( interfaces != null && interfaces.length > 0 ) { inheritables.addAll( Arrays.asList( interfaces ) ); } if ( pipeBitClass.getSuperclass() != null ) { inheritables.add( pipeBitClass.getSuperclass() ); } inheritables.stream().map( ParameterMapper::createParameterTypeMap ).forEach( parameterMap::putAll ); final Field[] fields = pipeBitClass.getDeclaredFields(); Arrays.stream( fields ) .filter( f -> f.getAnnotation( ConfigurationParameter.class ) != null ) .forEach( f -> parameterMap .put( f.getAnnotation( ConfigurationParameter.class ), f.getType().getSimpleName() ) ); return parameterMap; } /** * @param pipeBitClass - * @return Configuration Parameters and default values for the Pipe Bit and all of its parent classes */ static public Map<ConfigurationParameter, String[]> createParameterDefaultsMap( final Class<?> pipeBitClass ) { final Map<ConfigurationParameter, String[]> parameterMap = new HashMap<>(); final Collection<Class<?>> inheritables = new ArrayList<>(); final Class<?>[] interfaces = pipeBitClass.getInterfaces(); if ( interfaces != null && interfaces.length > 0 ) { inheritables.addAll( Arrays.asList( interfaces ) ); } if ( pipeBitClass.getSuperclass() != null ) { inheritables.add( pipeBitClass.getSuperclass() ); } inheritables.stream().map( ParameterMapper::createParameterDefaultsMap ).forEach( parameterMap::putAll ); final Field[] fields = pipeBitClass.getDeclaredFields(); Arrays.stream( fields ) .map( f -> f.getAnnotation( ConfigurationParameter.class ) ) .filter( Objects::nonNull ) .forEach( cp -> parameterMap.put( cp, cp.defaultValue() ) ); return parameterMap; } }
23,758
https://github.com/chmac/deffy-deno/blob/master/lib/deffy.ts
Github Open Source
Open Source
MIT
null
deffy-deno
chmac
TypeScript
Code
98
243
// Dependencies import {Typpy} from "https://deno.land/x/typpy/lib/typpy.ts" function Deffy(input: any, def: Function | any, options?: boolean | {empty: boolean}): any { // Default is a function if (typeof def === "function") { return def(input); } //@ts-ignore Will never be {empry: {empty: boolean}} (as TS things could occur) due to Ternary let parsedOptions: {empty: boolean} = Typpy(options) === "boolean" ? { empty: options } : { empty: false }; // Handle empty if (parsedOptions.empty) { return input || def; } // Return input if (Typpy(input) === Typpy(def)) { return input; } // Return the default return def; } export {Deffy}
13,425
https://github.com/GDconcentration/GDConcMeasure/blob/master/Setup.sh
Github Open Source
Open Source
LicenseRef-scancode-warranty-disclaimer, MIT
2,019
GDConcMeasure
GDconcentration
Shell
Code
11
151
#!/bin/bash #Application path location of applicaiton ToolDAQapp=`pwd` source ${ToolDAQapp}/ToolDAQ/root-6.14.06/install/bin/thisroot.sh export LD_LIBRARY_PATH=${ToolDAQapp}/lib:${ToolDAQapp}/ToolDAQ/zeromq-4.0.7/lib:${ToolDAQapp}/ToolDAQ/boost_1_66_0/install/lib:/home/pi/seabreeze-3.0.11/SeaBreeze/lib:$LD_LIBRARY_PATH
19,537
https://github.com/biehlermi/ScottPlot/blob/master/src/ScottPlot/plottables/PlottableErrorBars.cs
Github Open Source
Open Source
MIT
2,020
ScottPlot
biehlermi
C#
Code
528
1,650
using ScottPlot.Config; using ScottPlot.Diagnostic.Attributes; using ScottPlot.Drawing; using System; using System.Drawing; using System.Linq; namespace ScottPlot { public class PlottableErrorBars : Plottable { [FiniteNumbers, EqualLength] private readonly double[] xs; [FiniteNumbers, EqualLength] private readonly double[] ys; [FiniteNumbers, EqualLength] private readonly double[] xPositiveError; [FiniteNumbers, EqualLength] private readonly double[] xNegativeError; [FiniteNumbers, EqualLength] private readonly double[] yPositiveError; [FiniteNumbers, EqualLength] private readonly double[] yNegativeError; private readonly float capSize; private readonly Pen penLine; public string label; public Color color; public LineStyle lineStyle = LineStyle.Solid; public PlottableErrorBars(double[] xs, double[] ys, double[] xPositiveError, double[] xNegativeError, double[] yPositiveError, double[] yNegativeError, Color color, double lineWidth, double capSize, string label) { //check input if (xs.Length != ys.Length) throw new ArgumentException("X and Y arrays must have the same length"); //save properties this.xs = xs; this.ys = ys; this.xPositiveError = SanitizeErrors(xPositiveError, xs.Length); this.xNegativeError = SanitizeErrors(xNegativeError, xs.Length); this.yPositiveError = SanitizeErrors(yPositiveError, xs.Length); this.yNegativeError = SanitizeErrors(yNegativeError, xs.Length); this.capSize = (float)capSize; this.color = color; this.label = label; penLine = GDI.Pen(this.color, (float)lineWidth, lineStyle, true); } private double[] SanitizeErrors(double[] errorArray, int expectedLength) { if (errorArray is null) return null; if (errorArray.Length != expectedLength) throw new ArgumentException("Point arrays and error arrays must have the same length"); for (int i = 0; i < errorArray.Length; i++) if (errorArray[i] < 0) errorArray[i] = -errorArray[i]; return errorArray; } public override string ToString() { string label = string.IsNullOrWhiteSpace(this.label) ? "" : $" ({this.label})"; return $"PlottableErrorBars{label} with {GetPointCount()} points"; } public override Config.AxisLimits2D GetLimits() { double xMin = double.PositiveInfinity; double yMin = double.PositiveInfinity; double xMax = double.NegativeInfinity; double yMax = double.NegativeInfinity; if (xNegativeError is null) { xMin = xs.Min(); } else { for (int i = 0; i < xs.Length; i++) xMin = Math.Min(xMin, xs[i] - xNegativeError[i]); } if (xPositiveError is null) { xMax = xs.Max(); } else { for (int i = 0; i < xs.Length; i++) xMax = Math.Max(xMax, xs[i] + xPositiveError[i]); } if (yNegativeError is null) { yMin = ys.Min(); } else { for (int i = 0; i < xs.Length; i++) yMin = Math.Min(yMin, ys[i] - yNegativeError[i]); } if (yPositiveError is null) { yMax = ys.Max(); } else { for (int i = 0; i < xs.Length; i++) yMax = Math.Max(yMax, ys[i] + yPositiveError[i]); } return new Config.AxisLimits2D(new double[] { xMin, xMax, yMin, yMax }); } public override void Render(Settings settings) { DrawErrorBar(settings, xPositiveError, true, true); DrawErrorBar(settings, xNegativeError, true, false); DrawErrorBar(settings, yPositiveError, false, true); DrawErrorBar(settings, yNegativeError, false, false); } public void DrawErrorBar(Settings settings, double[] errorArray, bool xError, bool positiveError) { if (errorArray is null) return; float slightPixelOffset = 0.01f; // to fix GDI bug that happens when small straight lines are drawn with anti-aliasing on for (int i = 0; i < xs.Length; i++) { PointF centerPixel = settings.GetPixel(xs[i], ys[i]); float errorSize = positiveError ? (float)errorArray[i] : -(float)errorArray[i]; if (xError) { float xWithError = (float)settings.GetPixelX(xs[i] + errorSize); settings.gfxData.DrawLine(penLine, centerPixel.X, centerPixel.Y, xWithError, centerPixel.Y); settings.gfxData.DrawLine(penLine, xWithError, centerPixel.Y - capSize, xWithError + slightPixelOffset, centerPixel.Y + capSize); } else { float yWithError = (float)settings.GetPixelY(ys[i] + errorSize); settings.gfxData.DrawLine(penLine, centerPixel.X, centerPixel.Y, centerPixel.X, yWithError); settings.gfxData.DrawLine(penLine, centerPixel.X - capSize, yWithError, centerPixel.X + capSize, yWithError + slightPixelOffset); } } } public override int GetPointCount() { return ys.Length; } public override LegendItem[] GetLegendItems() { var singleLegendItem = new Config.LegendItem(label, color, markerShape: MarkerShape.none); return new LegendItem[] { singleLegendItem }; } } }
4,831
https://github.com/jHards/square-php-sdk/blob/master/src/Models/CatalogCustomAttributeDefinitionStringConfig.php
Github Open Source
Open Source
Apache-2.0
2,020
square-php-sdk
jHards
PHP
Code
212
455
<?php declare(strict_types=1); namespace Square\Models; /** * Configuration associated with Custom Attribute Definitions of type `STRING`. */ class CatalogCustomAttributeDefinitionStringConfig implements \JsonSerializable { /** * @var bool|null */ private $enforceUniqueness; /** * Returns Enforce Uniqueness. * * If true, each Custom Attribute instance associated with this Custom Attribute * Definition must have a unique value within the seller's catalog. For * example, this may be used for a value like a SKU that should not be * duplicated within a seller's catalog. May not be modified after the * definition has been created. */ public function getEnforceUniqueness(): ?bool { return $this->enforceUniqueness; } /** * Sets Enforce Uniqueness. * * If true, each Custom Attribute instance associated with this Custom Attribute * Definition must have a unique value within the seller's catalog. For * example, this may be used for a value like a SKU that should not be * duplicated within a seller's catalog. May not be modified after the * definition has been created. * * @maps enforce_uniqueness */ public function setEnforceUniqueness(?bool $enforceUniqueness): void { $this->enforceUniqueness = $enforceUniqueness; } /** * Encode this object to JSON * * @return mixed */ public function jsonSerialize() { $json = []; $json['enforce_uniqueness'] = $this->enforceUniqueness; return array_filter($json, function ($val) { return $val !== null; }); } }
4,727
https://github.com/AAI-USZ/FixJS/blob/master/input/100+/after/f472619e06612895dbcc9a8fa3e72952e9a4e3d8_0_3.js
Github Open Source
Open Source
MIT
2,022
FixJS
AAI-USZ
JavaScript
Code
56
191
function($root) { var rootedQuery = function(selector, context, rootQuery) { $root = $root || (Mobify.conf.data && Mobify.conf.data.$html); return ($.fn.init || $.zepto.init).call(this, selector, context || anchored.context(), rootQuery); } , anchored = $.sub(rootedQuery); anchored.context = function() { return $root || (Mobify.conf.data ? Mobify.conf.data.$html : '<div>'); } if (!anchored.zepto) { anchored.fn.init = rootedQuery; anchored.fn.init.prototype = $.fn; } return anchored; }
22,531
https://github.com/ExchangeUnion/indra/blob/master/modules/cf-core/src/testing/scenarios/uninstall-concurrent.spec.ts
Github Open Source
Open Source
MIT
null
indra
ExchangeUnion
TypeScript
Code
242
846
import { CONVENTION_FOR_ETH_ASSET_ID, InstallMessage, ProposeMessage, UninstallMessage, } from "@connext/types"; import { constants, utils } from "ethers"; import { CFCore } from "../../cfCore"; import { TestContractAddresses } from "../contracts"; import { toBeLt } from "../bignumber-jest-matcher"; import { setup, SetupContext } from "../setup"; import { collateralizeChannel, constructUninstallRpc, createChannel, makeInstallCall, makeProposeCall, } from "../utils"; const { One } = constants; const { parseEther } = utils; expect.extend({ toBeLt }); jest.setTimeout(7500); const { TicTacToeApp } = global["contracts"] as TestContractAddresses; describe("Node method follows spec - uninstall", () => { let multisigAddress: string; let nodeA: CFCore; let nodeB: CFCore; describe("Should be able to successfully uninstall apps concurrently", () => { beforeEach(async () => { const context: SetupContext = await setup(global); nodeA = context["A"].node; nodeB = context["B"].node; multisigAddress = await createChannel(nodeA, nodeB); }); it("uninstall apps with ETH concurrently", async (done) => { const appIdentityHashes: string[] = []; let uninstalledApps = 0; await collateralizeChannel( multisigAddress, nodeA, nodeB, parseEther("2"), // We are depositing in 2 and use 1 for each concurrent app ); nodeB.on("PROPOSE_INSTALL_EVENT", (msg: ProposeMessage) => { makeInstallCall(nodeB, msg.data.appInstanceId, multisigAddress); }); nodeA.on("INSTALL_EVENT", (msg: InstallMessage) => { appIdentityHashes.push(msg.data.appIdentityHash); }); const proposeRpc = makeProposeCall( nodeB, TicTacToeApp, multisigAddress, /* initialState */ undefined, One, CONVENTION_FOR_ETH_ASSET_ID, One, CONVENTION_FOR_ETH_ASSET_ID, ); nodeA.rpcRouter.dispatch(proposeRpc); nodeA.rpcRouter.dispatch(proposeRpc); while (appIdentityHashes.length !== 2) { await new Promise((resolve) => setTimeout(resolve, 100)); } nodeA.rpcRouter.dispatch(constructUninstallRpc(appIdentityHashes[0], multisigAddress)); nodeA.rpcRouter.dispatch(constructUninstallRpc(appIdentityHashes[1], multisigAddress)); // NOTE: nodeA does not ever emit this event nodeB.on("UNINSTALL_EVENT", (msg: UninstallMessage) => { expect(appIdentityHashes.includes(msg.data.appIdentityHash)).toBe(true); expect(msg.data.multisigAddress).toBe(multisigAddress); uninstalledApps += 1; if (uninstalledApps === 2) done(); }); }); }); });
3,893
https://github.com/AjaySinghPathania/gdcdictionary/blob/master/Jenkinsfile
Github Open Source
Open Source
Apache-2.0
2,021
gdcdictionary
AjaySinghPathania
Groovy
Code
9
39
#!groovy library identifier: "jenkins-lib@master" scriptedLibPipeline{ testRunner = "docker-compose" }
8,842
https://github.com/Jukoleda/labv_banco/blob/master/banco_lab_v/src/com/bank/handler/AccountHandler.java
Github Open Source
Open Source
MIT
null
labv_banco
Jukoleda
Java
Code
64
267
package com.bank.handler; import java.sql.SQLException; import java.util.ArrayList; import com.bank.model.AccountModel; import com.bank.model.TypeAccountModel; import com.bank.service.AccountsService; import com.bank.service.TypesAccountsService; public class AccountHandler { public static ArrayList<AccountModel> findAll() throws ClassNotFoundException, SQLException{ ArrayList<AccountModel> accounts = new ArrayList<AccountModel>(); accounts = AccountsService.getAll(); ArrayList<TypeAccountModel> typeAccounts = new ArrayList<TypeAccountModel>(); typeAccounts = TypesAccountsService.getAll(); for(AccountModel account : accounts) { for(TypeAccountModel typeAccount : typeAccounts) { if(typeAccount.getIdTypeAccount() == account.getTypeAccount().getIdTypeAccount()) { account.setTypeAccount(typeAccount); break; } } } return accounts; } }
18,626
https://github.com/kalismeras61/flutter_dynamic_forms/blob/master/packages/expression_language/test/supporting_files/steps/when_then_expression_num.dart
Github Open Source
Open Source
MIT
2,019
flutter_dynamic_forms
kalismeras61
Dart
Code
341
1,169
import 'package:expression_language/src/expressions/expression_provider.dart'; import 'package:expression_language/src/expressions/expressions.dart'; import 'package:expression_language/src/number_type/decimal.dart'; import 'package:expression_language/src/number_type/integer.dart'; import 'package:expression_language/src/parser/expression_grammar_parser.dart'; import 'package:gherkin/gherkin.dart'; import 'package:petitparser/petitparser.dart'; class GivenFormElementIsProvided extends GivenWithWorld<ExpressionWorld> { @override Future<void> executeStep() async { world.buildGrammarParser({"testElement": TestElement()}); } @override RegExp get pattern => RegExp(r"form element is provided"); } class WhenExpressionIsEvaluated extends When1WithWorld<String, ExpressionWorld> { @override Future<void> executeStep(String expression) async { try { var result = world.parser.parse(expression); var expressionValue = result.value as Expression; var value = expressionValue.evaluate(); world.result = value; } catch (exception) { world.result = exception; } } RegExp get pattern => RegExp(r"expression {string} is evaluated"); } class ThenIntExpressionResult extends Then1WithWorld<String, ExpressionWorld> { @override Future<void> executeStep(String result) async { expectMatch(world.result, Integer.parse(result)); } RegExp get pattern => RegExp(r"int expression result is {string}"); } class ThenStringExpressionResult extends Then1WithWorld<String, ExpressionWorld> { @override Future<void> executeStep(String result) async { expectMatch(world.result, result); } RegExp get pattern => RegExp(r"string expression result is {string}"); } class ThenDecimalExpressionResult extends Then1WithWorld<String, ExpressionWorld> { @override Future<void> executeStep(String result) async { expectMatch(world.result, Decimal.parse(result)); } RegExp get pattern => RegExp(r"decimal expression result is {string}"); } class ThenDateTimeExpressionResult extends Then1WithWorld<String, ExpressionWorld> { @override Future<void> executeStep(String result) async { expectMatch(world.result, DateTime.parse(result)); } RegExp get pattern => RegExp(r"DateTime expression result is {string}"); } class ThenBoolExpressionResult extends Then1WithWorld<String, ExpressionWorld> { @override Future<void> executeStep(String result) async { expectMatch(world.result, result == "true"); } RegExp get pattern => RegExp(r"bool expression result is {string}"); } class ThenExceptionThrownResult extends Then1WithWorld<String, ExpressionWorld> { @override Future<void> executeStep(String result) async { expectMatch(world.result.runtimeType.toString(), result); } RegExp get pattern => RegExp(r"{string} exception is thrown"); } class ExpressionWorld extends World { ExpressionGrammarParser grammarParser; Object result; Parser parser; ExpressionWorld() { grammarParser = ExpressionGrammarParser({}); parser = grammarParser.build(); } void buildGrammarParser( Map<String, ExpressionProviderElement> expressionProviderElementMap) { grammarParser = ExpressionGrammarParser(expressionProviderElementMap); parser = grammarParser.build(); } } class TestElement extends ExpressionProviderElement { Map<String, ExpressionProvider> properties = { "value": ConstantExpressionProvider<Integer>(Integer(27)), "label": ConstantExpressionProvider<String>("LabelText"), "intValue": ConstantExpressionProvider<int>(14), "doubleValue": ConstantExpressionProvider<double>(6.5), }; @override ExpressionProvider getExpressionProvider([String propertyName]) { if (propertyName == null || propertyName == "") { propertyName = "value"; } return properties[propertyName]; } @override ExpressionProviderElement clone( ExpressionProvider<ExpressionProviderElement> parent) { //Nothing to do return null; } } class ConstantExpressionProvider<T> extends ExpressionProvider<T> { final T value; ConstantExpressionProvider(this.value); @override Expression<T> getExpression() { return ConstantExpression(value); } }
23,030
https://github.com/simplesoft-pt/Database/blob/master/src/Simplesoft.Database.Contracts/IHaveExternalId.cs
Github Open Source
Open Source
MIT
2,021
Database
simplesoft-pt
C#
Code
89
215
using System; namespace SimpleSoft.Database { /// <summary> /// Represents an entity with an unique identifier to be used /// across multiple systems /// </summary> /// <typeparam name="TId">The external id type</typeparam> public interface IHaveExternalId<TId> where TId : IEquatable<TId> { /// <summary> /// Unique identifier /// </summary> TId ExternalId { get; set; } } /// <summary> /// Represents an entity with an unique identifier to be used /// across multiple systems, with a <see cref="Guid"/> for the /// <see cref="IHaveExternalId{TId}.ExternalId"/> property. /// </summary> public interface IHaveExternalId : IHaveExternalId<Guid> { } }
46,601
https://github.com/katout/NoteEditor/blob/master/Assets/Scripts/Presenter/Settings/SettingMusicPathPresenter.cs
Github Open Source
Open Source
MIT
null
NoteEditor
katout
C#
Code
79
305
using NoteEditor.Model; using System.IO; using UniRx; using UnityEngine; using UnityEngine.UI; namespace NoteEditor.Presenter { public class SettingMusicPathPresenter : MonoBehaviour { [SerializeField] InputField musicPathInputField = default; [SerializeField] Text musicPathInputFieldText = default; [SerializeField] Color defaultTextColor = default; [SerializeField] Color invalidStateTextColor = default; void Awake() { musicPathInputField.OnValueChangedAsObservable() .Select(path => Directory.Exists(Path.Combine(Settings.WorkSpacePath.Value ?? "", path))) .Subscribe(exists => musicPathInputFieldText.color = exists ? defaultTextColor : invalidStateTextColor); musicPathInputField.OnValueChangedAsObservable() .Where(path => Directory.Exists(Path.Combine(Settings.WorkSpacePath.Value ?? "", path))) .Subscribe(path => Settings.MusicPath.Value = path); Settings.MusicPath.DistinctUntilChanged() .Subscribe(path => musicPathInputField.text = path); } } }
45,644
https://github.com/CreepPork/Rezent/blob/master/app/Driver.php
Github Open Source
Open Source
MIT
null
Rezent
CreepPork
PHP
Code
276
959
<?php namespace App; use Illuminate\Http\Request; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\ValidationException; abstract class Driver { use Notifiable { notify as protected traitNotify; } protected const VALIDATION_RULES = self::VALIDATION_RULES; protected const STATUSES_CANCELED = self::STATUSES_CANCELED; protected const STATUSES_FAILED = self::STATUSES_FAILED; protected const STATUSES_PASSED = self::STATUSES_PASSED; protected const STATUSES_PENDING = self::STATUSES_PENDING; public $embed = []; public $commitHash = ''; public $branch = ''; public function wasSuccessful(): bool { return $this->embed['color'] == Colors::PASSED(); } public static function validate(Request $request) { $validator = Validator::make($request->all(), static::VALIDATION_RULES); if ($validator->fails()) { throw new ValidationException($validator); } return $validator->validated(); } public function wasAlreadySent(): bool { $builds = Build::where('commit_hash', $this->commitHash)->get(); // If we already have a commit with that hash, then don't post it again. if (count($builds) != 0) { return true; } /** * @var null|\App\Build $build */ $build = Build::where('branch', $this->branch)->latest()->first(); // If the last build was successful and the new build was sucessful too, then ignore. if ($build && $build->successful && $this->wasSuccessful()) { return true; } return false; } public function notify($notification) { $this->traitNotify($notification); Build::create([ 'commit_hash' => $this->commitHash, 'branch' => $this->branch, 'successful' => $this->wasSuccessful(), ]); } public function routeNotificationForSlack($notification) { return config('services.slack.hook', ''); } public function getBuildDescription($sha, $commitUrl, $commitName): string { $gitHash = substr($sha, 0, 7); return "[{$gitHash}]({$commitUrl}) {$commitName}"; } public function getBuildTitle($orgAndRepo, $branch, $number, $conclusion): string { $repoInfo = "[{$orgAndRepo}]:{$branch}"; $status = ucfirst($conclusion); return "{$repoInfo} Build #{$number} {$status}"; } public function getBuildColor(string $status): Colors { $canceled = explode('|', $this::STATUSES_CANCELED); $failed = explode('|', $this::STATUSES_FAILED); $passed = explode('|', $this::STATUSES_PASSED); $pending = explode('|', $this::STATUSES_PENDING); if (in_array($status, $canceled)) { return Colors::CANCELED(); } if (in_array($status, $failed)) { return Colors::FAILED(); } if (in_array($status, $passed)) { return Colors::PASSED(); } if (in_array($status, $pending)) { return Colors::PENDING(); } return Colors::CANCELED(); } }
35,683
https://github.com/Nyovelt/vscode-rainbow-fart/blob/master/src/page/src/components/player/index.vue
Github Open Source
Open Source
MIT
2,022
vscode-rainbow-fart
Nyovelt
Vue
Code
210
847
<template> <div> <audio ref="audio"></audio> <q-panel class="permission" secondary v-if="!authorized" @click="doAuthorize"> <q-icon class="icon" name="warning-circle"></q-icon> <q-text mode="normal" v-html="$t('permission-required')"></q-text> </q-panel> <q-panel class="permission" style="pointer-events: none;" secondary v-else> <q-icon class="icon" name="smile"></q-icon> <q-text mode="normal">{{ $t("authorized") }}</q-text> <q-footnote mode="normal">{{ $t("authorized-tip") }}</q-footnote> </q-panel> <q-popover class="tip" :text="$t('permission-explain')" width="240px" position="bottom-left"> <q-icon name="question-circle"></q-icon> <q-footnote>{{ $t("permission-why") }}</q-footnote> </q-popover> </div> </template> <style lang="less" scoped> @import "~@qiqi1996/qi-design-vue/standard.less"; .permission { border-radius: 10px; cursor: pointer; overflow: hidden; text-align: left; padding: 3*@grid; .transition(); .icon { float: left; margin-right: 2 * @grid; font-size: 48px; } } .permission:hover { transform: scale(1.05); } .tip { margin-top: @grid; * { display: inline-block; vertical-align: middle; } } </style> <script> import axios from "axios"; import piano from "/assets/piano.mp3"; import messages from "./player.i18n.json"; export default { i18n: { messages }, data(){ return { authorized: false, failedTimes: 0 } }, mounted(){ this.requestPlaySound(); }, methods: { doAuthorize() { let audio = this.$refs["audio"]; audio.src = piano; audio.currentTime = 0; audio.play(); this.authorized = true; }, play(name) { console.log("play - " + name); let audio = this.$refs["audio"]; audio.src = "/voices/" + name; audio.currentTime = 0; audio.play(); }, async requestPlaySound() { var response; try { response = await axios.get("/playsound"); }catch(e){ if(this.failedTimes > 5){ setTimeout(this.requestPlaySound, 1000); }else{ this.failedTimes++; this.requestPlaySound(); } return; } this.failedTime = 0; let voice = response.data; if(voice.lastIndexOf(".") < voice.length - 5){ return; } this.play(voice); this.requestPlaySound(); } } } </script>
10,425
https://github.com/FreckleIOT/django-advanced-filters/blob/master/advanced_filters/views.py
Github Open Source
Open Source
MIT
null
django-advanced-filters
FreckleIOT
Python
Code
550
1,744
from operator import itemgetter import logging from django.apps import apps from django.conf import settings from django.contrib.admin.utils import get_fields_from_path from django.db import models from django.db.models.fields import FieldDoesNotExist from django.utils.encoding import force_text from django.views.generic import View from braces.views import (CsrfExemptMixin, StaffuserRequiredMixin, JSONResponseMixin) from advanced_filters.forms import AdvancedFilterQueryForm from django.core.paginator import Paginator, EmptyPage logger = logging.getLogger('advanced_filters.views') class GetFieldChoices(CsrfExemptMixin, StaffuserRequiredMixin, JSONResponseMixin, View): """ A JSONResponse view that accepts a model and a field (path to field), resolves and returns the valid choices for that field. Model must use the "app.Model" notation. If this field is not a simple Integer/CharField with predefined choices, all distinct entries in the DB are presented, unless field name is in ADVANCED_FILTERS_DISABLE_FOR_FIELDS and limited to display only results under ADVANCED_FILTERS_MAX_CHOICES. """ def get(self, request, model=None, field_name=None): search = request.GET.get('search', '') page = request.GET.get('page', 1) has_next = False if model is field_name is None: return self.render_json_response( {'error': "GetFieldChoices view requires 2 arguments"}, status=400) app_label, model_name = model.split('.', 1) try: model_obj = apps.get_model(app_label, model_name) field = get_fields_from_path(model_obj, field_name)[-1] model_obj = field.model # use new model if followed a ForeignKey except AttributeError as e: logger.debug("Invalid kwargs passed to view: %s", e) return self.render_json_response( {'error': "No installed app/model: %s" % model}, status=400) except (LookupError, FieldDoesNotExist) as e: logger.debug("Invalid kwargs passed to view: %s", e) return self.render_json_response( {'error': force_text(e)}, status=400) choices = field.choices choices = sorted(choices) # if no choices, populate with distinct values from instances if not choices: choices = [] disabled = getattr(settings, 'ADVANCED_FILTERS_DISABLE_FOR_FIELDS', tuple()) if field.name in disabled: logger.debug('Skipped lookup of choices for disabled fields') elif isinstance(field, (models.BooleanField, models.DateField, models.TimeField)): logger.debug('No choices calculated for field %s of type %s', field, type(field)) else: # the order_by() avoids ambiguity with values() and distinct() filter_kwargs = { "{}__icontains".format(field.name): search, "{}__isnull".format(field.name): False } queryset = model_obj.objects.filter( **filter_kwargs).order_by(field.name).values_list( field.name, flat=True).distinct() page_size = getattr( settings, 'ADVANCED_FILTERS_PAGE_SIZE', 20) paginator = Paginator(queryset, page_size) try: page = paginator.page(page) choices = zip(page, page) has_next = page.has_next() except EmptyPage: choices = [] has_next = False results = [{'id': c[0], 'text': force_text(c[1])} for c in choices] return self.render_json_response( {'results': results, "more": has_next}) class GetOperatorChoices(CsrfExemptMixin, StaffuserRequiredMixin, JSONResponseMixin, View): def get(self, request, model=None, field_name=None): if model is field_name is None: return self.render_json_response( {'error': "GetOperatorChoices view requires 2 arguments"}, status=400) app_label, model_name = model.split('.', 1) try: model_obj = apps.get_model(app_label, model_name) field = get_fields_from_path(model_obj, field_name)[-1] model_obj = field.model internal_type = field.get_internal_type() disabled = getattr(settings, 'ADVANCED_FILTERS_DISABLE_FOR_FIELDS', tuple()) if field.name in disabled: logger.debug('Skipped lookup of operators for disabled fields') choices = [] else: af_options = dict(AdvancedFilterQueryForm.OPERATORS) choices = [] field_options = [] if ( internal_type == 'CharField' or internal_type == 'EmailField' or internal_type == 'URLField'): field_options = ["iexact", "icontains", "iregex", "isnull"] elif internal_type == 'BooleanField': field_options = ["istrue", "isfalse", "isnull"] elif ( internal_type == 'PositiveIntegerField' or internal_type == 'SmallIntegerField' or internal_type == 'PositiveSmallIntegerField' or internal_type == 'BigIntegerField' or internal_type == 'IntegerField' or internal_type == 'FloatField' or internal_type == 'DecimalField'): field_options = ["lt", "gt", "lte", "gte", "isnull"] elif ( internal_type == 'DateTimeField' or internal_type == 'DateField'): field_options = ["range", "lt", "gt", "lte", "gte","isnull"] else: field_options = af_options choices = [ {'key': option, 'value': af_options[option] } for option in field_options ] return self.render_json_response({'results': choices }) except AttributeError as e: logger.debug("Invalid kwargs passed to view: %s", e) return self.render_json_response( {'error': "No installed app/model: %s" % model}, status=400) except (LookupError, FieldDoesNotExist) as e: logger.debug("Invalid kwargs passed to view: %s", e) return self.render_json_response( {'error': force_text(e)}, status=400)
107
https://github.com/Teneko-NET-Tools/Teneko.MessagesVersioning/blob/master/src/Vernuntii.Calculator/MessagesProviders/IMessageProvidingDebugMessage.cs
Github Open Source
Open Source
MIT
null
Teneko.MessagesVersioning
Teneko-NET-Tools
C#
Code
38
101
using Vernuntii.Logging; namespace Vernuntii.MessagesProviders { /// <summary> /// Enabled a message to have a debug message. /// </summary> public interface IMessageProvidingDebugMessage { /// <summary> /// Gets a debug message. /// </summary> LoggerMessageAmendmentFactory? DebugMessageFactory { get; } } }
41,056
https://github.com/nanometer-core/javaHighConcurrency/blob/master/ForkTest.java
Github Open Source
Open Source
Apache-2.0
2,019
javaHighConcurrency
nanometer-core
Java
Code
179
898
package java高并发; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinTask; import java.util.concurrent.RecursiveAction; import java.util.concurrent.RecursiveTask; public class ForkTest extends RecursiveTask<Integer>{ //继承带返回值的任务类 private static final int MaxCount=100; //定义最大处理数 private int start; //声明起始量 private int end; //声明终止量 public ForkTest(int start,int end) { //定义构造方法 this.start=start; //保存起始量 this.end=end; //保存终止量 } public static void main(String[] args) { //主方法提供流程控制 ForkJoinPool threadPool = new ForkJoinPool(); //新建分而治之线程池 ForkTest job = new ForkTest(1, 1000); //实例化本类 ForkJoinTask<Integer> result = threadPool.submit(job); //提交任务 try { int value = result.get(); //获取结果 System.out.println("sum="+value); //输出结果 }catch(InterruptedException e) { //捕捉中断异常 e.printStackTrace(); //输出异常信息 }catch(ExecutionException e) { //捕捉线程异常 e.printStackTrace(); //输出异常信息 } } public Integer compute() { //重写执行方法 int sum=0; //声明统计变量 if(end-start<=100) { //如果在能力范围内 for(int i = start;i<=end;i++) { //统计范围量 sum+=i; //加入统计量 } } else { //如果超出能力范围 int jobCount = (end-start)/100+1; //计算分多少批次 ArrayList<ForkTest> jobs = new ArrayList<ForkTest>(jobCount); //新建分解任务组 int endValue = this.start-1; //如果初始化开始量 for(int i = 0;i<jobCount;i++) { //循环批次数 ForkTest temp = new ForkTest(endValue+1,(endValue+100)>end?end:(endValue+100)); //计算每一个任务的起始量与终止量 endValue+=100; //开始量后移 jobs.add(temp); //添加到任务组 temp.fork(); //分解任务 } for(ForkTest t:jobs) { //遍历任务组 sum += t.join(); //获取每一个任务的返回值 } } return sum; //返回最终结果 } } class info extends RecursiveAction{ //继承不带返回值的任务类 protected void compute() { //重写业务流程 } }
14,828
https://github.com/nageshwadhera/weatherreport/blob/master/check_public_login.php
Github Open Source
Open Source
CC0-1.0
null
weatherreport
nageshwadhera
PHP
Code
42
156
<?php include "connection.php"; $s= "select * from signup"; $result= mysqli_query($conn,$s); $flag=0; while ($row= mysqli_fetch_array($result)){ if($row[0]== $_REQUEST["email"] && $row[1] == $_REQUEST["pass"]){ $flag=1; break; } } if($flag == 1) { session_start(); $_SESSION["useremail"] = $_REQUEST["email"]; header("location:userhome.php"); } else{ echo "wrong user name and password"; }
43,811
https://github.com/kragen/mod_pubsub/blob/master/kn_apps/sitewatch/asyncgeturl.py
Github Open Source
Open Source
BSD-3-Clause-Clear
2,021
mod_pubsub
kragen
Python
Code
577
1,432
#!/usr/bin/python """ asyncgeturl.py -- A sensor for whether a site is up or not. Works fine on Debian GNU Linux 3.0 with Python 2.1.3. Known Issues: None. Contact Information: http://mod-pubsub.sf.net/ [email protected] """ ## Copyright 2000-2004 KnowNow, Inc. All rights reserved. ## @KNOWNOW_LICENSE_START@ ## ## 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 KnowNow, Inc., 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 ## OWNER 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. ## ## @KNOWNOW_LICENSE_END@ ## ## $Id: asyncgeturl.py,v 1.6 2004/04/19 05:39:13 bsittler Exp $ # Include standard system libraries: import sys, string, urllib, urlparse # Include local libraries: sys.path = [ "../../python_pubsub" ] + sys.path import asyncore, asynchttp # Included with python_pubsub distribution. """ Note that we are using the event-driven python_pubsub asyncore, not the polling "standard" asyncore. -- Ben and Adam, 2/8/2003 """ class AsyncGetURL(asynchttp.AsyncHTTPConnection): def __init__(self, url, _onResponse = None): # print "AsyncGetURL.__init__" + str((url, _onResponse)) self._onResponse = _onResponse parts = urlparse.urlparse(url) hostport = urllib.splitport(parts[1]) request = parts[2] if parts[3]: request += ";" + parts[3] if parts[4]: request += "?" + parts[4] # print '%-10s : %s : %s : %s' % (self.server_url, parts, hostport, request) asynchttp.AsyncHTTPConnection.__init__(self, hostport[0], int(hostport[1] or "80")) self._url = request def handle_response(self): self.close() if not self._onResponse is None: self._onResponse(self) def handle_connect(self): # print "AsyncGetURL.handle_connect" asynchttp.AsyncHTTPConnection.handle_connect(self) self.putrequest("GET", self._url) self.endheaders() self.getresponse() class AsyncGetURLProgressReport(AsyncGetURL): """Overrides asynchttp.AsyncHTTPConnection""" def __init__(self, url, _onResponse = None): AsyncGetURL.__init__(self, url, _onResponse) self.bytesread = 0 def intercept_body(self, data): self.bytesread += len(data) print "Bytes read: " + str(self.bytesread) class AsyncGetURLTest: def __init__(self, url): # Simpler call: self.http = AsyncGetURL(url, self) self.http = AsyncGetURLProgressReport(url, self) self.http.connect() def __call__(self, tester): if not hasattr(tester, "response"): print "No rsponse" sys.exit(-1) print "results %s %d %s" % ( tester.response.version, tester.response.status, tester.response.reason ) print "headers:" for hdr in tester.response.msg.headers: print "%s" % (string.strip(hdr)) if tester.response.status == 200: print "body:" print tester.response.body def main(argv): # Take the url provided on the command line... url = "" if len(argv) > 1: url = argv[1] # ...or print out Google's i-mode. http = AsyncGetURLTest(url or "http://www.google.com/imode") # Keep the asyncore loop as close to main as possible -- # in command of the main, not the library. asyncore.loop(); if __name__ == "__main__": main(sys.argv) # End of asyncgeturl.py
3,073
https://github.com/andrecarlucci/SharpSenses/blob/master/SharpSenses/ISpeech.cs
Github Open Source
Open Source
MIT
2,016
SharpSenses
andrecarlucci
C#
Code
35
104
using System; namespace SharpSenses { public interface ISpeech { SupportedLanguage CurrentLanguage { get; set; } void Say(string sentence); void Say(string sentence, SupportedLanguage language); void EnableRecognition(); void EnableRecognition(SupportedLanguage language); void DisableRecognition(); event EventHandler<SpeechRecognitionEventArgs> SpeechRecognized; } }
29,185
https://github.com/KerangRebus12/SiswakuApp/blob/master/resources/views/siswa/edit.blade.php
Github Open Source
Open Source
MIT
2,020
SiswakuApp
KerangRebus12
Blade
Code
17
113
@extends('admin/admin') @section('main') <div id="siswa"> <h2>Edit Data Siswa</h2> {!!Form::model($siswa, ['method'=>'PATCH', 'files'=>'true', 'action'=>['SiswaController@update', $siswa->id]])!!} @include('siswa.form', ['submitButtonText'=>'Update']) {!!Form::close()!!} </div> @stop
32,283
https://github.com/lylwo317/MediaParser/blob/master/src/mov/SampleDescBox.h
Github Open Source
Open Source
Apache-2.0
2,022
MediaParser
lylwo317
C
Code
30
114
#ifndef SAMPLEDESCBOX_H #define SAMPLEDESCBOX_H #include "BaseBox.h" class SampleDescBox : public BaseBox { public: SampleDescBox(uint32_t type, uint32_t size); ~SampleDescBox(); public: virtual int Parse(class mp4Parser* parser, uint32_t start_pos); }; #endif // SAMPLEDESCBOX_H
5,984
https://github.com/nullice/UI-DNA/blob/master/DVE/components/vue-color-cylinder/lib/color-map.vue
Github Open Source
Open Source
Apache-2.0, CC0-1.0
2,022
UI-DNA
nullice
Vue
Code
1,046
3,926
<template> <div class="color-map" v-bind:class="{'sv':(value_type=='sv'),'hue':(value_type=='hue') }"> <div class="picker-map-box" v-on:click="map_select($event)" v-on:mousewheel="mousewheel($event)" > <div class="map-thumb" v-bind:style="mapThumbMapStyle" v-on:mousedown="thumb_mousedown($event)" ></div> <div class="picker-map-background-s" v-bind:style="pickerMapStyle_s"></div> <div class="picker-map-background-v" v-bind:style="pickerMapStyle_v"></div> <div class="picker-map-background-h" v-bind:style="pickerMapStyle_h"></div> </div> </div> </template> <style lang="scss" rel="stylesheet/scss"> .color-map { cursor: default; .picker-map-box { position: absolute; width: 100%; height: 60px; top: 0; right: 0; border-radius: 4px 4px 0 0; overflow: hidden; .map-thumb { width: 5px; height: 5px; position: absolute; background: rgba(0, 0, 0, 0); z-index: 4; bottom: 0px; left: 0px; border-radius: 10px; border: 2px solid #fff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.39); margin-bottom: -3px; margin-left: -3px; cursor: default; } .map-thumb:after { content: " "; position: absolute; top: 0; display: inline-block; color: #fff; background: rgba(255, 0, 0, 0); width: 20px; height: 20px; margin-top: -9px; margin-left: -8px; } .picker-map-background-h, .picker-map-background-s, .picker-map-background-v { position: absolute; width: 100%; height: 100%; } .picker-map-background-h { z-index: 1; } .picker-map-background-s { z-index: 2; } .picker-map-background-v { z-index: 3; } } &.sv { .picker-map-background-h { background: #ff944a; z-index: 1; } .picker-map-background-s { background: linear-gradient(90deg, #fff, hsla(0, 0%, 100%, 0)); z-index: 2; } .picker-map-background-v { background: linear-gradient(0deg, #000, transparent); z-index: 3; } } &.hue { .picker-map-background-h { background: linear-gradient(90deg, red 0, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, red); z-index: 1; } .picker-map-background-s { background: linear-gradient(0deg, #fff, rgba(255, 255, 255, 0)); z-index: 2; } .picker-map-background-v { z-index: 3; } } } </style> <script> export default{ ready: function () { this.map_thumb_value2offset(); this.update_refer_color(); }, watch: { 'edit_color.int': function (val) { this.update_refer_color(); }, "value_type": function (val) { if (val == 'sv') { this.pickerMapStyle_s.background = "background: linear-gradient(90deg, #fff, hsla(0, 0%, 100%, 0));" this.pickerMapStyle_v.background = "linear-gradient(0deg, #000, transparent);" this.pickerMapStyle_h.background = "" } if (val == 'hue') { this.pickerMapStyle_h.background = "linear-gradient(90deg, red 0, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, red);" this.pickerMapStyle_s.background = "linear-gradient(0deg, #fff, rgba(255, 255, 255, 0));" this.pickerMapStyle_v.background = "" } this.map_thumb_value2offset(); this.update_refer_color(); }, 'in_value': function (val) // S { if (val > 100) { this.in_value = 100; } if (val < 0) { this.in_value = 0; } if (this.o_set_once) { this.o_set_once = false; this.edit_color.hsv.s = this.in_value; } this.map_thumb_value2offset(); }, 'in_value2': function (val) // V { if (val > 100) { this.in_value2 = 100; } if (val < 0) { this.in_value2 = 0; } if (this.o_set_once2) { this.o_set_once2 = false; this.edit_color.hsv.v = this.in_value2; } this.map_thumb_value2offset(); }, 'in_value3': function (val) // H { if (val > 360) { this.in_value3 = 360; } if (val < 0) { this.in_value3 = 0; } if (this.o_set_once) { this.o_set_once = false; this.edit_color.hsv.h = this.in_value3; } this.map_thumb_value2offset(); }, }, props: ['in_value', 'in_value2', 'in_value3', 'value_type', 'edit_color'], data(){ return { width: 260, height: 60, mouse_offset: 0, mouse_start: 0, offsetX: 0, offsetY: 0, mouse_startX: 0, mouse_startY: 0, o_set_once: true, o_set_once2: true, o_mouse_active: false, o_temp_color: new window.IchiColor({h: 0, s: 100, l: 50}), mapThumbMapStyle: { left: "0px", right: "0px", bottom: "0px" }, pickerMapStyle_s: { background: "" }, pickerMapStyle_v: { background: "" }, pickerMapStyle_h: { background: "" } } }, methods: { map_thumb_value2offset: function () { // console.log(this.value_type, this.edit_color.rgba) if (this.value_type == "sv") { var offsetX = this.in_value * this.width / 100; var offsetY = this.in_value2 * this.height / 100 this.mapThumbMapStyle.left = offsetX + "px"; this.mapThumbMapStyle.bottom = offsetY + "px"; } if (this.value_type == "hue") { var offsetX = this.in_value3 * this.width / 360; var offsetY = this.in_value * this.height / 100 this.mapThumbMapStyle.left = offsetX + "px"; this.mapThumbMapStyle.bottom = offsetY + "px"; } this.offsetX = offsetX; this.offsetY = offsetY; // console.log("value2offset" + this.value_type, "in_value:", this.in_value, "offsetX", offsetX, "edit_color", this.edit_color.rgba) }, map_thumb_offset2value: function (offsetX, width, offsetY, height) { if (this.value_type == "sv") { var z1 = ( offsetX / width) * 100; //s var z2 = 100 - ( offsetY / height) * 100; //l if (z1 < 0) { z1 = 0; } if (z2 < 0) { z2 = 0; } if (z1 > 100) { z1 = 100; } if (z2 > 100) { z2 = 100; } } if (this.value_type == "hue") { var z1 = ( offsetX / width) * 360; var z2 = 100 - ( offsetY / height) * 100; //l if (z1 < 0) { z1 = 0; } if (z2 < 0) { z2 = 0; } if (z1 > 360) { z1 = 360; } if (z2 > 100) { z2 = 100; } } z1 = Math.floor(z1); z2 = Math.floor(z2); if (this.value_type == "sv") { this.in_value = z1; this.in_value2 = z2; } else if (this.value_type == "hue") { this.in_value3 = z1; this.in_value = z2; } this.o_set_once = true; this.o_set_once2 = true; // console.log("s:" + z1, "l:" + z2) }, map_select: function (e) { if (e.target.className == "map-thumb" || this.o_mouse_active) { return false; } var mouseX = e.pageX; var mouseY = e.pageY; var rect = e.srcElement.getBoundingClientRect() var positionX = rect.left + window.pageXOffset; var positionY = rect.top + window.pageYOffset; var offsetX = mouseX - positionX; var offsetY = mouseY - positionY; var width = e.target.offsetWidth this.width = width var height = e.target.offsetHeight this.height = height // console.info("=======map_select-e",e.srcElement.getBoundingClientRect()) // console.info("=======map_select-offsetX, width, offsetY, height",offsetX, width, offsetY, height) this.map_thumb_offset2value(offsetX, width, offsetY, height) }, thumb_mousedown: function (e) { this.o_mouse_active = true; this.mouse_offsetX = e.pageX; this.mouse_startX = this.offsetX; this.mouse_offsetY = e.pageY; this.mouse_startY = this.height - this.offsetY; window.addEventListener('mousemove', this.thumb_hold_mouse) window.addEventListener('mouseup', this.thumb_hold_mouse_end) }, thumb_hold_mouse: function (e) { var moveOffsetX = e.pageX - this.mouse_offsetX; var moveOffsetY = e.pageY - this.mouse_offsetY; this.map_thumb_offset2value(this.mouse_startX + moveOffsetX, this.width, this.mouse_startY + moveOffsetY, this.height); }, thumb_hold_mouse_end: function (e) { this.o_mouse_active = false; window.removeEventListener('mousemove', this.thumb_hold_mouse) window.removeEventListener('mouseup', this.thumb_hold_mouse_end) }, update_refer_color: function () { if (this.value_type == "sv") { this.o_temp_color.hsv.h = this.edit_color.hsv.h; this.o_temp_color.hsv.s = 100; this.o_temp_color.hsv.v = 100; this.pickerMapStyle_h.background = this.o_temp_color.hex; this.pickerMapStyle_v.background = ""; } if (this.value_type == "hue") { this.o_temp_color.hsv.h = this.edit_color.hsv.h; this.o_temp_color.hsv.s = 100; this.o_temp_color.hsv.v = 100; this.pickerMapStyle_h.background = "" var l = this.edit_color.hsl.l; if (l < 50) { this.pickerMapStyle_v.background = "rgba(0,0,0," + (0.5 - (l / 100)) + ")" } else { this.pickerMapStyle_v.background = "rgba(255,255,255," + ((l - 50) / 52) + ")" } } }, mousewheel: function (e) { var offset = (e.wheelDelta / 120) / 5; if (offset < 1 && offset > 0) { offset = 1; } if (offset > -1 && offset < 0) { offset = -1; } if (e.altKey) { offset = offset * 5; } if (this.value_type == "hue") { offset = offset * 1.7; this.edit_color.hsv.v += offset; } else if (this.value_type == "sv") { offset = offset * 3.5; this.edit_color.hsv.h += offset; } e.preventDefault() } } } </script>
44,038
https://github.com/jenarvaezg/eth_scrapper/blob/master/contracts/0x0ccb03cb1a89808209eaebbcb059ed05e44cb9cf.sol
Github Open Source
Open Source
Apache-2.0
2,018
eth_scrapper
jenarvaezg
Solidity
Code
269
842
//Address: 0x0ccb03cb1a89808209eaebbcb059ed05e44cb9cf //Contract name: CrypviserICO //Balance: 0.146307819687629277 Ether //Verification Date: 5/20/2017 //Transacion Count: 32 // CODE STARTS HERE pragma solidity 0.4.11; // © 2016 Ambisafe Inc. No reuse without written permission is allowed. contract CrypviserICO { struct PendingOperation { mapping(address => bool) hasConfirmed; uint yetNeeded; } mapping(bytes32 => PendingOperation) pending; uint public required; mapping(address => bool) public isOwner; address[] public owners; event Confirmation(address indexed owner, bytes32 indexed operation, bool completed); function CrypviserICO(address[] _owners, uint _required) { if (_owners.length == 0 || _required == 0 || _required > _owners.length) { selfdestruct(msg.sender); } required = _required; for (uint i = 0; i < _owners.length; i++) { owners.push(_owners[i]); isOwner[_owners[i]] = true; } } function hasConfirmed(bytes32 _operation, address _owner) constant returns(bool) { return pending[_operation].hasConfirmed[_owner]; } function n() constant returns(uint) { return required; } function m() constant returns(uint) { return owners.length; } modifier onlyowner() { if (!isOwner[msg.sender]) { throw; } _; } modifier onlymanyowners(bytes32 _operation) { if (_confirmAndCheck(_operation)) { _; } } function _confirmAndCheck(bytes32 _operation) onlyowner() internal returns(bool) { if (hasConfirmed(_operation, msg.sender)) { throw; } var pendingOperation = pending[_operation]; if (pendingOperation.yetNeeded == 0) { pendingOperation.yetNeeded = required; } if (pendingOperation.yetNeeded <= 1) { Confirmation(msg.sender, _operation, true); _removeOperation(_operation); return true; } else { Confirmation(msg.sender, _operation, false); pendingOperation.yetNeeded--; pendingOperation.hasConfirmed[msg.sender] = true; } return false; } function _removeOperation(bytes32 _operation) internal { var pendingOperation = pending[_operation]; for (uint i = 0; i < owners.length; i++) { if (pendingOperation.hasConfirmed[owners[i]]) { pendingOperation.hasConfirmed[owners[i]] = false; } } delete pending[_operation]; } function send(address _to, uint _value) onlymanyowners(sha3(msg.data)) returns(bool) { return _to.send(_value); } event Received(address indexed addr, uint value); function () payable { if (msg.value > 0) { Received(msg.sender, msg.value); } } }
4,582
https://github.com/shayoisaack/annpso/blob/master/node_modules/@tensorflow/tfjs/dist/version.d.ts
Github Open Source
Open Source
MIT
null
annpso
shayoisaack
TypeScript
Code
9
18
declare const version = "0.11.6"; export { version };
5,631
https://github.com/pygabo/bus_system/blob/master/bus_system/apps/trip/migrations/0001_initial.py
Github Open Source
Open Source
MIT
null
bus_system
pygabo
Python
Code
135
895
# Generated by Django 3.1.12 on 2021-06-23 04:42 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('bus_driver', '0001_initial'), ('bus', '0001_initial'), ] operations = [ migrations.CreateModel( name='DestinationModel', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('is_removed', models.BooleanField(default=False)), ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('name', models.CharField(max_length=150)), ], options={ 'db_table': 'destination', }, ), migrations.CreateModel( name='TripModel', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('is_removed', models.BooleanField(default=False)), ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('is_available', models.BooleanField()), ('arrival', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='arrival', to='trip.destinationmodel')), ('departure', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='departure', to='trip.destinationmodel')), ], options={ 'db_table': 'trip', }, ), migrations.CreateModel( name='TravelModel', fields=[ ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('is_removed', models.BooleanField(default=False)), ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), ('departure_time', models.DateTimeField()), ('price', models.PositiveSmallIntegerField()), ('bus', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='bus.busmodel')), ('driver', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='bus_driver.busdrivermodel')), ('trip', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='trip.tripmodel')), ], options={ 'db_table': 'travel', }, ), ]
29,738
https://github.com/wingel/sds7102/blob/master/fpga/myhdl/fifo/interleaver.py
Github Open Source
Open Source
MIT
2,021
sds7102
wingel
Python
Code
170
599
#! /usr/bin/python from __future__ import absolute_import if __name__ == '__main__': import hacking hacking.run_as_module('fifo.test_fifo') from myhdl import (Signal, intbv, always_seq, always_comb, instances) from simple.reg import Reg, RoField from ._mem import FifoMem class FifoInterleaver(object): """Interleave data from a wide fifo into a narrower fifo""" def __init__(self, fifo, parts = 2): self.parent = fifo self.parts = parts assert len(self.parent.RD_DATA) % parts == 0 self.data_width = len(self.parent.RD_DATA) / parts self.RD_CLK = self.parent.RD_CLK self.RD_RST = self.parent.RD_RST self.RD = Signal(False) self.RD_DATA = Signal(intbv(0)[self.data_width:]) self.RD_EMPTY = Signal(False) def extract(self, s, i): lo = i * self.data_width hi = lo + self.data_width @always_comb def comb(): s.next = self.parent.RD_DATA[hi:lo] return instances() def gen(self): idx = Signal(intbv(0, 0, self.parts)) insts = [] rd_parts = [] for i in range(self.parts): s = Signal(intbv(0)[self.data_width:]) insts.append(self.extract(s, i)) rd_parts.append(s) @always_comb def comb(): self.parent.RD.next = 0 self.RD_DATA.next = rd_parts[idx] self.RD_EMPTY.next = self.parent.RD_EMPTY if self.RD and idx == self.parts - 1: self.parent.RD.next = 1 @always_seq(self.RD_CLK.posedge, self.RD_RST) def seq(): if self.RD: idx.next = 0 if idx != self.parts - 1: idx.next = idx + 1 return instances()
4,952
https://github.com/ValeeraJS/X/blob/master/build/interfaces/IComponentManager.d.ts
Github Open Source
Open Source
MIT
2,022
X
ValeeraJS
TypeScript
Code
35
100
import IComponent from "./IComponent"; import IEntity from "./IEntity"; import IManager from "./IManager"; export default interface IComponentManager extends IManager<IComponent<any>> { readonly isComponentManager: true; usedBy: IEntity[]; isMixedFrom: (entity: IComponentManager) => boolean; mixFrom: (entity: IComponentManager) => this; }
4,640
https://github.com/equirs/fashionscape-plugin/blob/master/src/main/java/eq/uirs/fashionscape/data/kit/TorsoKit.java
Github Open Source
Open Source
BSD-2-Clause
null
fashionscape-plugin
equirs
Java
Code
138
576
package eq.uirs.fashionscape.data.kit; import lombok.RequiredArgsConstructor; import net.runelite.api.kit.KitType; @RequiredArgsConstructor public enum TorsoKit implements Kit { PLAIN("Plain", false, 18), LIGHT_BUTTONS("Light buttons", false, 19), DARK_BUTTONS("Dark buttons", false, 20), JACKET("Jacket", false, 21), SHIRT("Shirt", false, 22), STITCHING("Stitching", false, 23), TORN("Torn", false, 24), TWO_TONED("Two-toned", false, 25), SWEATER("Sweater", false, 105), BUTTONED_SHIRT("Buttoned shirt", false, 106), VEST("Vest", false, 107), PRINCELY_T("Princely", false, 108), RIPPED_WESKIT("Ripped weskit", false, 109), TORN_WESKIT("Torn weskit", false, 110), PLAIN_F("Plain", true, 56), CROP_TOP("Crop-top", true, 57), POLO_NECK("Polo-neck", true, 58), SIMPLE("Simple", true, 59), TORN_F("Torn", true, 60), SWEATER_F("Sweater", true, 89), SHIRT_F("Shirt", true, 90), VEST_F("Vest", true, 91), FRILLY("Frilly", true, 92), CORSETRY("Corsetry", true, 93), BODICE("Bodice", true, 94); private final String displayName; private final boolean isFemale; private final int kitId; @Override public KitType getKitType() { return KitType.TORSO; } @Override public String getDisplayName() { return displayName; } @Override public boolean isFemale() { return isFemale; } @Override public int getKitId() { return kitId; } }
33,208
https://github.com/xin-huang/sstar/blob/master/tests/test_get_tract.py
Github Open Source
Open Source
Apache-2.0
2,022
sstar
xin-huang
Python
Code
198
714
# Apache License Version 2.0 # Copyright 2022 Xin Huang # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest from sstar.get_tract import get_tract @pytest.fixture def data(): pytest.threshold = "./tests/data/test.tract.threshold" pytest.src1_match_pct = "./tests/data/test.tract.src1.match.pct" pytest.src2_match_pct = "./tests/data/test.tract.src2.match.pct" pytest.exp_bed = "./tests/results/test.tract.exp.bed" pytest.exp_src1_bed = "./tests/results/test.tract.exp.src1.bed" pytest.exp_src2_bed = "./tests/results/test.tract.exp.src2.bed" def test_get_tract(data): get_tract(threshold_file=pytest.threshold, match_pct_files=None, output_prefix='./tests/results/test.tract', diff=0) f1 = open('./tests/results/test.tract.bed', 'r') res = f1.read() f1.close() f2 = open(pytest.exp_bed, 'r') exp_res = f2.read() f2.close() assert res == exp_res get_tract(threshold_file=pytest.threshold, match_pct_files=[pytest.src1_match_pct, pytest.src2_match_pct], output_prefix='./tests/results/test.tract', diff=0) f1 = open('./tests/results/test.tract.src1.bed', 'r') res1 = f1.read() f1.close() f2 = open('./tests/results/test.tract.src2.bed', 'r') res2 = f2.read() f2.close() f3 = open(pytest.exp_src1_bed, 'r') exp_res1 = f3.read() f3.close() f4 = open(pytest.exp_src2_bed, 'r') exp_res2 = f4.read() f4.close() assert res1 == exp_res1 assert res2 == exp_res2
2,888
https://github.com/longjl/JFinal-ext2/blob/master/src/com/jfinal/ext2/upload/filerenamepolicy/CustomNameFileRenamePolicy.java
Github Open Source
Open Source
MIT
2,015
JFinal-ext2
longjl
Java
Code
82
249
/** * */ package com.jfinal.ext2.upload.filerenamepolicy; import java.io.File; /** * @author BruceZCQ * 自定义文件名称 */ public class CustomNameFileRenamePolicy extends FileRenamePolicyWrapper { private String customName = null; public CustomNameFileRenamePolicy(String customName) { this.customName = customName; } @Override public File nameProcess(File f, String name, String ext) { if (null == this.customName) { throw new IllegalArgumentException("Please Set Custom File Name!"); } // add "/" postfix StringBuilder path = new StringBuilder(f.getParent()); String _path = path.toString(); this.setSaveDirectory(_path); String fileName = this.customName + ext; return (new File(_path, fileName)); } }
40,614
https://github.com/LenSunko01/SpringBackEnd/blob/master/demo/src/main/java/ru/hse/gears/GearsApplication.java
Github Open Source
Open Source
MIT
2,021
SpringBackEnd
LenSunko01
Java
Code
21
85
package ru.hse.gears; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GearsApplication { public static void main(String... args) { SpringApplication.run(GearsApplication.class, args); } }
17,893
https://github.com/zhxinyu/cosan/blob/master/docs/html/annotated_dup.js
Github Open Source
Open Source
MIT
null
cosan
zhxinyu
JavaScript
Code
10
33
var annotated_dup = [ [ "Cosan", "namespace_cosan.html", "namespace_cosan" ] ];
38,501
https://github.com/arboehme/theia-xtext/blob/master/template/templates/java/odata/olingo/service/v2/edm/bridge/EdmEntityTypeBridge.java
Github Open Source
Open Source
Apache-2.0
2,020
theia-xtext
arboehme
Java
Code
513
2,184
package {service.namespace}.odata.edm.bridge; import java.util.ArrayList; import java.util.List; import org.apache.olingo.commons.api.edm.EdmAnnotation; import org.apache.olingo.commons.api.edm.EdmElement; import org.apache.olingo.commons.api.edm.EdmEntityType; import org.apache.olingo.commons.api.edm.EdmException; import org.apache.olingo.commons.api.edm.EdmKeyPropertyRef; import org.apache.olingo.commons.api.edm.EdmNavigationProperty; import org.apache.olingo.commons.api.edm.EdmProperty; import org.apache.olingo.commons.api.edm.EdmTerm; import org.apache.olingo.commons.api.edm.EdmType; import org.apache.olingo.commons.api.edm.FullQualifiedName; import org.apache.olingo.commons.api.edm.constants.EdmTypeKind; import org.apache.olingo.commons.api.ex.ODataNotSupportedException; import org.apache.olingo.odata2.api.edm.EdmTyped; public class EdmEntityTypeBridge implements EdmEntityType { private org.apache.olingo.odata2.api.edm.EdmEntityType edmEntityType; public EdmEntityTypeBridge(org.apache.olingo.odata2.api.edm.EdmEntityType edmEntityType) { this.edmEntityType = edmEntityType; } @Override public EdmElement getProperty(String name) { try { EdmTyped property = this.edmEntityType.getProperty(name); if (org.apache.olingo.odata2.api.edm.EdmNavigationProperty.class.isAssignableFrom(property.getClass())) { return new EdmNavigationPropertyBridge( (org.apache.olingo.odata2.api.edm.EdmNavigationProperty) property); } else if (org.apache.olingo.odata2.api.edm.EdmProperty.class.isAssignableFrom(property.getClass())) { return new EdmPropertyBridge((org.apache.olingo.odata2.api.edm.EdmProperty) property); } else if (org.apache.olingo.odata2.api.edm.EdmElement.class.isAssignableFrom(property.getClass())) { return new EdmElementBridge(property); } else { throw new ODataNotSupportedException("This method is not supported by this bridge"); } } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } @Override public List<String> getPropertyNames() { try { return this.edmEntityType.getPropertyNames(); } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } @Override public EdmProperty getStructuralProperty(String name) { throw new ODataNotSupportedException("This method is not supported by this bridge"); } @Override public EdmNavigationProperty getNavigationProperty(String name) { throw new ODataNotSupportedException("This method is not supported by this bridge"); } @Override public List<String> getNavigationPropertyNames() { throw new ODataNotSupportedException("This method is not supported by this bridge"); } @Override public boolean compatibleTo(EdmType targetType) { throw new ODataNotSupportedException("This method is not supported by this bridge"); } @Override public boolean isOpenType() { throw new ODataNotSupportedException("This method is not supported by this bridge"); } @Override public boolean isAbstract() { throw new ODataNotSupportedException("This method is not supported by this bridge"); } @Override public FullQualifiedName getFullQualifiedName() { try { return new FullQualifiedName(this.edmEntityType.getNamespace(), this.edmEntityType.getName()); } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } @Override public String getNamespace() { try { return this.edmEntityType.getNamespace(); } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } @Override public EdmTypeKind getKind() { return EdmTypeKindBridge.get(this.edmEntityType.getKind()); } @Override public String getName() { try { return this.edmEntityType.getName(); } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } @Override public EdmAnnotation getAnnotation(EdmTerm term, String qualifier) { throw new ODataNotSupportedException("This method is not supported by this bridge"); } @Override public List<EdmAnnotation> getAnnotations() { throw new ODataNotSupportedException("This method is not supported by this bridge"); } @Override public List<String> getKeyPredicateNames() { try { List<org.apache.olingo.odata2.api.edm.EdmProperty> keyProperties = this.edmEntityType.getKeyProperties(); if (keyProperties != null) { List<String> resultKeyPredicateNames = new ArrayList<String>(); for (org.apache.olingo.odata2.api.edm.EdmProperty keyProperty : keyProperties) { resultKeyPredicateNames.add(keyProperty.getName()); } return resultKeyPredicateNames; } else { return null; } } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } @Override public List<EdmKeyPropertyRef> getKeyPropertyRefs() { try { List<org.apache.olingo.odata2.api.edm.EdmProperty> keyProperties = this.edmEntityType.getKeyProperties(); if (keyProperties != null) { List<EdmKeyPropertyRef> resultKeyPropertyRefs = new ArrayList<EdmKeyPropertyRef>(); for (org.apache.olingo.odata2.api.edm.EdmProperty keyProperty : keyProperties) { resultKeyPropertyRefs.add(new EdmKeyPropertyRefBridge(keyProperty)); } return resultKeyPropertyRefs; } else { return null; } } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } @Override public EdmKeyPropertyRef getKeyPropertyRef(String keyPredicateName) { try { List<org.apache.olingo.odata2.api.edm.EdmProperty> keyProperties = this.edmEntityType.getKeyProperties(); if (keyProperties != null) { for (org.apache.olingo.odata2.api.edm.EdmProperty keyProperty : keyProperties) { if (keyProperty.getName() != null && keyProperty.getName().equals(keyPredicateName)) { return new EdmKeyPropertyRefBridge(keyProperty); } } } return null; } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } @Override public boolean hasStream() { try { return this.edmEntityType.hasStream(); } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } @Override public EdmEntityType getBaseType() { try { return new EdmEntityTypeBridge(this.edmEntityType.getBaseType()); } catch (org.apache.olingo.odata2.api.edm.EdmException e) { throw new EdmException(e); } } }
30,754
https://github.com/akbarmmln/fundesk/blob/master/assetss/assets/js/pages/elements/raty-custom.js
Github Open Source
Open Source
MIT
null
fundesk
akbarmmln
JavaScript
Code
168
558
$.fn.raty.defaults.path = '../../../plugins/raty/images'; $('#default').raty(); $('#score').raty({ score: 3 }); $('#score-callback').raty({ score: function() { return $(this).attr('data-score'); } }); $('#number').raty({ number: 10 }); $('#number-callback').raty({ number: function() { return $(this).attr('data-number'); } }); $('#numberMax').raty({ numberMax : 6, number : 100 }); $('#readOnly').raty({ readOnly: true, score: 3 }); $('#readOnly-callback').raty({ readOnly: function() { return 'true becomes readOnly' == 'true becomes readOnly'; } }); $('#noRatedMsg').raty({ readOnly : true, noRatedMsg : "I'am readOnly and I haven't rated yet!" }); $('#half').raty({ half : true, score : 3.26, hints : [['bad 1/2', 'bad'], ['poor 1/2', 'poor'], ['regular 1/2', 'regular'], ['good 1/2', 'good'], ['gorgeous 1/2', 'gorgeous']] }); $('#click').raty({ click: function(score, evt) { alert('ID: ' + this.id + "\nscore: " + score + "\nevent: " + evt.type); } }); $('#cancel').raty({ cancel: true }); $('#cancelHint').raty({ cancel : true, cancelHint : 'My cancel hint!' }); $('#cancelPlace').raty({ cancel : true, cancelPlace : 'right' }); $('#target-div').raty({ cancel : true, target : '#target-div-hint' }); $('#targetType').raty({ cancel : true, target : '#targetType-hint', targetType : 'percentage' }); $('#starType').raty({ cancel : true, half : true, starType : 'i' });
22,766
https://github.com/Icemaush/ToDoo/blob/master/src/todolist/Board.java
Github Open Source
Open Source
MIT
null
ToDoo
Icemaush
Java
Code
665
2,070
package todolist; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javafx.application.Platform; import javafx.event.Event; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.ButtonType; import javafx.stage.Stage; public class Board implements Serializable { public final transient ToDoListController controller; public final transient Stage stage; private final List<Column> columnList; private final List<Card> cardList; private double colWidth; private static int cardCount = 0; public Board(ToDoListController controller, Stage stage) { this.controller = controller; this.stage = stage; columnList = new ArrayList(); cardList = new ArrayList(); } // Add column to board public void addColumn() { if (columnList.size() == 4) { Alert alert = new Alert(AlertType.ERROR, "Maximum number of columns reached."); alert.setHeaderText(null); alert.showAndWait(); } else { Column column = new Column(stage, this); columnList.add(column); // Assign colour to new column switch (columnList.size()) { case 1 -> column.setColour(Column.Colour.Blue); case 2 -> column.setColour(Column.Colour.Green); case 3 -> column.setColour(Column.Colour.Yellow); case 4 -> column.setColour(Column.Colour.Red); default -> column.setColour(Column.Colour.Blue); } clearColumns(false); displayColumns(); } } // Remove column public void removeColumn(Column column) { if (columnList.size() == 1 && !cardList.isEmpty()) { ButtonType yes = new ButtonType("Yes"); ButtonType no = new ButtonType("No"); Alert alert = new Alert(AlertType.CONFIRMATION, "Removing all columns will clear all cards!\nDo you want to continue?", yes, no); alert.setTitle("Warning!"); alert.setHeaderText(null); alert.showAndWait().ifPresent(response -> { if (response == yes) { clearCards(); clearColumns(false); columnList.remove(column); displayColumns(); } }); } else { clearColumns(false); columnList.remove(column); displayColumns(); } } // Remove card public void removeCard(Card card) { try { controller.boardPane.getChildren().remove(card.grid); cardList.remove(card); cardCount--; } catch (NullPointerException ex) { } } // Add card to board public void addCard() { if (columnList.isEmpty()) { Alert alert = new Alert(AlertType.ERROR, "Add a column first!"); alert.setHeaderText(null); alert.showAndWait(); } else { if (cardCount == 40) { Alert alert = new Alert(Alert.AlertType.ERROR, "Card limit reached!\nRemove some cards to add new ones."); alert.setTitle("Card Limit Reached"); alert.setHeaderText(null); alert.showAndWait(); } else { Card card = new Card(stage, this); controller.boardPane.getChildren().add(card.grid); card.focusCard(); cardList.add(card); cardCount++; } } } // Display cards public void displayCards() { if (!cardList.isEmpty()) { for (Card card : cardList) { card.grid.setLayoutX(card.layoutX); card.grid.setLayoutY(card.layoutY); controller.boardPane.getChildren().add(card.grid); } } } // Display columns public void displayColumns() { if (!columnList.isEmpty()) { int posX = 0; colWidth = (stage.getWidth() - 16) / columnList.size(); for (Column column : columnList) { column.posX = posX; column.colWidth = colWidth; column.adjustSize(posX, colWidth); controller.boardPane.getChildren().add(column.grid); posX += colWidth; } for (Card card : cardList) { card.adjustSize(colWidth); } } controller.setButtonColours(columnList.size()); } // Clear columns public void clearColumns(boolean clearColumnList) { try { for (Column column : columnList) { controller.boardPane.getChildren().remove(column.grid); } if (clearColumnList) { columnList.clear(); } } catch (NullPointerException ex) { } } // Remove all cards public void clearCards() { try { for (Card card : cardList) { controller.boardPane.getChildren().remove(card.grid); } cardList.clear(); cardCount = 0; } catch (NullPointerException ex) { } } // Load board public void loadBoard() { try (FileInputStream fileIn = new FileInputStream("board.bin")) { ObjectInputStream objIn = new ObjectInputStream(fileIn); Board loadedBoard = (Board)objIn.readObject(); // Load columns clearColumns(true); for (Column column : loadedBoard.columnList) { Column loadedColumn = new Column(stage, this, column.header, column.bgColour, column.posX, column.colWidth); columnList.add(loadedColumn); } displayColumns(); // Load cards clearCards(); for (Card card : loadedBoard.cardList) { Card loadedCard = new Card(stage, this, card.layoutX, card.layoutY, card.taskName, card.taskDescription); cardList.add(loadedCard); } displayCards(); } catch (IOException | ClassNotFoundException | NullPointerException e) { } } // Save board public void saveBoard() { try (FileOutputStream fileOut = new FileOutputStream("board.bin")) { ObjectOutputStream objectOut = new ObjectOutputStream(fileOut); objectOut.writeObject(this); Alert alert = new Alert(Alert.AlertType.INFORMATION, "Board saved."); alert.setTitle("Save Board"); alert.setHeaderText(null); alert.show(); } catch (IOException | NullPointerException e) { } } // Save prompt on program close public void savePromptOnClose(Event event) { if (!columnList.isEmpty()) { ButtonType yes = new ButtonType("Yes"); ButtonType no = new ButtonType("No"); ButtonType cancel = new ButtonType("Cancel"); Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Do you want to save the current board?", yes, no, cancel); alert.setTitle("Save Board"); alert.setHeaderText(null); alert.showAndWait().ifPresent(response -> { if (response == yes) { saveBoard(); Platform.exit(); } else if (response == no) { Platform.exit(); } else { event.consume(); } }); } else { Platform.exit(); } } public List<Column> getColumnList() { return columnList; } public List<Card> getCardList() { return cardList; } public double getColWidth() { return colWidth; } public int getCardCount() { return cardCount; } }
47,947
https://github.com/EBI-Metagenomics/imm/blob/master/src/state.h
Github Open Source
Open Source
MIT
null
imm
EBI-Metagenomics
C
Code
18
95
#ifndef STATE_H #define STATE_H #include "imm/state.h" static inline void state_detach(struct imm_state *state) { cco_stack_init(&state->trans.outgoing); cco_stack_init(&state->trans.incoming); cco_hash_del(&state->hnode); } #endif
45,241
https://github.com/0xPool/fish-redux-template/blob/master/templates/adapter/dynamic/adapter.dart
Github Open Source
Open Source
MIT
2,020
fish-redux-template
0xPool
Dart
Code
57
218
import 'package:fish_redux/fish_redux.dart'; import 'reducer.dart'; import 'state.dart'; class $nameAdapter extends DynamicFlowAdapter<$nameState> { $nameAdapter() : super( pool: <String, Component<Object>>{ }, connector: _$nameConnector(), reducer: buildReducer(), ); } class _$nameConnector extends ConnOp<$nameState, List<ItemBean>> { @override List<ItemBean> get($nameState state) { return <ItemBean>[]; } @override void set($nameState state, List<ItemBean> items) { } @override subReducer(reducer) { // TODO: implement subReducer return super.subReducer(reducer); } }
1,753
https://github.com/henricazottes/cordova-jsbackgroundservice/blob/master/src/android/JSBackgroundServicePlugin.java
Github Open Source
Open Source
MIT, LicenseRef-scancode-unknown-license-reference
2,018
cordova-jsbackgroundservice
henricazottes
Java
Code
418
1,412
package io.cozy.jsbackgroundservice; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import android.util.Log; import org.apache.cordova.CordovaPlugin; import android.text.TextUtils; import android.content.SharedPreferences; import android.content.Context; import org.apache.cordova.CordovaWebView; import org.apache.cordova.CordovaInterface; import android.content.Intent; public class JSBackgroundServicePlugin extends CordovaPlugin { private static final String TAG = "JSBackgroundPlugin"; final static String PREFERENCES = "jsBgService"; final static String PREF_ACTIVITY_ALIVE = "activity_alive"; final static String PREF_ACTIVITY_FOREGROUND = "activity_foreground"; final static String PREF_IS_REPEATING = "is_repeating"; final static String PREF_LISTEN_NEW_PICTURE = "listen_new_pictures"; final static String PREF_SERVICE_RUNNING = "service_running"; private enum Command { setRepeating, cancelRepeating, isRepeating, listenNewPictures, startService, isRunning, startMainActivity } @Override public boolean execute(final String action, final JSONArray data, final CallbackContext callback) throws JSONException { LifecycleManager manager = new LifecycleManager(cordova.getActivity()); boolean result = true; try { Command command = Command.valueOf(action); switch(Command.valueOf(action)) { case startService: { cordova.getActivity().startService(new Intent(cordova.getActivity(), WebViewService.class)); callback.success(); }; break; case setRepeating: { manager.startAlarmManager(data.optLong(0, -1)); setPreference(PREF_IS_REPEATING, true); callback.success(); }; break; case cancelRepeating: { manager.stopAlarmManager(); setPreference(PREF_IS_REPEATING, false); callback.success(); }; break; case isRepeating: { callback.success(manager.isRepeating() ? "true" : "false"); }; break; case isRunning: { boolean running = cordova.getActivity() .getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) .getBoolean(PREF_SERVICE_RUNNING, false); callback.success(running ? "true" : "false"); }; break; case startMainActivity: { //TODO : Z hard dependancy on cozy-mobile ! Intent intent = new Intent(cordova.getActivity(), io.cozy.drive.mobile.MainActivity.class); // But generic way would need CATEGORY_DEFAULT in manifest to work. // Intent intent = new Intent(); // intent.setAction(Intent.ACTION_MAIN); // intent.addCategory(Intent.CATEGORY_LAUNCHER); // intent.setPackage(mContext.getPackageName()); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); cordova.getActivity().startActivity(intent); callback.success(); }; break; // TODO: put in new pictures plugin. case listenNewPictures: { setPreference(PREF_LISTEN_NEW_PICTURE, data.optBoolean(0, false)); callback.success(); }; break; default: { result = false; }; break; } } catch (IllegalArgumentException e) { throw new JSONException(action + " isn't a valid command, use one of " + TextUtils.join( ", ", Command.values())); } return result; } //// // The 4 following method reflect CordovaApp Activity lifecycle in // preferences. Service uses it later to avoid conflict around shared // resources by it and CordovaApp Activity. //// public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); setPreference(PREF_ACTIVITY_ALIVE, true); // Initialize occurs during app start. setPreference(PREF_ACTIVITY_FOREGROUND, true); } public void onDestroy() { setPreference(PREF_ACTIVITY_ALIVE, false); } /** * Called when the activity will start interacting with the user. * * @param multitasking Flag indicating if multitasking is turned on for app */ public void onResume(boolean multitasking) { setPreference(PREF_ACTIVITY_FOREGROUND, true); } /** * Called when the system is about to start resuming a previous activity. * * @param multitasking Flag indicating if multitasking is turned on for app */ public void onPause(boolean multitasking) { setPreference(PREF_ACTIVITY_FOREGROUND, false); } private void setPreference(String key, boolean value) { SharedPreferences preferences = cordova.getActivity() .getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean(key, value); editor.commit(); } }
1,824