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/bitjjj/HFTracker/blob/master/HFTrackerAndroid/src/com/oppsis/app/hftracker/ui/PortValueChartActivity.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
HFTracker
|
bitjjj
|
Java
|
Code
| 68
| 526
|
package com.oppsis.app.hftracker.ui;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import com.oppsis.app.hftracker.R;
import com.oppsis.app.hftracker.pojo.FundLocalInfoManager;
import com.oppsis.app.hftracker.pojo.FundObject;
import com.oppsis.app.hftracker.ui.base.BaseSwipeAndActionBarActivity;
import com.oppsis.app.hftracker.ui.fragment.FundDetailHoldingChartFragment;
import com.oppsis.app.hftracker.ui.fragment.FundDetailHoldingChartFragment_;
import com.oppsis.app.hftracker.util.Constants;
@EActivity(R.layout.activity_port_value_chart)
public class PortValueChartActivity extends BaseSwipeAndActionBarActivity{
@Extra protected FundObject fund;
@AfterViews
public void initUI(){
super.initUI(getString(R.string.chart_holdings_value_title),Constants.FUND_MANAGER_ICONS.get(FundLocalInfoManager.getFundProperty(this, fund.getName(),FundObject.PROPERTY_FUND_ID)));
FundDetailHoldingChartFragment fragment = FundDetailHoldingChartFragment_.builder().fund(fund).build();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if(fragmentManager.findFragmentByTag(Constants.FUND_HOLDINGS_CHART_FRAGMENT_TAG) != null){
fragmentTransaction.replace(R.id.fund_holding_chart_fragment, fragment);
}
else{
fragmentTransaction.add(R.id.fund_holding_chart_fragment, fragment, Constants.FUND_HOLDINGS_CHART_FRAGMENT_TAG);
}
fragmentTransaction.commit();
}
}
| 12,787
|
https://github.com/TecKnow/learning/blob/master/rosalind/rear/rearPath.py
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
learning
|
TecKnow
|
Python
|
Code
| 606
| 1,789
|
import itertools
import sys
def inverse(permutation):
x, y = zip(*sorted((tuple(reversed(x)) for x in enumerate(permutation))))
adjustment = min(permutation)
y = [i + adjustment for i in y]
return tuple(y)
def composition(theta, ro):
pi_list = list([0]*len(ro))
for x in range(len(pi_list)):
pi_list[x] = theta[ro[x]-min(ro)]
return tuple(pi_list)
def getBreakpoints(seq):
return [i for i in range(1, len(seq)) if abs(seq[i] - seq[i-1]) != 1 ]
def getStrips(seq):
""" find contained intervals where sequence is ordered, and return intervals
in as lists, increasing and decreasing. Single elements are considered
decreasing. "Contained" excludes the first and last interval. """
#print("getStrips called with: ", seq)
deltas = [seq[i+1] - seq[i] for i in range(len(seq)-1)]
increasing = list()
decreasing = list()
start = 0
for i, diff in enumerate(deltas):
if (abs(diff) == 1) and (diff == deltas[start]):
continue
if (start > 0):
if deltas[start] == 1:
increasing.append((start, i+1))
else:
decreasing.append((start, i+1))
start = i+1
#print("Strips in func: ", increasing, decreasing)
return increasing, decreasing
def getReversals(seq, decreasing):
ret = list()
intervalStarts = [i for i, j in decreasing]
for i, j in decreasing:
endValue = seq[j-1]
predIndex = seq.index(endValue-1) #Basically, where do we want the end of the reversal to "end up"
k = predIndex + 1
#if not k in intervalStarts:
ret.append((min(j,k),max(j,k)))
return ret
def doReversal(seq, i,j):
revapplied = tuple(seq[:i]) + tuple([element for element in reversed(seq[i:j])]) + tuple(seq[j:])
#print("Reversal:", seq, i, j, revapplied)
return revapplied
def countReversals(seq):
workQueue = list()
triedSet = set()
solutions = list()
pseq = tuple([0]) + tuple(seq) + tuple([len(seq) + 1])
breakpoints = getBreakpoints(pseq)
if not breakpoints: return 0
increasingStrips, decreasingStrips = getStrips(pseq)
allStrips = increasingStrips + decreasingStrips
candidates = getReversals(pseq, decreasingStrips)
for swap in candidates:
newSeq = doReversal(pseq, *swap)
#if len(getBreakpoints(newSeq)) <= len(breakpoints):
triedSet.add(tuple(newSeq))
workQueue.append([pseq, newSeq])
#print("Initial workQueue:", workQueue)
while workQueue:
history = workQueue.pop()
#print("History:",history)
cseq = history[-1]
breakpoints = getBreakpoints(cseq)
if not breakpoints:
solutions.append(history)
#print(history)
else:
increasingStrips, decreasingStrips = getStrips(cseq)
allStrips = increasingStrips + decreasingStrips
candidates = getReversals(cseq, decreasingStrips)
for swap in candidates:
newSeq = doReversal(cseq, *swap)
if tuple(newSeq) not in triedSet: # and len(getBreakpoints(newSeq)) <= len(breakpoints)
triedSet.add(tuple(newSeq))
newHistory = list(history)
newHistory.append(newSeq)
workQueue.append(newHistory)
#if len(workQueue) % 10 == 0:
#print( len(workQueue))
return solutions
def demo1():
sigma = [int(x) for x in "1 2 3 4 5 6 7 8 9 10".split()]
#print("sigma", sigma)
tau = [int(x) for x in "3 1 5 2 7 4 9 6 10 8".split()]
#print("tau", tau)
tauInv = inverse(tau)
#print("tauInv", tauInv)
composite = composition(tauInv, sigma)
#print("composite:", composite)
print(countReversals(composite))
def demo2():
sigma = [int(x) for x in "3 10 8 2 5 4 7 1 6 9".split()]
#print("sigma", sigma)
tau = [int(x) for x in "5 2 3 1 7 4 10 8 6 9".split()]
#print("tau", tau)
tauInv = inverse(tau)
#print("tauInv", tauInv)
composite = composition(tauInv, sigma)
#print("composite:", composite)
print(countReversals(composite))
def demo3():
sigma = [int(x) for x in "8 6 7 9 4 1 3 10 2 5".split()]
#print("sigma", sigma)
tau = [int(x) for x in "8 2 7 6 9 1 5 3 10 4".split()]
#print("tau", tau)
tauInv = inverse(tau)
#print("tauInv", tauInv)
composite = composition(tauInv, sigma)
#print("composite:", composite)
print(countReversals(composite))
def demo4():
sigma = [int(x) for x in "3 9 10 4 1 8 6 7 5 2".split()]
#print("sigma", sigma)
tau = [int(x) for x in "2 9 8 5 1 7 3 4 6 10".split()]
#print("tau", tau)
tauInv = inverse(tau)
#print("tauInv", tauInv)
composite = composition(tauInv, sigma)
#print("composite:", composite)
print(countReversals(composite))
def demo5():
sigma = [int(x) for x in "1 2 3 4 5 6 7 8 9 10".split()]
#print("sigma", sigma)
tau = [int(x) for x in "1 2 3 4 5 6 7 8 9 10".split()]
#print("tau", tau)
tauInv = inverse(tau)
#print("tauInv", tauInv)
composite = composition(tauInv, sigma)
#print("composite:", composite)
print(countReversals(composite))
if __name__=="__main__":
#demo1()
#demo2()
demo3()
demo4()
#demo5()
| 24,798
|
https://github.com/freebsd/freebsd-ports/blob/master/www/p5-CGI-Application-Plugin-Authentication/Makefile
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,023
|
freebsd-ports
|
freebsd
|
Makefile
|
Code
| 51
| 375
|
PORTNAME= CGI-Application-Plugin-Authentication
PORTVERSION= 0.23
CATEGORIES= www perl5
MASTER_SITES= CPAN
PKGNAMEPREFIX= p5-
MAINTAINER= bofh@FreeBSD.org
COMMENT= Support for authenticating requests in CGI::Application
WWW= https://metacpan.org/release/CGI-Application-Plugin-Authentication
LICENSE= ART10 GPLv1+
LICENSE_COMB= dual
BUILD_DEPENDS= ${RUN_DEPENDS}
RUN_DEPENDS= p5-Apache-Htpasswd>=0:security/p5-Apache-Htpasswd \
p5-CGI-Application>=4:www/p5-CGI-Application \
p5-Digest-SHA1>=0:security/p5-Digest-SHA1 \
p5-UNIVERSAL-require>=0:devel/p5-UNIVERSAL-require \
p5-Color-Calc>=1.073:graphics/p5-Color-Calc
TEST_DEPENDS= p5-Test-Exception>=0:devel/p5-Test-Exception \
p5-Test-Warn>=0.11:devel/p5-Test-Warn
USES= perl5
USE_PERL5= configure
NO_ARCH= yes
.include <bsd.port.mk>
| 954
|
https://github.com/liufangqi/hudi/blob/master/hudi-utilities/src/test/java/org/apache/hudi/utilities/sources/helpers/TestS3EventsMetaSelector.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
hudi
|
liufangqi
|
Java
|
Code
| 296
| 1,106
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.hudi.utilities.sources.helpers;
import org.apache.hudi.common.config.TypedProperties;
import org.apache.hudi.common.util.Option;
import org.apache.hudi.common.util.ReflectionUtils;
import org.apache.hudi.common.util.collection.Pair;
import org.apache.hudi.testutils.HoodieClientTestHarness;
import org.apache.hudi.utilities.testutils.CloudObjectTestUtils;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.model.Message;
import org.apache.hadoop.fs.Path;
import org.json.JSONObject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.List;
import static org.apache.hudi.utilities.sources.helpers.CloudObjectsSelector.Config.S3_SOURCE_QUEUE_REGION;
import static org.apache.hudi.utilities.sources.helpers.CloudObjectsSelector.Config.S3_SOURCE_QUEUE_URL;
import static org.apache.hudi.utilities.sources.helpers.TestCloudObjectsSelector.REGION_NAME;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestS3EventsMetaSelector extends HoodieClientTestHarness {
TypedProperties props;
String sqsUrl;
@Mock
AmazonSQS sqs;
@Mock
private S3EventsMetaSelector s3EventsMetaSelector;
@BeforeEach
void setUp() {
initSparkContexts();
initPath();
initFileSystem();
MockitoAnnotations.initMocks(this);
props = new TypedProperties();
sqsUrl = "test-queue";
props.setProperty(S3_SOURCE_QUEUE_URL, sqsUrl);
props.setProperty(S3_SOURCE_QUEUE_REGION, REGION_NAME);
}
@AfterEach
public void teardown() throws Exception {
Mockito.reset(s3EventsMetaSelector);
cleanupResources();
}
@ParameterizedTest
@ValueSource(classes = {S3EventsMetaSelector.class})
public void testNextEventsFromQueueShouldReturnsEventsFromQueue(Class<?> clazz) {
S3EventsMetaSelector selector = (S3EventsMetaSelector) ReflectionUtils.loadClass(clazz.getName(), props);
// setup s3 record
String bucket = "test-bucket";
String key = "part-foo-bar.snappy.parquet";
Path path = new Path(bucket, key);
CloudObjectTestUtils.setMessagesInQueue(sqs, path);
List<Message> processed = new ArrayList<>();
// test the return values
Pair<List<String>, String> eventFromQueue =
selector.getNextEventsFromQueue(sqs, Option.empty(), processed);
assertEquals(1, eventFromQueue.getLeft().size());
assertEquals(1, processed.size());
assertEquals(
key,
new JSONObject(eventFromQueue.getLeft().get(0))
.getJSONObject("s3")
.getJSONObject("object")
.getString("key"));
assertEquals("1627376736755", eventFromQueue.getRight());
}
}
| 38,464
|
https://github.com/brookyu/vue-playground/blob/master/src-javascript/components/Coupon.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
vue-playground
|
brookyu
|
Vue
|
Code
| 63
| 212
|
<script>
import { ref } from 'vue';
export default {
name: 'Coupon',
props: ['percent'],
emits: ['redeem'],
setup(props, { emit }) {
const percent = ref(props.percent);
const useCoupon = () => emit('redeem', percent.value);
return { percent, useCoupon };
}
}
</script>
<template>
<form class="card p-2">
<div class="input-group">
<input v-model="percent" type="text" class="form-control" placeholder="Promo code">
<div class="input-group-append">
<button @click="useCoupon" type="button" class="btn btn-secondary">Redeem</button>
</div>
</div>
</form>
</template>
| 42,524
|
https://github.com/xxlv/Test/blob/master/JS/game/js/game.js
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
Test
|
xxlv
|
JavaScript
|
Code
| 20
| 131
|
var mycanvas = document.getElementById("myCanvasTag")
var ctx = mycanvas.getContext('2d');
function drawTank(ctx){
ctx.strokeStyle="#FF0000";
ctx.beginPath();
ctx.moveTo(10,10);
ctx.lineTo(150,10);
ctx.moveTo(10,10);
ctx.lineTo(10,150);
ctx.closePath();
ctx.stroke();
}
drawTank(ctx);
| 5,058
|
https://github.com/devhani/fulcrum_ui/blob/master/packages/bzx-common/src/contracts/artifacts/kovan/iTokenList.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
fulcrum_ui
|
devhani
|
JavaScript
|
Code
| 30
| 290
|
export const iTokenList = [
[
'1',
'0xe3d99c2152Fc8eA5F87B733706FAA241C37592f1',
'0xfBE16bA4e8029B759D3c5ef8844124893f3ae470',
'ifWETH',
'ifWETH',
'1'
],
[
'1',
'0xF6a0690f22da5464924A28a8198E8ecA69ffc47e',
'0x5aE55494Ccda82f1F7c653BC2b6EbB4aD3C77Dac',
'iWBTC',
'iWBTC',
'1'
],
[
'1',
'0x021C5923398168311Ff320902BF8c8C725B4F288',
'0xB443f30CDd6076b1A5269dbc08b774F222d4Db4e',
'iUSDC',
'iUSDC',
'1'
]
]
| 29,729
|
https://github.com/Mrizwanshaik/bosh-ext-cli/blob/master/src/github.com/bosh-tools/bosh-ext-cli/web/deployments_table.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
bosh-ext-cli
|
Mrizwanshaik
|
Go
|
Code
| 86
| 326
|
package web
const deploymentsTable string = `
<table id="deployment-tmpl" class="tmpl">
<tr>
<td class="deployment">
<a href="#" data-query="deployment" data-value="{name}">{name}</a>
<a href="#" data-query="instances-canvas" data-value="{name}">...</a>
</td>
</tr>
</table>
<script type="text/javascript">
function DeploymentsTable($el) {
var dataSource = null;
function setUp() {
var moreCallback = function() { dataSource.More(); }
var tmpls = {
empty: Tmpl('<tr><td colspan="1">No deployments</td></tr>', []),
error: Tmpl('<tr><td colspan="1">Error fetching deployments</td></tr>', []),
dataItem: Tmpl($("#deployment-tmpl").html(), ["name"]),
};
var table = Table($el, moreCallback, tmpls);
dataSource = TableDataSource("deployments", table, null);
}
setUp();
return {
Load: function() { dataSource.Load(); }
};
}
</script>
`
| 15,475
|
https://github.com/akemimadoka/WinCustomDesktop/blob/master/CustomDesktop/CheckCovered.h
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
WinCustomDesktop
|
akemimadoka
|
C++
|
Code
| 55
| 226
|
#pragma once
#include "Singleton.h"
#include <thread>
#include <memory>
namespace cd
{
// 检测桌面是否被遮挡了
class CheckCovered final : public Singleton<CheckCovered>
{
DECL_SINGLETON(CheckCovered);
public:
bool IsReady() { return m_runThreadFlag; }
bool Init();
bool Uninit();
private:
CheckCovered();
~CheckCovered();
std::unique_ptr<std::thread> m_thread;
bool m_runThreadFlag = true;
bool m_isCovered = false;
HWND m_coveredByHwnd = NULL;
void CheckCoveredThread();
bool IsDesktopCovered();
};
}
| 49,288
|
https://github.com/gnumarcelo/DayRunning/blob/master/build/iphone/build/DayRunning.build/Debug-iphonesimulator/DayRunning.build/Objects-normal/i386/TiMapRouteAnnotationView.d
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,012
|
DayRunning
|
gnumarcelo
|
Makefile
|
Code
| 25
| 236
|
dependencies: \
/Users/marcelomenezes/Documents/Titanium\ Studio\ Workspace/DayRunning/build/iphone/Classes/TiMapRouteAnnotationView.m \
/Users/marcelomenezes/Documents/Titanium\ Studio\ Workspace/DayRunning/build/iphone/Classes/TiBase.h \
/Users/marcelomenezes/Documents/Titanium\ Studio\ Workspace/DayRunning/build/iphone/Classes/TiThreading.h \
/Users/marcelomenezes/Documents/Titanium\ Studio\ Workspace/DayRunning/build/iphone/Classes/TiPublicAPI.h \
/Users/marcelomenezes/Documents/Titanium\ Studio\ Workspace/DayRunning/build/iphone/Classes/TiMapRouteAnnotationView.h \
/Users/marcelomenezes/Documents/Titanium\ Studio\ Workspace/DayRunning/build/iphone/Classes/TiMapRouteAnnotation.h
| 48,328
|
https://github.com/domien96/SolvasFleet/blob/master/backend/src/main/resources/db/migration/V3_7__unique_plate_vin.sql
|
Github Open Source
|
Open Source
|
MIT
| null |
SolvasFleet
|
domien96
|
SQL
|
Code
| 11
| 25
|
-- Drop the unique constraint
ALTER TABLE vehicles DROP CONSTRAINT vehicles_license_plate_key;
| 2,172
|
https://github.com/tomhaigh/aws-sdk-net/blob/master/sdk/src/Services/Lightsail/Generated/Model/Region.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
aws-sdk-net
|
tomhaigh
|
C#
|
Code
| 467
| 1,030
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the lightsail-2016-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Lightsail.Model
{
/// <summary>
/// Describes the AWS Region.
/// </summary>
public partial class Region
{
private List<AvailabilityZone> _availabilityZones = new List<AvailabilityZone>();
private string _continentCode;
private string _description;
private string _displayName;
private RegionName _name;
/// <summary>
/// Gets and sets the property AvailabilityZones.
/// <para>
/// The Availability Zones. Follows the format <code>us-east-2a</code> (case-sensitive).
/// </para>
/// </summary>
public List<AvailabilityZone> AvailabilityZones
{
get { return this._availabilityZones; }
set { this._availabilityZones = value; }
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this._availabilityZones != null && this._availabilityZones.Count > 0;
}
/// <summary>
/// Gets and sets the property ContinentCode.
/// <para>
/// The continent code (e.g., <code>NA</code>, meaning North America).
/// </para>
/// </summary>
public string ContinentCode
{
get { return this._continentCode; }
set { this._continentCode = value; }
}
// Check to see if ContinentCode property is set
internal bool IsSetContinentCode()
{
return this._continentCode != null;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The description of the AWS Region (e.g., <code>This region is recommended to serve
/// users in the eastern United States and eastern Canada</code>).
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property DisplayName.
/// <para>
/// The display name (e.g., <code>Ohio</code>).
/// </para>
/// </summary>
public string DisplayName
{
get { return this._displayName; }
set { this._displayName = value; }
}
// Check to see if DisplayName property is set
internal bool IsSetDisplayName()
{
return this._displayName != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// The region name (e.g., <code>us-east-2</code>).
/// </para>
/// </summary>
public RegionName Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
}
}
| 36,814
|
https://github.com/YunLemon/highj/blob/master/src/main/java/org/highj/data/transformer/StreamArrow.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
highj
|
YunLemon
|
Java
|
Code
| 162
| 806
|
package org.highj.data.transformer;
import org.derive4j.hkt.__2;
import org.derive4j.hkt.__3;
import org.highj.data.Stream;
import org.highj.data.transformer.stream_arrow.StreamArrowArrow;
import org.highj.data.transformer.stream_arrow.StreamArrowArrowCircuit;
import org.highj.data.transformer.stream_arrow.StreamArrowArrowLoop;
import org.highj.data.transformer.stream_arrow.StreamArrowCategory;
import org.highj.data.transformer.stream_arrow.StreamArrowSemigroupoid;
import org.highj.data.tuple.T2;
import org.highj.typeclass2.arrow.Arrow;
import org.highj.typeclass2.arrow.ArrowLoop;
import org.highj.typeclass2.arrow.Category;
import org.highj.typeclass2.arrow.Semigroupoid;
/**
*
* @author clintonselke
*/
public class StreamArrow<A,B,C> implements __3<StreamArrow.µ,A,B,C> {
public static class µ {}
private final __2<A,Stream<B>,Stream<C>> _unstreamArrow;
private StreamArrow(__2<A,Stream<B>,Stream<C>> unstreamArrow) {
this._unstreamArrow = unstreamArrow;
}
public static <A,B,C> StreamArrow<A,B,C> streamArrow(__2<A,Stream<B>,Stream<C>> unstreamArrow) {
return new StreamArrow<>(unstreamArrow);
}
public __2<A,Stream<B>,Stream<C>> unstreamArrow() {
return _unstreamArrow;
}
public static <A,E,B,C> __2<A,T2<E,Stream<B>>,Stream<C>> run(ArrowLoop<A> aArrowLoop, StreamArrow<A,T2<E,B>,C> x) {
Arrow<A> a = aArrowLoop;
return a.dot(
x.unstreamArrow(),
a.arr((T2<E,Stream<B>> x2) -> x2._2().map((B x3) -> T2.of(x2._1(), x3)))
);
}
public static <A> StreamArrowSemigroupoid<A> semigroupoid(Semigroupoid<A> a) {
return () -> a;
}
public static <A> StreamArrowCategory<A> category(Category<A> a) {
return () -> a;
}
public static <A> StreamArrowArrow<A> arrow(Arrow<A> a) {
return () -> a;
}
public static <A> StreamArrowArrowLoop<A> arrowLoop(ArrowLoop<A> a) {
return () -> a;
}
public static <A> StreamArrowArrowCircuit<A> arrowCircuit(ArrowLoop<A> a) {
return () -> a;
}
}
| 1,846
|
https://github.com/natduca/ndbg/blob/master/tests/progdb/test_database.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
ndbg
|
natduca
|
Python
|
Code
| 235
| 728
|
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import unittest
import progdb
from util import *
import os
class TestDatabase(unittest.TestCase):
def test_basic(self):
db = progdb.Database()
db.add_search_path("./tests")
sleep_start = time.time()
MessageLoop.run_while(lambda: time.time() < sleep_start + 1.0) # sleep for a bit so the db can find things
self.assertTrue(db.get_num_files() != 0)
goal = os.path.abspath("./tests/apps/test1.c")
log1("Searching...")
matching = db.find_files_matching("test1.c")
self.assertTrue(goal in matching)
db.shutdown()
def test_ignores(self):
db = progdb.Database()
db.add_ignore("Makefile")
db.add_search_path("./tests")
sleep_start = time.time()
MessageLoop.run_while(lambda: time.time() < sleep_start + 1.0) # sleep for a bit so the db can find things
self.assertTrue(db.get_num_files() != 0)
log1("Searching...")
matching = db.find_files_matching("Makefile")
self.assertEqual(len(matching), 0)
goal = os.path.abspath("./tests/apps/test1.c")
matching = db.find_files_matching("test1.c")
self.assertTrue(goal in matching)
db.shutdown()
def test_remoted_basic(self):
db = RemoteClass(progdb.Database)
db.call_async.add_search_path("./tests")
sleep_start = time.time()
MessageLoop.run_while(lambda: time.time() < sleep_start + 1.0) # sleep for a bit so the db can find things
self.assertTrue(db.call.get_num_files() != 0)
goal = os.path.abspath("./tests/apps/test1.c")
log1("Searching...")
matching = db.call.find_files_matching("test1.c")
self.assertTrue(goal in matching)
db.shutdown()
| 16,692
|
https://github.com/yola/ultradns/blob/master/tests/client_tests.py
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
ultradns
|
yola
|
Python
|
Code
| 80
| 345
|
from mock import Mock, patch
from unittest2 import TestCase
import ultradns
from ultradns.client import UltraDNSClient
from ultradns.exceptions import HTTPError
class ClientTestCase(TestCase):
def _mock_response(self, requests_mock, json_result, status_code=200,
content=None):
response_mock = Mock()
response_mock.status_code = status_code
response_mock.json = Mock(return_value=json_result)
response_mock.content = content
requests_mock.return_value = response_mock
class TestCreatePrimaryZone(ClientTestCase):
@patch.object(ultradns.client.UltraDNSAuthentication, 'is_authenticated')
@patch.object(ultradns.client.requests, 'request')
def test_http_error_is_raised(self, post_mock, auth_mock):
self._mock_response(post_mock, '', 504, content='')
auth_mock.return_value = True
client = UltraDNSClient('user', 'password')
with self.assertRaises(HTTPError) as exc:
client.create_primary_zone('aaa.bbb.ccc')
expected_message = 'HTTP-level error. HTTP code: 504; response body: '
self.assertEqual(exc.exception.message, expected_message)
| 45,972
|
https://github.com/v-yves-es/jdpe2/blob/master/src/main/java/chapter18/Gearbox.java
|
Github Open Source
|
Open Source
|
ADSL
| 2,022
|
jdpe2
|
v-yves-es
|
Java
|
Code
| 173
| 427
|
/*
* Java Design Pattern Essentials - Second Edition, by Tony Bevis
* Copyright 2012, Ability First Limited
*
* This source code is provided to accompany the book and is provided AS-IS without warranty of any kind.
* It is intended for educational and illustrative purposes only, and may not be re-published
* without the express written permission of the publisher.
*/
package chapter18;
public class Gearbox {
public enum Gear {NEUTRAL,
FIRST, SECOND, THIRD, FOURTH, FIFTH,
REVERSE};
private EngineManagementSystem mediator;
private boolean enabled;
private Gear currentGear;
// Constructor accepts mediator as an argument
public Gearbox(EngineManagementSystem mediator) {
this.mediator = mediator;
enabled = false;
currentGear = Gear.NEUTRAL;
mediator.registerGearbox(this);
}
public void enable() {
enabled = true;
mediator.gearboxEnabled();
System.out.println("Gearbox enabled");
}
public void disable() {
enabled = false;
mediator.gearboxDisabled();
System.out.println("Gearbox disabled");
}
public boolean isEnabled() {
return enabled;
}
public void setGear(Gear g) {
if ((isEnabled()) && (getGear() != g)) {
currentGear = g;
mediator.gearChanged();
System.out.println("Now in " + getGear() + " gear");
}
}
private Gear getGear() {
return currentGear;
}
}
| 33,781
|
https://github.com/mfkiwl/GNSS-Tools-Public-PPP-INS/blob/master/Utility Functions/Geo functions/antennaOffsetGPS.m
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
GNSS-Tools-Public-PPP-INS
|
mfkiwl
|
MATLAB
|
Code
| 796
| 2,709
|
function offset = antennaOffsetGPS(block)
% Input- GPS SV block (IIA/IIR/IIR-M/IIF)
% Output- antenna phase center offset from SV CM in body fixed coordinates
% using IGS convention [km]
switch block{1}
case 'IIF'
offset = [0.394 0 1.093]';%/1000; % IIF
offset = [0.394 0 1.6]';%/1000; % IIF
offset = [0.279 0 0.952]'; % From NGA Data
case 'IIR'
offset = [0 0 1.308]';%/1000; % IIR
offset = [0 0 1.6]'; % From NGA Data
case 'IIRM'
offset = [0 0 0.847]';%/1000; % IIR-M
offset = [0 0 0]'; % From NGA Data
case 'IIA'
% offset = [0.279 0 2.564]';%/1000; % IIA
offset = [0.279 0 0.952]'; % From NGA Data
otherwise
offset = [0 0 0]';
end
offsetTable = [...
% PRN SVN START EPOCH END EPOCH DX DY DZ
1 32 406425600 908236800 0.279 0 2.3195
1 37 908755200 915321600 0.279 0 2.2893
1 49 921888000 988761600 0 0 0.9632
1 35 991008000 994550400 0.279 0 2.5742
1 63 994809600 Inf 0.394 0 1.5018
2 13 297475200 768441600 0.279 0 2.6584
2 61 783734400 Inf 0.0013 -0.0011 0.7288
3 11 181699200 450662400 0.21 0 1.8845
3 33 512006400 1092441600 0.279 0 2.7573
3 35 1093910400 1097884800 0.279 0 2.5742
3 69 1098576000 Inf 0.394 0 1.5506
4 1 0 174528000 0 0 1.9
4 34 435628800 1131148800 0.279 0 2.3524
4 49 1138406400 1157846400 0 0 0.9632
4 32 1157932800 1165017600 0.279 0 2.3195
4 34 1165276800 1167523200 0.279 0 2.3524
4 49 1167696000 Inf 0 0 0.9632
5 5 2937600 137203200 0 0 1.9
5 35 430704000 928540800 0.279 0 2.5742
5 50 934502400 Inf -0.0033 -0.0003 0.778
6 3 0 390268800 0 0 1.9
6 36 447292800 1077926400 0.279 0 2.8341
6 49 1080518400 1083369600 0 0 0.9632
6 67 1084320000 Inf 0.394 0 1.467
7 2 0 255744000 0 0 1.9
7 37 421286400 884390400 0.279 0 2.2893
7 48 889574400 Inf -0.0004 0.005 0.8224
8 4 0 308448000 0 0 1.9
8 38 562809600 1113004800 0.279 0 2.5171
8 49 1114387200 1119830400 0 0 0.9632
8 72 1120953600 Inf 0.394 0 1.5014
9 6 9590400 352339200 0.21 0 1.9
9 39 425088000 1090022400 0.279 0 2.391
9 68 1090972800 Inf 0.394 0 1.5226
10 40 521510400 1122681600 0.279 0 2.4717
10 36 1126396800 1129939200 0.279 0 2.8341
10 73 1130284800 Inf 0.394 0 1.5151
11 8 111024000 420595200 0.21 0 1.9
11 46 623289600 Inf -0.0007 -0.0012 1.1178
12 10 147484800 512006400 0.21 0 1.7775
12 58 847756800 Inf 0.0102 -0.0056 0.7678
13 9 139968000 456192000 0.21 0 2.0307
13 43 553651200 Inf -0.0024 -0.0016 1.3483
14 14 287452800 640051200 0.279 0 2.7857
14 41 657849600 Inf -0.0025 -0.0017 1.3045
15 15 338774400 857952000 0.279 0 2.4066
15 55 876614400 Inf 0.0045 0.0019 0.6228
16 16 303436800 655516800 0.279 0 2.4512
16 56 727833600 Inf 0.0126 -0.0069 1.4687
17 17 313372800 793238400 0.279 0 2.3506
17 53 811728000 Inf 0.003 0.001 0.7709
18 18 317174400 650678400 0.279 0 2.5166
18 54 664848000 Inf 0.0139 0.0003 1.2486
19 19 308966400 684460800 0.279 0 2.9116
19 59 763776000 Inf 0.0086 -0.0006 0.8082
20 20 322444800 534556800 0.279 0 2.483
20 51 642038400 Inf 0.001 -0.0032 1.3135
21 21 333590400 727747200 0.279 0 2.4557
21 45 733104000 Inf -0.0034 0.0029 1.3591
22 22 412732800 744249600 0.279 0 2.3906
22 47 756000000 Inf -0.0022 0.0022 0.8506
23 23 343612800 761529600 0.279 0 2.7208
23 60 771984000 Inf 0.0154 0.0068 0.7661
24 24 362620800 1001462400 0.279 0 2.546
24 49 1012176000 1015804800 0 0 0.9632
24 32 1015804800 1019433600 0.279 0 2.3195
24 37 1019433600 1022457600 0.279 0 2.2893
24 49 1028505600 1029715200 0 0 0.9632
24 65 1033344000 Inf 0.394 0 1.4071
25 25 382838400 949708800 0.279 0 2.4307
25 35 949708800 959040000 0.279 0 2.5742
25 62 959040000 Inf 0.394 0 1.5174
26 26 394502400 1104537600 0.279 0 2.381
26 32 1107129600 1108857600 0.279 0 2.3195
26 27 1109030400 1110585600 0.279 0 2.5655
26 71 1111276800 Inf 0.394 0 1.5035
27 27 400032000 1034553600 0.279 0 2.5655
27 49 1034553600 1052179200 0 0 0.9632
27 66 1052611200 Inf 0.394 0 1.5223
28 28 386899200 555724800 0.279 0 2.2552
28 44 647740800 Inf 0.0014 0.0047 0.9995
29 29 408672000 877219200 0.279 0 2.46
29 57 882144000 Inf 0.0109 -0.0045 0.7918
30 30 526521600 996537600 0.279 0 2.5641
30 35 996537600 1051920000 0.279 0 2.5742
30 49 1052179200 1061164800 0 0 0.9632
30 32 1061164800 1063411200 0.279 0 2.3195
30 37 1063584000 1065225600 0.279 0 2.2893
30 27 1070064000 1071360000 0.279 0 2.5655
30 49 1071446400 1076112000 0 0 0.9632
30 64 1076976000 Inf 0.394 0 1.5221
31 31 417484800 814233600 0.279 0 2.1976
31 52 843177600 Inf -0.0008 0.0058 0.9125
32 23 849052800 1137801600 0.279 0 2.7208
32 70 1138665600 Inf 0.394 0 1.5348];
end
| 36,360
|
https://github.com/ry/tokio/blob/master/tokio-udp/tests/udp.rs
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
tokio
|
ry
|
Rust
|
Code
| 709
| 2,579
|
extern crate futures;
extern crate tokio_udp;
extern crate tokio_codec;
#[macro_use]
extern crate tokio_io;
extern crate bytes;
extern crate env_logger;
use std::io;
use std::net::SocketAddr;
use futures::{Future, Poll, Stream, Sink};
use tokio_udp::{UdpSocket, UdpFramed};
use tokio_codec::{Encoder, Decoder};
use bytes::{BytesMut, BufMut};
macro_rules! t {
($e:expr) => (match $e {
Ok(e) => e,
Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
})
}
fn send_messages<S: SendFn + Clone, R: RecvFn + Clone>(send: S, recv: R) {
let mut a = t!(UdpSocket::bind(&([127, 0, 0, 1], 0).into()));
let mut b = t!(UdpSocket::bind(&([127, 0, 0, 1], 0).into()));
let a_addr = t!(a.local_addr());
let b_addr = t!(b.local_addr());
{
let send = SendMessage::new(a, send.clone(), b_addr, b"1234");
let recv = RecvMessage::new(b, recv.clone(), a_addr, b"1234");
let (sendt, received) = t!(send.join(recv).wait());
a = sendt;
b = received;
}
{
let send = SendMessage::new(a, send, b_addr, b"");
let recv = RecvMessage::new(b, recv, a_addr, b"");
t!(send.join(recv).wait());
}
}
#[test]
fn send_to_and_recv_from() {
send_messages(SendTo {}, RecvFrom {});
}
#[test]
fn send_and_recv() {
send_messages(Send {}, Recv {});
}
trait SendFn {
fn send(&self, &mut UdpSocket, &[u8], &SocketAddr) -> Result<usize, io::Error>;
}
#[derive(Debug, Clone)]
struct SendTo {}
impl SendFn for SendTo {
fn send(&self, socket: &mut UdpSocket, buf: &[u8], addr: &SocketAddr) -> Result<usize, io::Error> {
socket.send_to(buf, addr)
}
}
#[derive(Debug, Clone)]
struct Send {}
impl SendFn for Send {
fn send(&self, socket: &mut UdpSocket, buf: &[u8], addr: &SocketAddr) -> Result<usize, io::Error> {
socket.connect(addr).expect("could not connect");
socket.send(buf)
}
}
struct SendMessage<S> {
socket: Option<UdpSocket>,
send: S,
addr: SocketAddr,
data: &'static [u8],
}
impl<S: SendFn> SendMessage<S> {
fn new(socket: UdpSocket, send: S, addr: SocketAddr, data: &'static [u8]) -> SendMessage<S> {
SendMessage {
socket: Some(socket),
send: send,
addr: addr,
data: data,
}
}
}
impl<S: SendFn> Future for SendMessage<S> {
type Item = UdpSocket;
type Error = io::Error;
fn poll(&mut self) -> Poll<UdpSocket, io::Error> {
let n = try_nb!(self.send.send(self.socket.as_mut().unwrap(), &self.data[..], &self.addr));
assert_eq!(n, self.data.len());
Ok(self.socket.take().unwrap().into())
}
}
trait RecvFn {
fn recv(&self, &mut UdpSocket, &mut [u8], &SocketAddr) -> Result<usize, io::Error>;
}
#[derive(Debug, Clone)]
struct RecvFrom {}
impl RecvFn for RecvFrom {
fn recv(&self, socket: &mut UdpSocket, buf: &mut [u8],
expected_addr: &SocketAddr) -> Result<usize, io::Error> {
socket.recv_from(buf).map(|(s, addr)| {
assert_eq!(addr, *expected_addr);
s
})
}
}
#[derive(Debug, Clone)]
struct Recv {}
impl RecvFn for Recv {
fn recv(&self, socket: &mut UdpSocket, buf: &mut [u8], _: &SocketAddr) -> Result<usize, io::Error> {
socket.recv(buf)
}
}
struct RecvMessage<R> {
socket: Option<UdpSocket>,
recv: R,
expected_addr: SocketAddr,
expected_data: &'static [u8],
}
impl<R: RecvFn> RecvMessage<R> {
fn new(socket: UdpSocket, recv: R, expected_addr: SocketAddr,
expected_data: &'static [u8]) -> RecvMessage<R> {
RecvMessage {
socket: Some(socket),
recv: recv,
expected_addr: expected_addr,
expected_data: expected_data,
}
}
}
impl<R: RecvFn> Future for RecvMessage<R> {
type Item = UdpSocket;
type Error = io::Error;
fn poll(&mut self) -> Poll<UdpSocket, io::Error> {
let mut buf = vec![0u8; 10 + self.expected_data.len() * 10];
let n = try_nb!(self.recv.recv(&mut self.socket.as_mut().unwrap(), &mut buf[..],
&self.expected_addr));
assert_eq!(n, self.expected_data.len());
assert_eq!(&buf[..self.expected_data.len()], &self.expected_data[..]);
Ok(self.socket.take().unwrap().into())
}
}
#[test]
fn send_dgrams() {
let mut a = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse())));
let mut b = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse())));
let mut buf = [0u8; 50];
let b_addr = t!(b.local_addr());
{
let send = a.send_dgram(&b"4321"[..], &b_addr);
let recv = b.recv_dgram(&mut buf[..]);
let (sendt, received) = t!(send.join(recv).wait());
assert_eq!(received.2, 4);
assert_eq!(&received.1[..4], b"4321");
a = sendt.0;
b = received.0;
}
{
let send = a.send_dgram(&b""[..], &b_addr);
let recv = b.recv_dgram(&mut buf[..]);
let received = t!(send.join(recv).wait()).1;
assert_eq!(received.2, 0);
}
}
pub struct ByteCodec;
impl Decoder for ByteCodec {
type Item = Vec<u8>;
type Error = io::Error;
fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Vec<u8>>, io::Error> {
let len = buf.len();
Ok(Some(buf.split_to(len).to_vec()))
}
}
impl Encoder for ByteCodec {
type Item = Vec<u8>;
type Error = io::Error;
fn encode(&mut self, data: Vec<u8>, buf: &mut BytesMut) -> Result<(), io::Error> {
buf.reserve(data.len());
buf.put(data);
Ok(())
}
}
#[test]
fn send_framed() {
drop(env_logger::try_init());
let mut a_soc = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse())));
let mut b_soc = t!(UdpSocket::bind(&t!("127.0.0.1:0".parse())));
let a_addr = t!(a_soc.local_addr());
let b_addr = t!(b_soc.local_addr());
{
let a = UdpFramed::new(a_soc, ByteCodec);
let b = UdpFramed::new(b_soc, ByteCodec);
let msg = b"4567".to_vec();
let send = a.send((msg.clone(), b_addr));
let recv = b.into_future().map_err(|e| e.0);
let (sendt, received) = t!(send.join(recv).wait());
let (data, addr) = received.0.unwrap();
assert_eq!(msg, data);
assert_eq!(a_addr, addr);
a_soc = sendt.into_inner();
b_soc = received.1.into_inner();
}
{
let a = UdpFramed::new(a_soc, ByteCodec);
let b = UdpFramed::new(b_soc, ByteCodec);
let msg = b"".to_vec();
let send = a.send((msg.clone(), b_addr));
let recv = b.into_future().map_err(|e| e.0);
let received = t!(send.join(recv).wait()).1;
let (data, addr) = received.0.unwrap();
assert_eq!(msg, data);
assert_eq!(a_addr, addr);
}
}
| 22,839
|
https://github.com/MSmedal/globalpayments-woocommerce/blob/master/vendor/globalpayments/php-sdk/src/Utils/CardUtils.php
|
Github Open Source
|
Open Source
|
MIT
| null |
globalpayments-woocommerce
|
MSmedal
|
PHP
|
Code
| 595
| 2,432
|
<?php
namespace GlobalPayments\Api\Utils;
use GlobalPayments\Api\Builders\AuthorizationBuilder;
use GlobalPayments\Api\Builders\ManagementBuilder;
use GlobalPayments\Api\Entities\Enums\CvnPresenceIndicator;
use GlobalPayments\Api\Entities\Enums\EmvLastChipRead;
use GlobalPayments\Api\Entities\Enums\PaymentMethodType;
use GlobalPayments\Api\Entities\Enums\Target;
use GlobalPayments\Api\Entities\Enums\TrackNumber;
use GlobalPayments\Api\Entities\Enums\TransactionType;
use GlobalPayments\Api\Entities\GpApi\DTO\Card;
use GlobalPayments\Api\PaymentMethods\Interfaces\ICardData;
use GlobalPayments\Api\PaymentMethods\Interfaces\IPinProtected;
use GlobalPayments\Api\PaymentMethods\Interfaces\ITrackData;
use Zend\Filter\Compress\Tar;
class CardUtils
{
private static $trackOnePattern = "/%?[B0]?([\d]+)\\^[^\\^]+\\^([\\d]{4})([^?]+)?/";
private static $trackTwoPattern = "/;([\d]+)=([\d]{4})([^?]+)?/";
private static $fleetBinMap = [
'Visa' => [
'448460' => '448611',
'448613' => '448615',
'448617' => '448674',
'448676' => '448686',
'448688' => '448699',
'461400' => '461421',
'461423' => '461499',
'480700' => '480899'
],
'MC' => [
'553231' => '553380',
'556083' => '556099',
'556100' => '556599',
'556700' => '556999',
],
'Wex' => [
'690046' => '690046',
'707138' => '707138'
],
'Voyager' => [
'708885' => '708889'
]
];
/**
* Card type regex patterns
*
* @var array
*/
private static $cardTypes = [
'Visa' => '/^4/',
'MC' => '/^(5[1-5]|2[2-7])/',
'Amex' => '/^3[47]/',
'DinersClub' => '/^3[0689]/',
'EnRoute' => '/^2(014|149)/',
'Discover' => '/^6([045]|22)/',
'Jcb' => '/^35/',
'Wex' => '/^(?:690046|707138)/',
];
public static function parseTrackData($paymentMethod)
{
$trackData = $paymentMethod->value;
preg_match(static::$trackTwoPattern, $trackData, $matches);
if (!empty($matches[1]) && !empty($matches[2]) && !empty($matches[3])) {
$pan = $matches[1];
$expiry = $matches[2];
$discretionary = $matches[3];
if (!empty($discretionary)) {
if (strlen($pan.$expiry.$discretionary) == 37 &&
substr(strtolower($discretionary), -1) == 'f') {
$discretionary = substr($discretionary, 0, strlen($discretionary) - 1);
}
}
$paymentMethod->trackNumber = TrackNumber::TRACK_TWO;
$paymentMethod->pan = $pan;
$paymentMethod->expiry = $expiry;
$paymentMethod->discretionaryData = $discretionary;
$paymentMethod->trackData = sprintf("%s=%s%s?", $pan, $expiry, $discretionary);
} else {
preg_match(static::$trackOnePattern, $trackData, $matches);
if (!empty($matches[1]) && !empty($matches[2]) && !empty($matches[3])) {
$paymentMethod->trackNumber = TrackNumber::TRACK_ONE;
$paymentMethod->pan = $matches[1];
$paymentMethod->expiry = $matches[2];
$paymentMethod->discretionaryData = $matches[3];
$paymentMethod->trackData = str_replace('%', '', $matches[0]);
}
}
return $paymentMethod;
}
/**
* Gets a card's type based on the BIN
*
* @return string
*/
public static function getCardType($number)
{
$number = str_replace(
[' ', '-'],
'',
$number
);
$type = 'Unknown';
foreach (static::$cardTypes as $type => $regex) {
if (1 === preg_match($regex, $number)) {
return $type;
}
}
if ($type === "Unknown") {
if (static::isFleet($type, $number)) {
$type += "Fleet";
}
}
return $type;
}
public static function isFleet($cardType, $pan)
{
if (!empty($pan)) {
$compareValue = substr($pan, 0, 6);
$baseCardType = str_replace("Fleet", '', $cardType);
if (!empty(static::$fleetBinMap[$baseCardType])) {
$binRanges = static::$fleetBinMap[$baseCardType];
foreach ($binRanges as $lowerRange => $upperRange) {
if ($compareValue >= $lowerRange && $compareValue <= $upperRange) {
return true;
}
}
}
}
return false;
}
/**
* Generate a card
*
* @param AuthorizationBuilder|ManagementBuilder $builder
*
* @return Card
*/
public static function generateCard($builder)
{
$paymentMethod = $builder->paymentMethod;
$transactionType = $builder->transactionType;
$funding = ($paymentMethod->paymentMethodType == PaymentMethodType::DEBIT) ? 'DEBIT' : 'CREDIT';
$card = new Card();
if ($paymentMethod instanceof ITrackData) {
$card->track = $paymentMethod->value;
if ($transactionType == TransactionType::SALE) {
if (empty($paymentMethod->value)) {
$card->number = $paymentMethod->pan;
if (!empty($paymentMethod->expiry)) {
$card->expiry_month = substr($paymentMethod->expiry, 2, 2);
$card->expiry_year = substr($paymentMethod->expiry, 0, 2);
}
}
if (!empty($builder->emvChipCondition)) {
$card->chip_condition = EmvLastChipRead::$emvLastChipRead[$builder->emvChipCondition][Target::GP_API];
}
$card->funding = $funding;
}
} elseif ($paymentMethod instanceof ICardData) {
$card->number = $paymentMethod->number;
$card->expiry_month = str_pad($paymentMethod->expMonth, 2, '0', STR_PAD_LEFT);
$card->expiry_year = substr(str_pad($paymentMethod->expYear, 4, '0', STR_PAD_LEFT), 2, 2);
if (!empty($paymentMethod->cvn)) {
$card->cvv = $paymentMethod->cvn;
$cvnPresenceIndicator = !empty($paymentMethod->cvn) ? CvnPresenceIndicator::PRESENT :
(!empty($paymentMethod->cvnPresenceIndicator) ? $paymentMethod->cvnPresenceIndicator : '');
$card->cvv_indicator = self::getCvvIndicator($cvnPresenceIndicator);
}
$card->funding = $funding;
//we can't have tag and chip_condition in the same time in the request
if (!empty($builder->emvLastChipRead) && empty($builder->tagData)) {
$card->chip_condition = EmvLastChipRead::$emvLastChipRead[$builder->emvLastChipRead][Target::GP_API];
}
}
$billingAddress = !empty($builder->billingAddress) ? $builder->billingAddress->streetAddress1 : '';
$postalCode = !empty($builder->billingAddress) ? $builder->billingAddress->postalCode : '';
$card->tag = $builder->tagData;
$card->avs_address = $billingAddress;
$card->avs_postal_code = $postalCode;
$card->authcode = $builder->offlineAuthCode;
if ($paymentMethod instanceof IPinProtected) {
$card->pin_block =$paymentMethod->pinBlock;
}
return $card;
}
public static function getCvvIndicator($cvnPresenceIndicator)
{
switch ($cvnPresenceIndicator) {
case 1:
$cvvIndicator = 'PRESENT';
break;
case 2:
$cvvIndicator = 'ILLEGIBLE';
break;
case 3:
$cvvIndicator = 'NOT_ON_CARD';
break;
default:
$cvvIndicator = 'NOT_PRESENT';
break;
}
return $cvvIndicator;
}
}
| 38,212
|
https://github.com/c0nr3f/ocpp/blob/master/ocpp/v16/datatypes.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ocpp
|
c0nr3f
|
Python
|
Code
| 338
| 940
|
from dataclasses import dataclass
from typing import List, Optional
from ocpp.v16.enums import (
AuthorizationStatus,
CiStringType,
ChargingRateUnitType,
ChargingProfilePurposeType,
ChargingProfileKindType,
Location,
RecurrencyKind,
ReadingContext,
UnitOfMeasure,
ValueFormat,
Measurand,
Phase
)
@dataclass
class IdToken:
"""
Contains the identifier to use for authorization. It is a case
insensitive string. In future releases this may become a complex type to
support multiple forms of identifiers.
"""
id_token: str
@dataclass
class IdTagInfo:
"""
Contains status information about an identifier. It is returned in
Authorize, Start Transaction and Stop Transaction responses.
If expiryDate is not given, the status has no end date.
"""
status: AuthorizationStatus
parent_id_tag: Optional[IdToken] = None
expiry_date: Optional[str] = None
@dataclass
class AuthorizationData:
"""
Elements that constitute an entry of a Local Authorization List update.
"""
id_tag: IdToken
id_tag_info: Optional[IdTagInfo]
@dataclass
class ChargingSchedulePeriod:
start_period: int
limit: float
number_phases: Optional[int] = None
@dataclass
class ChargingSchedule:
charging_rate_unit: ChargingRateUnitType
charging_schedule_period: List[ChargingSchedulePeriod]
duration: Optional[int] = None
start_schedule: Optional[str] = None
min_charging_rate: Optional[float] = None
@dataclass
class ChargingProfile:
"""
A ChargingProfile consists of a ChargingSchedule, describing the
amount of power or current that can be delivered per time interval.
"""
charging_profile_id: int
stack_level: int
charging_profile_purpose: ChargingProfilePurposeType
charging_profile_kind: ChargingProfileKindType
charging_schedule: ChargingSchedule
transaction_id: Optional[int] = None
recurrency_kind: Optional[RecurrencyKind] = None
valid_from: Optional[str] = None
valid_to: Optional[str] = None
@dataclass
class KeyValue:
"""
Contains information about a specific configuration key.
It is returned in GetConfiguration.conf.
"""
key: str
readonly: bool
value: Optional[str] = None
def __post_init__(self):
if len(self.key) > CiStringType.ci_string_50:
msg = "Field key is longer than 50 characters"
raise ValueError(msg)
if self.value and len(self.value) > CiStringType.ci_string_500:
msg = "Field key is longer than 500 characters"
raise ValueError(msg)
@dataclass
class SampledValue:
"""
Single sampled value in MeterValues. Each value can be accompanied by
optional fields.
"""
value: str
context: ReadingContext
format: Optional[ValueFormat] = None
measurand: Optional[Measurand] = None
phase: Optional[Phase] = None
location: Optional[Location] = None
unit: Optional[UnitOfMeasure] = None
@dataclass
class MeterValue:
"""
Collection of one or more sampled values in MeterValues.req.
All sampled values in a MeterValue are sampled at the same point in time.
"""
timestamp: str
sampled_value: List[SampledValue]
| 41,399
|
https://github.com/Cleitoon1/Engenharia-de-Software-3/blob/master/src/model/Subject.java
|
Github Open Source
|
Open Source
|
MIT
| null |
Engenharia-de-Software-3
|
Cleitoon1
|
Java
|
Code
| 31
| 102
|
package model;
import java.util.List;
import org.json.JSONException;
import com.db4o.ObjectSet;
public interface Subject {
public ObjectSet<EducacaoMOD> getData(String link) throws JSONException;
public List<EducacaoMOD> exibirDados(String link, Boolean organizar, String campo, String ordem) throws JSONException;
}
| 8,206
|
https://github.com/maicong/OpenAPI/blob/master/MetInfo5.2/admin/admin/editor_pass.php
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
OpenAPI
|
maicong
|
PHP
|
Code
| 36
| 218
|
<?php
# MetInfo Enterprise Content Management System
# Copyright (C) MetInfo Co.,Ltd (http://www.metinfo.cn). All rights reserved.
require_once '../login/login_check.php';
$id=$admin_list[id];
$sexx[$admin_list[admin_sex]]="checked='checked'";
$css_url="../templates/".$met_skin."/css";
$img_url="../templates/".$met_skin."/images";
include template('admin/admin_pass');
footer();
# 本程序是一个开源系统,使用时请你仔细阅读使用协议,商业用途请自觉购买商业授权.
# Copyright (C) 长沙米拓信息技术有限公司 (http://www.metinfo.cn). All rights reserved.
?>
| 25,291
|
https://github.com/RobertWeaver10/CS361-Movie-Analyzer/blob/master/Graph.java
|
Github Open Source
|
Open Source
|
BSD-4-Clause-UC
| null |
CS361-Movie-Analyzer
|
RobertWeaver10
|
Java
|
Code
| 741
| 1,680
|
package graph;
import java.util.*;
/**
* this class is an implementation of the GraphIfc interface. It uses
* a HashMap of vertex keys and list of vertex values.
* @authors Robert Weaver, Kyler Greenway
* This implementation assumes a directed graph
* @version 10/6/2021
*/
public class Graph<V> implements GraphIfc<V>{
HashMap<V, List<V>> graph;
int numEdges = 0;
public Graph(){
this.graph = new HashMap<>();
}
/**
* Returns the number of vertices in the graph
* @return The number of vertices in the graph
*/
public int numVertices(){
return this.graph.keySet().size();
}
/**
* Returns the number of edges in the graph
* @return The number of edges in the graph
*/
public int numEdges(){
return numEdges;
}
/**
* Removes all vertices from the graph
*/
public void clear(){
this.graph.clear();
}
/**
* Adds a vertex to the graph. This method has no effect if the vertex already exists in the graph.
* @param v The vertex to be added
*/
public void addVertex(V v){
if (!this.graph.containsKey(v)) {
this.graph.put(v, new ArrayList<>());
}
}
/**
* Adds an edge between vertices u and v in the graph.
*
* @param u A vertex in the graph
* @param v A vertex in the graph
* @throws IllegalArgumentException if either vertex does not occur in the graph.
*/
public void addEdge(V u, V v){
if(!this.graph.containsKey(u) || !this.graph.containsKey(v)){
throw new IllegalArgumentException("a vertex did not exist in the graph");
}
if (!edgeExists(u,v)){
this.graph.get(u).add(v);
numEdges++;
}
}
/**
* Returns the set of all vertices in the graph.
* @return A set containing all vertices in the graph
*/
public Set<V> getVertices(){
return this.graph.keySet();
}
/**
* Returns the neighbors of v in the graph. A neighbor is a vertex that is connected to
* v by an edge. If the graph is directed, this returns the vertices u for which an
* edge (v, u) exists.
*
* @param v An existing node in the graph
* @return All neighbors of v in the graph.
* @throws IllegalArgumentException if the vertex does not occur in the graph
*/
public List<V> getNeighbors(V v){
if(!this.graph.containsKey(v)){
throw new IllegalArgumentException("Vertex did not appear in the graph");
}
return this.graph.get(v);
}
/**
* Determines whether the given vertex is already contained in the graph. The comparison
* is based on the <code>equals()</code> method in the class V.
*
* @param v The vertex to be tested.
* @return True if v exists in the graph, false otherwise.
*/
public boolean containsVertex(V v){
return this.graph.containsKey(v);
}
/**
* Determines whether an edge exists between two vertices. In a directed graph,
* this returns true only if the edge starts at v and ends at u.
* @param v A node in the graph
* @param u A node in the graph
* @return True if an edge exists between the two vertices
* @throws IllegalArgumentException if either vertex does not occur in the graph
*/
public boolean edgeExists(V v, V u){
if (!this.graph.containsKey(v) || !this.graph.containsKey(u)){
throw new IllegalArgumentException("a vertex did not appear in the graph");
}
return this.graph.get(v).contains(u);
}
/**
* Returns the degree of the vertex. In a directed graph, this returns the outdegree of the
* vertex.
* @param v A vertex in the graph
* @return The degree of the vertex
* @throws IllegalArgumentException if the vertex does not occur in the graph
*/
public int degree(V v){
if (!this.graph.containsKey(v)){
throw new IllegalArgumentException("Vertex did not appear in graph");
}
return this.graph.get(v).size();
}
public V maxDegree(){
V maxDegree = null;
int mDegree = 0;
for(V v : graph.keySet()){
if(degree(v)>mDegree){
mDegree = degree(v);
maxDegree = v;
}
}
return maxDegree;
}
/**
* Returns a string representation of the graph. The string representation shows all
* vertices and edges in the graph.
* @return A string representation of the graph
*/
public String toString(){
return this.graph.toString();
}
public static void main(String[] args) {
Graph g = new Graph();
System.out.println("Add a Vertex: ");
g.addVertex('a');
System.out.println(g.toString());
g.addVertex('a'); // test adding a vertex that already exists
g.addVertex('b');
g.addVertex('c');
g.addVertex('d');
g.addEdge('a','b');
g.addEdge('b','c');
g.addEdge('c','d');
g.addEdge('a','d');
g.addEdge('c','d');
g.addEdge('d','c');
System.out.println(g.toString());
//g.addEdge('a','e'); // test to see if crashes when adding edge with a vertex that doesn't exist
System.out.println("Vertices: " + g.getVertices());
System.out.println("Neighbors To vertex 'a' : " + g.getNeighbors('a'));
System.out.println("Edge Exist between 'a' and 'b'? : " + g.edgeExists('a', 'b'));
System.out.println("Degree of vertex 'a' : " + g.degree('a'));
System.out.println("Vertex 'a' exits? : " + g.containsVertex('a'));
System.out.println("Num Vertices: " + g.numVertices());
System.out.println("Num Edges: " + g.numEdges());
g.clear();
System.out.println(g.toString());
}
}
| 11,846
|
https://github.com/vatsalkul/Rocket.Chat.iOS/blob/master/Rocket.Chat/Views/Chat/ChatAnnouncementView.swift
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Rocket.Chat.iOS
|
vatsalkul
|
Swift
|
Code
| 143
| 473
|
//
// ChatAnnouncementView.swift
// Rocket.Chat
//
// Created by Bryan Lew on 24/1/19.
// Copyright © 2019 Rocket.Chat. All rights reserved.
//
import UIKit
final class ChatAnnouncementView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var subscription: UnmanagedSubscription? {
didSet {
guard let subscription = subscription else { return }
guard let announcement = subscription.roomAnnouncement else { return }
let attributedString = NSAttributedString(string: announcement)
announcementLabel.attributedText = MarkdownManager.shared.transformAttributedString(attributedString)
}
}
let announcementLabel: UILabel = {
let label = UILabel()
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
fileprivate func setupUI() {
translatesAutoresizingMaskIntoConstraints = false
addSubview(announcementLabel)
NSLayoutConstraint.activate([
announcementLabel.topAnchor.constraint(equalTo: topAnchor),
announcementLabel.bottomAnchor.constraint(equalTo: bottomAnchor),
announcementLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 12),
announcementLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -12)
])
}
}
// MARK: Themeable
extension ChatAnnouncementView {
override func applyTheme() {
super.applyTheme()
backgroundColor = theme?.bannerBackground
announcementLabel.textColor = theme?.auxiliaryText
}
}
| 45,435
|
https://github.com/emmersion/Emmersion.EventLogWalker/blob/master/Emmersion.EventLogWalker.UnitTests/EventLogWalkerStatusTests.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Emmersion.EventLogWalker
|
emmersion
|
C#
|
Code
| 390
| 1,532
|
using System;
using System.Collections.Generic;
using Emmersion.Testing;
using NUnit.Framework;
namespace Emmersion.EventLogWalker.UnitTests
{
internal class EventLogWalkerStatusTests : With_an_automocked<EventLogWalkerStatus>
{
[Test]
public void When_getting_current_event_index()
{
var walkState = new WalkState
{
PageEventIndex = 1
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.PageEventIndex, Is.EqualTo(walkState.PageEventIndex));
}
[Test]
public void When_getting_count_of_events_in_page()
{
var walkState = new WalkState
{
Events = new List<InsightEvent>
{
new InsightEvent(),
new InsightEvent()
}
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.PageEventsCount, Is.EqualTo(walkState.Events.Count));
}
[Test]
public void When_getting_page_number()
{
var walkState = new WalkState
{
PageNumber = 1
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.PageNumber, Is.EqualTo(walkState.PageNumber));
}
[Test]
public void When_the_first_event_of_the_page_is_being_processed()
{
var walkState = new WalkState
{
PageEventIndex = 0,
Events = new List<InsightEvent>
{
new InsightEvent(),
new InsightEvent()
}
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.PageStatus, Is.EqualTo(PageStatus.Start));
}
[Test]
public void When_the_last_event_of_the_page_is_being_processed()
{
var walkState = new WalkState
{
PageEventIndex = 2,
Events = new List<InsightEvent>
{
new InsightEvent(),
new InsightEvent(),
new InsightEvent()
}
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.PageStatus, Is.EqualTo(PageStatus.End));
}
[Test]
public void When_all_events_for_the_page_have_been_processed()
{
var walkState = new WalkState
{
PageEventIndex = 3,
Events = new List<InsightEvent>
{
new InsightEvent(),
new InsightEvent(),
new InsightEvent()
}
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.PageStatus, Is.EqualTo(PageStatus.Done));
}
[Test]
public void When_an_event_of_the_page_is_being_processed_which_is_not_the_first_or_last()
{
var walkState = new WalkState
{
PageEventIndex = 1,
Events = new List<InsightEvent>
{
new InsightEvent(),
new InsightEvent(),
new InsightEvent()
}
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.PageStatus, Is.EqualTo(PageStatus.InProgress));
}
[Test]
public void When_the_page_is_empty()
{
var walkState = new WalkState
{
PageEventIndex = 0,
Events = new List<InsightEvent>()
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.PageStatus, Is.EqualTo(PageStatus.Empty));
}
[Test]
public void When_getting_total_processed_events()
{
var walkState = new WalkState
{
TotalEventsProcessed = 5
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.TotalEventsProcessed, Is.EqualTo(walkState.TotalEventsProcessed));
}
[Test]
public void When_getting_the_resume_token()
{
var walkState = new WalkState
{
Cursor = new Cursor(),
PreviousCursor = new Cursor(),
PageEventIndex = 1,
PageNumber = 2,
TotalEventsProcessed = 3
};
var expectedTokenJson = RandomString();
ResumeToken capturedToken = null;
var jsonSerializerMock = GetMock<IJsonSerializer>();
jsonSerializerMock.Setup(x => x.Serialize(IsAny<ResumeToken>()))
.Callback<ResumeToken>(token => capturedToken = token)
.Returns(expectedTokenJson);
var status = new EventLogWalkerStatus(walkState, jsonSerializerMock.Object);
var tokenJson = status.GetResumeToken();
Assert.That(tokenJson, Is.EqualTo(expectedTokenJson));
Assert.That(capturedToken, Is.Not.Null);
Assert.That(capturedToken.Cursor, Is.EqualTo(walkState.PreviousCursor));
Assert.That(capturedToken.PageEventIndex, Is.EqualTo(walkState.PageEventIndex));
Assert.That(capturedToken.PageNumber, Is.EqualTo(walkState.PageNumber));
Assert.That(capturedToken.TotalProcessedEvents, Is.EqualTo(walkState.TotalEventsProcessed));
}
[Test]
public void When_getting_the_error_message()
{
var walkState = new WalkState
{
Exception = new Exception(RandomString())
};
var status = new EventLogWalkerStatus(walkState, null);
Assert.That(status.Exception, Is.EqualTo(walkState.Exception));
}
}
}
| 6,419
|
https://github.com/xuqinghan/chatroom_flask/blob/master/app/static/js/userlist.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
chatroom_flask
|
xuqinghan
|
JavaScript
|
Code
| 34
| 128
|
(function () {
w = window,
w.user_list = {
clicked: function(item){
var temp = item.innerHTML;
var name = item.name;
var cNode = d.getElementById("user_list").getElementsByTagName('li');
for( var i=0; i<cNode.length; i++){
alert(cNode[i].innerHTML);
}
//console.log(name)
},
};
})();
| 2,908
|
https://github.com/Shi-Lin-Wang/gateway/blob/master/app/Http/Controllers/signupController.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
gateway
|
Shi-Lin-Wang
|
PHP
|
Code
| 70
| 258
|
<?php
namespace App\Http\Controllers;
use App\sign_up;
use App\Traits\ApiResponser;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Services\registerService;
class signupController extends Controller
{
use ApiResponser;
public $registerService;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct(registerService $registerService)
{
//
$this->registerService = $registerService;
}
public function index()
{
//return $this->successResponse($this->registerService->obtainsignup());
}
public function store(Request $request)
{
return $this->successResponse($this->registerService->createsignup($request->all(), Response::HTTP_CREATED));
}
public function create()
{
//
return $this->registerService->obtainsignup();
}
//
}
| 6,474
|
https://github.com/Zingsla/franz-instagram/blob/master/franz-instagram/View Controllers/ProfileViewController.m
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
franz-instagram
|
Zingsla
|
Objective-C
|
Code
| 441
| 1,752
|
//
// ProfileViewController.m
// franz-instagram
//
// Created by Jacob Franz on 7/9/20.
// Copyright © 2020 Jacob Franz. All rights reserved.
//
#import "ProfileViewController.h"
#import "DetailsViewController.h"
#import "LoginViewController.h"
#import "Post.h"
#import "PostCell.h"
#import "SceneDelegate.h"
#import <Parse/Parse.h>
@interface ProfileViewController () <UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet PFImageView *profileImageView;
@property (weak, nonatomic) IBOutlet UILabel *usernameLabel;
@property (strong, nonatomic) NSMutableArray *posts;
@property (strong, nonatomic) UIRefreshControl *refreshControl;
@property (strong, nonatomic) PFUser *user;
@end
@implementation ProfileViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.user = [PFUser currentUser];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.refreshControl = [[UIRefreshControl alloc] init];
[self.refreshControl addTarget:self action:@selector(fetchPosts) forControlEvents:UIControlEventValueChanged];
[self.tableView insertSubview:self.refreshControl atIndex:0];
[self loadProfile];
[self fetchPosts];
}
- (void)loadProfile {
self.usernameLabel.text = self.user.username;
PFFileObject *profileImage = self.user[@"profileImage"];
if (profileImage != nil) {
self.profileImageView.file = self.user[@"profileImage"];
[self.profileImageView loadInBackground];
}
}
- (IBAction)didTapEditImage:(id)sender {
UIImagePickerController *imagePickerVC = [UIImagePickerController new];
imagePickerVC.delegate = self;
imagePickerVC.allowsEditing = YES;
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
} else {
NSLog(@"Camera unavailable, using photo library instead.");
imagePickerVC.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
[self presentViewController:imagePickerVC animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info {
UIImage *editedImage = [self resizeImage:info[UIImagePickerControllerEditedImage] withSize:CGSizeMake(128, 128)];
self.profileImageView.image = editedImage;
self.user[@"profileImage"] = [Post getPFFileObjectFromImage:editedImage];
[self.user saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Error updating profile image: %@", error.localizedDescription);
} else {
NSLog(@"Successfully updated profile image!");
}
}];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)fetchPosts {
PFQuery *postQuery = [Post query];
[postQuery whereKey:@"author" equalTo:self.user];
[postQuery orderByDescending:@"createdAt"];
[postQuery includeKey:@"author"];
postQuery.limit = 20;
[postQuery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable posts, NSError * _Nullable error) {
if (posts) {
self.posts = [NSMutableArray arrayWithArray:posts];
NSLog(@"Successfully fetched profile posts from database!");
[self.tableView reloadData];
[self.refreshControl endRefreshing];
} else {
NSLog(@"Error fetching profile posts: %@", error.localizedDescription);
}
}];
}
- (IBAction)didTapLogout:(id)sender {
SceneDelegate *myDelegate = (SceneDelegate *) self.view.window.windowScene.delegate;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
LoginViewController *loginViewController = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
myDelegate.window.rootViewController = loginViewController;
[PFUser logOutInBackgroundWithBlock:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Error logging out: %@", error.localizedDescription);
} else {
NSLog(@"Successfully logged out!");
}
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.posts.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
PostCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PostCell"];
cell.post = self.posts[indexPath.row];
return cell;
}
- (UIImage *)resizeImage:(UIImage *)image withSize:(CGSize)size {
UIImageView *resizeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, size.width, size.height)];
resizeImageView.contentMode = UIViewContentModeScaleAspectFill;
resizeImageView.image = image;
UIGraphicsBeginImageContext(size);
[resizeImageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"ProfileDetailsSegue"]) {
UITableViewCell *tappedCell = sender;
NSIndexPath *indexPath = [self.tableView indexPathForCell:tappedCell];
Post *post = self.posts[indexPath.row];
DetailsViewController *detailsViewController = [segue destinationViewController];
detailsViewController.post = post;
}
}
@end
| 28,616
|
https://github.com/anastasiard/riiablo/blob/master/core/src/main/java/com/riiablo/table/schema/Missiles.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
riiablo
|
anastasiard
|
Java
|
Code
| 440
| 1,230
|
package com.riiablo.table.schema;
import com.riiablo.table.annotation.Format;
import com.riiablo.table.annotation.PrimaryKey;
import com.riiablo.table.annotation.Schema;
@Schema
@SuppressWarnings("unused")
public class Missiles {
@Override
public String toString() {
return Missile;
}
@PrimaryKey
public String Missile;
public int Id;
public int pCltDoFunc;
public int pCltHitFunc;
public int pSrvDoFunc;
public int pSrvHitFunc;
public int pSrvDmgFunc;
public String SrvCalc1;
@Format(
startIndex = 1,
endIndex = 6)
public int Param[];
public String CltCalc1;
@Format(
startIndex = 1,
endIndex = 6)
public int CltParam[];
public String SHitCalc1;
@Format(
startIndex = 1,
endIndex = 4)
public int sHitPar[];
public String CHitCalc1;
@Format(
startIndex = 1,
endIndex = 4)
public int cHitPar[];
public String DmgCalc1;
@Format(
startIndex = 1,
endIndex = 3)
public int dParam[];
public int Vel;
public int MaxVel;
public int VelLev;
public int Accel;
public int Range;
public int LevRange;
public int Light;
public int Flicker;
public int Red;
public int Green;
public int Blue;
public int InitSteps;
public int Activate;
public int LoopAnim;
public String CelFile;
public int animrate;
public int AnimLen;
public int AnimSpeed;
public int RandStart;
public int SubLoop;
public int SubStart;
public int SubStop;
public int CollideType;
public boolean CollideKill;
public boolean CollideFriend;
public boolean LastCollide;
public boolean Collision;
public boolean ClientCol;
public boolean ClientSend;
public boolean NextHit;
public int NextDelay;
public int xoffset;
public int yoffset;
public int zoffset;
public int Size;
public boolean SrcTown;
public int CltSrcTown;
public boolean CanDestroy;
public boolean ToHit;
public boolean AlwaysExplode;
public int Explosion;
public boolean Town;
public boolean NoUniqueMod;
public int NoMultiShot;
public int Holy;
public boolean CanSlow;
public boolean ReturnFire;
public boolean GetHit;
public boolean SoftHit;
public int KnockBack;
public int Trans;
public boolean Qty;
public boolean Pierce;
public boolean SpecialSetup;
public boolean MissileSkill;
public String Skill;
public int ResultFlags;
public int HitFlags;
public int HitShift;
public boolean ApplyMastery;
public int SrcDamage;
public boolean Half2HSrc;
public int SrcMissDmg;
public int MinDamage;
@Format(
startIndex = 1,
endIndex = 6)
public String MinLevDam[];
public String MaxDamage;
@Format(
startIndex = 1,
endIndex = 6)
public int MaxLevDam[];
public String DmgSymPerCalc;
public String EType;
public int EMin;
@Format(
startIndex = 1,
endIndex = 6)
public int MinELev[];
public String Emax;
@Format(
startIndex = 1,
endIndex = 6)
public String MaxELev[];
public String EDmgSymPerCalc;
public int ELen;
@Format(
startIndex = 1,
endIndex = 4)
public int ELevLen[];
public int HitClass;
public int NumDirections;
public boolean LocalBlood;
public int DamageRate;
public String TravelSound;
public String HitSound;
public String ProgSound;
public String ProgOverlay;
public String ExplosionMissile;
@Format(
startIndex = 1,
endIndex = 4)
public String SubMissile[];
@Format(
startIndex = 1,
endIndex = 5)
public String HitSubMissile[];
@Format(
startIndex = 1,
endIndex = 4)
public String CltSubMissile[];
@Format(
startIndex = 1,
endIndex = 5)
public String CltHitSubMissile[];
}
| 33,650
|
https://github.com/wahibium/KFF/blob/master/logga/dataarray.h
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
KFF
|
wahibium
|
C
|
Code
| 34
| 91
|
#ifndef _DATAARRAY_H_
#define _DATAARRAY_H_
#define ArrayIDoffset 1000
struct DataArray
{
/* data */
int arrayID; // Array IDs range from 1001~2000
char * arrayName;
int dimension;
int xsize;
int ysize;
int zsize;
};
#endif
| 9,457
|
https://github.com/alexluscombe/sajari-sdk-react/blob/master/src/components/Tabs/Tab/Tab.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
sajari-sdk-react
|
alexluscombe
|
TypeScript
|
Code
| 158
| 429
|
/** @jsx jsx */ jsx;
import { jsx } from "@emotion/core";
import classnames from "classnames";
import * as React from "react";
import { FilterConsumer } from "../../context/filter";
import { CSSObject } from "@emotion/css";
import { Container } from "./styled";
const ReturnKeyCode = 13;
const SpaceKeyCode = 32;
export interface TabProps {
title: string;
styles?: CSSObject;
}
export const Tab: React.SFC<TabProps> = ({ title, styles = {} }) => (
<FilterConsumer>
{({ selected, set }) => {
const isSelected = selected.includes(title);
return (
<Container
className={classnames("sj-tabs__tab", {
"sj-tabs__tab--selected": isSelected
})}
role="button"
tabIndex={0}
onKeyDown={(e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.keyCode === ReturnKeyCode || e.keyCode === SpaceKeyCode) {
e.preventDefault();
setFilter(set, title, !isSelected)();
}
}}
isSelected={isSelected}
onClick={setFilter(set, title, !isSelected)}
css={styles}
>
{title}
</Container>
);
}}
</FilterConsumer>
);
type SetFn = (name: string, value: boolean) => void;
const setFilter = (set: SetFn, name: string, value: boolean) => () => {
if (!value) {
// make tab act like radio button
return;
}
set(name, value);
};
| 12,386
|
https://github.com/atimhome/Wexflow/blob/master/tests/Wexflow.Tests/TextsDecryptor.cs
|
Github Open Source
|
Open Source
|
MIT, LicenseRef-scancode-free-unknown
| 2,019
|
Wexflow
|
atimhome
|
C#
|
Code
| 79
| 402
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;
namespace Wexflow.Tests
{
[TestClass]
public class TextsDecryptor
{
private static readonly string TextsDecryptorSrcFolder = @"C:\WexflowTesting\TextsDecryptor_src\";
private static readonly string TextsDecryptorDestFolder = @"C:\WexflowTesting\TextsDecryptor_dest\";
private static readonly string TextsEncryptorFolder = @"C:\WexflowTesting\TextsEncryptor\";
[TestInitialize]
public void TestInitialize()
{
Helper.DeleteFiles(TextsDecryptorSrcFolder);
Helper.DeleteFiles(TextsDecryptorDestFolder);
}
[TestCleanup]
public void TestCleanup()
{
Helper.DeleteFiles(TextsDecryptorSrcFolder);
Helper.DeleteFiles(TextsDecryptorDestFolder);
Helper.DeleteFiles(TextsEncryptorFolder);
}
[TestMethod]
public void TextsDecryptorTest()
{
var files = GetFiles(TextsDecryptorDestFolder);
Assert.AreEqual(0, files.Length);
Helper.StartWorkflow(83);
Helper.StartWorkflow(84);
files = GetFiles(TextsDecryptorDestFolder);
Assert.AreEqual(2, files.Length);
}
private string[] GetFiles(string dir)
{
return Directory.GetFiles(dir);
}
}
}
| 27,174
|
https://github.com/andy-hanson/mason-compile/blob/master/lib/private/ast/With.d.ts
|
Github Open Source
|
Open Source
|
Unlicense
| null |
mason-compile
|
andy-hanson
|
TypeScript
|
Code
| 43
| 100
|
import Loc from 'esast/lib/Loc';
import Block from './Block';
import { Val, ValOrDo } from './LineContent';
import { LocalDeclare } from './locals';
export default class With extends ValOrDo {
declare: LocalDeclare;
value: Val;
block: Block;
constructor(loc: Loc, declare: LocalDeclare, value: Val, block: Block);
}
| 33,208
|
https://github.com/findnr/vue-element-puls-temp/blob/master/src/components/auth/CymLogin.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
vue-element-puls-temp
|
findnr
|
Vue
|
Code
| 409
| 1,859
|
<!--
* @Author: 程英明
* @Date: 2022-01-18 14:03:01
* @LastEditTime: 2022-05-05 14:43:21
* @LastEditors: 程英明
* @Description:
* @FilePath: \vue-element-plus-temp\src\components\auth\CymLogin.vue
* QQ:504875043@qq.com
-->
<template>
<div class="index bg-gradient-to-t from-blue-500 to-blue-300 h-screen grid justify-items-center content-center">
<div class="bg-[#fff] rounded-lg shadow-2xl justify-items-center" style="width: 850px; height: 500px">
<div class="flex h-full">
<div class="h-full w-1/2 pt-14 pl-10 pr-10">
<div class="content-center leading-[50px] w-full mt-10 text-center text-[30px]">欢迎单位会员登录123</div>
<div class="pt-3">
<input v-model="forms.user"
class="text-sm w-full py-2 px-3 border-2 border-indigo-200 rounded-lg focus:outline-blue-500"
placeholder="请输入用户名" />
</div>
<div class="pt-3">
<input v-model="forms.pwd"
class="text-sm w-full py-2 px-3 border-2 border-indigo-200 rounded-lg focus:outline-blue-500"
placeholder="请输入密码" />
</div>
<div class="pt-3 grid grid-cols-2 gap-2 place-items-stretch">
<input v-model="forms.code"
class="text-sm py-2 px-3 border-2 border-indigo-200 rounded-lg focus:outline-blue-500"
placeholder="请输入验证码" />
<img :src="code_img.url" alt @click="getNewCode" class="cursor-pointer" />
</div>
<div class="pt-3 grid grid-cols-2 gap-2 place-items-stretch">
<el-button class="bg-[#409eff]" type="primary" @click="login">确认登录</el-button>
<el-button class="bg-[#f56c6c]" type="danger" @click="reset">重置信息</el-button>
</div>
<div class="pt-3 grid grid-cols-3 gap-4 place-items-stretch">
<el-link href="https://element.eleme.io" target="_blank">注册用户</el-link>
<el-link href="https://element.eleme.io" target="_blank">找回密码</el-link>
<el-link href="https://element.eleme.io" target="_blank">查看其它信息</el-link>
</div>
</div>
<div class="h-full w-1/2 bg-green-700 rounded-r-lg">
<div class="p-2 pt-4 text-gray-200 text-[20px] animate-bounce">
<span class="relative inline-flex rounded-full h-3 w-3 bg-red-300"></span>
贵州省水利工程协会温馨提示
</div>
<div class="content text-gray-200 p-4 border-1 border-t border-solid border-blue-gray-800">
<div class="inline-block align-text-bottom mt-1">1、单位会员用户名为18位统一社会信用代码。</div>
<div class="inline-block align-text-bottom mt-1">2、单位未更换统一社会信用代码的为营业执照注册号。</div>
<div class="inline-block align-text-bottom mt-1">3、初始密码为123456,请在登录后及时修改密码。</div>
<div class="inline-block align-text-bottom mt-1">4、如有问题,请联系会员管理部门。</div>
<div class="inline-block align-text-bottom mt-1">5、联系电话: 0851-88173437、0851-88173059。</div>
<div class="inline-block align-text-bottom mt-1">6、会费确认及票据查询: 0851-88173443。</div>
<div class="inline-block align-text-bottom mt-1">7、传真号码: 0851-88173437。</div>
<div>
<p class="inline-block align-text-bottom mt-1">8、联系方式 汇款单位及账号。</p>
<p class="inline-block align-text-bottom ml-6 mt-1">单位全称: 贵州省水利工程协会</p>
<p class="inline-block align-text-bottom ml-6 mt-1">开 户 行: 交通银行贵阳市中山东路支行</p>
<p class="inline-block align-text-bottom ml-6 mt-1">账 号: 521145000018010005402</p>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { get } from "@/api/code";
import { ElMessage } from 'element-plus'
const emits = defineEmits(['loginFun'])
const forms = reactive({ name: "", pwd: "", code: "" });
const code_img = reactive({ code_key: "", url: "" });
onMounted(() => {
GET_CODE({}, false);
});
const getNewCode = (msgShow = true) => {
if (code_img.code_key == "") {
GET_CODE({}, msgShow);
} else {
GET_CODE({ code_key: code_img.code_key }, msgShow);
}
};
const GET_CODE = (data = {}, msgShow = true) => {
get("common/code/code", data, msgShow).then((res) => {
if (res.code == 200) {
code_img.code_key = res.code_key;
code_img.url = res.img_base64;
}
});
};
const reset = () => {
for (const key in forms) {
forms[key] = "";
}
getNewCode(false);
};
const login = () => {
for (const key in forms) {
if (forms[key] == "") {
ElMessage.success({
message: '填写的数据不能为空,请查看!',
type: 'success',
})
return;
}
}
emits('loginFun', { ...forms, code_name: code_img.code_key }
);
};
const updateCode = () => {
getNewCode()
}
defineExpose({ updateCode })
</script>
<style scoped lang="scss">
.index {}
</style>
.index {
}
| 7,438
|
https://github.com/cvbn127/captal-engine/blob/master/captal/src/captal/data/default.vert
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
captal-engine
|
cvbn127
|
GLSL
|
Code
| 82
| 206
|
#version 450
layout(row_major, set = 0, binding = 0) uniform view_uniform
{
mat4 view;
mat4 proj;
} view;
layout(row_major, set = 1, binding = 0) uniform model_uniform
{
mat4 model;
} model;
layout(location = 0) in vec3 position;
layout(location = 1) in vec4 color;
layout(location = 2) in vec2 texture_coord;
layout(location = 0) out vec4 frag_color;
layout(location = 1) out vec2 frag_texture_coord;
void main()
{
gl_Position = view.proj * view.view * model.model * vec4(position, 1.0);
frag_color = color;
frag_texture_coord = texture_coord;
}
| 14,460
|
https://github.com/CMGS/core/blob/master/engine/docker/docker.go
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
core
|
CMGS
|
Go
|
Code
| 311
| 976
|
package docker
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/projecteru2/core/engine"
enginetypes "github.com/projecteru2/core/engine/types"
"github.com/projecteru2/core/log"
coretypes "github.com/projecteru2/core/types"
dockerapi "github.com/docker/docker/client"
"github.com/docker/go-connections/tlsconfig"
)
const (
// TCPPrefixKey indicate tcp prefix
TCPPrefixKey = "tcp://"
// SockPrefixKey indicate sock prefix
SockPrefixKey = "unix://"
)
// Engine is engine for docker
type Engine struct {
client dockerapi.APIClient
config coretypes.Config
}
// MakeClient make docker cli
func MakeClient(ctx context.Context, config coretypes.Config, nodename, endpoint, ca, cert, key string) (engine.API, error) {
var client *http.Client
if config.CertPath != "" && ca != "" && cert != "" && key != "" { // nolint
caFile, err := ioutil.TempFile(config.CertPath, fmt.Sprintf("ca-%s", nodename))
if err != nil {
return nil, err
}
certFile, err := ioutil.TempFile(config.CertPath, fmt.Sprintf("cert-%s", nodename))
if err != nil {
return nil, err
}
keyFile, err := ioutil.TempFile(config.CertPath, fmt.Sprintf("key-%s", nodename))
if err != nil {
return nil, err
}
if err = dumpFromString(ctx, caFile, certFile, keyFile, ca, cert, key); err != nil {
return nil, err
}
options := tlsconfig.Options{
CAFile: caFile.Name(),
CertFile: certFile.Name(),
KeyFile: keyFile.Name(),
InsecureSkipVerify: true,
}
defer os.Remove(caFile.Name())
defer os.Remove(certFile.Name())
defer os.Remove(keyFile.Name())
tlsc, err := tlsconfig.Client(options)
if err != nil {
return nil, err
}
client = &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsc,
},
}
}
log.Debugf(ctx, "[MakeDockerEngine] Create new http.Client for %s, %s", endpoint, config.Docker.APIVersion)
return makeRawClient(ctx, config, client, endpoint)
}
// Info show node info
// 2 seconds timeout
// used to be 5, but client won't wait that long
func (e *Engine) Info(ctx context.Context) (*enginetypes.Info, error) {
r, err := e.client.Info(ctx)
if err != nil {
return nil, err
}
return &enginetypes.Info{ID: r.ID, NCPU: r.NCPU, MemTotal: r.MemTotal}, nil
}
// ResourceValidate validate resource usage
func (e *Engine) ResourceValidate(ctx context.Context, cpu float64, cpumap map[string]int64, memory, storage int64) error {
// TODO list all workloads, calcuate resource
return nil
}
// Ping test connection
func (e *Engine) Ping(ctx context.Context) error {
_, err := e.client.Ping(ctx)
return err
}
| 45,916
|
https://github.com/Core-Team-META/Strike-Team-Sector-9/blob/master/NewSniperAlley/Data/Scenes/Main/AudioFolderEnter_1/Tree.pbt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
Strike-Team-Sector-9
|
Core-Team-META
|
Protocol Buffer Text Format
|
Code
| 79
| 294
|
Name: "AudioFolderEnter_1"
RootId: 9839474685740850460
Objects {
Id: 14692678752658692276
Name: "Wire Chain Link Fence Gate Hit Impact Heavy 01 SFX"
Transform {
Location {
Z: 59.6877518
}
Rotation {
Roll: 4.02874366e-06
}
Scale {
X: 1
Y: 1
Z: 1
}
}
ParentId: 9839474685740850460
Collidable_v2 {
Value: "mc:ecollisionsetting:inheritfromparent"
}
Visible_v2 {
Value: "mc:evisibilitysetting:inheritfromparent"
}
CameraCollidable {
Value: "mc:ecollisionsetting:inheritfromparent"
}
AudioInstance {
AudioAsset {
Id: 3788103636985471116
}
Volume: 2.00835848
Falloff: 2000
Radius: -1
EnableOcclusion: true
IsSpatializationEnabled: true
IsAttenuationEnabled: true
}
}
| 23,798
|
https://github.com/rtoy/cmucl/blob/master/src/code/sysmacs.lisp
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-warranty-disclaimer, LicenseRef-scancode-public-domain
| 2,023
|
cmucl
|
rtoy
|
Common Lisp
|
Code
| 959
| 3,365
|
;;; -*- Mode: Lisp; Package: Lisp; Log: code.log -*-
;;;
;;; **********************************************************************
;;; This code was written as part of the CMU Common Lisp project at
;;; Carnegie Mellon University, and has been placed in the public domain.
;;;
(ext:file-comment
"$Header: src/code/sysmacs.lisp $")
;;;
;;; **********************************************************************
;;;
;;; Miscellaneous system hacking macros.
;;;
(in-package "LISP")
(in-package "SYSTEM")
(intl:textdomain "cmucl")
(export '(without-gcing without-hemlock
register-lisp-feature register-lisp-runtime-feature))
(defmacro register-lisp-feature (feature)
"Register the feature as having influenced the CMUCL build
process. Feature is added to *feature*"
`(pushnew ,feature *features*))
(defmacro register-lisp-runtime-feature (feature)
"Register the feature as having influenced the CMUCL build process,
and also the CMUCL C runtime. Feature is added to*features* and
sys::*runtime-features*."
(let ((f (gensym)))
`(progn
(let ((,f ,feature))
(pushnew ,f *features*)
(pushnew ,f sys::*runtime-features*)))))
(in-package "LISP")
;;; WITH-ARRAY-DATA -- Interface
;;;
;;; Checks to see if the array is simple and the start and end are in
;;; bounds. If so, it proceeds with those values. Otherwise, it calls
;;; %WITH-ARRAY-DATA. Note that there is a derive-type method for
;;; %WITH-ARRAY-DATA.
;;;
(defmacro with-array-data (((data-var array &key (offset-var (gensym)))
(start-var &optional (svalue 0))
(end-var &optional (evalue nil)))
&rest forms)
"Given any Array, binds Data-Var to the array's data vector and Start-Var and
End-Var to the start and end of the designated portion of the data vector.
Svalue and Evalue are any start and end specified to the original operation,
and are factored into the bindings of Start-Var and End-Var. Offset-Var is
the cumulative offset of all displacements encountered, and does not
include Svalue."
(once-only ((n-array array)
(n-svalue `(the index ,svalue))
(n-evalue `(the (or index null) ,evalue)))
`(multiple-value-bind
(,data-var ,start-var ,end-var ,offset-var)
(if (not (array-header-p ,n-array))
(let ((,n-array ,n-array))
(declare (type (simple-array * (*)) ,n-array))
,(once-only ((n-len `(length ,n-array))
(n-end `(or ,n-evalue ,n-len)))
`(if (<= ,n-svalue ,n-end ,n-len)
(values ,n-array ,n-svalue ,n-end 0)
(%with-array-data ,n-array ,n-svalue ,n-evalue))))
(%with-array-data ,n-array ,n-svalue ,n-evalue))
(declare (ignorable ,offset-var))
,@forms)))
#-gengc
(defmacro without-gcing (&rest body)
"Executes the forms in the body without doing a garbage collection."
`(unwind-protect
(let ((*gc-inhibit* t))
,@body)
(when (and *need-to-collect-garbage* (not *gc-inhibit*))
(maybe-gc nil))))
#+gengc
(defmacro without-gcing (&rest body)
_N"Executes the forms in the body without doing a garbage collection."
`(without-interrupts ,@body))
#-no-hemlock
(defmacro without-hemlock (&body body)
`(progn
(when (and hi::*in-the-editor* (null debug::*in-the-debugger*))
(let ((device (hi::device-hunk-device
(hi::window-hunk (hi::current-window)))))
(funcall (hi::device-exit device) device)))
,@body
(when (and hi::*in-the-editor* (null debug::*in-the-debugger*))
(let ((device (hi::device-hunk-device
(hi::window-hunk (hi::current-window)))))
(funcall (hi::device-init device) device)))))
#+no-hemlock
(defmacro without-hemlock (&body body)
`(progn ,@body))
;;; Eof-Or-Lose is a useful macro that handles EOF.
(defmacro eof-or-lose (stream eof-errorp eof-value)
`(if ,eof-errorp
(error 'end-of-file :stream ,stream)
,eof-value))
;;; These macros handle the special cases of t and nil for input and
;;; output streams.
;;;
(defmacro in-synonym-of (stream &optional check-type)
(let ((svar (gensym)))
`(let ((,svar ,stream))
(cond ((null ,svar) *standard-input*)
((eq ,svar t) *terminal-io*)
(T ,@(if check-type `((check-type ,svar ,check-type)))
,svar)))))
(defmacro out-synonym-of (stream &optional check-type)
(let ((svar (gensym)))
`(let ((,svar ,stream))
(cond ((null ,svar) *standard-output*)
((eq ,svar t) *terminal-io*)
(T ,@(if check-type `((check-type ,svar ,check-type)))
,svar)))))
;;; Execute the appropriate code for each stream subtype
(defmacro stream-dispatch (stream simple lisp &optional (gray nil gray-p))
`(etypecase ,stream
(lisp-stream
,lisp)
(stream:simple-stream
,simple)
(ext:fundamental-stream
,(if gray-p gray `(no-gray-streams ,stream)))))
;;;; These are hacks to make the reader win.
;;; Prepare-For-Fast-Read-Char -- Internal
;;;
;;; This macro sets up some local vars for use by the
;;; Fast-Read-Char macro within the enclosed lexical scope. The stream
;;; is assumed to be a lisp-stream.
;;;
(defmacro prepare-for-fast-read-char (stream &body forms)
`(let* ((%frc-stream% ,stream)
(%frc-method% (lisp-stream-in %frc-stream%))
(%frc-buffer% (lisp-stream-in-buffer %frc-stream%))
(%frc-index% (lisp-stream-in-index %frc-stream%))
#+unicode
(%frc-string-buffer% (lisp-stream-string-buffer %frc-stream%))
#+unicode
(%frc-string-index% (lisp-stream-string-index %frc-stream%))
#+unicode
(%frc-string-length% (lisp-stream-string-buffer-len %frc-stream%)))
(declare #+unicode
(type index %frc-string-index% %frc-string-length%)
#+unicode
(type (or null simple-string) %frc-string-buffer%)
(type lisp-stream %frc-stream%))
,@forms))
;;; Done-With-Fast-Read-Char -- Internal
;;;
;;; This macro must be called after one is done with fast-read-char
;;; inside it's scope to decache the lisp-stream-in-index.
;;;
(defmacro done-with-fast-read-char ()
`(progn
(setf (lisp-stream-in-index %frc-stream%) %frc-index%)
#+unicode
(setf (lisp-stream-string-index %frc-stream%) %frc-string-index%)))
;;; Fast-Read-Char -- Internal
;;;
;;; This macro can be used instead of Read-Char within the scope of
;;; a Prepare-For-Fast-Read-Char.
;;;
(defmacro fast-read-char (&optional (eof-errorp t) (eof-value ()))
`(cond
((/= (lisp-stream-flags %frc-stream%) 1)
;; Call the method if we're doing a read-char on a character stream.
(funcall %frc-method% %frc-stream% ,eof-errorp ,eof-value))
#+unicode
(%frc-string-buffer%
(cond ((>= %frc-string-index% %frc-string-length%)
(prog1 (fast-read-char-string-refill %frc-stream% ,eof-errorp ,eof-value)
(setq %frc-index% (lisp-stream-in-index %frc-stream%))
(setf %frc-string-index% (lisp-stream-string-index %frc-stream%))
(setf %frc-string-length% (lisp-stream-string-buffer-len %frc-stream%))))
(t
(prog1 (aref %frc-string-buffer% %frc-string-index%)
(incf %frc-string-index%)))))
(%frc-buffer%
(cond ((= %frc-index% in-buffer-length)
(prog1 (fast-read-char-refill %frc-stream% ,eof-errorp ,eof-value)
(setq %frc-index% (lisp-stream-in-index %frc-stream%))))
(t
;; This only works correctly for :iso8859-1!
(prog1 (code-char (aref %frc-buffer% %frc-index%))
(incf %frc-index%)))))
(t
(funcall %frc-method% %frc-stream% ,eof-errorp ,eof-value))))
;;;; And these for the fasloader...
;;; Prepare-For-Fast-Read-Byte -- Internal
;;;
;;; Just like Prepare-For-Fast-Read-Char except that we get the Bin
;;; method. The stream is assumed to be a lisp-stream.
;;;
(defmacro prepare-for-fast-read-byte (stream &body forms)
`(let* ((%frc-stream% ,stream)
(%frc-method% (lisp-stream-bin %frc-stream%))
(%frc-buffer% (lisp-stream-in-buffer %frc-stream%))
(%frc-index% (lisp-stream-in-index %frc-stream%)))
(declare (type index %frc-index%)
(type lisp-stream %frc-stream%))
,@forms))
;;; Fast-Read-Byte, Done-With-Fast-Read-Byte -- Internal
;;;
;;; Similar to fast-read-char, but we use a different refill routine & don't
;;; convert to characters. If ANY-TYPE is true, then this can be used on any
;;; integer streams, and we don't assert the result type.
;;;
(defmacro fast-read-byte (&optional (eof-errorp t) (eof-value ()) any-type)
`(truly-the
,(if (and (eq eof-errorp 't) (not any-type)) '(unsigned-byte 8) 't)
(cond
((or (not %frc-buffer%) (/= (lisp-stream-flags %frc-stream%) #b10))
;; Call the method if we're doing a read-byte on a stream that
;; is has no in-buffer (a binary-text-stream) or is not a
;; binary stream (flags /= #b10).
(funcall %frc-method% %frc-stream% ,eof-errorp ,eof-value))
((= %frc-index% in-buffer-length)
(prog1 (fast-read-byte-refill %frc-stream% ,eof-errorp ,eof-value)
(setq %frc-index% (lisp-stream-in-index %frc-stream%))))
(t
(prog1 (aref %frc-buffer% %frc-index%)
(incf %frc-index%))))))
;;;
(defmacro done-with-fast-read-byte ()
`(progn
(setf (lisp-stream-in-index %frc-stream%) %frc-index%)))
| 3,002
|
https://github.com/elsayed85/medical_iot/blob/master/resources/views/layouts/user.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
medical_iot
|
elsayed85
|
PHP
|
Code
| 1,031
| 4,172
|
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- Tell the browser to be responsive to screen width -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<style>
span.logo-text {
color: #fff;
font-size: 29px;
font-weight: bold;
font-family: sans-serif;
position: relative;
top: 6px;
text-shadow: 0px 2px 5px #e74424;
}
</style>
<!-- Favicon icon -->
<link rel="icon" type="image/png" sizes="16x16" href="/assets/favicon.png">
<title>@yield('title')</title>
@yield('css')
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- ============================================================== -->
<!-- Preloader - style you can find in spinners.css -->
<!-- ============================================================== -->
<div class="preloader">
<div class="lds-ripple">
<div class="lds-pos"></div>
<div class="lds-pos"></div>
</div>
</div>
<!-- ============================================================== -->
<!-- Main wrapper - style you can find in pages.scss -->
<!-- ============================================================== -->
<div id="main-wrapper">
<header class="topbar">
<nav class="navbar top-navbar navbar-expand-md navbar-dark">
<div class="navbar-header">
<!-- This is for the sidebar toggle which is visible on mobile only -->
<a class="nav-toggler waves-effect waves-light d-block d-md-none" href="javascript:void(0)"><i class="ti-menu ti-close"></i></a>
<!-- ============================================================== -->
<!-- Logo -->
<!-- ============================================================== -->
<a class="navbar-brand" href="{{route('home')}}" style="display: block;
width: 100%;">
<!-- Logo icon -->
<b class="logo-icon">
<!--You can put here icon as well // <i class="wi wi-sunset"></i> //-->
<!-- Dark Logo icon -->
<!-- Light Logo icon -->
<img src="https://image.flaticon.com/icons/svg/119/119058.svg" alt="homepage" class="light-logo" style="width: 48px;" />
</b>
<!--End Logo icon -->
<!-- Logo text -->
</a>
<!-- ============================================================== -->
<!-- End Logo -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Toggle which is visible on mobile only -->
<!-- ============================================================== -->
<a class="topbartoggler d-block d-md-none waves-effect waves-light" href="javascript:void(0)" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"><i class="ti-more"></i></a>
</div>
<!-- ============================================================== -->
<!-- End Logo -->
<!-- ============================================================== -->
<div class="navbar-collapse collapse" id="navbarSupportedContent">
<!-- ============================================================== -->
<!-- toggle and nav items -->
<!-- ============================================================== -->
<ul class="navbar-nav float-left mr-auto">
<li class="nav-item d-none d-md-block"><a class="nav-link sidebartoggler waves-effect waves-light" href="javascript:void(0)" data-sidebartype="mini-sidebar"><i class="mdi mdi-menu font-24"></i></a></li>
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- Search -->
<!-- ============================================================== -->
<li class="nav-item search-box"> <a class="nav-link waves-effect waves-dark" href="javascript:void(0)"><i class="ti-search"></i></a>
<form class="app-search position-absolute" action="{{route("search")}}" method="GET">
<input type="text" name="name" class="form-control" placeholder="Search & enter"> <a class="srh-btn"><i class="ti-close"></i></a>
</form>
</li>
</ul>
<!-- ============================================================== -->
<!-- Right side toggle and nav items -->
<!-- ============================================================== -->
<ul class="navbar-nav float-right">
<!-- ============================================================== -->
<!-- create new -->
<!-- Comment -->
<!-- ============================================================== -->
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle waves-effect waves-dark" href="" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="mdi mdi-bell font-24"></i>
</a>
<div class="dropdown-menu dropdown-menu-right mailbox animated bounceInDown">
<span class="with-arrow"><span class="bg-primary"></span></span>
<ul class="list-style-none">
<li>
<div class="drop-title bg-primary text-white">
<h4 class="m-b-0 m-t-5">{{count(Auth::user()->families)}} New</h4>
<span class="font-light">Family</span>
</div>
</li>
<li>
<div class="message-center notifications">
@foreach (Auth::user()->families as $mem)
<a href="javascript:void(0)" class="message-item">
<span class="btn btn-primary btn-circle">
@if($mem->user->geneder == 'male')
<i class="icon-user"></i>
@else
<i class="icon-user-female"></i>
@endif
</span>
<span class="mail-contnet">
<h5 class="message-title">{{$mem->user->name}}</h5>
@if(count($mem->user->lastBpm($mem->user->id)))
<span class="mail-desc">my last Bpm is {{$mem->user->lastBpm($mem->user->id)['bpm']}}</span>
<span class="time">{{$mem->user->lastBpm($mem->user->id)['created_at']->diffforhumans()}}</span>
@endif
</span>
</a>
@endforeach
</div>
</li>
<li>
<a class="nav-link text-center m-b-5" href="{{route('family')}}"> <strong>Check all Family</strong> <i class="fa fa-angle-right"></i> </a>
</li>
</ul>
</div>
</li>
<!-- ============================================================== -->
<!-- End Comment -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- ============================================================== -->
<!-- User profile and search -->
<!-- ============================================================== -->
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle text-muted waves-effect waves-dark pro-pic" href="" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<img src="{{Auth::user()->avatar != null ? Auth::user()->avatar : "https://ui-avatars.com/api/?size=500&name=" . Auth::user()->name}}" alt="user" class="rounded-circle" width="31">
</a>
<div class="dropdown-menu dropdown-menu-right user-dd animated flipInY">
<span class="with-arrow"><span class="bg-primary"></span></span>
<div class="d-flex no-block align-items-center p-15 bg-primary text-white m-b-10">
<div class=""><img src="{{Auth::user()->avatar != null ? Auth::user()->avatar : "https://ui-avatars.com/api/?size=500&name=" . Auth::user()->name}}" alt="user" class="rounded-circle" width="60"></div>
<div class="m-l-10">
<h4 class="m-b-0">{{Auth::user()->name}}</h4>
<p class=" m-b-0">{{Auth::user()->email}}</p>
</div>
</div>
<a class="dropdown-item" href="{{ route('user_profile') }}"><i class="ti-user m-r-5 m-l-5"></i> My Profile</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{{route("logout")}}"><i class="fa fa-power-off m-r-5 m-l-5"></i> Logout</a>
</div>
</li>
<!-- ============================================================== -->
<!-- User profile and search -->
<!-- ============================================================== -->
</ul>
</div>
</nav>
</header>
<aside class="left-sidebar">
<!-- Sidebar scroll-->
<div class="scroll-sidebar">
<!-- Sidebar navigation-->
<nav class="sidebar-nav">
<ul id="sidebarnav">
<!-- User Profile-->
<li>
<!-- User Profile-->
<div class="user-profile d-flex no-block dropdown mt-3">
<div class="user-pic"><img src="{{Auth::user()->avatar != null ? Auth::user()->avatar : "https://ui-avatars.com/api/?size=500&name=" . Auth::user()->name}}" alt="users" class="rounded-circle" width="40" /></div>
<div class="user-content hide-menu ml-2">
<a href="javascript:void(0)" class="" id="Userdd" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<h5 class="mb-0 user-name font-medium">{{Auth::user()->name}} <i class="fa fa-angle-down"></i></h5>
<span class="op-5 user-email">{{Auth::user()->email}}</span>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="Userdd">
<a class="dropdown-item" href="{{ route('user_profile') }}"><i class="ti-user mr-1 ml-1"></i> My Profile</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="{{route("logout")}}"><i class="fa fa-power-off mr-1 ml-1"></i> Logout</a>
</div>
</div>
</div>
<!-- End User Profile-->
</li>
<li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{{route('home')}}" aria-expanded="false"><i class="fas fa-home"></i><span class="hide-menu">home</span></a></li>
<li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{{route('user_profile')}}" aria-expanded="false"><i class="fas fa-user-circle"></i><span class="hide-menu">profile</span></a></li>
<li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{{route('heartModel')}}" aria-expanded="false"><i class="fas fa-heartbeat"></i><span class="hide-menu">My heart model</span></a></li>
<li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{{route("family")}}" aria-expanded="false"><i class="fas fa-users"></i><span class="hide-menu">my family</span></a></li>
<li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{{route("doctor.index")}}" aria-expanded="false"><i class="fas fa-user-md"></i><span class="hide-menu">my Doctors</span></a></li>
<li class="nav-small-cap"><i class="mdi mdi-dots-horizontal"></i> <span class="hide-menu">Api</span></li>
<li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{{route('user_api')}}" aria-expanded="false"><i class="mdi mdi-content-paste"></i><span class="hide-menu">API</span></a></li>
<li class="sidebar-item"> <a class="sidebar-link waves-effect waves-dark sidebar-link" href="{{route("logout")}}" aria-expanded="false"><i class="mdi mdi-directions"></i><span class="hide-menu">Log Out</span></a></li>
</ul>
</nav>
<!-- End Sidebar navigation -->
</div>
<!-- End Sidebar scroll-->
</aside>
@yield('main')
</div>
<div class="chat-windows"></div>
<!-- ============================================================== -->
<!-- All Jquery -->
<!-- ============================================================== -->
<script src="/assets/libs/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap tether Core JavaScript -->
<script src="/assets/libs/popper.js/dist/umd/popper.min.js"></script>
<script src="/assets/libs/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- apps -->
<script src="/dist/js/app.min.js"></script>
<!-- minisidebar -->
<script>
$(function() {
"use strict";
$("#main-wrapper").AdminSettings({
Theme: false, // this can be true or false ( true means dark and false means light ),
Layout: 'vertical',
LogoBg: 'skin1', // You can change the Value to be skin1/skin2/skin3/skin4/skin5/skin6
NavbarBg: 'skin6', // You can change the Value to be skin1/skin2/skin3/skin4/skin5/skin6
SidebarType: 'mini-sidebar', // You can change it full / mini-sidebar / iconbar / overlay
SidebarColor: 'skin1', // You can change the Value to be skin1/skin2/skin3/skin4/skin5/skin6
SidebarPosition: false, // it can be true / false ( true means Fixed and false means absolute )
HeaderPosition: false, // it can be true / false ( true means Fixed and false means absolute )
BoxedLayout: false, // it can be true / false ( true means Boxed and false means Fluid )
});
});
</script>
<script src="/dist/js/app-style-switcher.js"></script>
<!-- slimscrollbar scrollbar JavaScript -->
<script src="/assets/libs/perfect-scrollbar/dist/perfect-scrollbar.jquery.min.js"></script>
<!--Wave Effects -->
<script src="/dist/js/waves.js"></script>
<!--Menu sidebar -->
<script src="/dist/js/sidebarmenu.js"></script>
<!--Custom JavaScript -->
<script src="/dist/js/custom.min.js"></script>
@yield('js')
</body>
</html>
| 553
|
https://github.com/leeonky/DAL-java/blob/master/src/test/java/com/github/leeonky/dal/format/ComparatorTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
DAL-java
|
leeonky
|
Java
|
Code
| 54
| 449
|
package com.github.leeonky.dal.format;
import org.junit.jupiter.api.Test;
import static com.github.leeonky.util.function.Comparator.*;
import static org.assertj.core.api.Assertions.assertThat;
class ComparatorTest {
@Test
void less_than() {
assertThat(lessThan(1).compareTo(0)).isTrue();
assertThat(lessThan("A").compareTo("B")).isFalse();
assertThat(lessThan(1.0).compareTo(1.0)).isFalse();
}
@Test
void greater_than() {
assertThat(greaterThan(1).compareTo(0)).isFalse();
assertThat(greaterThan("A").compareTo("B")).isTrue();
assertThat(greaterThan(1.0).compareTo(1.0)).isFalse();
}
@Test
void less_or_equal_to() {
assertThat(lessOrEqualTo(1).compareTo(0)).isTrue();
assertThat(lessOrEqualTo("A").compareTo("B")).isFalse();
assertThat(lessOrEqualTo(1.0).compareTo(1.0)).isTrue();
}
@Test
void greater_or_equal_to() {
assertThat(greaterOrEqualTo(1).compareTo(0)).isFalse();
assertThat(greaterOrEqualTo("A").compareTo("B")).isTrue();
assertThat(greaterOrEqualTo(1.0).compareTo(1.0)).isTrue();
}
@Test
void equal_to() {
assertThat(equalTo(1).compareTo(0)).isFalse();
assertThat(equalTo("A").compareTo("B")).isFalse();
assertThat(equalTo(1.0).compareTo(1.0)).isTrue();
}
}
| 9,840
|
https://github.com/adam-bates/wikisearch/blob/master/src/main/java/com/adambates/wikisearch/search/factories/DirectoryFactory.java
|
Github Open Source
|
Open Source
|
MIT
| null |
wikisearch
|
adam-bates
|
Java
|
Code
| 41
| 203
|
package com.adambates.wikisearch.search.factories;
import lombok.SneakyThrows;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.MMapDirectory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.nio.file.Paths;
@Component
public class DirectoryFactory {
private final String searchIndexesDir;
DirectoryFactory(@Value("${search.indexes.dir}") final String searchIndexesDir) {
this.searchIndexesDir = searchIndexesDir;
}
@SneakyThrows
public FSDirectory createDirectory() {
return MMapDirectory.open(Paths.get(searchIndexesDir));
}
}
| 30,410
|
https://github.com/ZhuoZhuoCrayon/bk-sops/blob/master/gcloud/tests/taskflow3/test_api.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
bk-sops
|
ZhuoZhuoCrayon
|
Python
|
Code
| 483
| 2,098
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from copy import deepcopy
from django.test import TestCase, Client
from pipeline.utils.uniqid import node_uniqid
from gcloud.tests.mock import * # noqa
from gcloud.tests.mock_settings import * # noqa
from gcloud.taskflow3 import api
TEST_PROJECT_ID = '2' # do not change this to non number
TEST_ID_LIST = [node_uniqid() for i in range(10)]
TEST_PIPELINE_TREE = {
'id': TEST_ID_LIST[0],
'name': 'name',
'start_event': {
'id': TEST_ID_LIST[1],
'name': 'start',
'type': 'EmptyStartEvent',
'incoming': None,
'outgoing': TEST_ID_LIST[5]
},
'end_event': {
'id': TEST_ID_LIST[2],
'name': 'end',
'type': 'EmptyEndEvent',
'incoming': TEST_ID_LIST[7],
'outgoing': None
},
'activities': {
TEST_ID_LIST[3]: {
'id': TEST_ID_LIST[3],
'type': 'ServiceActivity',
'name': 'first_task',
'incoming': TEST_ID_LIST[5],
'outgoing': TEST_ID_LIST[6],
'optional': True,
'component': {
'code': 'test',
'data': {
'input_test': {
'hook': False,
'value': '${custom_key1}',
},
'radio_test': {
'hook': False,
'value': '1',
},
},
}
},
TEST_ID_LIST[4]: {
'id': TEST_ID_LIST[4],
'type': 'ServiceActivity',
'name': 'first_task',
'incoming': TEST_ID_LIST[6],
'outgoing': TEST_ID_LIST[7],
'optional': True,
'component': {
'code': 'test',
'data': {
'input_test': {
'hook': True,
'value': '${custom_key2}'
},
'radio_test': {
'hook': False,
'value': '2'
},
},
}
},
},
'flows': { # 存放该 Pipeline 中所有的线
TEST_ID_LIST[5]: {
'id': TEST_ID_LIST[5],
'source': TEST_ID_LIST[1],
'target': TEST_ID_LIST[3]
},
TEST_ID_LIST[6]: {
'id': TEST_ID_LIST[6],
'source': TEST_ID_LIST[3],
'target': TEST_ID_LIST[4]
},
TEST_ID_LIST[7]: {
'id': TEST_ID_LIST[7],
'source': TEST_ID_LIST[4],
'target': TEST_ID_LIST[2]
},
},
'gateways': { # 这里存放着网关的详细信息
},
'constants': {
'${custom_key1}': {
'index': 0,
'name': 'input1',
'key': '${custom_key1}',
'desc': '',
'validation': '^.*$',
'show_type': 'show',
'value': 'value1',
'source_type': 'custom',
'source_tag': '',
'source_info': {},
'custom_type': 'input',
},
'${custom_key2}': {
'index': 1,
'name': 'input2',
'key': '${custom_key2}',
'desc': '',
'validation': '^.*$',
'show_type': 'show',
'value': 'value1',
'source_type': 'custom',
'source_tag': '',
'source_info': {},
'custom_type': 'input',
},
},
'outputs': ['${custom_key1}'],
}
class APITest(TestCase):
def setUp(self):
self.PREVIEW_TASK_TREE_URL = '/taskflow/api/preview_task_tree/{biz_cc_id}/'
self.client = Client()
@mock.patch('gcloud.taskflow3.api.JsonResponse', MockJsonResponse())
def test_preview_task_tree__constants_not_referred(self):
with mock.patch(TASKTEMPLATE_GET,
MagicMock(return_value=MockBaseTemplate(id=1, pipeline_tree=deepcopy(TEST_PIPELINE_TREE)))):
data1 = {
'template_source': 'project',
'template_id': 1,
'version': 'test_version',
'exclude_task_nodes_id': '["%s"]' % TEST_ID_LIST[3]
}
result = api.preview_task_tree(MockRequest('POST', data1), TEST_PROJECT_ID)
self.assertTrue(result['result'])
self.assertEqual(list(result['data']['constants_not_referred'].keys()), ['${custom_key1}'])
with mock.patch(TASKTEMPLATE_GET,
MagicMock(return_value=MockBaseTemplate(id=1, pipeline_tree=deepcopy(TEST_PIPELINE_TREE)))):
data2 = {
'template_source': 'project',
'template_id': 1,
'version': 'test_version',
'exclude_task_nodes_id': '["%s"]' % TEST_ID_LIST[4]
}
result = api.preview_task_tree(MockRequest('POST', data2), TEST_PROJECT_ID)
self.assertTrue(result['result'])
self.assertEqual(list(result['data']['constants_not_referred'].keys()), ['${custom_key2}'])
with mock.patch(TASKTEMPLATE_GET,
MagicMock(return_value=MockBaseTemplate(id=1, pipeline_tree=deepcopy(TEST_PIPELINE_TREE)))):
data3 = {
'template_source': 'project',
'template_id': 1,
'version': 'test_version',
'exclude_task_nodes_id': '[]'
}
result = api.preview_task_tree(MockRequest('POST', data3), TEST_PROJECT_ID)
self.assertTrue(result['result'])
self.assertEqual(list(result['data']['constants_not_referred'].keys()), [])
with mock.patch(TASKTEMPLATE_GET,
MagicMock(return_value=MockBaseTemplate(id=1, pipeline_tree=deepcopy(TEST_PIPELINE_TREE)))):
data4 = {
'template_source': 'project',
'template_id': 1,
'version': 'test_version',
'exclude_task_nodes_id': '["%s", "%s"]' % (TEST_ID_LIST[3], TEST_ID_LIST[4])
}
result = api.preview_task_tree(MockRequest('POST', data4), TEST_PROJECT_ID)
self.assertTrue(result['result'])
self.assertEqual(list(result['data']['constants_not_referred'].keys()),
['${custom_key1}', '${custom_key2}'])
| 7,515
|
https://github.com/bernhard-buss/payload-plugin-cloud-storage/blob/master/src/collection/readHook.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
payload-plugin-cloud-storage
|
bernhard-buss
|
TypeScript
|
Code
| 82
| 230
|
import { CollectionAfterReadHook } from 'payload/types'
import type { AdapterInterface } from '../adapter.d'
const readHook = (adapter: AdapterInterface<unknown, unknown>, propertyName: string) => {
const afterReadHook: CollectionAfterReadHook = async ({ doc }) => {
if (typeof doc.filename === 'string') {
doc[propertyName] = adapter.getEndpointUrl(doc.filename)
}
if (typeof doc.sizes === 'object' && doc.sizes !== null && !Array.isArray(doc.sizes)) {
for (const i in doc.sizes) {
if (typeof doc.sizes[i].filename === 'string') {
doc.sizes[i][propertyName] = adapter.getEndpointUrl(doc.sizes[i].filename)
}
}
}
return doc
}
return afterReadHook
}
export default readHook
| 11,153
|
https://github.com/NeuroRoboticTech/AnimatLabPublicSource/blob/master/Libraries/AnimatGUI/DataObjects/ExternalStimuli/PropertyControlStimulus.vb
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
AnimatLabPublicSource
|
NeuroRoboticTech
|
Visual Basic
|
Code
| 1,420
| 5,138
|
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Diagnostics
Imports System.IO
Imports System.Xml
Imports AnimatGuiCtrls.Controls
Imports AnimatGUI.Framework
Namespace DataObjects.ExternalStimuli
Public Class PropertyControlStimulus
Inherits AnimatGUI.DataObjects.ExternalStimuli.Stimulus
#Region " Attributes "
Protected m_thLinkedObject As AnimatGUI.TypeHelpers.LinkedDataObjectTree
Protected m_thLinkedProperty As AnimatGUI.TypeHelpers.LinkedDataObjectPropertiesList
Protected m_fltSetThreshold As Single = 0.5
Protected m_fltInitialValue As Single = 0
Protected m_fltFinalValue As Single = 1
Protected m_fltStimulusValue As Single = 1
'Only used during loading
Protected m_strLinkedObjectID As String = ""
Protected m_strLinkedObjectProperty As String = ""
#End Region
#Region " Properties "
<Browsable(False)> _
Public Overrides Property StimulatedItem() As Framework.DataObject
Get
Return m_doStimulatedItem
End Get
Set(value As Framework.DataObject)
DisconnectItemEvents()
m_doStimulatedItem = value
Me.LinkedObject = New TypeHelpers.LinkedDataObjectTree(value)
Me.LinkedProperty = New TypeHelpers.LinkedDataObjectPropertiesList(value, False, True)
ConnectItemEvents()
End Set
End Property
<Browsable(False)> _
Public Overridable Property LinkedObject() As AnimatGUI.TypeHelpers.LinkedDataObjectTree
Get
Return m_thLinkedObject
End Get
Set(ByVal Value As AnimatGUI.TypeHelpers.LinkedDataObjectTree)
If Not Value Is Nothing AndAlso Not Value.Item Is Nothing Then
SetSimData("TargetID", Value.Item.ID, True)
Else
SetSimData("TargetID", "", True)
End If
m_thLinkedObject = Value
If Not m_thLinkedObject Is Nothing AndAlso Not m_thLinkedObject.Item Is m_doStimulatedItem Then
m_thLinkedProperty = New TypeHelpers.LinkedDataObjectPropertiesList(Nothing, False, True)
Me.StimulatedItem = m_thLinkedObject.Item
End If
End Set
End Property
<Browsable(False)> _
Public Overrides Property PhysicalStructure() As DataObjects.Physical.PhysicalStructure
Get
If Not m_thLinkedObject Is Nothing AndAlso Not m_thLinkedObject.Item Is Nothing Then
If Util.IsTypeOf(m_thLinkedObject.Item.GetType(), GetType(DataObjects.Physical.BodyPart), False) Then
Dim bpPart As DataObjects.Physical.BodyPart = DirectCast(m_thLinkedObject.Item, DataObjects.Physical.BodyPart)
Return bpPart.ParentStructure
ElseIf Util.IsTypeOf(m_thLinkedObject.Item.GetType(), GetType(DataObjects.Behavior.Node), False) Then
Dim bpPart As DataObjects.Behavior.Node = DirectCast(m_thLinkedObject.Item, DataObjects.Behavior.Node)
Return bpPart.Organism
ElseIf Util.IsTypeOf(m_thLinkedObject.Item.GetType(), GetType(DataObjects.Physical.PhysicalStructure), False) Then
Dim bpPart As DataObjects.Physical.PhysicalStructure = DirectCast(m_thLinkedObject.Item, DataObjects.Physical.PhysicalStructure)
Return bpPart
End If
End If
Return Nothing
End Get
Set(ByVal Value As DataObjects.Physical.PhysicalStructure)
End Set
End Property
<Browsable(False)> _
Public Overridable Property LinkedProperty() As AnimatGUI.TypeHelpers.LinkedDataObjectPropertiesList
Get
Return m_thLinkedProperty
End Get
Set(ByVal Value As AnimatGUI.TypeHelpers.LinkedDataObjectPropertiesList)
If Not Value Is Nothing AndAlso Not Value.Item Is Nothing AndAlso Not Value.PropertyName Is Nothing Then
SetSimData("PropertyName", Value.PropertyName, True)
Else
SetSimData("PropertyName", "", True)
End If
m_thLinkedProperty = Value
End Set
End Property
<Browsable(False)> _
Public Overridable Property LinkedPropertyName() As String
Get
If Not m_thLinkedProperty Is Nothing AndAlso Not m_thLinkedProperty.PropertyName Is Nothing Then
Return m_thLinkedProperty.PropertyName
Else
Return ""
End If
End Get
Set(value As String)
If m_thLinkedObject Is Nothing OrElse m_thLinkedObject.Item Is Nothing Then
Throw New System.Exception("You cannot set the linked object property name until the linked object is set.")
End If
Me.LinkedProperty = New TypeHelpers.LinkedDataObjectPropertiesList(m_thLinkedObject.Item, value, False, True)
End Set
End Property
<Browsable(False)> _
Public Overridable Property SetThreshold() As Single
Get
Return m_fltSetThreshold
End Get
Set(ByVal Value As Single)
If Value < 0 Then
Throw New System.Exception("Set threshold value must be greater than 0.")
End If
SetSimData("SetThreshold", Value.ToString, True)
m_fltSetThreshold = Value
End Set
End Property
<Browsable(False)> _
Public Overridable Property InitialValue() As Single
Get
Return m_fltInitialValue
End Get
Set(ByVal Value As Single)
SetSimData("InitialValue", Value.ToString, True)
m_fltInitialValue = Value
End Set
End Property
<Browsable(False)> _
Public Overridable Property FinalValue() As Single
Get
Return m_fltFinalValue
End Get
Set(ByVal Value As Single)
SetSimData("FinalValue", Value.ToString, True)
m_fltFinalValue = Value
End Set
End Property
Public Overridable Property StimulusValue() As Single
Get
Return m_fltStimulusValue
End Get
Set(ByVal Value As Single)
SetStimulusValue(Value.ToString)
m_fltStimulusValue = Value
End Set
End Property
Public Overrides Property ValueType() As enumValueType
Get
Return m_eValueType
End Get
Set(ByVal Value As enumValueType)
m_eValueType = Value
SetSimData("ValueType", Value.ToString, True)
SetStimulusValue()
If Not Util.ProjectWorkspace Is Nothing Then
Util.ProjectWorkspace.RefreshProperties()
End If
End Set
End Property
Public Overrides Property Equation() As String
Get
Return m_strEquation
End Get
Set(ByVal Value As String)
If Value.Trim.Length = 0 Then
Throw New System.Exception("Equation cannot be blank.")
End If
SetStimulusValue(Value)
m_strEquation = Value
End Set
End Property
Public Overrides ReadOnly Property TypeName() As String
Get
Return "Property Control"
End Get
End Property
Public Overrides ReadOnly Property WorkspaceImageName() As String
Get
Return "AnimatGUI.EnablerStimulus_Small.gif"
End Get
End Property
Public Overrides Property Description() As String
Get
Return "This stimulus can set any property of any object within the system."
End Get
Set(value As String)
End Set
End Property
Public Overrides ReadOnly Property StimulusClassType() As String
Get
Return "PropertyControlStimulus"
End Get
End Property
Public Overrides ReadOnly Property DragImageName() As String
Get
Return "AnimatGUI.EnablerStimulus_Small.gif"
End Get
End Property
#End Region
#Region " Methods "
Public Sub New(ByVal doParent As AnimatGUI.Framework.DataObject)
MyBase.New(doParent)
m_thLinkedObject = New AnimatGUI.TypeHelpers.LinkedDataObjectTree(Nothing)
m_thLinkedProperty = New AnimatGUI.TypeHelpers.LinkedDataObjectPropertiesList(Nothing, False, True)
End Sub
Protected Overrides Sub SetSimEquation(ByVal strEquation As String)
If strEquation.Trim.Length > 0 Then
'Lets verify the equation before we use it.
'We need to convert the infix equation to postfix
Dim oMathEval As New MathStringEval
oMathEval.AddVariable("t")
oMathEval.Equation = strEquation
oMathEval.Parse()
SetSimData("Equation", oMathEval.PostFix, True)
Else
SetSimData("Equation", "0", True)
End If
End Sub
Protected Sub SetStimulusValue(Optional ByVal strEquation As String = "")
If m_eValueType = enumValueType.Constant Then
If strEquation.Trim.Length = 0 Then strEquation = Me.StimulusValue.ToString
SetSimData("Equation", strEquation, True)
Else
If strEquation.Trim.Length = 0 Then strEquation = Me.Equation
SetSimEquation(strEquation)
End If
End Sub
Protected Overrides Sub CloneInternal(ByVal doOriginal As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _
ByVal doRoot As AnimatGUI.Framework.DataObject)
MyBase.CloneInternal(doOriginal, bCutData, doRoot)
Dim bpPart As DataObjects.ExternalStimuli.PropertyControlStimulus = DirectCast(doOriginal, DataObjects.ExternalStimuli.PropertyControlStimulus)
bpPart.m_thLinkedObject = DirectCast(m_thLinkedObject.Clone(Me, bCutData, doRoot), TypeHelpers.LinkedDataObjectTree)
bpPart.m_thLinkedProperty = DirectCast(m_thLinkedProperty.Clone(Me, bCutData, doRoot), TypeHelpers.LinkedDataObjectPropertiesList)
bpPart.m_fltSetThreshold = m_fltSetThreshold
bpPart.m_fltInitialValue = m_fltInitialValue
bpPart.m_fltFinalValue = m_fltFinalValue
bpPart.m_fltStimulusValue = m_fltStimulusValue
End Sub
Public Overrides Function Clone(ByVal doParent As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _
ByVal doRoot As AnimatGUI.Framework.DataObject) As AnimatGUI.Framework.DataObject
Dim doStim As DataObjects.ExternalStimuli.PropertyControlStimulus = New DataObjects.ExternalStimuli.PropertyControlStimulus(doParent)
CloneInternal(doStim, bCutData, doRoot)
If Not doRoot Is Nothing AndAlso doRoot Is Me Then doStim.AfterClone(Me, bCutData, doRoot, doStim)
Return doStim
End Function
Public Overrides Function GetSimulationXml(ByVal strName As String, Optional ByRef nmParentControl As AnimatGUI.Framework.DataObject = Nothing) As String
If m_thLinkedObject Is Nothing OrElse m_thLinkedObject.Item Is Nothing Then
Throw New System.Exception("No target object was defined for the stimulus '" & m_strName & "'.")
End If
Dim oXml As ManagedAnimatInterfaces.IStdXml = Util.Application.CreateStdXml()
oXml.AddElement("Root")
SaveSimulationXml(oXml, nmParentControl, strName)
Return oXml.Serialize()
End Function
Public Overrides Sub InitializeAfterLoad()
MyBase.InitializeAfterLoad()
If m_strLinkedObjectID.Trim.Length > 0 Then
Me.StimulatedItem = Util.Simulation.FindObjectByID(m_strLinkedObjectID)
Me.LinkedProperty = New TypeHelpers.LinkedDataObjectPropertiesList(Me.StimulatedItem, m_strLinkedObjectProperty, False, True)
End If
End Sub
Public Overrides Sub SaveSimulationXml(ByVal oXml As ManagedAnimatInterfaces.IStdXml, Optional ByRef nmParentControl As AnimatGUI.Framework.DataObject = Nothing, Optional ByVal strName As String = "")
If m_thLinkedObject Is Nothing OrElse m_thLinkedObject.Item Is Nothing Then
Throw New System.Exception("No target object was defined for the stimulus '" & m_strName & "'.")
End If
oXml.AddChildElement("Stimulus")
oXml.IntoElem()
oXml.AddChildElement("ID", m_strID)
oXml.AddChildElement("Name", m_strName)
oXml.AddChildElement("AlwaysActive", m_bAlwaysActive)
oXml.AddChildElement("Enabled", m_bEnabled)
oXml.AddChildElement("ModuleName", Me.StimulusModuleName)
oXml.AddChildElement("Type", Me.StimulusClassType)
oXml.AddChildElement("TargetID", Me.LinkedObject.Item.ID)
oXml.AddChildElement("PropertyName", Me.LinkedPropertyName)
oXml.AddChildElement("SetThreshold", Me.SetThreshold)
oXml.AddChildElement("InitialValue", Me.InitialValue)
oXml.AddChildElement("FinalValue", Me.FinalValue)
oXml.AddChildElement("StartTime", m_snStartTime.ActualValue)
oXml.AddChildElement("EndTime", m_snEndTime.ActualValue)
If m_eValueType = enumValueType.Constant Then
oXml.AddChildElement("Equation", m_fltStimulusValue)
Else
'We need to convert the infix equation to postfix
Dim oMathEval As New MathStringEval
oMathEval.AddVariable("t")
oMathEval.Equation = m_strEquation
oMathEval.Parse()
oXml.AddChildElement("Equation", oMathEval.PostFix)
End If
oXml.OutOfElem()
End Sub
Public Overrides Sub Automation_SetLinkedItem(ByVal strItemPath As String, ByVal strLinkedItemPath As String)
Dim tnLinkedNode As Crownwood.DotNetMagic.Controls.Node = Util.FindTreeNodeByPath(strLinkedItemPath, Util.ProjectWorkspace.TreeView.Nodes)
If tnLinkedNode Is Nothing OrElse tnLinkedNode.Tag Is Nothing OrElse Not Util.IsTypeOf(tnLinkedNode.Tag.GetType, GetType(Framework.DataObject), False) Then
Throw New System.Exception("The path to the specified linked node was not the correct node type.")
End If
Dim doLinkedObject As Framework.DataObject = DirectCast(tnLinkedNode.Tag, Framework.DataObject)
Me.LinkedObject = New TypeHelpers.LinkedDataObjectTree(doLinkedObject)
Util.ProjectWorkspace.RefreshProperties()
End Sub
#Region " DataObject Methods "
Public Overrides Sub BuildProperties(ByRef propTable As AnimatGuiCtrls.Controls.PropertyTable)
MyBase.BuildProperties(propTable)
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Linked Object", GetType(AnimatGUI.TypeHelpers.LinkedDataObjectTree), "LinkedObject", _
"Stimulus Properties", "Sets the object that is associated with this connector.", m_thLinkedObject, _
GetType(AnimatGUI.TypeHelpers.DropDownTreeEditor), _
GetType(AnimatGUI.TypeHelpers.LinkedDataObjectTypeConverter)))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Linked Property", GetType(AnimatGUI.TypeHelpers.LinkedDataObjectPropertiesList), "LinkedProperty", _
"Stimulus Properties", "Determines the property that is set by this controller.", m_thLinkedProperty, _
GetType(AnimatGUI.TypeHelpers.DropDownListEditor), _
GetType(AnimatGUI.TypeHelpers.LinkedDataObjectPropertiesTypeConverter)))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Set Threshold", m_fltSetThreshold.GetType(), "SetThreshold", _
"Stimulus Properties", "Threshold at which the property value will be set. This is the difference between the current value and value when it was last set", Me.SetThreshold))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Start Value", m_fltInitialValue.GetType(), "InitialValue", _
"Stimulus Properties", "Initial value the property control will set for the property when simulation starts", Me.InitialValue))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("End Value", m_fltFinalValue.GetType(), "FinalValue", _
"Stimulus Properties", "Final value the property control will set for the property when simulation ends", Me.FinalValue))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Value Type", m_eValueType.GetType(), "ValueType", _
"Stimulus Properties", "Determines if a constant or an equation is used to set the object property value.", m_eValueType))
If m_eValueType = enumValueType.Equation Then
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Equation", m_strEquation.GetType(), "Equation", _
"Stimulus Properties", "If setup to use equations, then this is the one used.", m_strEquation))
Else
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Stimulus Value", m_fltStimulusValue.GetType(), "StimulusValue", _
"Stimulus Properties", "If setup to use constant, then this is the one used.", m_fltStimulusValue))
End If
End Sub
Public Overrides Sub LoadData(ByVal oXml As ManagedAnimatInterfaces.IStdXml)
MyBase.LoadData(oXml)
oXml.IntoElem()
m_strLinkedObjectID = oXml.GetChildString("LinkedDataObjectID", "")
m_strLinkedObjectProperty = oXml.GetChildString("LinkedDataObjectProperty", "")
m_fltSetThreshold = oXml.GetChildFloat("SetThreshold", m_fltSetThreshold)
m_fltInitialValue = oXml.GetChildFloat("InitialValue", m_fltInitialValue)
m_fltFinalValue = oXml.GetChildFloat("FinalValue", m_fltFinalValue)
m_fltStimulusValue = oXml.GetChildFloat("StimulusValue", m_fltStimulusValue)
oXml.OutOfElem()
Me.IsDirty = False
End Sub
Public Overrides Sub SaveData(ByVal oXml As ManagedAnimatInterfaces.IStdXml)
MyBase.SaveData(oXml)
oXml.IntoElem()
If Not m_thLinkedObject Is Nothing AndAlso Not m_thLinkedObject.Item Is Nothing Then
oXml.AddChildElement("LinkedDataObjectID", m_thLinkedObject.Item.ID)
oXml.AddChildElement("LinkedDataObjectProperty", Me.LinkedPropertyName)
End If
oXml.AddChildElement("SetThreshold", m_fltSetThreshold)
oXml.AddChildElement("InitialValue", m_fltInitialValue)
oXml.AddChildElement("FinalValue", m_fltFinalValue)
oXml.AddChildElement("StimulusValue", m_fltStimulusValue)
oXml.OutOfElem() ' Outof Node Element
End Sub
#End Region
#End Region
End Class
End Namespace
| 37,391
|
https://github.com/rachitmishra/define/blob/master/app/src/main/java/in/ceeq/define/data/source/DefinitionDataSource.kt
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
define
|
rachitmishra
|
Kotlin
|
Code
| 12
| 50
|
package `in`.ceeq.define.data.source
import `in`.ceeq.define.data.entity.Definition
interface DefinitionDataSource {
fun getDefinition(phrase: String): Definition
}
| 11,489
|
https://github.com/midopple/infidel-sensor/blob/master/electrical/smt/gerber/filaSens.GTS
|
Github Open Source
|
Open Source
|
CC0-1.0
| 2,021
|
infidel-sensor
|
midopple
|
Gerber Image
|
Code
| 102
| 1,011
|
G04 EAGLE Gerber RS-274X export*
G75*
%MOMM*%
%FSLAX34Y34*%
%LPD*%
%INSoldermask Top*%
%IPPOS*%
%AMOC8*
5,1,8,0,0,1.08239X$1,22.5*%
G01*
%ADD10C,1.311200*%
%ADD11C,1.727200*%
%ADD12C,6.045200*%
%ADD13C,1.727200*%
%ADD14P,1.869504X8X292.500000*%
%ADD15R,0.703200X2.403200*%
%ADD16R,0.903200X0.803200*%
%ADD17R,1.103200X0.903200*%
%ADD18R,1.503200X1.753200*%
%ADD19R,1.115000X0.815000*%
D10*
X177800Y164560D02*
X177800Y175640D01*
X165100Y175640D02*
X165100Y164560D01*
X152400Y164560D02*
X152400Y175640D01*
D11*
X398780Y163750D02*
X414020Y163750D01*
X414020Y138350D02*
X398780Y138350D01*
X398780Y112950D02*
X414020Y112950D01*
X414020Y87550D02*
X398780Y87550D01*
X398780Y62150D02*
X414020Y62150D01*
X414020Y36750D02*
X398780Y36750D01*
X449580Y163750D02*
X464820Y163750D01*
X464820Y138350D02*
X449580Y138350D01*
X449580Y112950D02*
X464820Y112950D01*
X464820Y87550D02*
X449580Y87550D01*
X449580Y62150D02*
X464820Y62150D01*
X464820Y36750D02*
X449580Y36750D01*
D12*
X331000Y48000D03*
X43000Y153000D03*
D13*
X317500Y163750D03*
D14*
X317500Y138350D03*
X317500Y112950D03*
X342900Y163750D03*
X342900Y138350D03*
X342900Y112950D03*
D15*
X184150Y95040D03*
X171550Y95040D03*
X158850Y95040D03*
X146150Y95040D03*
X184150Y31960D03*
X171450Y31960D03*
X158750Y31960D03*
X146050Y31960D03*
D16*
X234950Y58500D03*
X234950Y68500D03*
X120650Y58500D03*
X120650Y68500D03*
X260350Y58500D03*
X260350Y68500D03*
X247650Y58500D03*
X247650Y68500D03*
X273050Y58500D03*
X273050Y68500D03*
D17*
X209550Y57000D03*
X209550Y70000D03*
X222250Y57000D03*
X222250Y70000D03*
D18*
X66950Y23750D03*
X66950Y103250D03*
X21950Y23750D03*
X21950Y103250D03*
D19*
X101600Y71000D03*
X101600Y56000D03*
M02*
| 17,163
|
https://github.com/marcelloti/bootcamp-rocketseat-DESAFIO-FINAL/blob/master/mobile/src/pages/HelpOrders/SendHelpOrder/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
bootcamp-rocketseat-DESAFIO-FINAL
|
marcelloti
|
JavaScript
|
Code
| 151
| 514
|
import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { withNavigationFocus } from 'react-navigation';
import { Alert } from 'react-native';
import PropTypes from 'prop-types';
import Background from '~/components/Background';
import api from '~/services/api';
import { reloadRequest } from '~/store/modules/helporder/actions';
import {
Container,
HelpOrderContainer,
HelpOrderTextArea,
HelpOrderSendButton,
} from './styles';
function SendHelpOrder({ navigation }) {
const dispatch = useDispatch();
const [question, setQuestion] = useState();
const studentid = useSelector(state => state.auth.studentid);
async function handleSubmit() {
try {
await api.post(`/students/${studentid}/help-orders`, {
question,
});
await dispatch(reloadRequest(studentid));
Alert.alert('Confirmação', 'Seu pedido de auxílio foi registrado');
navigation.navigate('HelpOrderList');
} catch (err) {
Alert.alert('', 'Não foi possível cadastrar o pedido de auxílio');
}
}
return (
<Background>
<Container>
<HelpOrderContainer>
<HelpOrderTextArea
multiline
numberOfLines={10}
textAlignVertical="top"
placeholder="Inclua seu pedido de auxílio"
onChangeText={setQuestion}
maxLength={250}
/>
<HelpOrderSendButton onPress={handleSubmit}>
Enviar pedido
</HelpOrderSendButton>
</HelpOrderContainer>
</Container>
</Background>
);
}
SendHelpOrder.propTypes = {
navigation: PropTypes.objectOf(PropTypes.any),
};
SendHelpOrder.defaultProps = {
navigation: PropTypes.object,
};
export default withNavigationFocus(SendHelpOrder);
| 37,496
|
https://github.com/DreamJieEn/jie-mall/blob/master/src/App.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
jie-mall
|
DreamJieEn
|
Vue
|
Code
| 80
| 481
|
<template>
<div id="app">
<mt-header fixed title="可爱的鱼"></mt-header>
<router-view/>
<nav class="mui-bar mui-bar-tab">
<a class="mui-tab-item mui-active" href="#tabbar">
<span class="mui-icon mui-icon-home"></span>
<span class="mui-tab-label">首页</span>
</a>
<a class="mui-tab-item" href="#tabbar-with-chat">
<span class="mui-icon mui-icon-email"><span class="mui-badge">9</span></span>
<span class="mui-tab-label">消息</span>
</a>
<a class="mui-tab-item" href="#tabbar-with-contact">
<span class="mui-icon mui-icon-contact"></span>
<span class="mui-tab-label">通讯录</span>
</a>
<a class="mui-tab-item" href="#tabbar-with-map">
<span class="mui-icon mui-icon-gear"></span>
<span class="mui-tab-label">设置322121</span>
</a>
</nav>
<h1>123</h1>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
| 32,889
|
https://github.com/mecchu/mall/blob/master/mall-member/src/test/java/me/cchu/mall/member/MallMemberApplicationTests.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
mall
|
mecchu
|
Java
|
Code
| 28
| 141
|
package me.cchu.mall.member;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@SpringBootTest
class MallMemberApplicationTests {
@Test
void contextLoads() {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String encode = bCryptPasswordEncoder.encode("123456");
System.out.println(encode);
}
}
| 3,721
|
https://github.com/aalba6675/python-pkcs11/blob/master/tests/test_x509.py
|
Github Open Source
|
Open Source
|
Unlicense
| null |
python-pkcs11
|
aalba6675
|
Python
|
Code
| 509
| 4,398
|
"""
X.509 Certificate Tests
"""
import base64
import subprocess
import datetime
from asn1crypto import pem
from asn1crypto.x509 import Certificate, TbsCertificate, Time, Name
from asn1crypto.keys import RSAPublicKey
from asn1crypto.csr import CertificationRequest, CertificationRequestInfo
import pkcs11
from pkcs11.util.rsa import encode_rsa_public_key
from pkcs11.util.dsa import decode_dsa_signature
from pkcs11.util.ec import decode_ecdsa_signature
from pkcs11.util.x509 import decode_x509_certificate, decode_x509_public_key
from pkcs11 import (
Attribute,
KeyType,
Mechanism,
)
from . import TestCase, Not, Only, requires, OPENSSL
# X.509 self-signed certificate (generated with OpenSSL)
# openssl req -x509 \
# -newkey rsa:512 \
# -keyout key.pem \
# -out cert.pem \
# -days 365 \
# -nodes
_, _, CERT = pem.unarmor(b"""
-----BEGIN CERTIFICATE-----
MIICKzCCAdWgAwIBAgIJAK3BO9rnLZd9MA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV
BAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBX
aWRnaXRzIFB0eSBMdGQwHhcNMTcwNjAyMDI0ODMyWhcNMTgwNjAyMDI0ODMyWjBF
MQswCQYDVQQGEwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50
ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK5z
DJiUDIutdWY8sT2O2ABKh5nmWjc4uEjNj/i5ZLQ4YlRmDL4e2vWs/GOFLVtTJKj6
rh4fj65Xo6X/5R/y+U8CAwEAAaOBpzCBpDAdBgNVHQ4EFgQU+cG240Pzz0y6igtm
hnk1+1KFv6gwdQYDVR0jBG4wbIAU+cG240Pzz0y6igtmhnk1+1KFv6ihSaRHMEUx
CzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRl
cm5ldCBXaWRnaXRzIFB0eSBMdGSCCQCtwTva5y2XfTAMBgNVHRMEBTADAQH/MA0G
CSqGSIb3DQEBBQUAA0EAOdvMKLrIFOYF3aVLGharY196heO0fndm39sZAXJ4PItx
n28DytHEdAoltksfJ2Ds3XAjQqcpI5eBbhIoN9Ckxg==
-----END CERTIFICATE-----
""")
class X509Tests(TestCase):
def test_import_ca_certificate_easy(self):
cert = self.session.create_object(decode_x509_certificate(CERT))
self.assertIsInstance(cert, pkcs11.Certificate)
@Not.nfast
@Not.opencryptoki
def test_import_ca_certificate(self):
cert = self.session.create_object(
decode_x509_certificate(CERT, extended_set=True))
self.assertIsInstance(cert, pkcs11.Certificate)
self.assertEqual(cert[Attribute.HASH_OF_ISSUER_PUBLIC_KEY],
b'\xf9\xc1\xb6\xe3\x43\xf3\xcf\x4c\xba\x8a'
b'\x0b\x66\x86\x79\x35\xfb\x52\x85\xbf\xa8')
# Cert is self signed
self.assertEqual(cert[Attribute.HASH_OF_SUBJECT_PUBLIC_KEY],
b'\xf9\xc1\xb6\xe3\x43\xf3\xcf\x4c\xba\x8a'
b'\x0b\x66\x86\x79\x35\xfb\x52\x85\xbf\xa8')
@requires(Mechanism.SHA1_RSA_PKCS)
def test_verify_certificate_rsa(self):
# Warning: proof of concept code only!
x509 = Certificate.load(CERT)
key = self.session.create_object(decode_x509_public_key(CERT))
self.assertIsInstance(key, pkcs11.PublicKey)
value = x509['tbs_certificate'].dump()
signature = x509.signature
assert x509.signature_algo == 'rsassa_pkcs1v15'
assert x509.hash_algo == 'sha1'
self.assertTrue(key.verify(value, signature,
mechanism=Mechanism.SHA1_RSA_PKCS))
@requires(Mechanism.DSA_SHA1)
def test_verify_certificate_dsa(self):
# Warning: proof of concept code only!
CERT = base64.b64decode("""
MIIDbjCCAy6gAwIBAgIJAKPBInGiPjXNMAkGByqGSM44BAMwRTELMAkGA1UEBhMC
QVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdp
dHMgUHR5IEx0ZDAeFw0xNzA3MDMxMjI1MTBaFw0xOTA3MDMxMjI1MTBaMEUxCzAJ
BgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5l
dCBXaWRnaXRzIFB0eSBMdGQwggG3MIIBLAYHKoZIzjgEATCCAR8CgYEA7U0AshA/
4MXQ3MHykoeotEoPc+OXFMJ2PHzKfbFD80UC5bloxC9kp908GG3emdqbJuCTfVUD
sex1vEgMj1sEwilBow954zMqncu5lLBIGZKjT6tloW8sFt50sE0l+YnBvAiw9uoL
9lBOZLKh87zWPZUuORm8lWhZEwjUnZ+3S5ECFQCNJGd68RpctgkA1kDp33NhQhev
lQKBgQCQ6uYkvNpHMtXwyGII4JyOyStbteHjHdKfJfLNRyIEEq/E4e3Do6NGIr26
Z7u9iBsA5/aU6gKSBrYprxY1hdR4gTRBNzSUDEzf7IX3bfRIbBhjlNBSBba5Fs0z
/kszZbZ8XYGVxs92aWFk/1JIZ0wnToC794+juq72/TvrtvxdowOBhAACgYAjoknQ
kRD0+x3GkbngQCU+VNspZuXboB22CU3bDGVAVhmI5N02M8NmeuN7SqqYZAlw01Ju
rzBF7i9VW4qxBaWszMCwyozerSVjZ2JA/Qubb57v/p7F3FDHq7E33FZzgyhOimds
rzXpVErCGJJ1oBGz5H5fvoKnQmfh0X8N/VHkZqOBpzCBpDAdBgNVHQ4EFgQUQayv
usUnpvRgc9OtXGddqMiwm5cwdQYDVR0jBG4wbIAUQayvusUnpvRgc9OtXGddqMiw
m5ehSaRHMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYD
VQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGSCCQCjwSJxoj41zTAMBgNVHRME
BTADAQH/MAkGByqGSM44BAMDLwAwLAIUNE+zTuFe01v0BRTLarPtGK8ZHHcCFB9Y
YAwtpblAgUEdGuoAtnoEQ2tc
""")
x509 = Certificate.load(CERT)
key = self.session.create_object(decode_x509_public_key(CERT))
self.assertIsInstance(key, pkcs11.PublicKey)
value = x509['tbs_certificate'].dump()
assert x509.signature_algo == 'dsa'
assert x509.hash_algo == 'sha1'
signature = decode_dsa_signature(x509.signature)
self.assertTrue(key.verify(value, signature,
mechanism=Mechanism.DSA_SHA1))
@requires(Mechanism.ECDSA_SHA1)
def test_verify_certificate_ecdsa(self):
# Warning: proof of concept code only!
CERT = base64.b64decode("""
MIIDGjCCAsKgAwIBAgIJAL+PbwiJUZB1MAkGByqGSM49BAEwRTELMAkGA1UEBhMC
QVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0IFdpZGdp
dHMgUHR5IEx0ZDAeFw0xNzA3MDMxMTUxMTBaFw0xOTA3MDMxMTUxMTBaMEUxCzAJ
BgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5l
dCBXaWRnaXRzIFB0eSBMdGQwggFLMIIBAwYHKoZIzj0CATCB9wIBATAsBgcqhkjO
PQEBAiEA/////wAAAAEAAAAAAAAAAAAAAAD///////////////8wWwQg/////wAA
AAEAAAAAAAAAAAAAAAD///////////////wEIFrGNdiqOpPns+u9VXaYhrxlHQaw
zFOw9jvOPD4n0mBLAxUAxJ02CIbnBJNqZnjhE50mt4GffpAEQQRrF9Hy4SxCR/i8
5uVjpEDydwN9gS3rM6D0oTlF2JjClk/jQuL+Gn+bjufrSnwPnhYrzjNXazFezsu2
QGg3v1H1AiEA/////wAAAAD//////////7zm+q2nF56E87nKwvxjJVECAQEDQgAE
royPJHkCQMq55egxmQxkFWqiz+yJx0MZP98is99SrkiK5UadFim3r3ZSt5kfh/cc
Ccmy94BZCmihhGJ0F4eB2qOBpzCBpDAdBgNVHQ4EFgQURNXKlYGsAMItf4Ad8fkg
Rg9ATqEwdQYDVR0jBG4wbIAURNXKlYGsAMItf4Ad8fkgRg9ATqGhSaRHMEUxCzAJ
BgNVBAYTAkFVMRMwEQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5l
dCBXaWRnaXRzIFB0eSBMdGSCCQC/j28IiVGQdTAMBgNVHRMEBTADAQH/MAkGByqG
SM49BAEDRwAwRAIgAdJp/S9vSjS6EvRy/9zl5k2DBKGI52A3Ygsp1a96UicCIDul
m/eL2OcGdNbzqzsC11alhemJX7Qt9GOcVqQwROIm
""")
x509 = Certificate.load(CERT)
key = self.session.create_object(decode_x509_public_key(CERT))
self.assertIsInstance(key, pkcs11.PublicKey)
value = x509['tbs_certificate'].dump()
assert x509.signature_algo == 'ecdsa'
assert x509.hash_algo == 'sha1'
signature = decode_ecdsa_signature(x509.signature)
self.assertTrue(key.verify(value, signature,
mechanism=Mechanism.ECDSA_SHA1))
@Only.openssl
@requires(Mechanism.RSA_PKCS_KEY_PAIR_GEN, Mechanism.SHA1_RSA_PKCS)
def test_self_sign_certificate(self):
# Warning: proof of concept code only!
pub, priv = self.session.generate_keypair(KeyType.RSA, 1024)
tbs = TbsCertificate({
'version': 'v1',
'serial_number': 1,
'issuer': Name.build({
'common_name': 'Test Certificate',
}),
'subject': Name.build({
'common_name': 'Test Certificate',
}),
'signature': {
'algorithm': 'sha1_rsa',
'parameters': None,
},
'validity': {
'not_before': Time({
'utc_time': datetime.datetime(2017, 1, 1, 0, 0),
}),
'not_after': Time({
'utc_time': datetime.datetime(2038, 12, 31, 23, 59),
}),
},
'subject_public_key_info': {
'algorithm': {
'algorithm': 'rsa',
'parameters': None,
},
'public_key': RSAPublicKey.load(encode_rsa_public_key(pub)),
}
})
# Sign the TBS Certificate
value = priv.sign(tbs.dump(),
mechanism=Mechanism.SHA1_RSA_PKCS)
cert = Certificate({
'tbs_certificate': tbs,
'signature_algorithm': {
'algorithm': 'sha1_rsa',
'parameters': None,
},
'signature_value': value,
})
# Pipe our certificate to OpenSSL to verify it
with subprocess.Popen((OPENSSL, 'verify'),
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL) as proc:
proc.stdin.write(pem.armor('CERTIFICATE', cert.dump()))
proc.stdin.close()
self.assertEqual(proc.wait(), 0)
@Only.openssl
@requires(Mechanism.RSA_PKCS_KEY_PAIR_GEN, Mechanism.SHA1_RSA_PKCS)
def test_sign_csr(self):
# Warning: proof of concept code only!
pub, priv = self.session.generate_keypair(KeyType.RSA, 1024)
info = CertificationRequestInfo({
'version': 0,
'subject': Name.build({
'common_name': 'Test Certificate',
}),
'subject_pk_info': {
'algorithm': {
'algorithm': 'rsa',
'parameters': None,
},
'public_key': RSAPublicKey.load(encode_rsa_public_key(pub)),
},
})
# Sign the CSR Info
value = priv.sign(info.dump(),
mechanism=Mechanism.SHA1_RSA_PKCS)
csr = CertificationRequest({
'certification_request_info': info,
'signature_algorithm': {
'algorithm': 'sha1_rsa',
'parameters': None,
},
'signature': value,
})
# Pipe our CSR to OpenSSL to verify it
with subprocess.Popen((OPENSSL, 'req',
'-inform', 'der',
'-noout',
'-verify'),
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL) as proc:
proc.stdin.write(csr.dump())
proc.stdin.close()
self.assertEqual(proc.wait(), 0)
| 1,839
|
https://github.com/jared2501/gerrit/blob/master/gerrit-server/src/main/java/com/google/gerrit/server/git/ProjectLevelConfig.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
gerrit
|
jared2501
|
Java
|
Code
| 316
| 887
|
// Copyright (C) 2013 The Android Open Source Project
//
// 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.google.gerrit.server.git;
import com.google.common.collect.Iterables;
import com.google.gerrit.reviewdb.client.RefNames;
import com.google.gerrit.server.project.ProjectState;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Config;
import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
/** Configuration file in the projects refs/meta/config branch. */
public class ProjectLevelConfig extends VersionedMetaData {
private final String fileName;
private final ProjectState project;
private Config cfg;
public ProjectLevelConfig(String fileName, ProjectState project) {
this.fileName = fileName;
this.project = project;
}
@Override
protected String getRefName() {
return RefNames.REFS_CONFIG;
}
@Override
protected void onLoad() throws IOException, ConfigInvalidException {
cfg = readConfig(fileName);
}
public Config get() {
if (cfg == null) {
cfg = new Config();
}
return cfg;
}
public Config getWithInheritance() {
Config cfgWithInheritance = new Config();
try {
cfgWithInheritance.fromText(get().toText());
} catch (ConfigInvalidException e) {
// cannot happen
}
ProjectState parent = Iterables.getFirst(project.parents(), null);
if (parent != null) {
Config parentCfg = parent.getConfig(fileName).getWithInheritance();
for (String section : parentCfg.getSections()) {
Set<String> allNames = get().getNames(section);
for (String name : parentCfg.getNames(section)) {
if (!allNames.contains(name)) {
cfgWithInheritance.setStringList(section, null, name,
Arrays.asList(parentCfg.getStringList(section, null, name)));
}
}
for (String subsection : parentCfg.getSubsections(section)) {
allNames = get().getNames(section, subsection);
for (String name : parentCfg.getNames(section, subsection)) {
if (!allNames.contains(name)) {
cfgWithInheritance.setStringList(section, subsection, name,
Arrays.asList(parentCfg.getStringList(section, subsection, name)));
}
}
}
}
}
return cfgWithInheritance;
}
@Override
protected boolean onSave(CommitBuilder commit) throws IOException,
ConfigInvalidException {
if (commit.getMessage() == null || "".equals(commit.getMessage())) {
commit.setMessage("Updated configuration\n");
}
saveConfig(fileName, cfg);
return true;
}
}
| 11,622
|
https://github.com/rui19921122/MeetingSystem/blob/master/src/views/ClassPlan/index.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
MeetingSystem
|
rui19921122
|
TypeScript
|
Code
| 7
| 18
|
import ClassPlanView from './ClassPlanView'
export default ClassPlanView
| 48,335
|
https://github.com/ttsirkia/koodisailo/blob/master/src/components/TextFileIcon.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
koodisailo
|
ttsirkia
|
TSX
|
Code
| 114
| 368
|
import { FC } from "react";
export const TextFileIcon: FC = () => {
return (
// https://icons.getbootstrap.com/icons/file-earmark-text/
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
fill="currentColor"
className="bi bi-file-earmark-text"
viewBox="0 0 16 16"
>
<path d="M5.5 7a.5.5 0 0 0 0 1h5a.5.5 0 0 0 0-1h-5zM5 9.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5zm0 2a.5.5 0 0 1 .5-.5h2a.5.5 0 0 1 0 1h-2a.5.5 0 0 1-.5-.5z" />
<path d="M9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4.5L9.5 0zm0 1v2A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5z" />
</svg>
);
};
| 45,419
|
https://github.com/pyfundation/cine-tasty-mobile/blob/master/src/components/screens/home/components/media-section-view-all/MediaSectionViewAll.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
cine-tasty-mobile
|
pyfundation
|
TSX
|
Code
| 124
| 575
|
import React from 'react';
import { Platform, FlatList } from 'react-native';
import MediaSectionViewAllListItem from '@components/common/full-media-list-item/FullMediaListItem';
import ListFooterComponent from '@components/common/pagination-footer/PaginationFooter';
import PopupAdvice from '@components/common/popup-advice/PopupAdvice';
import { MediaSectionViewAllStackProps } from '../../routes/route-params-types';
import useMediaSectionViewAll from './useMediaSectionViewAll';
const MediaSectionViewAll = ({ navigation, route }: MediaSectionViewAllStackProps) => {
const {
shouldShowListBottomReloadButton,
onPressBottomReloadButton,
hasPaginationError,
onEndReached,
isPaginating,
onPressItem,
dataset,
error,
} = useMediaSectionViewAll({
initialMediaItems: route.params.initialDataset,
trendingMediaItemKey: route.params.sectionKey,
isMovie: route.params.isMovie,
navigation,
});
return (
<>
<FlatList
ListFooterComponent={() => shouldShowListBottomReloadButton && (
<ListFooterComponent
onPressReloadButton={onPressBottomReloadButton}
hasError={hasPaginationError}
isPaginating={isPaginating}
/>
)}
onEndReachedThreshold={Platform.select({
android: 0.5,
ios: 0.1,
})}
renderItem={({ item }) => (
<MediaSectionViewAllListItem
onPressDetails={() => onPressItem(item)}
voteCount={item.voteCount}
votes={item.voteAverage}
image={item.posterPath}
genres={item.genreIds}
title={item.title}
/>
)}
keyExtractor={({ id }, index) => `${id}-${index}`}
testID="media-view-all-list"
onEndReached={onEndReached}
data={dataset}
/>
{!!error && (
<PopupAdvice
text={error}
/>
)}
</>
);
};
export default MediaSectionViewAll;
| 36,124
|
https://github.com/peterkrauz/rpg-achievements-django/blob/master/achievements/admin.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
rpg-achievements-django
|
peterkrauz
|
Python
|
Code
| 9
| 28
|
from django.contrib import admin
from achievements import models
admin.site.register(models.Achievement)
| 25,035
|
https://github.com/rafaelpascoalrodrigues/realm/blob/master/realm/database.php
|
Github Open Source
|
Open Source
|
MIT
| null |
realm
|
rafaelpascoalrodrigues
|
PHP
|
Code
| 340
| 1,107
|
<?php
namespace Realm;
class Database {
public $connections;
public $errors;
public $config;
public function __construct() {
$this->connections = array();
$this->errors = array();
$this->config = \Realm\Configuration::Load('databases');
}
/* Try to open a database */
public static function Open($database = '') {
global $REALM;
/* Verify if this database is already opened */
if (array_key_exists($database, $REALM->getDatabase()->connections)) {
return true;
}
/* Verify if the configuration file has been found */
if ($REALM->getDatabase()->config == null) {
return false;
}
/* Verify if the database configuration data has been found */
if (!array_key_exists($database, $REALM->getDatabase()->config)) {
return false;
}
$config = $REALM->getDatabase()->config[$database];
$dsn = "";
$dsn .= $config['driver'];
$dsn .= ":host=" . $config['host'];
if (array_key_exists('port', $config) && $config['port'] != null) {
$dsn .= ";port=" . $config['port'];
}
if (array_key_exists('name', $config) && $config['name'] != null) {
$dsn .= ";dbname=" . $config['name'];
}
$charset = (array_key_exists('charset', $config) && $config['charset'] != null) ? $config['charset'] : 'utf8';
$dsn .= ";charset=" . $charset;
$user = (array_key_exists('user', $config) && $config['user'] != null) ? $config['user'] : '';
$pass = (array_key_exists('pass', $config) && $config['pass'] != null) ? $config['pass'] : '';
/* Try to connect */
try {
$REALM->getDatabase()->connections[$database] = new \PDO($dsn, $user, $pass, array(
\PDO::ATTR_TIMEOUT => CONNECTION_TIMEOUT,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_SILENT,
\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$charset}"));
$REALM->getDatabase()->errors[$database] = array();
} catch (\PDOException $e) {
preg_match('/^\D*\[(\d*)\]\s\[(\d*)\]\s(.*)$/', $e->getMessage(), $matches);
if (count($matches) > 0) {
$error = array($matches[1], intval($matches[2]), $matches[3]);
} else {
$error = $e->getMessage();
}
$REALM->getDatabase()->errors[$database] = $error;
unset($REALM->getDatabase()->connections[$database]);
return false;
}
if ( version_compare(PHP_VERSION, '5.3.6') < 0 &&
array_key_exists('charset', $config) &&
$config['charset'] != null) {
$REALM->getDatabase()->connections[$database]->exec('set names ' . ['charset']);
}
return true;
}
/* Prepare a SQL statement to be executed */
public static function Prepare($database, $query) {
global $REALM;
/* Verify if database is open */
if (!array_key_exists($database, $REALM->getDatabase()->connections)) {
return;
}
try {
$statement = $REALM->getDatabase()->connections[$database]->prepare($query);
} catch (\PDOException $e) {
$statement = false;
}
return $statement;
}
/* Inform the error on last called method */
public function ErrorInfo($database) {
global $REALM;
/* Verify if database is open */
if (array_key_exists($database, $REALM->getDatabase()->errors)) {
return $REALM->getDatabase()->errors[$database];
}
return array();
}
}
| 16,135
|
https://github.com/akazad13/direct-honda-parts/blob/master/direct-honda-parts-frontend/src/fake-server/filters/range-filter-builder.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
direct-honda-parts
|
akazad13
|
TypeScript
|
Code
| 180
| 536
|
import { Product } from '../../app/interfaces/product';
import { products as dbProducts } from '../database/products';
import { RangeFilter } from '../../app/interfaces/filter';
import { AbstractFilterBuilder } from './abstract-filter-builder';
export class RangeFilterBuilder extends AbstractFilterBuilder {
private min: number;
private max: number;
private value: [number, number];
test(product: Product): boolean {
const value = this.extractValue(product);
return value >= this.value[0] && value <= this.value[1];
}
parseValue(value: string): [number, number] {
return value.split('-').map(x => parseFloat(x)) as [number, number];
}
makeItems(products: Product[], value: string): void {
this.max = dbProducts.reduce((acc, product) => Math.max(acc, this.extractValue(product)), 0);
this.min = dbProducts.reduce((acc, product) => Math.min(acc, this.extractValue(product)), this.max);
/** Calculates the number of digits for rounding. */
let digit = Math.max(Math.ceil(this.max).toString().length - 2, 1);
digit = Math.pow(10, digit);
this.max = Math.ceil(this.max / digit) * digit;
this.min = Math.floor(this.min / digit) * digit;
this.value = [this.min, this.max];
if (value) {
this.value = this.parseValue(value);
}
}
calc(filters: AbstractFilterBuilder[]): void {
}
extractValue(product: Product): number {
if (this.slug === 'price') {
return product.price;
}
throw Error();
}
build(): RangeFilter {
return {
type: 'range',
slug: this.slug,
name: this.name,
min: this.min,
max: this.max,
value: this.value,
};
}
}
| 37,931
|
https://github.com/ReykCS/navrep/blob/master/navrep/scripts/play_markoneencodedenv.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
navrep
|
ReykCS
|
Python
|
Code
| 30
| 122
|
import os
from navrep.tools.envplayer import EnvPlayer
from navrep.envs.markencodedenv import MarkOneEncodedEnv
from navrep.envs.markenv import FIRST_TRAIN_MAPS
if __name__ == "__main__":
os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # disable GPU
env = MarkOneEncodedEnv(maps=FIRST_TRAIN_MAPS)
player = EnvPlayer(env)
| 28,470
|
https://github.com/Davidccy/Unity-Sudoku/blob/master/Sudoku/Assets/Scripts/UI/Sudoku/UISudokuInputBoard.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
Unity-Sudoku
|
Davidccy
|
C#
|
Code
| 109
| 360
|
using System;
using System.Collections.Generic;
using UnityEngine;
public class UISudokuInputBoard : MonoBehaviour {
#region Serialized Fields
[SerializeField]
private List<UISudokuInput> _uiInputList = null;
#endregion
#region Internal Fields
private Action<UISudokuInput> _inputOnClickAction;
#endregion
#region Mono Behaviour Hooks
private void Awake() {
for (int i = 0; i < _uiInputList.Count; i++) {
_uiInputList[i].SetButtonOnClick(InputOnClick);
}
}
#endregion
#region APIs
public void SetOnClickAction(Action<UISudokuInput> action) {
_inputOnClickAction = action;
}
public void SetMarking(int inputValue) {
for (int i = 0; i < _uiInputList.Count; i++) {
_uiInputList[i].SetMarking(_uiInputList[i].InputValue == inputValue);
}
}
#endregion
#region Internal Methods
private void InputOnClick(UISudokuInput uiInput) {
if (uiInput == null) {
return;
}
if (_inputOnClickAction == null) {
return;
}
_inputOnClickAction(uiInput);
}
#endregion
}
| 24,675
|
https://github.com/AslanUOM/sqljet_modified/blob/master/sqljet/src/main/java/org/tmatesoft/sqljet/core/internal/db/SqlJetDbHandle.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
sqljet_modified
|
AslanUOM
|
Java
|
Code
| 390
| 1,428
|
/**
* SqlJetDbHandle.java
* Copyright (C) 2009-2010 TMate Software Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* For information on how to redistribute this software under
* the terms of a license other than GNU General Public License
* contact TMate Software at support@sqljet.com
*/
package org.tmatesoft.sqljet.core.internal.db;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.tmatesoft.sqljet.core.ISqlJetMutex;
import org.tmatesoft.sqljet.core.internal.ISqlJetBackend;
import org.tmatesoft.sqljet.core.internal.ISqlJetConfig;
import org.tmatesoft.sqljet.core.internal.ISqlJetDbHandle;
import org.tmatesoft.sqljet.core.internal.ISqlJetFileSystem;
import org.tmatesoft.sqljet.core.internal.SqlJetDbFlags;
import org.tmatesoft.sqljet.core.internal.SqlJetUtility;
import org.tmatesoft.sqljet.core.internal.fs.SqlJetFileSystemsManager;
import org.tmatesoft.sqljet.core.internal.mutex.SqlJetEmptyMutex;
import org.tmatesoft.sqljet.core.internal.mutex.SqlJetMutex;
import org.tmatesoft.sqljet.core.table.ISqlJetBusyHandler;
import org.tmatesoft.sqljet.core.table.ISqlJetOptions;
/**
* @author TMate Software Ltd.
* @author Sergey Scherbina (sergey.scherbina@gmail.com)
*
*/
public class SqlJetDbHandle implements ISqlJetDbHandle {
private Set<SqlJetDbFlags> flags = SqlJetUtility.noneOf(SqlJetDbFlags.class);
private ISqlJetConfig config = new SqlJetConfig();
private ISqlJetFileSystem fileSystem = SqlJetFileSystemsManager.getManager().find(null);
private ISqlJetMutex mutex = new SqlJetEmptyMutex();
private List<ISqlJetBackend> backends = new LinkedList<ISqlJetBackend>();
private ISqlJetOptions options;
private ISqlJetBusyHandler busyHandler;
public SqlJetDbHandle() {
if (config.isSynchronizedThreading()) {
mutex = new SqlJetMutex();
}
}
/*
* (non-Javadoc)
*
* @see org.tmatesoft.sqljet.core.ISqlJetDb#getBackends()
*/
public List<ISqlJetBackend> getBackends() {
return backends;
}
/*
* (non-Javadoc)
*
* @see org.tmatesoft.sqljet.core.ISqlJetDb#getBusyHaldler()
*/
public ISqlJetBusyHandler getBusyHandler() {
return busyHandler;
}
/**
* @param busyHandler
* the busyHandler to set
*/
public void setBusyHandler(ISqlJetBusyHandler busyHandler) {
this.busyHandler = busyHandler;
}
/*
* (non-Javadoc)
*
* @see org.tmatesoft.sqljet.core.ISqlJetDb#getConfig()
*/
public ISqlJetConfig getConfig() {
return config;
}
/*
* (non-Javadoc)
*
* @see org.tmatesoft.sqljet.core.ISqlJetDb#getFileSystem()
*/
public ISqlJetFileSystem getFileSystem() {
return fileSystem;
}
/*
* (non-Javadoc)
*
* @see org.tmatesoft.sqljet.core.ISqlJetDb#getFlags()
*/
public Set<SqlJetDbFlags> getFlags() {
// TODO Auto-generated method stub
return flags;
}
/*
* (non-Javadoc)
*
* @see org.tmatesoft.sqljet.core.ISqlJetDb#getMutex()
*/
public ISqlJetMutex getMutex() {
return mutex;
}
/*
* (non-Javadoc)
*
* @see org.tmatesoft.sqljet.core.ISqlJetDb#getSavepointNum()
*/
public int getSavepointNum() {
// TODO Auto-generated method stub
return 0;
}
/*
* (non-Javadoc)
*
* @see
* org.tmatesoft.sqljet.core.ISqlJetDb#setConfig(org.tmatesoft.sqljet.core
* .ISqlJetConfig)
*/
public void setConfig(ISqlJetConfig config) {
// TODO Auto-generated method stub
}
public ISqlJetOptions getOptions() {
return options;
}
public void setOptions(ISqlJetOptions options) {
this.options = options;
}
}
| 5,653
|
https://github.com/Psicowired87/TimeSeriesTools/blob/master/TimeSeriesTools/Burst_detection/bursts_detection.py
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
TimeSeriesTools
|
Psicowired87
|
Python
|
Code
| 638
| 1,725
|
"""This module contains the group of functions which carry out the pocess of
separate a sequence of spikes in bursts.
They share as input the sequence of spikes detected by some algorithm of spike
detection and returns a list of arrays which contains the times in which spikes
exists.
"""
import numpy as np
import math
def general_burst_detection(spks, method='', kwargs={}):
"""Burst detection is the problem of group the spikes into bursts
considering temporal information and temporal density. Usually is done with
spikes produced for the same element, but in this package we consider the
general situation of many elements.
Parameters
----------
spks: pandas.DataFrame
spikes format with columns: 'times', 'neuron', 'regime', 'descriptor'
method: str, optional
which method use. Depending of the selected method we have to input
the required variables.
kwargs: dict
parameters needed for the called functions selected by the method
parameter.
Returns
-------
bursts: list of lists
active times grouped by bursts.
"""
possible_methods = ['dummy']
method = method if method in possible_methods else ''
if method == 'dummy':
bursts = dummy_burst_detection(spks, **kwargs)
return bursts
def dummy_burst_detection(spks, t_max):
"""This algorithm works under the supposition that all the bursts are
separated at least by a gap with lenght which is a upper bound of the
bursts length.
Parameters
----------
spks: array-like, shape (Ns, variables)
the spikes descriptions.
t_max: int
lower-bound of gaps beween bursts or upper bound of bursts length.
It is expressed in index units.
Returns
-------
bursts: list of arrays
the active times in each burst.
"""
utimes = np.unique(spks[:, 0])
gaps = np.diff(utimes)
edges = np.where(gaps >= t_max)[0] + 1
edges = np.hstack([[0], edges, [utimes.shape[0]]])
bursts = []
for i in range(edges.shape[0]-1):
bursts.append(utimes[edges[i]:edges[i+1]])
return bursts
############################## Under supervision ##############################
###############################################################################
def kleinberg_burst_detection(spks, s=2, gamma=1):
import pybursts
utimes = list(spks[:, 0])
bursts = pybursts.kleinberg(utimes, s, gamma)
return bursts
############################ Under implementation #############################
###############################################################################
def kleinberg(spks, s=2, gamma=1):
# Control of inputs
if s <= 1:
raise ValueError("s must be greater than 1!")
if gamma <= 0:
raise ValueError("gamma must be positive!")
utimes = np.unique(spks[:, 0])
utimes = np.sort(utimes)
# Return bursts for only 1 time
if utimes.size == 1:
bursts = [utimes[0]]
return bursts
# Computation of gaps
gaps = np.diff(utimes)
# Computation of needed magnitudes
T = np.sum(gaps)
n = np.size(gaps)
g_hat = T / n
k = int(math.ceil(float(1+math.log(T, s) + math.log(1/np.amin(gaps), s))))
gamma_log_n = gamma * math.log(n)
alpha_function = np.vectorize(lambda x: s ** x / g_hat)
alpha = alpha_function(np.arange(k))
# Definition complementary functions
def tau(i, j):
if i >= j:
return 0
else:
return (j - i) * gamma_log_n
def f(j, x):
return alpha[j] * math.exp(-alpha[j] * x)
# Intialization of C (?)
C = np.repeat(float("inf"), k)
C[0] = 0
q = np.empty((k, 0))
for t in range(n):
C_prime = np.repeat(float("inf"), k)
q_prime = np.empty((k, t+1))
q_prime.fill(np.nan)
for j in range(k):
cost_function = np.vectorize(lambda x: C[x] + tau(x, j))
cost = cost_function(np.arange(0, k))
el = np.argmin(cost)
if f(j, gaps[t]) > 0:
C_prime[j] = cost[el] - math.log(f(j, gaps[t]))
if t > 0:
q_prime[j, :t] = q[el, :]
q_prime[j, t] = j + 1
C = C_prime
q = q_prime
j = np.argmin(C)
q = q[j, :]
prev_q = 0
N = 0
for t in range(n):
if q[t] > prev_q:
N = N + q[t] - prev_q
prev_q = q[t]
bursts = np.array([np.repeat(np.nan, N), np.repeat(utimes[0], N),
np.repeat(utimes[0], N)], ndmin=2,
dtype=object).transpose()
burst_counter = -1
prev_q = 0
stack = np.repeat(np.nan, N)
stack_counter = -1
for t in range(n):
if q[t] > prev_q:
num_levels_opened = q[t] - prev_q
for i in range(int(num_levels_opened)):
burst_counter += 1
bursts[burst_counter, 0] = prev_q + i
bursts[burst_counter, 1] = utimes[t]
stack_counter += 1
stack[stack_counter] = burst_counter
elif q[t] < prev_q:
num_levels_closed = prev_q - q[t]
for i in range(int(num_levels_closed)):
bursts[stack[stack_counter], 2] = utimes[t]
stack_counter -= 1
prev_q = q[t]
while stack_counter >= 0:
bursts[stack[stack_counter], 2] = utimes[n]
stack_counter -= 1
return bursts
| 36,306
|
https://github.com/arosenk35/dbt_old_20211101/blob/master/models/cscart/cs_dim_owner.sql
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
dbt_old_20211101
|
arosenk35
|
SQL
|
Code
| 432
| 2,609
|
{{
config({
"materialized": "table",
"post-hook": [
after_commit("create index index_{{this.name}}_on_acct_id on {{this.schema}}.{{this.name}} (account_id)"),
after_commit("create index index_{{this.name}}_on_arr_phone on {{this.schema}}.{{this.name}} using gin (array_phone)"),
after_commit("create index index_{{this.name}}_on_arr_email on {{this.schema}}.{{this.name}} using gin (array_email)"),
after_commit("create index index_{{this.name}}_on_lastname on {{this.schema}}.{{this.name}} (lastname)"),
after_commit("create index index_{{this.name}}_on_k_owner on {{this.schema}}.{{this.name}} (key_owner)"),
after_commit("create index index_{{this.name}}_on_email on {{this.schema}}.{{this.name}} (email)")]
})
}}
SELECT distinct on(coalesce(nullif(cs.pet_data__user_id,'0'),nullif(cs.user_id,'0'),'U'||order_id ) )
nullif(regexp_replace(lower(coalesce(cs.firstname,'')||coalesce(cs.lastname,'')),'\`| |\,|\&|\.|-|','','g'),'') as key_owner,
(coalesce(nullif(cs.vet_data__id,''),'U'||cs.order_id) ) as last_doctor_id,
btrim(initcap(coalesce(cs.b_firstname,''))||' '|| initcap(nullif(cs.b_lastname,''))) as owner_name,
coalesce(nullif(cs.pet_data__user_id,'0'),nullif(cs.user_id,'0'),'U'||order_id ) as account_id,
case
when nullif(cs.b_lastname,'') ilike '%vet%' or
nullif(cs.b_lastname,'') ilike '%hosp%' or
nullif(cs.b_lastname,'') ilike '%clinic%' or
nullif(cs.b_lastname,'') ilike '%animal%' or
nullif(cs.b_lastname,'') ilike '%center%' or
nullif(cs.b_lastname,'') ilike '%corpor%'
then initcap(split_part(cs.b_lastname,' ',1))
when nullif(cs.b_firstname,'') is null
then initcap(split_part(cs.b_lastname,' ',1))
else btrim(initcap(nullif(cs.b_firstname,'')) )
end as firstname,
case
when nullif(cs.b_lastname,'') is null
then btrim(lower(reverse(split_part(reverse(cs.b_firstname),' ',1))))
when nullif(cs.b_lastname,'') is not null and (
nullif(cs.b_lastname,'') ilike '%vet%' or
nullif(cs.b_lastname,'') ilike '%hosp%' or
nullif(cs.b_lastname,'') ilike '%clinic%' or
nullif(cs.b_lastname,'') ilike '%animal%' or
nullif(cs.b_lastname,'') ilike '%center%' or
nullif(cs.b_lastname,'') ilike '%corpor%' )
then btrim(initcap(substring(cs.b_lastname,POSITION(' ' in cs.b_lastname)+1,40)))
else btrim(initcap(reverse(split_part(reverse(btrim(cs.b_lastname)),' ',1))))
end as lastname,
upper(btrim(cs.b_state)) as state,
cs.b_zipcode as zip,
nullif(regexp_replace(cs.b_phone,' |\.|-|\(|\)','','g'),'') as phone,
btrim(nullif(cs.b_address,'')) as address,
btrim(nullif(cs.b_address_2,'')) as address2,
upper(nullif(cs.b_country,'')) as country,
initcap(nullif(cs.b_county,'')) as county,
initcap(btrim(nullif(cs.b_city,''))) as city,
{{ email_cleaned('cs.email') }} as email,
nullif(regexp_replace(cs.fax,' |\.|-|\(|\)','','g'),'') as fax,
TIMESTAMP 'epoch' + timestamp::numeric * INTERVAL '1 second' as last_order_date,
u.created_date,
array_remove(array_append(array[null::text], nullif(regexp_replace(cs.b_phone,' |\.|-|\(|\)','','g'),'')),null) as array_phone,
array_remove(array_append(array[null::text], nullif(lower(
case
when cs.email ilike '%ggvcp%' then null
when cs.email ilike '%ggcvp%' then null
else btrim(nullif(lower(cs.email),''))
end
),'')),null) as array_email,
initcap(reverse(split_part(reverse(cs.lastname),' ',1))) || ' '||initcap(nullif(cs.pet_data__name,'')) as last_patient_name,
case when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%banfield%' then 'Corp'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%vca%' then 'Corp'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%petco%' then 'Corp'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%village%' then 'Corp'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%vet %' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%hosp%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%clinic%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%animal%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%emergency%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%center%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.b_lastname,'') ilike '%corpor%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%banfield%' then 'Corp'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%vca%' then 'Corp'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%petco%' then 'Corp'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%village%' then 'Corp'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%emergency%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%vet %' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%hosp%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%clinic%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%animal%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%center%' then 'Clinic'
when coalesce(cs.b_firstname,'')||nullif(cs.s_lastname,'') ilike '%corpor%' then 'Clinic'
when cs.email ilike '%hosp%' then 'Clinic'
when cs.email ilike '%clinic%' then 'Clinic'
when cs.email ilike '%animal%' then 'Clinic'
when cs.email ilike '%center%' then 'Clinic'
when cs.email ilike '%corpo%' then 'Clinic'
when cs.email ilike '%payab%' then 'Clinic'
else 'Patient'
end as account_type
FROM cscart.orders cs
left join {{ ref('cs_dim_user') }} u on u.user_id=(coalesce(nullif(cs.pet_data__user_id,'0'),cs.user_id) )
order by account_id,
cs.timestamp desc
| 15,131
|
https://github.com/Lostefra/TranslationCoherence/blob/master/Datasets/WikiNER/ontologies/de/de_sentence125.ttl
|
Github Open Source
|
Open Source
|
MIT
| null |
TranslationCoherence
|
Lostefra
|
Turtle
|
Code
| 892
| 12,719
|
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_161_163_or>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"or"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Union> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"161"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"163"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#CC> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#since>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Census>
a <http://www.w3.org/2002/07/owl#Class> ;
<http://www.w3.org/2000/01/rdf-schema#subClassOf>
<http://www.ontologydesignpatterns.org/ont/d0.owl#Activity> , <http://www.w3.org/2006/03/wn/wn30/instances/supersense-noun_act> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#n> ;
<http://www.w3.org/2002/07/owl#equivalentClass>
<http://www.w3.org/2006/03/wn/wn30/instances/synset-census-noun-1> , <http://dbpedia.org/resource/Census> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Last>
a <http://www.w3.org/2002/07/owl#Class> ;
<http://www.w3.org/2000/01/rdf-schema#subClassOf>
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#Quality> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#a> ;
<http://www.w3.org/2002/07/owl#equivalentClass>
<http://www.w3.org/2006/03/wn/wn30/instances/synset-last-adjectivesatellite-1> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#qtyOf>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_67_76_estimates>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"estimates"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#estimate_1> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Estimate> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"67"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"76"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#VBZ> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_0_5_Since>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"Since"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Since> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"0"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"5"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#IN> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_82_92_Population>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"Population"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#population_1> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Population> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"82"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"92"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#NN> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_15_21_census>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"census"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#census_1> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Census> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"15"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"21"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#NN> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#to_1>
a <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#To> ;
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#hasDataValue>
"4.6619"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#qtyOf>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Berkshire> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_44_45_%27>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"'"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#%27_1> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#%27> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"44"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"45"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#POS> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_127_137_represents>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"represents"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#represent_1> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Represent> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"127"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"137"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#VBZ> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Estimate>
<http://www.w3.org/2000/01/rdf-schema#subClassOf>
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#Event> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#v> ;
<http://www.w3.org/2002/07/owl#equivalentClass>
<http://www.ontologydesignpatterns.org/ont/vn/data/Estimate_54040000> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_54_56_in>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"in"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#In> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"54"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"56"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#IN> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_44_46_%27s>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"'s"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Of> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"44"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"46"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#POS> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_10_14_last>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"last"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Last> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"10"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"14"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#JJ> .
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_105_106_%27>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"'"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Of> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"105"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"106"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#POS> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#in>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_107_109_to>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"to"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#to_1> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#To> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"107"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"109"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#TO> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_96_105_Berkshire>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"Berkshire"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Berkshire> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"96"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"105"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#NNP> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_141_149_increase>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"increase"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#increase_1> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Increase> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"141"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"149"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#NN> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#represent_1>
a <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Represent> ;
<http://www.ontologydesignpatterns.org/ont/vn/abox/role/Agent>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#%27_1> ;
<http://www.ontologydesignpatterns.org/ont/vn/abox/role/Theme>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#percent_1> , <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#increase_1> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_10_21_last+census>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"last census"^^<http://www.w3.org/2001/XMLSchema#string> , "Last Census"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#LastCensus> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"10"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"21"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_47_53_Office>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"Office"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Office> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"47"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"53"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#NNP> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_35_44_US+People>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"US People"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Us_people> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"35"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"44"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Berkshire>
<http://www.ontologydesignpatterns.org/ont/boxer/boxer.owl#possibleType>
<http://xmlns.com/foaf/0.1/Person> ;
<http://www.w3.org/2002/07/owl#sameAs>
<http://dbpedia.org/resource/Berkshire_County,_Massachusetts> , <http://dbpedia.org/resource/Berkshire> .
<http://dbpedia.org/resource/Berkshire>
a <http://schema.org/AdministrativeArea> , <http://schema.org/Place> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#of>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#increase_1>
a <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Increase> ;
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#increaseOf>
"214.545"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#hasDeterminer>
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#an> ;
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#hasQuantifier>
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#4.661%2C900> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_150_152_of>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"of"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Of> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"150"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"152"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#IN> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_22_24_in>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"in"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#In> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"22"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"24"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#IN> .
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://dbpedia.org/resource/Berkshire_County,_Massachusetts>
a <http://schema.org/Place> , <http://schema.org/AdministrativeArea> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#LastCensus>
a <http://www.w3.org/2002/07/owl#Class> ;
<http://www.w3.org/2000/01/rdf-schema#subClassOf>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Census> ;
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#hasQuality>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Last> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#census_1>
a <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#LastCensus> ;
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#hasQuality>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Last> ;
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#in>
"2000-01-01"^^<http://www.w3.org/2001/XMLSchema#date> ;
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#hasDeterminer>
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#the> .
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#hasQuality>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Office>
<http://www.ontologydesignpatterns.org/ont/boxer/boxer.owl#possibleType>
<http://xmlns.com/foaf/0.1/Organisation> ;
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#in>
"2008-07-01"^^<http://www.w3.org/2001/XMLSchema#date> ;
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#of>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Us_people> ;
<http://www.w3.org/2002/07/owl#sameAs>
<http://dbpedia.org/resource/Office> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse>
a <http://www.essepuntato.it/2008/12/earmark#StringDocuverse> ;
<http://www.essepuntato.it/2008/12/earmark#hasContent>
"Since the last census in 2000, the US People's Office in July 2008 estimates the 'Population of Berkshire' to 4.661,900, which represents an increase of 214.545 or 4.8%."^^<http://www.w3.org/2001/XMLSchema#string> .
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#associatedWith>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Population>
<http://www.w3.org/2000/01/rdf-schema#subClassOf>
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#Collection> , <http://www.w3.org/2006/03/wn/wn30/instances/supersense-noun_group> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#n> ;
<http://www.w3.org/2002/07/owl#equivalentClass>
<http://www.w3.org/2006/03/wn/wn30/instances/synset-population-noun-1> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#To>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#a> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#percent_1>
a <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Percent> ;
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#hasDataValue>
"4.8"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_167_168_%25>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"%"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#denotes>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#percent_1> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Percent> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"167"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"168"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#NN> .
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#%27_1>
a <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#%27> ;
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#associatedWith>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#population_1> ;
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#%27Of>
"4.6619"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Represent>
<http://www.w3.org/2000/01/rdf-schema#subClassOf>
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#Event> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#v> ;
<http://www.w3.org/2002/07/owl#equivalentClass>
<http://www.ontologydesignpatterns.org/ont/vn/data/Represent_29020110> .
<http://www.w3.org/2006/03/wn/wn30/instances/synset-census-noun-1>
<http://www.w3.org/2006/03/wn/wn30/schema/gloss>
"a periodic count of the population"@en-us .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#offset_93_95_of>
a <http://www.essepuntato.it/2008/12/earmark#PointerRange> ;
<http://www.w3.org/2000/01/rdf-schema#label>
"of"^^<http://www.w3.org/2001/XMLSchema#string> ;
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Of> ;
<http://www.essepuntato.it/2008/12/earmark#begins>
"93"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#ends>
"95"^^<http://www.w3.org/2001/XMLSchema#nonNegativeInteger> ;
<http://www.essepuntato.it/2008/12/earmark#refersTo>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#docuverse> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#pennpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#IN> .
<http://www.ontologydesignpatterns.org/ont/boxer/boxer.owl#possibleType>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.essepuntato.it/2008/12/earmark#refersTo>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Us_people>
<http://www.ontologydesignpatterns.org/ont/boxer/boxer.owl#possibleType>
<http://xmlns.com/foaf/0.1/Organisation> .
<http://www.essepuntato.it/2008/12/earmark#ends>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#estimate_1>
a <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Estimate> ;
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#since>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#census_1> ;
<http://www.ontologydesignpatterns.org/ont/vn/abox/role/Agent>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Office> ;
<http://www.ontologydesignpatterns.org/ont/vn/abox/role/Theme>
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#%27_1> .
<http://www.essepuntato.it/2008/12/earmark#hasContent>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.w3.org/2006/03/wn/wn30/instances/synset-population-noun-1>
<http://www.w3.org/2006/03/wn/wn30/schema/gloss>
"the people who inhabit a territory or state; \"the population seemed to be well fed and clothed\""@en-us .
<http://www.w3.org/2002/07/owl#equivalentClass>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#hasDeterminer>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Percent>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#n> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#%27Of>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.essepuntato.it/2008/12/earmark#begins>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.w3.org/2006/03/wn/wn30/instances/synset-addition-noun-3>
<http://www.w3.org/2006/03/wn/wn30/schema/gloss>
"a quantity that is added; \"there was an addition to property taxes this year\"; \"they recorded the cattle's gain in weight over a period of weeks\""@en-us .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#%27>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#n> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Increase>
<http://www.w3.org/2000/01/rdf-schema#subClassOf>
<http://www.w3.org/2006/03/wn/wn30/instances/supersense-noun_quantity> , <http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#Amount> ;
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#boxerpos>
<http://www.ontologydesignpatterns.org/ont/fred/pos.owl#n> ;
<http://www.w3.org/2002/07/owl#equivalentClass>
<http://www.w3.org/2006/03/wn/wn30/instances/synset-addition-noun-3> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#increaseOf>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/vn/abox/role/Theme>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/domain.owl#population_1>
a <http://www.ontologydesignpatterns.org/ont/fred/domain.owl#Population> ;
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#hasDeterminer>
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#the> .
<http://www.ontologydesignpatterns.org/ont/vn/abox/role/Agent>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.ontologydesignpatterns.org/ont/dul/DUL.owl#hasDataValue>
a <http://www.w3.org/2002/07/owl#DataTypeProperty> .
<http://www.ontologydesignpatterns.org/ont/fred/quantifiers.owl#hasQuantifier>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://ontologydesignpatterns.org/cp/owl/semiotics.owl#hasInterpretant>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
<http://www.w3.org/2000/01/rdf-schema#subClassOf>
a <http://www.w3.org/2002/07/owl#ObjectProperty> .
| 23,142
|
https://github.com/Dkbundi/santhathi-appointment/blob/master/app/helpers/cms/patients_helper.rb
|
Github Open Source
|
Open Source
|
MIT
| 2,012
|
santhathi-appointment
|
Dkbundi
|
Ruby
|
Code
| 27
| 89
|
module Cms::PatientsHelper
def row_class(name)
class_name = case name
#when "visited" then "color1"
when "prescribed" then "color5"
when "recommend_for_discharge" then "color3"
else ""
end
return class_name
end
end
| 3,765
|
https://github.com/opvizor/grafana/blob/master/pkg/services/alerting/init/init.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
grafana
|
opvizor
|
Go
|
Code
| 29
| 179
|
package init
import (
"github.com/grafana/grafana/pkg/services/alerting"
_ "github.com/grafana/grafana/pkg/services/alerting/conditions"
_ "github.com/grafana/grafana/pkg/services/alerting/notifiers"
"github.com/grafana/grafana/pkg/setting"
_ "github.com/grafana/grafana/pkg/tsdb/graphite"
)
var engine *alerting.Engine
func Init() {
if !setting.AlertingEnabled {
return
}
engine = alerting.NewEngine()
engine.Start()
}
| 17,016
|
https://github.com/factor-finance/xusd-contracts/blob/master/contracts/oracle/OracleRouter.sol
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
xusd-contracts
|
factor-finance
|
Solidity
|
Code
| 534
| 1,961
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.8.0;
import "../interfaces/chainlink/AggregatorV3Interface.sol";
import { IOracle } from "../interfaces/IOracle.sol";
import { Helpers } from "../utils/Helpers.sol";
abstract contract OracleRouterBase is IOracle {
uint256 constant MIN_DRIFT = uint256(70000000);
uint256 constant MAX_DRIFT = uint256(130000000);
/**
* @dev The price feed contract to use for a particular asset.
* @param asset address of the asset
* @return address address of the price feed for the asset
*/
function feed(address asset) internal view virtual returns (address);
/**
* @notice Returns the total price in 8 digit USD for a given asset.
* @param asset address of the asset
* @return uint256 USD price of 1 of the asset, in 8 decimal fixed
*/
function price(address asset) external view override returns (uint256) {
address _feed = feed(asset);
require(_feed != address(0), "Asset not available");
(, int256 _iprice, , , ) = AggregatorV3Interface(_feed)
.latestRoundData();
uint256 _price = uint256(_iprice);
if (isStablecoin(asset)) {
require(_price <= MAX_DRIFT, "Oracle: Price exceeds max");
require(_price >= MIN_DRIFT, "Oracle: Price under min");
}
return uint256(_price);
}
function isStablecoin(address _asset) internal view returns (bool) {
string memory symbol = Helpers.getSymbol(_asset);
bytes32 symbolHash = keccak256(abi.encodePacked(symbol));
return
symbolHash == keccak256(abi.encodePacked("DAI.e")) ||
symbolHash == keccak256(abi.encodePacked("USDC.e")) ||
symbolHash == keccak256(abi.encodePacked("USDC")) ||
symbolHash == keccak256(abi.encodePacked("USDT.e")) ||
symbolHash == keccak256(abi.encodePacked("USDT"));
}
}
contract OracleRouter is OracleRouterBase {
/**
* @dev The price feed contract to use for a particular asset.
* @param asset address of the asset
*/
function feed(address asset) internal pure override returns (address) {
// DAI
if (asset == address(0xd586E7F844cEa2F87f50152665BCbc2C279D8d70)) {
// Chainlink: DAI/USD
return address(0x51D7180edA2260cc4F6e4EebB82FEF5c3c2B8300);
} else if (
// USDCe
asset == address(0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664) ||
// USDC
asset == address(0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E)
) {
// Chainlink: USDC/USD
return address(0xF096872672F44d6EBA71458D74fe67F9a77a23B9);
} else if (
// USDTe
asset == address(0xc7198437980c041c805A1EDcbA50c1Ce5db95118) ||
// USDT
asset == address(0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7)
) {
// Chainlink: USDT/USD
return address(0xEBE676ee90Fe1112671f19b6B7459bC678B67e8a);
} else if (
// WAVAX
asset == address(0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7)
) {
// Chainlink: WAVAX/USD
return address(0x0A77230d17318075983913bC2145DB16C7366156);
} else if (
// ALPHAe
asset == address(0x2147EFFF675e4A4eE1C2f918d181cDBd7a8E208f)
) {
// Chainlink: ALPHA/USD
return address(0x7B0ca9A6D03FE0467A31Ca850f5bcA51e027B3aF);
} else if (
// CRVe
asset == address(0x249848BeCA43aC405b8102Ec90Dd5F22CA513c06)
) {
// Chainlink: CRVe/USD
return address(0x7CF8A6090A9053B01F3DF4D4e6CfEdd8c90d9027);
} else {
revert("Asset not available");
}
}
}
contract OracleRouterTestnet is OracleRouterBase {
/**
* @dev The price feed contract to use for a particular asset. Testnet hacks.
* @param asset address of the asset
*/
function feed(address asset) internal pure override returns (address) {
// DAI
if (asset == address(0x51BC2DfB9D12d9dB50C855A5330fBA0faF761D15)) {
// Chainlink: USDT/USD ~1
return address(0x7898AcCC83587C3C55116c5230C17a6Cd9C71bad);
} else if (
// rando USDC
asset == address(0x3a9fC2533eaFd09Bc5C36A7D6fdd0C664C81d659)
) {
// Chainlink: USDT/USD ~1
return address(0x7898AcCC83587C3C55116c5230C17a6Cd9C71bad);
} else if (
// USDTe
asset == address(0x02823f9B469960Bb3b1de0B3746D4b95B7E35543)
) {
// Chainlink: USDT/USD ~1
return address(0x7898AcCC83587C3C55116c5230C17a6Cd9C71bad);
} else if (
// WAVAX
asset == address(0xd00ae08403B9bbb9124bB305C09058E32C39A48c)
) {
// Chainlink: WAVAX/USD
return address(0x5498BB86BC934c8D34FDA08E81D444153d0D06aD);
} else if (
// CRVe
asset == address(0x249848BeCA43aC405b8102Ec90Dd5F22CA513c06)
) {
// Chainlink: CRV/USD
return address(0x7CF8A6090A9053B01F3DF4D4e6CfEdd8c90d9027);
} else {
revert("Asset not available");
}
}
}
contract OracleRouterDev is OracleRouterBase {
mapping(address => address) public assetToFeed;
function setFeed(address _asset, address _feed) external {
assetToFeed[_asset] = _feed;
}
/**
* @dev The price feed contract to use for a particular asset.
* @param asset address of the asset
*/
function feed(address asset) internal view override returns (address) {
return assetToFeed[asset];
}
}
| 34,692
|
https://github.com/nax2uk/nhs-virtual-visit-deploy/blob/master/src/components/TrustsListTable/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
nhs-virtual-visit-deploy
|
nax2uk
|
JavaScript
|
Code
| 103
| 511
|
import React from "react";
import AnchorLink from "../AnchorLink";
const TrustsTable = ({ trusts }) => (
<div className="nhsuk-table-responsive">
<table className="nhsuk-table">
<caption className="nhsuk-table__caption">List of trusts</caption>
<thead className="nhsuk-table__head">
<tr className="nhsuk-table__row">
<th className="nhsuk-table__header" scope="col">
Trust name
</th>
<th className="nhsuk-table__header" scope="col">
Status
</th>
<th className="nhsuk-table__header" scope="col" colSpan="2">
<span className="nhsuk-u-visually-hidden">Actions</span>
</th>
</tr>
</thead>
<tbody className="nhsuk-table__body">
{trusts.map((trust) => {
const trustKey = trust.name.toLowerCase().replace(/\W+/g, "-");
return (
<tr
key={trustKey}
className="nhsuk-table__row"
data-testid={trustKey}
>
<td className="nhsuk-table__cell">{trust.name}</td>
<td className="nhsuk-table__cell">
{trust.status == 0 ? "Disabled" : "Enabled"}
</td>
<td className="nhsuk-table__cell" style={{ textAlign: "center" }}>
<AnchorLink
href="/admin/trusts/[id]/delete"
as={`/admin/trusts/${trust.id}/delete`}
>
Delete
<span className="nhsuk-u-visually-hidden"> {trust.name}</span>
</AnchorLink>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
export default TrustsTable;
| 30,806
|
https://github.com/mobinseven/VinarishCSB/blob/master/src/VinarishCsb.Shared/Dto/Email/EmailDto.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
VinarishCSB
|
mobinseven
|
C#
|
Code
| 87
| 216
|
using System.ComponentModel.DataAnnotations;
namespace VinarishCsb.Shared
{
public class EmailDto
{
private string _name;
[Required]
public string ToAddress { get; set; }
public string ToName
{
get
{
if (string.IsNullOrEmpty(_name))
{
return ToAddress;
}
return _name;
}
set
{
_name = value;
}
}
public string FromName { get; set; }
public string FromAddress { get; set; }
public string ReplyToAddress { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
[Required]
public string TemplateName { get; set; }
}
}
| 44,866
|
https://github.com/JavaQualitasCorpus/nakedobjects-4.0.0/blob/master/core/metamodel/src/main/java/org/nakedobjects/metamodel/facets/SingleIntValueFacetAbstract.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
nakedobjects-4.0.0
|
JavaQualitasCorpus
|
Java
|
Code
| 43
| 121
|
package org.nakedobjects.metamodel.facets;
public abstract class SingleIntValueFacetAbstract extends FacetAbstract implements SingleIntValueFacet {
private final int value;
public SingleIntValueFacetAbstract(final Class<? extends Facet> facetType, final FacetHolder holder, final int value) {
super(facetType, holder, false);
this.value = value;
}
public int value() {
return value;
}
}
| 38,668
|
https://github.com/Rohit484/Distribution/blob/master/a/ag-grid/src/main/scala/typings/agGrid/mod/RowNode.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Distribution
|
Rohit484
|
Scala
|
Code
| 113
| 439
|
package typings.agGrid.mod
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@JSImport("ag-grid", "RowNode")
@js.native
class RowNode ()
extends typings.agGrid.rowNodeMod.RowNode
/* static members */
@JSImport("ag-grid", "RowNode")
@js.native
object RowNode extends js.Object {
var EVENT_ALL_CHILDREN_COUNT_CHANGED: String = js.native
var EVENT_CELL_CHANGED: String = js.native
var EVENT_CHILD_INDEX_CHANGED: String = js.native
var EVENT_DATA_CHANGED: String = js.native
var EVENT_DRAGGING_CHANGED: String = js.native
var EVENT_EXPANDED_CHANGED: String = js.native
var EVENT_FIRST_CHILD_CHANGED: String = js.native
var EVENT_HEIGHT_CHANGED: String = js.native
var EVENT_LAST_CHILD_CHANGED: String = js.native
var EVENT_MOUSE_ENTER: String = js.native
var EVENT_MOUSE_LEAVE: String = js.native
var EVENT_ROW_INDEX_CHANGED: String = js.native
var EVENT_ROW_SELECTED: String = js.native
var EVENT_SELECTABLE_CHANGED: String = js.native
var EVENT_TOP_CHANGED: String = js.native
var EVENT_UI_LEVEL_CHANGED: String = js.native
}
| 31,704
|
https://github.com/falkben/zoo-checks/blob/master/zoo_checks/templatetags/template_tags.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
zoo-checks
|
falkben
|
Python
|
Code
| 70
| 245
|
import datetime
from django import template
register = template.Library()
@register.filter
def index(List, i):
return List[int(i)]
@register.filter(name="range")
def _range(_min, args=None):
_max, _step = None, None
if args:
if not isinstance(args, int):
_max, _step = map(int, args.split(","))
else:
_max = args
args = filter(None, (_min, _max, _step))
return range(*args)
@register.filter()
def addDays(days, start_date=None):
if start_date is None:
start_date = datetime.date.today()
newDate = start_date + datetime.timedelta(days=days)
return newDate
@register.filter()
def hidden_initial_field(field):
return field.as_hidden(only_initial=True)
| 31,491
|
https://github.com/MrMartin92/vscode-lua-wow/blob/master/API/Item.lua
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
vscode-lua-wow
|
MrMartin92
|
Lua
|
Code
| 356
| 2,104
|
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!
-- This file is automaticly generated. Don't edit manualy!
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!
---@class C_Item
C_Item = {}
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.CanScrapItem)
---@param itemLoc table
---@return boolean @canBeScrapped
function C_Item.CanScrapItem(itemLoc)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.CanViewItemPowers)
---@param itemLoc table
---@return boolean @isItemViewable
function C_Item.CanViewItemPowers(itemLoc)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.DoesItemExist)
---@param emptiableItemLocation table
---@return boolean @itemExists
function C_Item.DoesItemExist(emptiableItemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.DoesItemExistByID)
---@param itemInfo string
---@return boolean @itemExists
function C_Item.DoesItemExistByID(itemInfo)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.DoesItemMatchBonusTreeReplacement)
---@param itemLoc table
---@return boolean @matchesBonusTree
function C_Item.DoesItemMatchBonusTreeReplacement(itemLoc)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetCurrentItemLevel)
---@param itemLocation table
---@return number @currentItemLevel
function C_Item.GetCurrentItemLevel(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemGUID)
---@param itemLocation table
---@return string @itemGuid
function C_Item.GetItemGUID(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemID)
---@param itemLocation table
---@return number @itemID
function C_Item.GetItemID(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemIcon)
---@param itemLocation table
---@return number @icon
function C_Item.GetItemIcon(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemIconByID)
---@param itemInfo string
---@return number @icon
function C_Item.GetItemIconByID(itemInfo)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemInventoryType)
---@param itemLocation table
---@return InventoryType @inventoryType
function C_Item.GetItemInventoryType(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemInventoryTypeByID)
---@param itemInfo string
---@return InventoryType @inventoryType
function C_Item.GetItemInventoryTypeByID(itemInfo)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemLink)
---@param itemLocation table
---@return string @itemLink
function C_Item.GetItemLink(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemName)
---@param itemLocation table
---@return string @itemName
function C_Item.GetItemName(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemNameByID)
---@param itemInfo string
---@return string @itemName
function C_Item.GetItemNameByID(itemInfo)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemQuality)
---@param itemLocation table
---@return ItemQuality @itemQuality
function C_Item.GetItemQuality(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetItemQualityByID)
---@param itemInfo string
---@return ItemQuality @itemQuality
function C_Item.GetItemQualityByID(itemInfo)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.GetStackCount)
---@param itemLocation table
---@return number @stackCount
function C_Item.GetStackCount(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.IsBound)
---@param itemLocation table
---@return boolean @isBound
function C_Item.IsBound(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.IsItemCorrupted)
---@param itemLoc table
---@return boolean @isCorrupted
function C_Item.IsItemCorrupted(itemLoc)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.IsItemCorruptionRelated)
---@param itemLoc table
---@return boolean @isCorruptionRelated
function C_Item.IsItemCorruptionRelated(itemLoc)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.IsItemCorruptionResistant)
---@param itemLoc table
---@return boolean @isCorruptionResistant
function C_Item.IsItemCorruptionResistant(itemLoc)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.IsItemDataCached)
---@param itemLocation table
---@return boolean @isCached
function C_Item.IsItemDataCached(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.IsItemDataCachedByID)
---@param itemInfo string
---@return boolean @isCached
function C_Item.IsItemDataCachedByID(itemInfo)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.IsItemKeystoneByID)
---@param itemInfo string
---@return boolean @isKeystone
function C_Item.IsItemKeystoneByID(itemInfo)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.IsLocked)
---@param itemLocation table
---@return boolean @isLocked
function C_Item.IsLocked(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.LockItem)
---@param itemLocation table
function C_Item.LockItem(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.LockItemByGUID)
---@param itemGUID string
function C_Item.LockItemByGUID(itemGUID)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.RequestLoadItemData)
---@param itemLocation table
function C_Item.RequestLoadItemData(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.RequestLoadItemDataByID)
---@param itemInfo string
function C_Item.RequestLoadItemDataByID(itemInfo)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.UnlockItem)
---@param itemLocation table
function C_Item.UnlockItem(itemLocation)
end
---[Wowpedia documentation](https://wow.gamepedia.com/API_C_Item.UnlockItemByGUID)
---@param itemGUID string
function C_Item.UnlockItemByGUID(itemGUID)
end
| 11,250
|
https://github.com/Hammerspoon/hammerspoon/blob/master/scripts/lua_stackguard_enforcer.py
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
hammerspoon
|
Hammerspoon
|
Python
|
Code
| 405
| 1,113
|
#!/usr/bin/env python
"""
Enforce the usage of Hammerspoon's Lua stack guarding macros
"""
from __future__ import print_function
import sys
from clang.cindex import Config
from clang.cindex import Index
from clang.cindex import CursorKind
from clang.cindex import TypeKind
FILENAME = "Unknown"
def is_function(node):
"""Is the given node a C function or an ObjC method?"""
return node.kind in [CursorKind.FUNCTION_DECL,
CursorKind.OBJC_INSTANCE_METHOD_DECL,
CursorKind.OBJC_CLASS_METHOD_DECL]
def is_implementation(node):
"""Is the given node an ObjC @implementation?"""
return node.kind == CursorKind.OBJC_IMPLEMENTATION_DECL
def is_luastate_param(node):
"""Is the given node a lua_State parameter?"""
# We need the underlying text tokens to detect the typedef 'lua_State'
tokens = [x.spelling for x in node.get_tokens()]
try:
return node.type.kind == TypeKind.POINTER and \
tokens[0] == 'lua_State'
except IndexError:
return False
def is_lua_call(node):
"""Is the given node a Lua->C call?"""
params = [x for x in node.get_children() if x.kind == CursorKind.PARM_DECL]
return node.result_type.kind == TypeKind.INT and len(params) == 1 and \
is_luastate_param(params[0])
def build_tree(node, recurse=True):
"""Build a tree below a node"""
if recurse:
children = [build_tree(c) for c in node.get_children()]
else:
children = ['skipped']
return {'node': node,
'kind': node.kind,
'spelling': node.spelling,
'tokens': ' '.join([x.spelling for x in node.get_tokens()]),
'children': children}
def contains_lua_calls(item):
"""Check if a node contains any Lua API calls"""
if 'lua_' in item['tokens']:
return True
if 'luaL_' in item['tokens']:
return True
if 'LuaSkin' in item['tokens']:
return True
return False
def main(filename):
"""Main function"""
functions = []
tree = []
Config.set_library_file(
"/Library/Developer/CommandLineTools/usr/lib/libclang.dylib")
index = Index.create()
ast = index.parse(None, [filename])
if not ast:
print("Unable to parse file")
sys.exit(1)
# Step 1: Find all the C/ObjC functions
functions = [x for x in ast.cursor.get_children() if is_function(x)]
# Step 1a: Add in ObjC class methods
for item in ast.cursor.get_children():
if is_implementation(item):
functions += [x for x in item.get_children() if is_function(x)]
# Step 2: Filter out all of the functions that are Lua->C calls
functions = [x for x in functions if not is_lua_call(x)]
# Step 3: Recursively walk the remaining functions
tree = [build_tree(x, False) for x in functions]
# Step 4: Filter the functions down to those which contain Lua calls
tree = [x for x in tree if contains_lua_calls(x)]
for thing in tree:
stacktxt = "NO STACKGUARD"
hasstackentry = "_lua_stackguard_entry" in thing['tokens']
hasstackexit = "_lua_stackguard_exit" in thing['tokens']
if hasstackentry and hasstackexit:
continue
if hasstackentry and not hasstackexit:
stacktxt = "STACK ENTRY, BUT NO EXIT"
if hasstackexit and not hasstackentry:
stacktxt = "STACK EXIT, BUT NO ENTRY (THIS IS A CRASH)"
print(u"%s :: %s :: %s" % (filename, thing['spelling'], stacktxt))
if __name__ == '__main__':
main(sys.argv[1])
| 40,561
|
https://github.com/uosorio/heroku_face/blob/master/venv/boost_1_73_0/libs/graph/example/vf2_sub_graph_iso_example.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
heroku_face
|
uosorio
|
C++
|
Code
| 158
| 551
|
//=======================================================================
// Copyright (C) 2012 Flavio De Lorenzi (fdlorenzi@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/vf2_sub_graph_iso.hpp>
using namespace boost;
int main()
{
typedef adjacency_list< setS, vecS, bidirectionalS > graph_type;
// Build graph1
int num_vertices1 = 8;
graph_type graph1(num_vertices1);
add_edge(0, 6, graph1);
add_edge(0, 7, graph1);
add_edge(1, 5, graph1);
add_edge(1, 7, graph1);
add_edge(2, 4, graph1);
add_edge(2, 5, graph1);
add_edge(2, 6, graph1);
add_edge(3, 4, graph1);
// Build graph2
int num_vertices2 = 9;
graph_type graph2(num_vertices2);
add_edge(0, 6, graph2);
add_edge(0, 8, graph2);
add_edge(1, 5, graph2);
add_edge(1, 7, graph2);
add_edge(2, 4, graph2);
add_edge(2, 7, graph2);
add_edge(2, 8, graph2);
add_edge(3, 4, graph2);
add_edge(3, 5, graph2);
add_edge(3, 6, graph2);
// Create callback to print mappings
vf2_print_callback< graph_type, graph_type > callback(graph1, graph2);
// Print out all subgraph isomorphism mappings between graph1 and graph2.
// Vertices and edges are assumed to be always equivalent.
vf2_subgraph_iso(graph1, graph2, callback);
return 0;
}
| 46,507
|
https://github.com/Depado/experiments/blob/master/app/__init__.py
|
Github Open Source
|
Open Source
|
WTFPL
| 2,015
|
experiments
|
Depado
|
Python
|
Code
| 24
| 73
|
# -*- coding: utf-8 -*-
from flask import Flask
from werkzeug.contrib.fixers import ProxyFix
app = Flask(__name__)
app.config.from_object('config')
app.wsgi_app = ProxyFix(app.wsgi_app)
from app import views
| 32,472
|
https://github.com/xmidt-org/libmetriks/blob/master/src/metrics.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
libmetriks
|
xmidt-org
|
C
|
Code
| 987
| 1,784
|
/*
* Copyright 2019 Comcast Cable Communications Management, LLC
*
* 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.
*/
#ifndef __METRICS_H__
#define __METRICS_H__
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <time.h>
/*----------------------------------------------------------------------------*/
/* Macros */
/*----------------------------------------------------------------------------*/
/* none */
/*----------------------------------------------------------------------------*/
/* Data Structures */
/*----------------------------------------------------------------------------*/
struct metrics_config {
/* The name to prefix all the metrics with. */
const char *base;
/* The initial report size in bytes. 0 means use default: 1024 */
size_t initial_report_size;
/* The unix time the process starts. */
time_t unix_time;
/*------------------------------------------------------------------------*/
const char *process_name;
const char *metrics_path;
/** Only used if ENABLE_PROCFS flag is enabled */
/* The reporting period in seconds. 0 means use the default: 15s */
uint32_t report_period_s;
};
typedef void* metrics_t;
/*----------------------------------------------------------------------------*/
/* Common Functions */
/*----------------------------------------------------------------------------*/
/**
* This function initializes the metrics service and returns the object
* to reference calls against.
*
* @param c - The structure defining the configuration.
*
* @returns the metrics object to reference
*/
metrics_t metrics_init( const struct metrics_config *c );
/**
* Shuts down the metrics service.
*
* @param the metrics object to reference
*/
void metrics_shutdown( metrics_t m );
/**
* Used to calculate the metric name based on the associated labels.
*
* This is useful if your code updates metrics very quickly and has several
* labels associated with the name because it will greatly speed up the lookup
* process for your metric.
*
* @note You will need to free the response if it is not NULL.
*
* @param name - The base metric name to build onto.
* @param label_count - The number of label/value pairs the function expects.
* Example: 1 is the pair of "label", "value".
* @param ... - const char *label, const char *value pairs
*
* @return The complete metric name that can be used for fastest lookup.
* The caller is responsible for freeing the returned pointer.
*/
char* metrics_calculate_name( const char *name, size_t label_count, ... );
/**
* The varidac version of the metrics_calculate_name() function.
*/
char* metrics_calculate_name_varidac( const char *name, size_t label_count,
va_list args );
/*----------------------------------------------------------------------------*/
/* Counter Functions */
/*----------------------------------------------------------------------------*/
/*
* Counters are designed to monotonically increase forever. By design, they
* never decrease. Internally they are backed by uint64_t values. If for
* some reason they should overflow, the counter shall be capped to
* 0xffffffffffffffff.
*
* Examples of counters
* ------------------
*
* 1. Number of bytes allocated (cumulitive)
* 2. Number of bytes freed (cumulitive)
* 3. TX byte count
* 4. Number of times a failure has been hit
* 5. Number of times a success value has been hit
*/
/**
* This function increments a metrics counter a specified amount.
*
* @note If you need labels, and have already called metrics_calculate_name(),
* you can simply call this function with the name you got back.
*
* @param m - The metric object to reference.
* @param name - The base metric name to increment.
* @param inc - The quantity to increment by.
*/
void metrics_counter_inc(metrics_t m, const char *name, uint32_t inc );
/**
* This function increments a metrics counter a specified amount.
*
* @note If you are performing repeated metric updates to the same metric,
* this is slower then using metrics_calculate_name() and locally
* caching the name.
*
* @param m - The metric object to reference.
* @param name - The metric name to increment.
* @param inc - The quantity to increment by.
* @param label_count - The number of label pairs to associate with this metric.
* @param ... - Label, value pair to associate with the metric.
*/
void metrics_counter_inc_labels(metrics_t m, const char *name, uint32_t inc,
size_t label_count, ... );
/*----------------------------------------------------------------------------*/
/* Gauge Functions */
/*----------------------------------------------------------------------------*/
/*
* Gauge functions are designed to track some real value. This metric may
* go up or down. Internally these are backed by int64_t values.
*
* Examples of gauges
* ------------------
*
* 1. Temperature in 1000's of degrees C 10.0C = 10000
* 2. Real time queue depth.
* 3. Start time of a process in unix time.
* 4. Number of outstanding allocated bytes.
*
*/
/**
* This function sets a metrics gauge a specified value.
*
* @note If you need labels, and have already called metrics_calculate_name(),
* you can simply call this function with the name you got back.
*
* @param m - The metric object to reference.
* @param name - The metric name to update.
* @param value - The value to set the gauge to.
*/
void metrics_gauge_set( metrics_t m, const char *name, int64_t value );
/**
* This function updates a metrics gauge to a specified value.
*
* @note If you are performing repeated metric updates to the same metric,
* this is slower then using metrics_calculate_name() and locally
* caching the name.
*
* @param m - The metric object to reference.
* @param name - The base metric name to update.
* @param value - The value to set the gauge to.
* @param label_count - The number of label pairs to associate with this metric.
* @param ... - Label, value pair to associate with the metric.
*/
void metrics_gauge_set_labels( metrics_t m, const char *name, int64_t value,
size_t label_count, ... );
/*----------------------------------------------------------------------------*/
/* Histogram Functions */
/*----------------------------------------------------------------------------*/
/* TBD */
/*----------------------------------------------------------------------------*/
/* Summary Functions */
/*----------------------------------------------------------------------------*/
/* TBD */
#endif
| 31,207
|
https://github.com/sGrys/it-academy/blob/master/java-basic/projekty/calculator-3/src/main/java/com/company/NodeReader.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
it-academy
|
sGrys
|
Java
|
Code
| 130
| 476
|
package com.company;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;
public class NodeReader {
private static Node readExpresion(InputStream str) throws IllegalAccessException, InstantiationException {
Scanner s=new Scanner(str);
//int x= s.nextInt();
//System.out.println("podales:" +x);
ArrayList<String> list= new ArrayList<>();
while(s.hasNext()) {
String wejscie = s.next();
if(wejscie.equals("stop")) {
break;
}
else {
String cos = wejscie;
list.add(cos);
}
}
Parser p = new Parser();
String[] st={};
return p.makeTree(list.toArray(st));
}
static List<String> readLines(Path path) throws IOException {
return Files.readAllLines(path);
}
static List<Optional<Node>> readNodes (Path path) throws IOException, InstantiationException, IllegalAccessException {
List<String> lines = Files.readAllLines(path);
ArrayList<Optional<Node>> Nodes = new ArrayList<>();
for (String s : lines){
InputStream stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
try {
Nodes.add(Optional.ofNullable(readExpresion(stream)));
}
catch (IllegalArgumentException e)
{
Nodes.add(Optional.empty());
}
}
return Nodes;
}
}
| 9,018
|
https://github.com/KattiaBibi/sis-tickets/blob/master/app/ColaboradorEmpresas.php
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
sis-tickets
|
KattiaBibi
|
PHP
|
Code
| 26
| 93
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ColaboradorEmpresas extends Model
{
//
protected $table ='colaborador_empresas';
protected $primaryKey = 'id';
protected $fillable = [
'colaborador_id',
'empresa_id',
];
}
| 33,493
|
https://github.com/M3nin0/ProgrammingMyVacation/blob/master/PythonTKinter/LayoutPackSide2.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ProgrammingMyVacation
|
M3nin0
|
Python
|
Code
| 51
| 278
|
#Colocando um item em cada canto da tela
from tkinter import *
def abreJanela():
janela2 = Tk()
janela2.title("Segunda janela =D")
janela2.geometry("300x300+400+300")
janela2.mainloop()
janela = Tk()
janela.title("Side Pack 2")
lb1 = Label(janela,text="Esquerda",bg="red")
lb1.pack(side=LEFT)
lb2 = Label(janela,text="Direita",bg="blue")
lb2.pack(side=RIGHT)
lb3 = Label(janela,text="Topo",bg="gray")
lb3.pack(side=TOP)
lb4 = Label(janela,text="Baixo",bg='yellow')
lb4.pack(side=BOTTOM)
bt1 = Button(janela,text="Outra tela",command=abreJanela)
bt1.place(x=120,y=150)
janela.geometry("300x300+200+200")
janela.mainloop()
| 2,095
|
https://github.com/Ragolsnagol/RagolEngine/blob/master/RagolEngine/RagolEngine/Controls/LinkLabel.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
RagolEngine
|
Ragolsnagol
|
C#
|
Code
| 109
| 346
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace RagolEngine.Controls
{
public class LinkLabel : Control
{
#region Fields and Properties
Color selectedColor = Color.Red;
public Color SelectedColor
{
get { return selectedColor; }
set { selectedColor = value; }
}
#endregion
#region Constructor Region
public LinkLabel()
{
TabStop = true;
HasFocus = false;
Position = Vector2.Zero;
}
#endregion
#region Abstract Methods
public override void Update(GameTime gameTime)
{
}
public override void Draw(SpriteBatch spriteBatch)
{
if (hasFocus)
spriteBatch.DrawString(SpriteFont, Text, Position, selectedColor);
else
spriteBatch.DrawString(SpriteFont, Text, Position, Color);
}
public override void HandleInput(PlayerIndex playerIndex)
{
if (!HasFocus)
return;
if (InputHandler.KeyReleased(Keys.Enter))
base.OnSelected(null);
}
#endregion
}
}
| 10,413
|
https://github.com/keenu1/frameworkwebUAS/blob/master/application/controllers/Profile.php
|
Github Open Source
|
Open Source
|
MIT
| null |
frameworkwebUAS
|
keenu1
|
PHP
|
Code
| 120
| 602
|
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Profile extends CI_Controller
{
public function index()
{
$this->load->model('M_profile');
$data['dataprofile'] = $this->M_profile->user();
$data['titleHeader'] = 'Profile';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('Profile/index', $data);
$this->load->view('templates/footer');
}
function edit()
{
$this->load->model('M_profile');
$akun = new stdClass();
$akun->id = null;
$data['titleHeader'] = 'Edit';
$data['user'] = $this->db->get_where('user', ['email' => $this->session->userdata('email')])->row_array();
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('Profile/index', $data);
$this->load->view('templates/footer');
}
function update()
{
$this->load->model('M_profile');
$id = $this->input->post('id');
$username = $this->input->post('username');
$alamat = $this->input->post('alamat');
$phone_number = $this->input->post('phone_number');
$address = $this->input->post('address');
$data = array(
'name' => $username,
'address' => $alamat,
'phone_number' => $phone_number,
'address' => $address
);
$where = array(
'id' => $id
);
$this->M_profile->update_user($where, $data, 'user');
redirect('Profile/index/' . $id);
}
}
| 9,781
|
https://github.com/aghasyedbilal/intellij-community/blob/master/plugins/configuration-script/src/providers/updateSettingsProvider.kt
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
intellij-community
|
aghasyedbilal
|
Kotlin
|
Code
| 91
| 447
|
package com.intellij.configurationScript.providers
import com.intellij.configurationScript.ConfigurationFileManager
import com.intellij.configurationScript.readIntoObject
import com.intellij.configurationScript.schemaGenerators.PluginJsonSchemaGenerator
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.processOpenedProjects
import com.intellij.openapi.updateSettings.impl.UpdateSettingsProvider
import com.intellij.openapi.util.NotNullLazyKey
import com.intellij.util.SmartList
import com.intellij.util.concurrency.SynchronizedClearableLazy
import com.intellij.util.xmlb.annotations.XCollection
private val dataKey = NotNullLazyKey.create<SynchronizedClearableLazy<PluginsConfiguration?>, Project>("MyUpdateSettingsProvider") { project ->
val data = SynchronizedClearableLazy {
val node = ConfigurationFileManager.getInstance(project).findValueNode(PluginJsonSchemaGenerator.plugins) ?: return@SynchronizedClearableLazy null
readIntoObject(PluginsConfiguration(), node)
}
ConfigurationFileManager.getInstance(project).registerClearableLazyValue(data)
data
}
private class MyUpdateSettingsProvider : UpdateSettingsProvider {
override fun getPluginRepositories(): List<String> {
val result = SmartList<String>()
processOpenedProjects { project ->
dataKey.getValue(project).value?.repositories?.let {
result.addAll(it)
}
}
return result
}
}
internal class PluginsConfiguration : BaseState() {
@get:XCollection
val repositories by list<String>()
}
| 1,965
|
https://github.com/Prometeus-Network/ignite-back-end/blob/master/src/push-notifications/entities/index.ts
|
Github Open Source
|
Open Source
|
Apache-1.1
| 2,021
|
ignite-back-end
|
Prometeus-Network
|
TypeScript
|
Code
| 12
| 24
|
export * from "./UserDevice";
export * from "./Notification";
export * from "./NotificationType";
| 27,730
|
https://github.com/kcjingjie/vue-element-admin/blob/master/src/views/layout/components/Navbar.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
vue-element-admin
|
kcjingjie
|
Vue
|
Code
| 139
| 577
|
<template>
<el-menu :default-active="$route.path" router class="navbar" mode="horizontal" background-color="#545c64" text-color="#fff" active-text-color="#ffd04b" >
<template v-for="(item, index) in permission_routers" v-if="!item.hidden&&item.children">
<el-menu-item :index="item.path" :key="index">
{{ item.title }}
</el-menu-item>
</template>
<div class="right-menu">
<error-log class="errLog-container right-menu-item"/>
<el-tooltip content="全屏" effect="dark" placement="bottom">
<screenfull class="right-menu-item"/>
</el-tooltip>
<el-button class="right-menu-item" @click="logout">退出登录</el-button>
</div>
</el-menu>
</template>
<script>
import { mapGetters } from 'vuex'
import ErrorLog from '@/components/ErrorLog'
import Screenfull from '@/components/Screenfull'
export default {
components: {
ErrorLog,
Screenfull
},
computed: {
...mapGetters([
'permission_routers',
'sidebar',
'name'
])
},
methods: {
logout() {
this.$store.dispatch('LogOut').then(() => {
location.reload()// In order to re-instantiate the vue-router object to avoid bugs
})
}
}
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.navbar {
height: 60px;
line-height: 60px;
border-radius: 0px !important;
.errLog-container {
display: inline-block;
vertical-align: top;
}
.right-menu {
float: right;
height: 100%;
&:focus{
outline: none;
}
.right-menu-item {
vertical-align: middle;
display: inline-block;
margin: 0 8px;
}
}
}
</style>
| 33,848
|
https://github.com/ixofoundation/ixo-webclient/blob/master/src/modules/Entities/SelectedEntity/EntityEdit/EditTemplate/EditTemplate.action.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
ixo-webclient
|
ixofoundation
|
TypeScript
|
Code
| 1,253
| 4,562
|
import { Dispatch } from 'redux'
import { FormData } from 'common/components/JsonForm/types'
import { ApiListedEntity } from 'common/api/blocksync-api/types/entities'
import blocksyncApi from 'common/api/blocksync-api/blocksync-api'
import { ApiResource } from 'common/api/blocksync-api/types/resource'
import { PageContent } from 'common/api/blocksync-api/types/page-content'
import { fromBase64 } from 'js-base64'
import { v4 as uuidv4 } from 'uuid'
import {
UpdateExistingEntityDidAction,
EditEntityTemplateActions,
ValidatedAction
} from './types'
import { importEntityPageContent } from '../EditEntityPageContent/EditEntityPageContent.actions'
import { importEntityClaims } from '../EditEntityClaims/EditEntityClaims.actions'
import { importEntitySettings } from '../EditEntitySettings/EditEntitySettings.actions'
import { importEntityAdvanced } from '../EditEntityAdvanced/EditEntityAdvanced.actions'
// const PDS_URL = process.env.REACT_APP_PDS_URL
export const updateExistingEntityDid = (formData: FormData): UpdateExistingEntityDidAction => {
const { existingEntityDid } = formData
return {
type: EditEntityTemplateActions.UpdateExistingEntityDid,
payload: {
existingEntityDid
}
}
}
export const fetchExistingEntity = (did: string) =>(
dispatch: Dispatch) => {
const fetchEntity: Promise<ApiListedEntity> = blocksyncApi.project.getProjectByProjectDid(
did,
)
const fetchContent = (
key: string,
cellNodeEndpoint: string,
): Promise<ApiResource> =>
blocksyncApi.project.fetchPublic(key, cellNodeEndpoint) as Promise<ApiResource>
fetchEntity.then((apiEntity: ApiListedEntity): any => {
let cellNodeEndpoint =
apiEntity.data.nodes.items.find((item) => item['@type'] === 'CellNode')
.serviceEndpoint ?? null
if (!cellNodeEndpoint) {
alert('CellNode does not exist!')
return dispatch({
type: EditEntityTemplateActions.FetchExistingEntityFailure,
})
}
cellNodeEndpoint =
cellNodeEndpoint + (cellNodeEndpoint.slice(-1) === '/' ? '' : '/')
console.log(cellNodeEndpoint)
return fetchContent(apiEntity.data.page.cid, cellNodeEndpoint).then((resourceData: ApiResource) => {
console.log(111, resourceData)
const content: PageContent = JSON.parse(
fromBase64(resourceData.data),
)
console.log(111, content)
const { header, body, images, profiles, social, embedded } = content
let identifiers = []
const pageContent = {
header: {
"title": header.title,
"shortDescription": header.shortDescription,
"sdgs": header.sdgs,
"brand": header.brand,
"location": header.location,
"headerFileSrc": header.image,
"headerFileUploading": false,
"logoFileSrc": header.logo,
"logoFileUploading": false
},
body: body.reduce((obj, item) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
title: item.title,
content: item.content,
fileSrc: item.image,
uploading: false,
}
}
}, {}),
images: images.reduce((obj, item) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
title: item.title,
content: item.content,
fileSrc: item.image,
uploading: false,
}
}
}, {}),
profiles: profiles.reduce((obj, item) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
name: item.name,
position: item.position,
fileSrc: item.image,
uploading: false,
}
}
}, {}),
social: {
linkedInUrl: social.linkedInUrl,
facebookUrl: social.facebookUrl,
twitterUrl: social.twitterUrl,
discourseUrl: social.discourseUrl,
instagramUrl: social.instagramUrl,
telegramUrl: social.telegramUrl,
githubUrl: social.githubUrl,
otherUrl: social.otherUrl,
},
embedded: embedded.reduce((obj, item) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
title: item.title,
urls: item.urls,
}
}
}, {}),
}
const validation = {
"header": {
"identifier": "header",
"validated": true,
"errors": []
},
"social": {
"identifier": "social",
"validated": true,
"errors": []
},
...identifiers.reduce((obj, identifier) => {
return {
...obj,
[identifier]: {
identifier,
validated: true,
errors: []
}
}
}, {})
}
dispatch(importEntityPageContent({
validation,
...pageContent
}))
const { entityClaims } = apiEntity.data
identifiers = []
dispatch(importEntityClaims({
"entityClaims": entityClaims.items.reduce((obj, entityClaim) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
template: {
id: uuidv4(),
entityClaimId: uuid,
templateId: entityClaim['@id'],
title: entityClaim.title,
description: entityClaim.description,
isPrivate: entityClaim.visibility !== "Public",
minTargetClaims: entityClaim.targetMin,
maxTargetClaims: entityClaim.targetMax,
goal: entityClaim.goal,
submissionStartDate: entityClaim.startDate,
submissionEndDate: entityClaim.endDate
},
agentRoles: entityClaim.agents.reduce((obj, agent) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
entityClaimId: entityClaim['@id'],
role: agent.role,
autoApprove: agent.autoApprove,
credential: agent.credential
}
}
}, {}),
evaluations: entityClaim.claimEvaluation.reduce((obj, evaluation) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
entityClaimId: entityClaim['@id'],
context: evaluation['@context'],
contextLink: evaluation['@context'],
evaluationAttributes: evaluation.attributes,
evaluationMethodology: evaluation.methodology
}
}
}, {}),
approvalCriteria: entityClaim.claimApproval.reduce((obj, approval) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
entityClaimId: entityClaim['@id'],
context: approval['@context'],
contextLink: approval['@context'],
approvalAttributes: approval.criteria
}
}
}, {}),
enrichments: entityClaim.claimEnrichment.reduce((obj, enrichment) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
entityClaimId: entityClaim['@id'],
context: enrichment['@context'],
contextLink: enrichment['@context'],
resources: enrichment.resources
}
}
}, {})
}
}
}, {}),
"validation": {
...identifiers.reduce((obj, identifier) => {
return {
...obj,
[identifier]: {
identifier,
validated: true,
errors: []
}
}
}, {}),
"creator": {
"identifier": "creator",
"validated": true,
"errors": []
},
"owner": {
"identifier": "owner",
"validated": true,
"errors": []
},
"status": {
"identifier": "status",
"validated": true,
"errors": []
},
"headline": {
"identifier": "headline",
"validated": true,
"errors": []
},
"version": {
"identifier": "version",
"validated": true,
"errors": []
},
"termsofuse": {
"identifier": "termsofuse",
"validated": true,
"errors": []
},
"privacy": {
"identifier": "privacy",
"validated": true,
"errors": []
},
"filter": {
"identifier": "filter",
"validated": true,
"errors": []
}
}
}))
const { creator, owner, startDate, endDate, stage, version, terms, privacy, ddoTags, displayCredentials, headlineMetric, embeddedAnalytics, linkedEntities, funding, fees, stake, nodes, keys, service, data } = apiEntity.data
identifiers = []
dispatch(importEntitySettings({
"creator": {
"displayName": creator.displayName,
"location": creator.location,
"email": creator.email,
"website": creator.website,
"mission": creator.mission,
"creatorId": creator.id,
"fileSrc": creator.logo,
"uploading": false
},
"owner": {
"displayName": owner.displayName,
"location": owner.location,
"email": owner.email,
"website": owner.website,
"mission": owner.mission,
"ownerId": owner.id,
"fileSrc": owner.logo,
"uploading": false
},
"status": {
"startDate": startDate,
"endDate": endDate,
"stage": stage,
},
"version": {
"versionNumber": version.versionNumber,
"effectiveDate": version.effectiveDate
},
"termsOfUse": {
"type": terms['@type'],
"paymentTemplateId": terms.paymentTemplateId
},
"privacy": {
"pageView": privacy.pageView,
"entityView": privacy.entityView
},
"requiredCredentials": {},
"filters": {
"Project Type": ddoTags[0] ? ddoTags[0].tags : undefined,
"SDG": ddoTags[1] ? ddoTags[1].tags : undefined,
"Stage": ddoTags[2] ? ddoTags[2].tags : undefined,
"Sector": ddoTags[3] ? ddoTags[3].tags : undefined
},
"displayCredentials": displayCredentials.items.reduce((obj, item) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
credential: item.credential,
badge: item.badge
}
}
}, {}),
"validation": {
...identifiers.reduce((obj, identifier) => {
return {
...obj,
[identifier]: {
identifier,
validated: true,
errors: []
}
}
}, {}),
"creator": {
"identifier": "creator",
"validated": true,
"errors": []
},
"owner": {
"identifier": "owner",
"validated": true,
"errors": []
},
"status": {
"identifier": "status",
"validated": true,
"errors": []
},
"headline": {
"identifier": "headline",
"validated": true,
"errors": []
},
"version": {
"identifier": "version",
"validated": true,
"errors": []
},
"termsofuse": {
"identifier": "termsofuse",
"validated": true,
"errors": []
},
"privacy": {
"identifier": "privacy",
"validated": true,
"errors": []
},
"filter": {
"identifier": "filter",
"validated": true,
"errors": []
}
},
"headlineTemplateId": headlineMetric ? headlineMetric.claimTemplateId : undefined,
"embeddedAnalytics": embeddedAnalytics.reduce((obj, item) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
title: item.title,
urls: item.urls
}
}
}, {})
}))
identifiers = []
dispatch(importEntityAdvanced({
"linkedEntities": linkedEntities.reduce((obj, linkedEntity) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
type: linkedEntity['@type'],
entityId: linkedEntity.id
}
}
}, {}),
"payments": fees.items.reduce((obj, fee) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
type: fee['@type'],
paymentId: fee.id
}
}
}, {}),
"staking": stake.items.reduce((obj, item) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
...obj,
[uuid]: {
id: uuid,
stakeId: item.id,
type: item['@type'],
denom: item.denom,
stakeAddress: item.stakeAddress,
minStake: item.minStake,
slashCondition: item.slashCondition,
slashFactor: item.slashFactor,
slashAmount: item.slashAmount,
unbondPeriod: item.unbondPeriod
}
}
}, {}) ,
"nodes": nodes.items.reduce((obj, node) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
[uuid]: {
id: uuid,
type: node['@type'],
nodeId: node.id,
serviceEndpoint: node.serviceEndpoint
}
}
}, {}),
"funding": funding.items.reduce((obj, fund) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
[uuid]: {
id: uuid,
source: fund['@type'],
fundId: fund.id
}
}
}, {}),
"keys": keys.items.reduce((obj, key) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
[uuid]: {
id: uuid,
purpose: key.purpose,
type: key['@type'],
keyValue: key.keyValue,
controller: key.controller,
signature: key.signature,
dateCreated: key.dateCreated,
dateUpdated: key.dateUpdated
}
}
}, {}),
"services": service.reduce((obj, item) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
[uuid]: {
id: uuid,
type: item['@type'],
shortDescription: item.description,
serviceEndpoint: item.serviceEndpoint,
publicKey: item.publicKey,
properties: item.properties,
serviceId: item.id
}
}
}, {}),
"dataResources": data.reduce((obj, item) => {
const uuid = uuidv4()
identifiers.push(uuid)
return {
[uuid]: {
id: uuid,
type: item['@type'],
dataId: item.id,
serviceEndpoint: item.serviceEndpoint,
properties: item.properties
}
}
}, {}),
"validation": identifiers.reduce((obj, identifier) => {
return {
...obj,
[identifier]: {
identifier,
validated: true,
errors: []
}
}
}, {})
}))
dispatch({
type: EditEntityTemplateActions.FetchExistingEntitySuccess
})
})
}).catch((err) => {
dispatch({
type: EditEntityTemplateActions.FetchExistingEntityFailure,
})
})
}
export const validated = (identifier: string): ValidatedAction => ({
type: EditEntityTemplateActions.Validated,
payload: {
identifier,
},
})
| 50,997
|
https://github.com/LykkeCity/EthereumApiDotNetCore/blob/master/src/Service.UnitTests/Config.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
EthereumApiDotNetCore
|
LykkeCity
|
C#
|
Code
| 54
| 233
|
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Lykke.Service.EthereumCore.Services.Signature;
using EthereumSamuraiApiCaller;
// ReSharper disable once CheckNamespace
namespace Service.UnitTests
{
public class Config
{
public static IServiceProvider Services { get; set; }
public async Task Initialize()
{
IServiceCollection collection = new ServiceCollection();
collection.AddSingleton<INonceCalculator, Mocks.MockNonceCalculator>();
collection.AddSingleton<IEthereumSamuraiAPI, Mocks.MockEthereumSamuraiApi>();
collection.AddSingleton<IEthereumSamuraiAPI, Mocks.MockEthereumSamuraiApi>();
collection.AddSingleton<ISignatureChecker, SignatureChecker>();
Services = collection.BuildServiceProvider();
}
}
}
| 43,078
|
https://github.com/yanghao2777/PassEncrypt/blob/master/encrypt-api/build.gradle
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
PassEncrypt
|
yanghao2777
|
Gradle
|
Code
| 106
| 354
|
apply plugin: 'java-library'
//apply plugin: 'com.novoda.bintray-release'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'org.xxtea:xxtea-java:1.0.5'
}
sourceCompatibility = "8"
targetCompatibility = "8"
def getPropertyFromLocalProperties(key) {
File file = project.rootProject.file('local.properties')
if (file.exists()) {
Properties properties = new Properties()
properties.load(file.newDataInputStream())
return properties.getProperty(key)
}
}
def groupName = 'com.wcg.field.encrypt'
def artifactName = 'encrypt-api'
def pubVersion = '0.0.4'
//publish {
// userOrg = 'wangkunlin1992'
// groupId = groupName
// artifactId = artifactName
// publishVersion = pubVersion
// uploadName = groupName + ':' + artifactName
// desc = 'a gradle plugin to handle annotation'
// website = 'https://github.com/wangkunlin/PassEncrypt'
// bintrayUser = getPropertyFromLocalProperties('bintray.user')
// bintrayKey = getPropertyFromLocalProperties('bintray.apikey')
// dryRun = false
//}
| 29,505
|
https://github.com/xueqiya/chromium_src/blob/master/out/release/gen/device/vr/public/mojom/browser_test_interfaces.mojom-forward.h
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
chromium_src
|
xueqiya
|
C++
|
Code
| 226
| 1,042
|
// device/vr/public/mojom/browser_test_interfaces.mojom-forward.h is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DEVICE_VR_PUBLIC_MOJOM_BROWSER_TEST_INTERFACES_MOJOM_FORWARD_H_
#define DEVICE_VR_PUBLIC_MOJOM_BROWSER_TEST_INTERFACES_MOJOM_FORWARD_H_
#include <stdint.h>
#include "mojo/public/cpp/bindings/struct_forward.h"
#include "mojo/public/cpp/bindings/deprecated_interface_types_forward.h"
#include "mojo/public/interfaces/bindings/native_struct.mojom-forward.h"
namespace device_test {
namespace mojom {
class ColorDataView;
class SubmittedFrameDataDataView;
class PoseFrameDataDataView;
class ProjectionRawDataView;
class DeviceConfigDataView;
class ControllerAxisDataDataView;
class ControllerFrameDataDataView;
class EventDataDataView;
enum class Eye : int32_t;
enum class TrackedDeviceClass : int32_t;
enum class ControllerRole : int32_t;
enum class EventType : int32_t;
enum class InteractionProfileType : int32_t;
class Color;
using ColorPtr = mojo::InlinedStructPtr<Color>;
class SubmittedFrameData;
using SubmittedFrameDataPtr = mojo::StructPtr<SubmittedFrameData>;
class PoseFrameData;
using PoseFrameDataPtr = mojo::StructPtr<PoseFrameData>;
class ProjectionRaw;
using ProjectionRawPtr = mojo::InlinedStructPtr<ProjectionRaw>;
class DeviceConfig;
using DeviceConfigPtr = mojo::StructPtr<DeviceConfig>;
class ControllerAxisData;
using ControllerAxisDataPtr = mojo::InlinedStructPtr<ControllerAxisData>;
class ControllerFrameData;
using ControllerFrameDataPtr = mojo::StructPtr<ControllerFrameData>;
class EventData;
using EventDataPtr = mojo::InlinedStructPtr<EventData>;
class XRTestHook;
using XRTestHookPtr = mojo::InterfacePtr<XRTestHook>;
using XRTestHookPtrInfo = mojo::InterfacePtrInfo<XRTestHook>;
using ThreadSafeXRTestHookPtr =
mojo::ThreadSafeInterfacePtr<XRTestHook>;
using XRTestHookRequest = mojo::InterfaceRequest<XRTestHook>;
using XRTestHookAssociatedPtr =
mojo::AssociatedInterfacePtr<XRTestHook>;
using ThreadSafeXRTestHookAssociatedPtr =
mojo::ThreadSafeAssociatedInterfacePtr<XRTestHook>;
using XRTestHookAssociatedPtrInfo =
mojo::AssociatedInterfacePtrInfo<XRTestHook>;
using XRTestHookAssociatedRequest =
mojo::AssociatedInterfaceRequest<XRTestHook>;
class XRServiceTestHook;
using XRServiceTestHookPtr = mojo::InterfacePtr<XRServiceTestHook>;
using XRServiceTestHookPtrInfo = mojo::InterfacePtrInfo<XRServiceTestHook>;
using ThreadSafeXRServiceTestHookPtr =
mojo::ThreadSafeInterfacePtr<XRServiceTestHook>;
using XRServiceTestHookRequest = mojo::InterfaceRequest<XRServiceTestHook>;
using XRServiceTestHookAssociatedPtr =
mojo::AssociatedInterfacePtr<XRServiceTestHook>;
using ThreadSafeXRServiceTestHookAssociatedPtr =
mojo::ThreadSafeAssociatedInterfacePtr<XRServiceTestHook>;
using XRServiceTestHookAssociatedPtrInfo =
mojo::AssociatedInterfacePtrInfo<XRServiceTestHook>;
using XRServiceTestHookAssociatedRequest =
mojo::AssociatedInterfaceRequest<XRServiceTestHook>;
} // namespace mojom
} // namespace device_test
#endif // DEVICE_VR_PUBLIC_MOJOM_BROWSER_TEST_INTERFACES_MOJOM_FORWARD_H_
| 23,803
|
https://github.com/MSFTAuDX/BrickBand/blob/master/src/uwp/BrickBand/BrickBand.UWP/View/Base/CameraPageBase.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
BrickBand
|
MSFTAuDX
|
C#
|
Code
| 321
| 1,125
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.Devices.Enumeration;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.System.Display;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Navigation;
using Autofac;
using BrickBand.UWP.Model.Contract;
namespace BrickBand.UWP.View.Base
{
public class CameraPageBase : ViewModelPageBase
{
protected MediaCapture _mediaCapture;
protected DisplayRequest _displayRequest = new DisplayRequest();
public CameraPageBase()
{
}
protected async Task InitDevice()
{
try
{
_mediaCapture = new MediaCapture();
var device = await FindDevice();
await _mediaCapture.InitializeAsync(new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview,
VideoDeviceId = device.Id
});
var maxResolution = _mediaCapture.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo).Aggregate((i1, i2) => (i1 as VideoEncodingProperties).Width > (i2 as VideoEncodingProperties).Width ? i1 : i2);
await _mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, maxResolution);
_displayRequest.RequestActive();
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Landscape;
}
catch (UnauthorizedAccessException)
{
// This will be thrown if the user denied access to the camera in privacy settings
ShowMessageToUser("The app was denied access to the camera");
return;
}
}
protected async Task<SoftwareBitmap> Capture()
{
//using (var stream = new InMemoryRandomAccessStream())
//{
// var properties = ImageEncodingProperties.CreateJpeg();
// await _mediaCapture.CapturePhotoToStreamAsync(properties, stream);
// var decoder = await BitmapDecoder.CreateAsync(stream);
// var sfbmp = await decoder.GetSoftwareBitmapAsync();
//}
//var picturesLibrary = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Pictures);
//// Fall back to the local app storage if the Pictures Library is not available
//var _captureFolder = picturesLibrary.SaveFolder ?? ApplicationData.Current.LocalFolder;
////var stream2 = new InMemoryRandomAccessStream();
//try
//{
// // Take and save the photo
// var file = await _captureFolder.CreateFileAsync("SimplePhoto.jpg", CreationCollisionOption.GenerateUniqueName);
// await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), file);
// //rootPage.NotifyUser("Photo taken, saved to: " + file.Path, NotifyType.StatusMessage);
//}
//catch (Exception ex)
//{
// // File I/O errors are reported as exceptions.
// //rootPage.NotifyUser("Exception when taking a photo: " + ex.Message, NotifyType.ErrorMessage);
//}
// Prepare and capture photo
var lowLagCapture = await _mediaCapture.PrepareLowLagPhotoCaptureAsync(ImageEncodingProperties.CreateUncompressed(MediaPixelFormat.Bgra8));
var capturedPhoto = await lowLagCapture.CaptureAsync();
var softwareBitmap = capturedPhoto.Frame.SoftwareBitmap;
await lowLagCapture.FinishAsync();
return softwareBitmap;
}
protected async Task<DeviceInformation> FindDevice()
{
// Get available devices for capturing pictures
var allVideoDevices = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
return allVideoDevices[SettingsService.CameraIndex];
}
protected void DisposeMediaDevice()
{
_mediaCapture.Dispose();
_mediaCapture = null;
}
protected void ShowMessageToUser(string message)
{
}
}
}
| 26,498
|
https://github.com/DG-xixuan/uwcssa_ca/blob/master/frontend/src/containers/Login.js
|
Github Open Source
|
Open Source
|
MIT, PostgreSQL, Unlicense
| 2,021
|
uwcssa_ca
|
DG-xixuan
|
JavaScript
|
Code
| 476
| 1,796
|
import React, { useState } from "react";
import Avatar from "@material-ui/core/Avatar";
import { Button } from "@material-ui/core";
import CssBaseline from "@material-ui/core/CssBaseline";
import TextField from "@material-ui/core/TextField";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";
// import Link from "@material-ui/core/Link";
import Grid from "@material-ui/core/Grid";
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import Container from "@material-ui/core/Container";
import { connect } from "react-redux";
import { login } from "../redux/actions/authActions";
import { Redirect } from "react-router-dom";
import { Box} from "@material-ui/core";
import { Link } from "react-router-dom";
import googleLogo from "../static/google.png"
import wechatLogo from "../static/wechat.png"
import { useLocation } from "react-router-dom";
import Auth from "@aws-amplify/auth";
import { useHistory } from "react-router-dom";
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: "flex",
flexDirection: "column",
alignItems: "center",
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: "75%", // Fix IE 11 issue.
marginTop: theme.spacing(1),
margin: "auto",
marginBottom: theme.spacing(5),
},
submit: {
margin: theme.spacing(5, 4, 0),
},
button: {
marginLeft: "1rem",
marginRight: "4rem",
},
third_party_button: {
width: 426,
height: 64,
marginBottom: "5rem",
},
wechatLogo: {
width: 24,
height: 24,
marginRight: "9rem",
},
googleLogo: {
width: 24,
height: 24,
marginRight: "8rem",
},
}));
const Login = ({ onSignIn, loggedIn }) => {
const classes = useStyles();
const history = useHistory();
const [formData, setFormData] = useState({
email: "",
password: "",
});
const location = useLocation();
const referer = location.state;
const { email, password } = formData;
const onChange = (event) =>
setFormData({ ...formData, [event.target.name]: event.target.value });
const handleSubmit = async function (event) {
event.preventDefault();
try {
const response = await Auth.signIn(email, password);
console.log("auth response", response);
history.push('/');
onSignIn();
} catch (error) {
console.log("there was an error logging in ", error);
}
};
let from;
if (referer != null) {
from = referer.from;
}
const urlTo = from || "/";
if (loggedIn) {
return <Redirect to={urlTo} />;
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5" align="left">
登入
</Typography>
<Typography>
还没有账户?
<Link to="/register">注册</Link>
</Typography>
<form
className={classes.form}
noValidate
onSubmit={(event) => handleSubmit(event)}
>
<TextField
variant="standard"
margin="normal"
required
id="email"
label="Email Address"
name="email"
fullWidth
autoComplete="email"
autoFocus
value={email}
onChange={(event) => onChange(event)}
/>
<TextField
variant="standard"
margin="normal"
required
name="password"
fullWidth
label="Password"
type="password"
id="password"
autoComplete="current-password"
value={password}
onChange={(event) => onChange(event)}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="我不是机器人"
/>
<Grid container>
<Button
type="submit"
variant="outlined"
color="primary"
className={classes.submit}
>
登陆
</Button>
<Button // 这个忘记密码的按钮不知道为什么不能redirect
// type="button"
variant="outlined"
component={Link}
to="/forgotpassword"
color="primary"
className={classes.submit}
>
忘记密码
</Button>
</Grid>
</form>
<Box marginTop="3rem">
<Button
type="submit"
variant="outlined"
className={classes.third_party_button}
onClick={() => Auth.federatedSignIn({ provider: "Google" })}
>
<Grid
container
direction="row"
justifyContent="flex-start"
alignItems="center"
>
<Grid>
<img
src={googleLogo}
alt="googleLogo"
className={classes.googleLogo}
/>
</Grid>
<Grid>
Google登入
</Grid>
</Grid>
</Button>
<Button
type="submit"
variant="outlined"
className={classes.third_party_button}
>
<Grid
container
direction="row"
justifyContent="flex-start"
alignItems="center"
>
<Grid>
<img
src={wechatLogo}
alt="wechatLogo"
className={classes.wechatLogo}
/>
</Grid>
<Grid>
微信登入
</Grid>
</Grid>
</Button>
</Box>
</div>
</Container>
);
};
const mapStateToProps = (state) => ({
isAuthenticated: state.userAuth.isAuthenticated,
});
export default connect(mapStateToProps, { login })(Login);
| 29,600
|
https://github.com/gprossignoli/Networks_Analysis_final_project/blob/master/src/Logic/SimulationLogic/OverloadModelUtils/ChartReport.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
Networks_Analysis_final_project
|
gprossignoli
|
Java
|
Code
| 194
| 842
|
package Logic.SimulationLogic.OverloadModelUtils;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtils;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYSplineRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ChartReport {
private List<Integer> downedNodesPerIterationModeA;
private List<Integer> downedNodesPerIterationModeB;
public ChartReport(){
downedNodesPerIterationModeA = new ArrayList<>();
downedNodesPerIterationModeB = new ArrayList<>();
}
public boolean addData(Integer downedNodes,String mode){
if(mode.equals("A"))
this.downedNodesPerIterationModeA.add(downedNodes);
else if(mode.equals("B"))
this.downedNodesPerIterationModeB.add(downedNodes);
else
return false;
return true;
}
public boolean buildChart(){
XYSeries serieA = new XYSeries("Mode A");
XYSeries serieB = new XYSeries("Mode B");
for (int i = 0; i < downedNodesPerIterationModeA.size();i++){
serieA.add(i,downedNodesPerIterationModeA.get(i));
}
for (int j = 0; j < downedNodesPerIterationModeB.size();j++){
serieB.add(j,downedNodesPerIterationModeB.get(j));
}
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(serieA);
dataset.addSeries(serieB);
NumberAxis xAxis = new NumberAxis("iteration");
NumberAxis yAxis = new NumberAxis("downed nodes");
XYSplineRenderer r = new XYSplineRenderer(3);
XYPlot xyPlot = new XYPlot(dataset,xAxis,yAxis,r);
JFreeChart chart = new JFreeChart(xyPlot);
try{
String fileSeparator = System.getProperty("file.separator");
String relativePath = "./results";
File file = new File(relativePath);
if(!file.exists())
if(!file.mkdir())
return false;
relativePath += fileSeparator + "overloadModel";
file = new File(relativePath);
if(!file.exists())
if(!file.mkdir())
return false;
relativePath += fileSeparator + "overload_model_Chart.PNG";
file = new File(relativePath);
//creates the file
ChartUtils.saveChartAsPNG(file,chart,400,400);
}
catch (IOException e){
return false;
}
return true;
}
}
| 2,324
|
https://github.com/krystianwieczorek/html-js-portfolio-webpage/blob/master/Local_Timer.js
|
Github Open Source
|
Open Source
|
MIT
| null |
html-js-portfolio-webpage
|
krystianwieczorek
|
JavaScript
|
Code
| 40
| 139
|
function timer(){
let today = new Date();
let hours = today.getHours();
if(hours<10) hours = "0"+hours;
let minutes = today.getMinutes();
if(minutes<10) minutes = "0"+minutes;
let seconds = today.getSeconds();
if(seconds<10) seconds = "0"+seconds;
document.getElementById("clock").innerHTML = +hours+ ":" +minutes+ ":" +seconds;
setTimeout("timer()",1000);
}
| 6,968
|
https://github.com/joelbrinkley/NetStreams.Insights/blob/master/src/NetStreams.ControlCenter/Server/NetStreams.ControlCenter.TelemetryProcessor/EventHandlers/StreamStoppedNotificationHandler.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
NetStreams.Insights
|
joelbrinkley
|
C#
|
Code
| 55
| 226
|
using MediatR;
using NetStreams.ControlCenter.Models.Abstractions;
using System.Threading;
using System.Threading.Tasks;
namespace NetStreams.ControlCenter.TelemetryProcessor.EventHandlers
{
public class StreamStoppedNotificationHandler : INotificationHandler<StreamStoppedNotification>
{
private IStreamProcessorRepository _streamProcessorRepository;
public StreamStoppedNotificationHandler(IStreamProcessorRepository streamProcessorRepository)
{
_streamProcessorRepository = streamProcessorRepository;
}
public async Task Handle(StreamStoppedNotification notification, CancellationToken cancellationToken)
{
var streamProcessor = await _streamProcessorRepository.GetAsync(notification.StreamProcessorName, cancellationToken);
if(streamProcessor!= null)
{
streamProcessor.Running = false;
await _streamProcessorRepository.UpdateAsync(streamProcessor, cancellationToken);
}
}
}
}
| 38,195
|
https://github.com/Kunstmaan/rocketeer/blob/master/bin/rocketeer
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
rocketeer
|
Kunstmaan
|
PHP
|
Code
| 44
| 132
|
#!/usr/bin/env php
<?php
$vendors = array(
__DIR__.'/../vendor/autoload.php',
__DIR__.'/../../../autoload.php'
);
// Loop through the possible vendor folders and require the first
// one available
foreach ($vendors as $vendor) {
if (file_exists($vendor)) {
require $vendor;
}
}
// Then we launch the console application
return Rocketeer\Facades\Console::run();
| 7,285
|
https://github.com/alissonads/basic_employment_agency/blob/master/bea/public/js/main.js
|
Github Open Source
|
Open Source
|
MIT
| null |
basic_employment_agency
|
alissonads
|
JavaScript
|
Code
| 2,740
| 9,243
|
function getElement(type, name) {
switch (type) {
case "id":
return document.getElementById(name);
break;
case "class":
return document.getElementsByClassName(name);
break;
case "name":
return document.getElementsByName(name);
break;
case "tag":
return document.getElementsByTagName(name);
break;
}
return null;
}
function setContent(element, content) {
element.innerHTML = content;
}
function validateNonEmpty(elem) {
return elem.value.length > 0;
}
function mask(elem, mk, reverse = false) {
if (elem.getAttribute('maxlength') &&
elem.value.length >= mk.length)
return;
var key= (window.event)? event.keyCode : event.which;
if (key > 47 && key < 58 || key == 8 || key == 0) {
elem.value = MaskSpecialist.apply(elem.value, mk, reverse)
}
}
function reset() {
var v = getElement('tag', 'input');
for (var i = 0; i < v.length; i++) {
if (v[i].type != "submit" &&
v[i].type != "button") {
v[i].value = '';
}
}
v = getElement('tag', 'textarea');
for (var i = 0; i < v.length; i++) {
v[i].value = '';
}
v = getElement('tag', 'select');
for (var i = 0; i < v.length; i++) {
v[i].value = '';
}
}
function addErrorInfo(parent, id, text) {
if(getElement('id', id))
return;
var error = new Element('label');
error.addAtt('class', 'error')
.addAtt('id', id)
.setContent(text);
parent.appendChild(error.get());
}
function removeErrorInfo(parent, errorId) {
var elemError = getElement('id', errorId);
if (elemError)
parent.removeChild(elemError);
}
function validateInfoExperienceRequested(form) {
var valid = true;
if (!validateNonEmpty(form["company_name"])) {
form["company_name"].style.setProperty("border-color", "#F00");
addErrorInfo(form["company_name"].parentElement,
'cpn-name-error',
'*Este campo é requerido');
valid = false;
}
if (!validateNonEmpty(form["func"])) {
form["func"].style.setProperty("border-color", "#F00");
addErrorInfo(form["func"].parentElement,
'func-error',
'*Este campo é requerido');
valid = false;
}
if (!validateNonEmpty(form["description"])) {
form["description"].style.setProperty("border-color", "#F00");
addErrorInfo(form["description"].parentElement,
'desc-error',
'*Este campo é requerido');
valid = false;
}
if (!validateNonEmpty(form["date_entrance"])) {
form["date_entrance"].style.setProperty("border-color", "#F00");
addErrorInfo(form["date_entrance"].parentElement,
'dt-ent-error',
'*Este campo é requerido');
valid = false;
} else if(!(/^\d{2}\/\d{2}\/\d{4}$/).test(form["date_entrance"].value)) {
form["date_entrance"].style.setProperty("border-color", "#F00");
addErrorInfo(form["date_entrance"].parentElement,
'dt-ent-error',
'*Entrada inválida');
valid = false;
} else if(!validateDate(form["date_entrance"].value)) {
form["date_entrance"].style.setProperty("border-color", "#F00");
addErrorInfo(form["date_entrance"].parentElement,
'dt-ent-error',
'*Data informada inválida');
valid = false;
}
if (validateNonEmpty(form["date_exit"])) {
if (!(/^\d{2}\/\d{2}\/\d{4}$/).test(form["date_exit"].value)) {
valid = false;
} else if (!validateDate(form["date_exit"].value)) {
form["date_exit"].style.setProperty("border-color", "#F00");
addErrorInfo(form["date_exit"].parentElement,
'dt-exit-error',
'*Data informada inválida');
valid = false;
}
}
return valid;
}
function addExperience(form) {
if (validateInfoExperienceRequested(form)) {
getElement("id", "included-experiences").style.removeProperty('display');
var result = getElement("id", "result");
var size = result.childElementCount;
if (size > 0) {
for (var i = 0; i < size; i++) {
if (form["company_name"].value == result.children[i].children[0].innerHTML &&
form['func'].value == result.children[i].children[1].innerHTML) {
showInfo('Rgistro de Experiência', 'Experiência já cadastrado');
reset();
return;
}
}
}
var div = '<div class="tr-content" id="' + 'exp-' + size + '">'+
'<div class="td-content" data-heading="Empresa">'+ form['company_name'].value + '</div>' +
'<div class="td-content" data-heading="Função">' + form['func'].value + '</div>' +
'<div class="td-content" data-heading="Entrada">' + form['date_entrance'].value + '</div>' +
'<div class="td-content" data-heading="Saída">' + form['date_exit'].value + '</div>' +
'<div style="display:none;" data-heading="Ramo">' + form['specialty'].value + '</div>' +
'<div style="display:none;" data-heading="Atividades">' + form['description'].value + '</div>' +
'<div class="td-content">editar/excluir</div>'
'</div>';
result.innerHTML += div;
reset();
}
}
function validateRegisterExperience(form) {
var result = getElement('id', 'result');
var size = result.childElementCount;
var elements = '';
for (var i = 0; i < size; i++) {
elements += '<input type="hidden" name="' + result.children[i].id + '" value="';
var s = result.children[i].childElementCount - 1;
var c = result.children[i];
for (var j = 0; j < s; j++) {
elements += c.children[j].innerHTML;
elements += ((j+1) < s)? '|' : ''
}
elements += '" />'
}
var content = form.innerHTML;
form.innerHTML = elements;
form.innerHTML += content;
activeProgress();
return true;
}
function testRegex(value, exp) {
return exp.test(value);
}
function validateText(elem, errorId) {
if (validateNonEmpty(elem)) {
removeErrorInfo(elem.parentElement, errorId)
elem.style.removeProperty("border-color");
}
}
function createErrorInfo(elem, errorId, info) {
var elemError = getElement('id', errorId);
if (elemError) {
elemError.innerHTML = info;
} else {
addErrorInfo(elem.parentElement, errorId, info);
elem.style.setProperty("border-color", "#F00");
}
}
function validateForRegex(elem, errorId, exp) {
if (validateNonEmpty(elem)) {
if (!exp.test(elem.value)) {
var info = '*Entrada inválida';
createErrorInfo(elem, errorId, info);
} else {
removeErrorInfo(elem.parentElement, errorId);
elem.style.removeProperty("border-color");
}
}
}
function validatePassword(elem, errorId) {
if (validateNonEmpty(elem)) {
if (elem.value.length < 6) {
var info = 'Senha pequena (minimo de caracteres 6)';
createErrorInfo(elem, errorId, info);
} else {
removeErrorInfo(elem.parentElement, errorId);
elem.style.removeProperty("border-color");
}
}
}
function validateRadio(elem, errorId) {
if (elem.checked) {
var elemError = getElement('id', errorId);
if (elemError)
elemError.parentElement.removeChild(elemError);
}
}
function verifyUserInfoIsEmpty(form) {
var empty = false;
if (!validateNonEmpty(form['username'])) {
var info = 'Este campo é requerido';
createErrorInfo(form['username'], 'username-error', info);
empty = true;
}
if (!validateNonEmpty(form['email'])) {
var info = 'Este campo é requerido';
createErrorInfo(form['email'], 'email-error', info);
empty = true;
}
if (!validateNonEmpty(form['name'])) {
var info = 'Este campo é requerido';
createErrorInfo(form['name'], 'name-error', info);
empty = true;
}
if (!validateNonEmpty(form['password'])) {
var info = 'Este campo é requerido';
createErrorInfo(form['password'], 'pw1-error', info);
empty = true;
}
if (!validateNonEmpty(form['password2'])) {
var info = 'Este campo é requerido';
createErrorInfo(form['password2'], 'pw2-error', info);
empty = true;
}
if (!form['gender-m'].checked && !form['gender-f'].checked) {
var info = 'Você deve escolher uma das duas opções';
createErrorInfo(form['gender-m'].parentElement.parentElement.parentElement, 'gender-error', info);
empty = true;
}
return empty;
}
function validateUserRegister(form) {
if (verifyUserInfoIsEmpty(form)) {
return false;
}
if ((form['password'].value.length == form['password2'].value.length) &&
(form['password'].value == form['password2'].value)) {
activeProgress();
return true;
}
form['password'].style.setProperty("border-color", "#F00");
form['password2'].style.setProperty("border-color", "#F00");
if (!getElement('id', 'pw-error-info-eq')) {
var info = '*As duas senhas devem ser iguais';
var parent = form['password'].parentElement.parentElement;
var elem = new Element('div');
elem.addAtt('id', 'pw-error-info-eq')
.setProperty('color', '#F00')
.setProperty('font-size', 'x-small')
.setProperty('font-style', 'italic')
.setProperty('width', '100%')
.setProperty('text-align', 'center')
.setProperty('margin-top', '5px')
.setContent(info);
parent.appendChild(elem.get());
}
return false;
}
function addFunction(form) {
if (!form['func'].value) {
var info = '*Escolha uma função para adicionar';
createErrorInfo(form['func'], 'func-error', info);
return;
}
removeErrorInfo(form['func'].parentElement, 'func-error');
form['func'].style.removeProperty("border-color");
var parent = getElement('id', 'result-funcs');
var size = parent.childElementCount;
if (size >= 3) {
showInfo('Registro de Informações Adicionais',
'Você pode cadastrar no máximo 3 funções');
form['func'].value = '';
return;
}
for (var i = 0; i < size; i++) {
if (parent.children[i].children[0].innerHTML == form['func'].value) {
//alert('Função (' + form['func'].value + ') já cadastrada');
showInfo('Registro de Informações Adicionais',
'Função (' + form['func'].value + ') já cadastrada');
form['func'].value = '';
return;
}
}
parent.parentElement.style.removeProperty('display');
var id = 'func-' + size;
var elem = new Element('div');
elem.addAtt('id', id)
.addAtt('name', id)
.addAtt('class', 'col-md-5')
.addAtt('style', 'margin-left:8px; margin-top:5px;')
.get().appendChild((new Element('div'))
.addAtt('class', 'col-1 width-90 result')
.setContent(form['func'].value).get());
elem.get().appendChild((new Element('div'))
.addAtt('class', 'mini-btn-close')
.addAtt('onclick', 'removeFunction(this)')
.setContent('X').get());
parent.appendChild(elem.get());
form['func'].value = '';
}
function removeFunction(elem) {
var parent = elem.parentElement;
var sParent = parent.parentElement;
sParent.removeChild(parent);
/*renomeia os elementos */
var size = sParent.childElementCount;
for (var i = 0; i < size; i++) {
sParent.children[i].id = 'func-' + i;
sParent.children[i].name = 'func-' + i;
}
}
function addObs(elem, size) {
if (elem.value.length == size) {
getElement('id', 'obs').style.removeProperty("display");
} else if (elem.value.length == 0) {
getElement('id', 'obs').style.setProperty('display', 'none');
getElement('id', 'message').checked = false;
getElement('id', 'own').checked = false;
}
}
function validateYear(year, date) {
var y = date.getFullYear();
if (year > y || year < (y - 60)) return -1;
if (year == y) return 0;
return 1;
}
function validateMonth(month, date) {
var m = date.getMonth() + 1;
if (month > 12 || month < 0) return -1;
if (month == m) return 0;
if (month > m) return 2;
return 1;
}
function month_31_days(month) {
return (month <= 7 && month % 2 == 1) ||
(month >= 8 && month % 2 == 0);
}
function leapYear(year) {
return (year % 4 == 0);
}
function february(year, month, day) {
if (leapYear(year)) {
if (month == 2 && day > 29) return false;
} else {
if (month == 2 && day > 28) return false;
}
return true;
}
function otherMonths(month, day) {
if (month_31_days(month)) {
if (day > 31) return false;
} else {
if (day > 30) return false;
}
return true;
}
function validateDate(value) {
var date = new Date();
var day = date.getDate();
//divide a string onde encontrar o caracter "/"
var v = value.split("/");
dt = new Array(parseInt(v[0]), parseInt(v[1]), parseInt(v[2]));
var y = validateYear(dt[2], date);
var m = validateMonth(dt[1], date);
if (y == -1 || m == -1 || day < 1) return false;
if (y == 0) {
if (m == 0) {
if (dt[0] > day) return false;
} else if (m == 2) {
return false;
} else if (!february(dt[2], dt[1], dt[0])) {
return false;
} else if (!otherMonths(dt[1], dt[0])) {
return false;
}
} else {
if (!february(dt[2], dt[1], dt[0])) {
return false;
} else if (!otherMonths(dt[1], dt[0])) {
return false;
}
}
return true;
}
function validateAdditionalInfo(form) {
var valid = true;
if (!validateNonEmpty(form['date_birth'])) {
var info = '*Este campo é requerido';
createErrorInfo(form['date_birth'], 'date_birth-error', info);
valid = false;
} else {
if (!validateDate(form["date_birth"].value)) {
var info = '*Data informada inválida';
createErrorInfo(form['date_birth'], 'date_birth-error', info);
valid = false;
}
}
if (!form['isbpd-s'].checked && !form['isbpd-n'].checked) {
var info = '*Você deve escolher uma das opções';
createErrorInfo(form['isbpd-s'].parentElement.parentElement.parentElement, 'isbpd-error', info);
valid = false;
}
if (!validateNonEmpty(form['cellular'])) {
var info = '*Este campo é requerido';
createErrorInfo(form['cellular'], 'cellular-error', info);
valid = false;
}
if (validateNonEmpty(form['residential']) &&
(!form['message'].checked && !form['own'].checked)) {
var info = '*Você deve escolher uma das opções';
createErrorInfo(form['message'].parentElement.parentElement.parentElement, 'observation-error', info);
valid = false;
}
if ((form['message'].checked || form['own'].checked) &&
!validateNonEmpty(form['residential'])) {
var info = '*Este campo é requerido';
createErrorInfo(form['residential'], 'residential-error', info);
valid = false;
}
if (!validateNonEmpty(form['city_state'])) {
var info = '*Este campo é requerido';
createErrorInfo(form['city_state'], 'city_state-error', info);
valid = false;
}
if (!validateNonEmpty(form['neighborhood'])) {
var info = '*Este campo é requerido';
createErrorInfo(form['neighborhood'], 'neighborhood-error', info);
valid = false;
}
if (getElement('id', 'result-funcs').childElementCount == 0) {
var info = '*Escolha pelo menos uma função';
createErrorInfo(form['func'], 'func-error', info);
valid = false;
} else {
var parent = getElement('id', 'result-funcs');
var size = parent.childElementCount;
var elem = new Element('input');
var funcs = "";
for (var i = 0; i < size; i++) {
funcs += parent.children[i].firstElementChild.innerHTML;
funcs += (i+1 < size)? '|' : '';
}
form.children[4].appendChild(elem.addAtt('type', 'hidden')
.addAtt('id', 'funcs')
.addAtt('name', 'funcs')
.addAtt('value', funcs)
.get());
}
if (validateNonEmpty(form['salary_pretension'])) {
valid = validateSalary(form['salary_pretension']);
}
if (valid) activeProgress();
return true;
}
function validateSalary(elem) {
var numbers = '';
for (var j = 0; j < elem.value.length; j++)
{
if ((/^\d$/).test(elem.value[j]))
numbers += elem.value[j];
}
numbers = parseInt(numbers);
if (!(/^(\d?\d\.)?\d{3},\d{2}$/).test(elem.value)) {
var info = '*Entrada inválida';
if (numbers > 3000000 || numbers < 100000) {
info += '(mínimo: 1.000,00; máximo: 30.000,00)';
}
createErrorInfo(elem, 'salary-error', info);
return false;
} else if (numbers > 3000000 || numbers < 100000) {
var info = '(mínimo: 1.000,00; máximo: 30.000,00)';
createErrorInfo(elem, 'salary-error', info);
return false;
} else {
removeErrorInfo(elem.parentElement, 'salary-error');
elem.style.removeProperty("border-color");
}
return true;
}
function validateEducationLevel(elem) {
var el = getElement("id", "group");
var size = el.childElementCount;
var children = el.children;
if (elem.value == "") {
if (children[1].children[0].childElementCount >= 3) {
removeErrorInfo(children[1].children[0], children[1].children[0].children[2].id)
children[1].children[0].children[1].style.removeProperty("border-color");
}
for (var i = 2; i < size; i++) {
children[i].style.setProperty("display", "none");
if (children[i].children[0].childElementCount >= 3) {
removeErrorInfo(children[i].children[0], children[i].children[0].children[2].id)
children[i].children[0].children[1].style.removeProperty("border-color");
}
}
}
else if (elem.value == "medio") {
for (var i = 2; i < size-2; i++) {
children[i].style.setProperty("display", "none");
}
children[size-1].style.setProperty("display", "");
children[size-2].style.setProperty("display", "");
}
else {
for (var i = 2; i < size-1; i++) {
children[i].style.setProperty("display", "");
}
children[size-1].style.setProperty("display", "none");
}
}
function verifyEducation(form) {
var valid = true;
var date = new Date();
if (!validateNonEmpty(form['level'])) {
var info = '*Escolhe o nivel do curso';
createErrorInfo(form['level'], 'level-error', info);
valid = false;
}
if (!validateNonEmpty(form['situation'])) {
var info = '*Escolhe o situação do curso';
createErrorInfo(form['situation'], 'situation-error', info);
valid = false;
}
if (!validateNonEmpty(form['institution']) &&
!form['institution'].parentElement.parentElement.style.getPropertyValue('display')) {
var info = '*Este campo é requerido';
createErrorInfo(form['institution'], 'institution-error', info);
valid = false;
}
if (!validateNonEmpty(form['name_course']) &&
!form['name_course'].parentElement.parentElement.style.getPropertyValue('display')) {
var info = '*Este campo é requerido';
createErrorInfo(form['name_course'], 'name_course-error', info);
valid = false;
}
if(validateNonEmpty(form['city']) &&
!(/^\w+\s*\/\s*\w{2}$/).test(form['city'].value) &&
!form['city'].parentElement.parentElement.style.getPropertyValue('display') ) {
var info = '*Entrada inválida';
createErrorInfo(form['city'], 'city-error', info);
valid = false;
}
if (!validateNonEmpty(form['year_conclusion']) &&
!form['year_conclusion'].parentElement.parentElement.style.getPropertyValue('display') ) {
var info = '*Este campo é requerido';
createErrorInfo(form['year_conclusion'], 'yc-error', info);
valid = false;
} else if(!(/^\d{4}$/).test(form['year_conclusion'].value) &&
!form['year_conclusion'].parentElement.parentElement.style.getPropertyValue('display') ) {
var info = '*Entrada inválida';
createErrorInfo(form['year_conclusion'], 'yc-error', info);
valid = false;
} else if(form['year_conclusion'].value > date.getFullYear()) {
var info = '*Ano superior ao ano atual (' + date.getFullYear() + ')';
createErrorInfo(form['year_conclusion'], 'yc-error', info);
valid = false;
}
return valid;
}
function addEducation(form) {
if (verifyEducation(form)) {
getElement("id", "included-education").style.removeProperty('display');
var result = getElement("id", "result");
var size = result.childElementCount;
if (size > 0) {
for (var i = 0; i < size; i++) {
if (result.children[i].children[0].innerHTML == (form['level'].value + ' ' + form['situation'].value)) {
if (form['level'].value == 'medio' ||
form['name_course'].value == result.firstElementChild.children[2].innerHTML) {
showInfo('Registro de Escolaridade', 'Curso já cadastrado');
reset();
return;
}
}
}
}
var div = '<div class="tr-content" id="' + 'ed-' + size + '">'+
'<div class="td-content" data-heading="Nível de Formação">'+
form['level'].selectedOptions[0].textContent + ' ' +
form['situation'].selectedOptions[0].textContent + '</div>' +
'<div class="td-content" data-heading="Instituição de Ensino">' + form['institution'].value + '</div>' +
'<div class="td-content" data-heading="Nome do Curso">' + form['name_course'].value + '</div>' +
'<div class="td-content" data-heading="Ano de Conclusão">' + form['year_conclusion'].value + '</div>' +
'<div style="display:none;" data-heading="Cidade / Estado">' + form['city'].value + '</div>' +
'<div class="td-content">editar/excluir</div>'
'</div>';
result.innerHTML += div;
reset();
}
}
function validateEducationRegister(form) {
var result = getElement('id', 'result');
var size = result.childElementCount;
if (size == 0) {
alert('Você precisa registrar pelo menos 1 formação');
return false;
}
var elements = '';
for (var i = 0; i < size; i++) {
elements += '<input type="hidden" name="' + result.children[i].id + '" value="';
var s = result.children[i].childElementCount - 1;
var c = result.children[i];
for (var j = 0; j < s; j++) {
elements += c.children[j].innerHTML;
elements += ((j+1) < s)? '|' : ''
}
elements += '" />'
}
var content = form.innerHTML;
form.innerHTML = elements;
form.innerHTML += content;
activeProgress();
return true;
}
function verifyCourse(form) {
var valid = true;
var date = new Date();
if (!validateNonEmpty(form['level'])) {
var info = '*Escolhe o nivel do curso';
createErrorInfo(form['level'], 'level-error', info);
valid = false;
}
if (!validateNonEmpty(form['institution'])) {
var info = '*Este campo é requerido';
createErrorInfo(form['institution'], 'institution-error', info);
valid = false;
}
if (!validateNonEmpty(form['name_course'])) {
var info = '*Este campo é requerido';
createErrorInfo(form['name_course'], 'name_course-error', info);
valid = false;
}
if (validateNonEmpty(form['city']) &&
!(/^[\w\s]+\s*\/\s*\w{2}$/).test(form['city'].value)) {
var info = '*Entrada inválida';
createErrorInfo(form['city'], 'city-error', info);
valid = false;
}
if (!validateNonEmpty(form['year_conclusion'])) {
var info = '*Este campo é requerido';
createErrorInfo(form['year_conclusion'], 'yc-error', info);
valid = false;
} else if(!(/^\d{4}$/).test(form['year_conclusion'].value) &&
!form['year_conclusion'].parentElement.parentElement.style.getPropertyValue('display') ) {
var info = '*Entrada inválida';
createErrorInfo(form['year_conclusion'], 'yc-error', info);
valid = false;
} else if(form['year_conclusion'].value > date.getFullYear()) {
var info = '*Ano superior ao ano atual (' + date.getFullYear() + ')';
createErrorInfo(form['year_conclusion'], 'yc-error', info);
valid = false;
}
return valid;
}
function addCourse(form) {
if (verifyCourse(form)) {
getElement("id", "included-courses").style.removeProperty('display');
var result = getElement("id", "result");
var size = result.childElementCount;
if (size > 0) {
for (var i = 0; i < size; i++) {
if (form['name_course'].value == result.children[0].children[2].innerHTML) {
showInfo('Registro de Cursos', 'Curso já cadastrado');
//alert('Curso já cadastrado');
reset();
return;
}
}
}
var div = '<div class="tr-content" id="' + 'course-' + size + '">'+
'<div class="td-content" data-heading="Nível do Curso">'+ form['level'].selectedOptions[0].textContent + '</div>' +
'<div class="td-content" data-heading="Instituição de Ensino">' + form['institution'].value + '</div>' +
'<div class="td-content" data-heading="Nome do Curso">' + form['name_course'].value + '</div>' +
'<div class="td-content" data-heading="Ano de Conclusão">' + form['year_conclusion'].value + '</div>' +
'<div style="display:none;" data-heading="Cidade / Estado">' + form['city'].value + '</div>' +
'<div class="td-content">editar/excluir</div>'
'</div>';
result.innerHTML += div;
reset();
}
}
function validateCourseRegister(form) {
var result = getElement('id', 'result');
var size = result.childElementCount;
var elements = '';
for (var i = 0; i < size; i++) {
elements += '<input type="hidden" name="' + result.children[i].id + '" value="';
var s = result.children[i].childElementCount - 1;
var c = result.children[i];
for (var j = 0; j < s; j++) {
elements += c.children[j].innerHTML;
elements += ((j+1) < s)? '|' : ''
}
elements += '" />'
}
var content = form.innerHTML;
form.innerHTML = elements;
form.innerHTML += content;
activeProgress();
return true;
}
function activeProgress() {
getElement('id', 'loader').style.removeProperty('display');
}
function showInfo(title, info) {
getElement('id', 'alert_cont').style.removeProperty('display');
var elem = getElement('id', 'title');
elem.innerHTML = title;
elem = getElement('id', 'info');
elem.innerHTML = info;
}
function closeInfo() {
getElement('id', 'alert_cont').style.setProperty('display', 'none');
}
function showInfoDeficiency() {
getElement('id', 'info_def').style.removeProperty('display');
getElement('id', 'edit-def').style.removeProperty('display');
}
function closeInfoDeficiency() {
getElement('id', 'info_def').style.setProperty('display', 'none');
}
function removeEditDeficiency() {
getElement('id', 'edit-def').style.setProperty('display', 'none');
var elem = getElement('id', 'resume-deficiency');
if (elem) {
elem.parentElement.removeChild(elem);
}
}
function configInfoDeficiency() {
var parent = getElement('id', 'def');
var children = parent.children;
var resume = '';
for (var c = 0; c < children.length; c++) {
var ch1 = children[c].children;
for (var i = 1; i < ch1.length; i++) {
var ch2 = ch1[i].children;
for (var j = 0; j < ch2.length; j++) {
if (ch2[j].children[0].checked) {
resume += ch2[j].children[1].innerHTML;
resume += ', ';
}
}
}
}
if (resume != '') {
var form = getElement('id', 'form-add-inf');
var input = getElement('id', 'resume-deficiency');
if (!input) {
var r = form.innerHTML;
var elem = new Element('input');
elem.addAtt('type', 'hidden')
.addAtt('name', 'resume-deficiency')
.addAtt('id', 'resume-deficiency')
.addAtt('value', resume.substring(0, resume.length-2));
form.children[5].appendChild(elem.get());
/*form.innerHTML = '<input type="hidden" name="resume-deficiency"' +
' id="resume-deficiency"' +
' value="' + resume.substring(0, resume.length-2) + '">';
form.innerHTML += r;*/
} else {
input.value = resume.substring(0, resume.length-2);
}
}
closeInfoDeficiency();
}
function dropdownMenu(elem) {
var menu = elem.parentElement.lastElementChild;
if (menu.style.getPropertyValue('display'))
menu.style.removeProperty('display');
else
menu.style.setProperty('display', 'none');
}
function navInfo(link, url) {
link.href = "#";
form = getElement('id', 'nav');
form.action = url;
form.submit();
}
| 38,706
|
https://github.com/BohdanMosiyuk/samples/blob/master/snippets/visualbasic/VS_Snippets_WebNet/XmlDocumentSchemaSample/VB/XmlDocumentSchemaSample.vb
|
Github Open Source
|
Open Source
|
CC-BY-4.0, MIT
| 2,022
|
samples
|
BohdanMosiyuk
|
Visual Basic
|
Code
| 234
| 558
|
'<Snippet1>
Imports Microsoft.VisualBasic
Imports System.Xml
Imports System.Web
Imports System.Web.UI.WebControls
Imports System.Web.UI.Design
Public Class XmlDocumentSchemaSample
' This method fills a TreeView Web control from an XML file.
Public Sub FillTreeView(ByVal treeVw As TreeView, ByVal fileName As String)
' Get a reference to the current HttpContext
Dim currentContext As HttpContext = HttpContext.Current
Dim i, j, k As Integer
Dim CurNode, NewNode As TreeNode
' Create and load an XML document
Dim XDoc As New XmlDocument()
XDoc.Load(currentContext.Server.MapPath(fileName))
' Get a map of the XML Document
Dim xSchema As New XmlDocumentSchema(XDoc, "")
' Get a list of the root child views
Dim RootViews As IDataSourceViewSchema() = xSchema.GetViews()
' Add each child to the TreeView
For i = 0 To RootViews.Length - 1
NewNode = New TreeNode(RootViews(i).Name)
treeVw.Nodes.Add(NewNode)
CurNode = treeVw.Nodes(i)
' Get a list of children of this child
Dim ChildViews As IDataSourceViewSchema() = RootViews(i).GetChildren()
' Add each child to the child node of the TreeView
For j = 0 To ChildViews.Length - 1
NewNode = New TreeNode(ChildViews(j).Name)
CurNode.ChildNodes.Add(NewNode)
CurNode = CurNode.ChildNodes(j)
' Get a list of children of this child
Dim ChildVws As IDataSourceViewSchema() = ChildViews(j).GetChildren()
' Add each child to the child node
For k = 0 To ChildVws.Length - 1
NewNode = New TreeNode(ChildVws(k).Name)
CurNode.ChildNodes.Add(NewNode)
Next
' Select the parent of the current child
CurNode = CurNode.Parent
Next
' Select the parent of the current child
CurNode = CurNode.Parent
Next
End Sub
End Class
'</Snippet1>
| 4,043
|
https://github.com/misery/AusweisApp2/blob/master/src/remote_device/RemoteDeviceModel.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
AusweisApp2
|
misery
|
C++
|
Code
| 708
| 3,136
|
/*!
* \copyright Copyright (c) 2017-2018 Governikus GmbH & Co. KG, Germany
*/
#include "RemoteDeviceModel.h"
#include "AppSettings.h"
#include "LanguageLoader.h"
#include "RemoteClient.h"
#include <QtGlobal>
using namespace governikus;
RemoteDeviceModelEntry::RemoteDeviceModelEntry(const QString pDeviceName, const QString pId, QSharedPointer<RemoteDeviceListEntry>& pRemoteDeviceListEntry)
: mDeviceName(pDeviceName)
, mId(pId)
, mPaired(false)
, mNetworkVisible(false)
, mSupported(pRemoteDeviceListEntry->getRemoteDeviceDescriptor().isSupported())
, mLastConnected()
, mRemoteDeviceListEntry(pRemoteDeviceListEntry)
{
}
RemoteDeviceModelEntry::RemoteDeviceModelEntry(const QString pDeviceName, const QString pId, bool pPaired, bool pNetworkVisible, bool pSupported, const QDateTime& pLastConnected)
: mDeviceName(pDeviceName)
, mId(pId)
, mPaired(pPaired)
, mNetworkVisible(pNetworkVisible)
, mSupported(pSupported)
, mLastConnected(pLastConnected)
, mRemoteDeviceListEntry(nullptr)
{
}
RemoteDeviceModelEntry::RemoteDeviceModelEntry(const QString pDeviceName)
: mDeviceName(pDeviceName)
, mId()
, mPaired(false)
, mNetworkVisible(false)
, mSupported(false)
, mLastConnected()
, mRemoteDeviceListEntry(nullptr)
{
}
const QSharedPointer<RemoteDeviceListEntry> RemoteDeviceModelEntry::getRemoteDeviceListEntry() const
{
return mRemoteDeviceListEntry;
}
QString RemoteDeviceModelEntry::getDeviceName() const
{
return mDeviceName;
}
bool RemoteDeviceModelEntry::isPaired() const
{
return mPaired;
}
void RemoteDeviceModelEntry::setPaired(bool pPaired)
{
mPaired = pPaired;
}
const QString& RemoteDeviceModelEntry::getId() const
{
return mId;
}
void RemoteDeviceModelEntry::setId(QString pId)
{
mId = pId;
}
bool RemoteDeviceModelEntry::isNetworkVisible() const
{
return mNetworkVisible;
}
bool RemoteDeviceModelEntry::isSupported() const
{
return mSupported;
}
void RemoteDeviceModelEntry::setNetworkVisible(bool pNetworkVisible)
{
mNetworkVisible = pNetworkVisible;
}
const QDateTime& RemoteDeviceModelEntry::getLastConnected() const
{
return mLastConnected;
}
void RemoteDeviceModelEntry::setLastConnected(const QDateTime& pLastConnected)
{
mLastConnected = pLastConnected;
}
RemoteDeviceModel::RemoteDeviceModel(QObject* pParent, bool pShowPairedReaders, bool pShowUnpairedReaders)
: QAbstractTableModel(pParent)
, mPairedReaders()
, mAllRemoteReaders()
, mShowPairedReaders(pShowPairedReaders)
, mShowUnpairedReaders(pShowUnpairedReaders)
{
RemoteServiceSettings& settings = Env::getSingleton<AppSettings>()->getRemoteServiceSettings();
connect(&settings, &RemoteServiceSettings::fireTrustedRemoteInfosChanged, this, &RemoteDeviceModel::onKnownRemoteReadersChanged);
onKnownRemoteReadersChanged();
const auto& remoteClient = Env::getSingleton<RemoteClient>();
connect(remoteClient, &RemoteClient::fireDeviceAppeared, this, &RemoteDeviceModel::constructReaderList);
connect(remoteClient, &RemoteClient::fireDeviceVanished, this, &RemoteDeviceModel::constructReaderList);
}
QHash<int, QByteArray> RemoteDeviceModel::roleNames() const
{
QHash<int, QByteArray> roles = QAbstractItemModel::roleNames();
roles.insert(REMOTE_DEVICE_NAME, QByteArrayLiteral("remoteDeviceName"));
roles.insert(LAST_CONNECTED, QByteArrayLiteral("lastConnected"));
roles.insert(DEVICE_ID, QByteArrayLiteral("deviceId"));
roles.insert(IS_NETWORK_VISIBLE, QByteArrayLiteral("isNetworkVisible"));
roles.insert(IS_SUPPORTED, QByteArrayLiteral("isSupported"));
return roles;
}
QString RemoteDeviceModel::getStatus(const RemoteDeviceModelEntry& pRemoteDeviceModelEntry) const
{
if (mAllRemoteReaders.isEmpty())
{
return tr("Not connected");
}
if (pRemoteDeviceModelEntry.isPaired())
{
if (pRemoteDeviceModelEntry.isNetworkVisible())
{
if (pRemoteDeviceModelEntry.isSupported())
{
return tr("Paired and available");
}
return tr("Paired, but unsupported");
}
return tr("Paired, but unavailable");
}
if (!pRemoteDeviceModelEntry.isSupported())
{
return tr("Unsupported version");
}
return tr("Not paired");
}
QVariant RemoteDeviceModel::headerData(int pSection, Qt::Orientation pOrientation, int pRole) const
{
if (pRole == Qt::DisplayRole && pOrientation == Qt::Horizontal)
{
switch (pSection)
{
case ColumnId::ReaderName:
return tr("Device");
case ColumnId::ReaderStatus:
return tr("Status");
default:
return QVariant();
}
}
return QVariant();
}
int RemoteDeviceModel::rowCount(const QModelIndex&) const
{
return mAllRemoteReaders.size();
}
int RemoteDeviceModel::columnCount(const QModelIndex&) const
{
return NUMBER_OF_COLUMNS;
}
QVariant RemoteDeviceModel::data(const QModelIndex& pIndex, int pRole) const
{
const auto& reader = mAllRemoteReaders.at(pIndex.row());
switch (pRole)
{
case Qt::DisplayRole:
if (pIndex.column() == ColumnId::ReaderStatus)
{
return getStatus(reader);
}
else
{
return reader.getDeviceName();
}
case REMOTE_DEVICE_NAME:
return reader.getDeviceName();
case LAST_CONNECTED:
{
const auto& locale = LanguageLoader::getInstance().getUsedLocale();
const auto& dateTimeFormat = tr("dd.MM.yyyy hh:mm AP");
return locale.toString(reader.getLastConnected(), dateTimeFormat);
}
case DEVICE_ID:
return reader.getId();
case IS_NETWORK_VISIBLE:
return reader.isNetworkVisible();
case IS_SUPPORTED:
return reader.isSupported();
default:
return QVariant();
}
Q_UNREACHABLE();
}
const QSharedPointer<RemoteDeviceListEntry> RemoteDeviceModel::getRemoteDeviceListEntry(const QModelIndex& pIndex) const
{
const int row = pIndex.row();
if (row < 0 || row >= mAllRemoteReaders.size())
{
return QSharedPointer<RemoteDeviceListEntry>();
}
return mAllRemoteReaders.at(row).getRemoteDeviceListEntry();
}
const QSharedPointer<RemoteDeviceListEntry> RemoteDeviceModel::getRemoteDeviceListEntry(QString pDeviceId) const
{
for (const auto& device : mAllRemoteReaders)
{
if (device.getId() == pDeviceId)
{
return device.getRemoteDeviceListEntry();
}
}
return QSharedPointer<RemoteDeviceListEntry>();
}
bool RemoteDeviceModel::isPaired(const QModelIndex& pIndex) const
{
return mAllRemoteReaders.at(pIndex.row()).isPaired();
}
bool RemoteDeviceModel::isSupported(const QModelIndex& pIndex) const
{
return mAllRemoteReaders.at(pIndex.row()).isSupported();
}
void RemoteDeviceModel::onWidgetShown()
{
if (!mShowUnpairedReaders)
{
return;
}
qDebug() << "Starting Remote Device Detection";
Env::getSingleton<RemoteClient>()->startDetection();
constructReaderList();
}
void RemoteDeviceModel::onWidgetHidden()
{
if (!mShowUnpairedReaders)
{
return;
}
qDebug() << "Stopping Remote Device Detection";
Env::getSingleton<RemoteClient>()->stopDetection();
constructReaderList();
}
void RemoteDeviceModel::onKnownRemoteReadersChanged()
{
mPairedReaders.clear();
RemoteServiceSettings& settings = Env::getSingleton<AppSettings>()->getRemoteServiceSettings();
auto pairedReaders = settings.getRemoteInfos();
for (const auto& reader : pairedReaders)
{
mPairedReaders[reader.getFingerprint()] = reader;
}
constructReaderList();
}
void RemoteDeviceModel::constructReaderList()
{
beginResetModel();
mAllRemoteReaders.clear();
RemoteClient* const remoteClient = Env::getSingleton<RemoteClient>();
if (mShowPairedReaders)
{
const QVector<QSharedPointer<RemoteDeviceListEntry> >& foundDevices = remoteClient->getRemoteDevices();
for (const auto& pairedReader : qAsConst(mPairedReaders))
{
bool found = false;
bool supported = true;
for (const auto& foundDevice : foundDevices)
{
if (foundDevice && foundDevice->getRemoteDeviceDescriptor().getIfdId() == pairedReader.getFingerprint())
{
found = true;
supported = foundDevice->getRemoteDeviceDescriptor().isSupported();
break;
}
}
auto newEntry = RemoteDeviceModelEntry(pairedReader.getName()
, pairedReader.getFingerprint()
, true
, found
, supported
, pairedReader.getLastConnected());
mAllRemoteReaders.append(newEntry);
}
}
if (mShowUnpairedReaders)
{
const QVector<QSharedPointer<RemoteDeviceListEntry> >& remoteDevices = remoteClient->getRemoteDevices();
for (auto deviceListEntry : remoteDevices)
{
if (!mPairedReaders.contains(deviceListEntry->getRemoteDeviceDescriptor().getIfdId()))
{
const RemoteDeviceDescriptor& descriptor = deviceListEntry->getRemoteDeviceDescriptor();
mAllRemoteReaders.append(RemoteDeviceModelEntry(descriptor.getIfdName(), descriptor.getIfdId(), deviceListEntry));
}
}
}
std::sort(mAllRemoteReaders.begin(), mAllRemoteReaders.end(), [](const RemoteDeviceModelEntry& pFirst, const RemoteDeviceModelEntry& pSecond){
return pFirst.getDeviceName() < pSecond.getDeviceName();
});
endResetModel();
Q_EMIT fireModelChanged();
}
void RemoteDeviceModel::forgetDevice(const QModelIndex& pIndex)
{
auto& modelEntry = mAllRemoteReaders.at(pIndex.row());
const QString& id = modelEntry.getId();
forgetDevice(id);
}
void RemoteDeviceModel::forgetDevice(const QString& pDeviceId)
{
RemoteServiceSettings& settings = Env::getSingleton<AppSettings>()->getRemoteServiceSettings();
settings.removeTrustedCertificate(pDeviceId);
}
void RemoteDeviceModel::onDeviceDisconnected(GlobalStatus::Code pCloseCode, const QString& pId)
{
Q_UNUSED(pCloseCode);
Q_UNUSED(pId);
constructReaderList();
}
| 21,560
|
https://github.com/arbdt/xiv-character-tracker/blob/master/models/user.js
|
Github Open Source
|
Open Source
|
MIT
| null |
xiv-character-tracker
|
arbdt
|
JavaScript
|
Code
| 49
| 109
|
// this is for the User DB entry
// imports
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// define User Schema
const UserSchema = new Schema({
userIdentity: {type: String, required: true},
savedCharacters: [Number]
});
// define model
const User = mongoose.model("User", UserSchema);
// export
module.exports = {User, UserSchema};
| 41,177
|
https://github.com/hskendall/microcosm/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
microcosm
|
hskendall
|
Ignore List
|
Code
| 13
| 57
|
coverage
node_modules
build
!bin/build
*.asm
*.cfg
tmp
.DS_Store
.babel-cache
lerna-debug.log
npm-debug.log
*.zip
.eslintcache
| 15,647
|
https://github.com/RedHatInsights/insights-frontend-components/blob/master/src/PresentationalComponents/Breadcrumbs/Breadcrumbs.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
insights-frontend-components
|
RedHatInsights
|
JavaScript
|
Code
| 130
| 413
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Breadcrumb, BreadcrumbItem } from '@patternfly/react-core';
const Breadcrumbs = ({ items, current, className, onNavigate, ...props }) => {
console.warn('Breadcrumbs from FE component shouldn\'t be used anymore. \
Instead use http://patternfly-react.surge.sh/patternfly-4/components/breadcrumb#Breadcrumb from PF repository.');
return (
<Breadcrumb className={ classnames('ins-c-breadcrumbs', className) } { ...props }>
{
items.map((oneLink, key) => (
<BreadcrumbItem key={ key } data-key={ key }>
<a onClick={ event => onNavigate(event, oneLink.navigate, key) }
aria-label={ oneLink.navigate }>
{ oneLink.title }
</a>
</BreadcrumbItem>
)
) }
{ current && <BreadcrumbItem isActive> { current } </BreadcrumbItem> }
</Breadcrumb>
);
};
Breadcrumbs.propTypes = {
items: PropTypes.arrayOf(PropTypes.shape({
navigate: PropTypes.any,
title: PropTypes.node
})),
current: PropTypes.node,
onNavigate: PropTypes.func
};
Breadcrumbs.defaultProps = {
items: [],
current: null,
onNavigate: Function.prototype,
className: ''
};
export default Breadcrumbs;
| 50,308
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.