Sampled Datasets
Collection
Random samples from large datasets, for convenience.
•
8 items
•
Updated
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"> </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"> </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"> ₦{{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"> </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"> ₦{{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"> </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: ₦{{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"> </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
|
No dataset card yet