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/aspectran/aspectran/blob/master/with-undertow/src/main/java/com/aspectran/undertow/server/HttpListenerConfig.java
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-free-unknown
| 2,023
|
aspectran
|
aspectran
|
Java
|
Code
| 165
| 377
|
/*
* Copyright (c) 2008-2023 The Aspectran 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.aspectran.undertow.server;
import io.undertow.Undertow;
/**
* <p>Created: 2019-08-21</p>
*/
public class HttpListenerConfig {
private int port;
private String host;
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
Undertow.ListenerBuilder getListenerBuilder() {
Undertow.ListenerBuilder listenerBuilder = new Undertow.ListenerBuilder();
listenerBuilder.setType(Undertow.ListenerType.HTTP);
listenerBuilder.setPort(port);
listenerBuilder.setHost(host);
return listenerBuilder;
}
}
| 4,534
|
https://github.com/getconversio/simple-storage/blob/master/storage/local.test.js
|
Github Open Source
|
Open Source
|
MIT
| null |
simple-storage
|
getconversio
|
JavaScript
|
Code
| 116
| 311
|
'use strict';
const fs = require('fs'),
Local = require('./local');
const local = new Local({ localDirectory: __dirname + '/../test' });
describe('storage/local', () => {
beforeAll(() => fs.writeFileSync(__dirname + '/../test/foo', Buffer.from('foo')));
afterAll(() => fs.unlinkSync(__dirname + '/../test/foo'));
describe('exists', () => {
it('should return true if a file exists', async () => {
expect(await local.exists('foo')).toEqual(true);
});
it('should return false if a file does not exists', async () => {
expect(await local.exists('bar')).toEqual(false);
});
});
describe('fetchText', () => {
it('should return the file content', async () => {
expect(await local.fetchText('foo')).toMatchSnapshot();
});
it('should throw an Error if file does not exists', async () => {
expect.assertions(1);
try {
await local.fetchText('bar');
} catch (e) {
expect(e.message).toMatch(/no such file or directory/);
}
});
});
});
| 33,191
|
https://github.com/Albeoris/MMXLegacy/blob/master/Legacy.Framework/AssetBundles/Core/AssetKey.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
MMXLegacy
|
Albeoris
|
C#
|
Code
| 103
| 321
|
using System;
namespace AssetBundles.Core
{
internal struct AssetKey : IEquatable<AssetKey>
{
public String Name;
public Type Type;
public AssetKey(String name, Type type)
{
Name = name;
Type = type;
}
public override Boolean Equals(Object obj)
{
if (obj != null && obj is AssetKey)
{
AssetKey assetKey = (AssetKey)obj;
return Equals(ref assetKey);
}
return false;
}
public Boolean Equals(ref AssetKey other)
{
return Type == other.Type && String.Equals(Name, other.Name, StringComparison.InvariantCulture);
}
public Boolean Equals(AssetKey other)
{
return Equals(ref other);
}
public override Int32 GetHashCode()
{
return Name.GetHashCode() ^ Type.GetHashCode();
}
public override String ToString()
{
return String.Format("[{0}] '{1}'", Type.ToString(), Name);
}
}
}
| 48,824
|
https://github.com/Jovilam77/vonce-sqlbean/blob/master/vonce-sqlbean-core/src/main/java/cn/vonce/sql/helper/Wrapper.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
vonce-sqlbean
|
Jovilam77
|
Java
|
Code
| 249
| 762
|
package cn.vonce.sql.helper;
import cn.vonce.sql.enumerate.SqlLogic;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 条件包装器
*
* @author Jovi
* @version 1.0
* @email 766255988@qq.com
* @date 2021年4月28日下午5:49:00
*/
public class Wrapper implements Serializable {
private List<Data> dataList = new ArrayList<>();
/**
* 条件
*
* @param cond
* @return
*/
public static Wrapper where(Cond cond) {
Wrapper wrapper = new Wrapper();
wrapper.dataList.add(new Data(SqlLogic.AND, cond));
return wrapper;
}
/**
* 条件
*
* @param cond
* @return
*/
public static Wrapper having(Cond cond) {
return where(cond);
}
/**
* 并且
*
* @param wrapper
* @return
*/
public Wrapper and(Wrapper wrapper) {
dataList.add(new Data(SqlLogic.AND, wrapper));
return this;
}
/**
* 并且
*
* @param cond
* @return
*/
public Wrapper and(Cond cond) {
dataList.add(new Data(SqlLogic.AND, cond));
return this;
}
/**
* 或者
*
* @param wrapper
* @return
*/
public Wrapper or(Wrapper wrapper) {
dataList.add(new Data(SqlLogic.OR, wrapper));
return this;
}
/**
* 或者
*
* @param cond
* @return
*/
public Wrapper or(Cond cond) {
dataList.add(new Data(SqlLogic.OR, cond));
return this;
}
/**
* 获得条件模型列表
*
* @return
*/
public List<Data> getDataList() {
return this.dataList;
}
/**
* 条件模型
*/
public static class Data {
private SqlLogic sqlLogic;
private Object item;
public Data() {
}
public Data(SqlLogic sqlLogic, Object item) {
this.sqlLogic = sqlLogic;
this.item = item;
}
public SqlLogic getSqlLogic() {
return sqlLogic;
}
public void setSqlLogic(SqlLogic sqlLogic) {
this.sqlLogic = sqlLogic;
}
public Object getItem() {
return item;
}
public void setItem(Object item) {
this.item = item;
}
}
}
| 14,536
|
https://github.com/Logicalis/eugenio-devices/blob/master/AzureMXChip/MXCHIPAZ3166/core/lib/netxduo/addons/azure_iot/azure_iot_security_module/iot-security-module-core/inc/asc_security_core/model/schema/system_information_json_printer.h
|
Github Open Source
|
Open Source
|
MIT
| null |
eugenio-devices
|
Logicalis
|
C
|
Code
| 77
| 400
|
#ifndef SYSTEM_INFORMATION_JSON_PRINTER_H
#define SYSTEM_INFORMATION_JSON_PRINTER_H
/* Generated by flatcc 0.6.1-dev FlatBuffers schema compiler for C by dvide.com */
#include "flatcc/flatcc_json_printer.h"
#include "flatcc/flatcc_prologue.h"
static void AzureIoTSecurity_SystemInformation_print_json_table(flatcc_json_printer_t *ctx, flatcc_json_printer_table_descriptor_t *td);
static void AzureIoTSecurity_SystemInformation_print_json_table(flatcc_json_printer_t *ctx, flatcc_json_printer_table_descriptor_t *td)
{
flatcc_json_printer_string_field(ctx, td, 0, "os_info", 7);
flatcc_json_printer_string_field(ctx, td, 1, "kernel_info", 11);
flatcc_json_printer_string_field(ctx, td, 2, "hw_info", 7);
}
static inline int AzureIoTSecurity_SystemInformation_print_json_as_root(flatcc_json_printer_t *ctx, const void *buf, size_t bufsiz, const char *fid)
{
return flatcc_json_printer_table_as_root(ctx, buf, bufsiz, fid, AzureIoTSecurity_SystemInformation_print_json_table);
}
#include "flatcc/flatcc_epilogue.h"
#endif /* SYSTEM_INFORMATION_JSON_PRINTER_H */
| 46,994
|
https://github.com/SebastianCarroll/AlgorithmsForJava/blob/master/src/Misc/stacksAndQueues/QueueTest.java
|
Github Open Source
|
Open Source
|
MIT
| 2,014
|
AlgorithmsForJava
|
SebastianCarroll
|
Java
|
Code
| 204
| 901
|
package Misc.stacksAndQueues;
import static org.junit.Assert.*;
import org.junit.Test;
public class QueueTest {
@Test
public void testIsEmpty() {
Queue<String> q = new Queue<String>(3);
Boolean isEmpty = q.isEmpty();
assertTrue(isEmpty);
}
@Test
public void testIsFull() {
Queue<String> q = new Queue<String>(3);
q.enqueue("1");
q.enqueue("2");
q.enqueue("3");
Boolean isFull = q.isFull();
assertTrue(isFull);
}
@Test
public void testEnqueue() {
Queue<String> q = new Queue<String>(3);
q.enqueue("1");
q.enqueue("2");
q.enqueue("3");
String[] test = new String[4];
test[0] = "1";
test[1] = "2";
test[2] = "3";
assertArrayEquals(q.elements, test);
}
@Test
public void testDequeue() {
Queue<String> q = new Queue<String>(3);
q.enqueue("1");
q.enqueue("2");
q.enqueue("3");
String firstIn = q.dequeue();
assertEquals(firstIn, "1");
assertEquals(q.dequeue(), "2");
assertEquals(q.dequeue(), "3");
}
@Test
public void testResize() {
Queue<String> q = new Queue<String>(3);
q.enqueue("1");
q.enqueue("2");
q.enqueue("3");
q.enqueue("4");
q.dequeue();
q.dequeue();
q.dequeue();
String lastIn = q.dequeue();
assertEquals(lastIn, "4");
}
@Test
public void testIntegers() {
Queue<Integer> q = new Queue<Integer>(3);
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
Integer firstIn = q.dequeue();
assertTrue(firstIn == 1);
assertTrue(q.dequeue() == 2);
assertTrue(q.dequeue() == 3);
}
@Test
public void testBooleans() {
Queue<Boolean> q = new Queue<Boolean>(3);
q.enqueue(true);
q.enqueue(false);
q.enqueue(false);
Boolean firstIn = q.dequeue();
assertTrue(firstIn);
assertFalse(q.dequeue());
assertFalse(q.dequeue());
}
@Test
public void testWrapping() {
Queue<Integer> q = new Queue<Integer>(3);
q.enqueue(1);
q.enqueue(2);
assertTrue(q.dequeue() == 1);
q.enqueue(3);
assertTrue(q.dequeue() == 2);
q.enqueue(4);
assertTrue(q.dequeue() == 3);
q.enqueue(4);
assertTrue(q.dequeue() == 4);
assertTrue(q.dequeue() == 4);
}
}
| 23,334
|
https://github.com/braveh4rt/ErlangPokerGame/blob/master/apps/poker/src/poker.erl
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,016
|
ErlangPokerGame
|
braveh4rt
|
Erlang
|
Code
| 53
| 219
|
%%%-------------------------------------------------------------------
%% @doc poker public API
%% @end
%%%-------------------------------------------------------------------
-module(poker).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
-export([new_game/0, player_join/3]).
%%====================================================================
%% API
%%====================================================================
start(_StartType, _Args) ->
game_sup:start_link(),
player_sup:start_link().
new_game() ->
G = make_ref(),
supervisor:start_child(game_sup, [G]),
{ok, G}.
player_join(PlayerId, Tokens, GameId) ->
supervisor:start_child(player_sup, [PlayerId, Tokens, GameId]).
%%--------------------------------------------------------------------
stop(_State) ->
ok.
%%====================================================================
%% Internal functions
%%====================================================================
| 33,889
|
https://github.com/killbilling/recurly-java-library/blob/master/src/main/java/com/ning/billing/recurly/model/Plan.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
recurly-java-library
|
killbilling
|
Java
|
Code
| 1,515
| 5,552
|
/*
* Copyright 2010-2014 Ning, Inc.
* Copyright 2014-2015 The Billing Project, LLC
*
* The Billing Project 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 com.ning.billing.recurly.model;
import com.google.common.base.Objects;
import org.joda.time.DateTime;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement(name = "plan")
public class Plan extends RecurlyObject {
@XmlTransient
public static final String PLANS_RESOURCE = "/plans";
@XmlElementWrapper(name = "add_ons")
@XmlElement(name = "add_on")
private AddOns addOns;
@XmlElement(name = "plan_code")
private String planCode;
@XmlElement(name = "name")
private String name;
@XmlElement(name = "pricing_model")
private PricingModel pricingModel;
@XmlElementWrapper(name = "ramp_intervals")
@XmlElement(name = "ramp_interval")
private PlanRampIntervals rampIntervals;
@XmlElement(name = "description")
private String description;
@XmlElement(name = "success_url")
private String successLink;
@XmlElement(name = "cancel_url")
private String cancelLink;
@XmlElement(name = "display_donation_amounts")
private Boolean displayDonationAmounts;
@XmlElement(name = "display_quantity")
private Boolean displayQuantity;
@XmlElement(name = "display_phone_number")
private Boolean displayPhoneNumber;
@XmlElement(name = "bypass_hosted_confirmation")
private Boolean bypassHostedConfirmation;
@XmlElement(name = "unit_name")
private String unitName;
@XmlElement(name = "plan_interval_unit")
private String planIntervalUnit;
@XmlElement(name = "plan_interval_length")
private Integer planIntervalLength;
@XmlElement(name = "trial_interval_length")
private Integer trialIntervalLength;
@XmlElement(name = "trial_interval_unit")
private String trialIntervalUnit;
@XmlElement(name = "total_billing_cycles")
private Integer totalBillingCycles;
@XmlElement(name = "trial_requires_billing_info")
private Boolean trialRequiresBillingInfo;
@XmlElement(name = "accounting_code")
private String accountingCode;
@XmlElement(name = "setup_fee_accounting_code")
private String setupFeeAccountingCode;
@XmlElement(name = "revenue_schedule_type")
private RevenueScheduleType revenueScheduleType;
@XmlElement(name = "setup_fee_revenue_schedule_type")
private RevenueScheduleType setupFeeRevenueScheduleType;
@XmlElement(name = "created_at")
private DateTime createdAt;
@XmlElement(name = "updated_at")
private DateTime updatedAt;
@XmlElement(name = "unit_amount_in_cents")
private RecurlyUnitCurrency unitAmountInCents;
@XmlElement(name = "setup_fee_in_cents")
private RecurlyUnitCurrency setupFeeInCents;
@XmlElement(name = "auto_renew")
private Boolean autoRenew;
@XmlElement(name = "tax_exempt")
private Boolean taxExempt;
@XmlElement(name = "tax_code")
private String taxCode;
@XmlElement(name = "allow_any_item_on_subscriptions")
private Boolean allowAnyItemOnSubscriptions;
@XmlElement(name = "dunning_campaign_id")
private String dunningCampaignId;
@XmlElementWrapper(name = "custom_fields")
@XmlElement(name= "custom_field")
private CustomFields customFields;
public PricingModel getPricingModel() {
return pricingModel;
}
public void setPricingModel(final Object pricingModel) {
this.pricingModel = enumOrNull(PricingModel.class, pricingModel, true);
}
public PlanRampIntervals getRampIntervals() {
return rampIntervals;
}
public void setRampIntervals(final PlanRampIntervals rampIntervals) {
this.rampIntervals = rampIntervals;
}
public String getPlanCode() {
return planCode;
}
public void setPlanCode(final Object planCode) {
this.planCode = stringOrNull(planCode);
}
public String getName() {
return name;
}
public void setName(final Object name) {
this.name = stringOrNull(name);
}
public String getDescription() {
return description;
}
public void setDescription(final Object description) {
this.description = stringOrNull(description);
}
public String getSuccessLink() {
return successLink;
}
public void setSuccessLink(final Object link) {
this.successLink = stringOrNull(link);
}
public String getCancelLink() {
return cancelLink;
}
public void setCancelLink(final Object link) {
this.cancelLink = stringOrNull(link);
}
public Boolean getDisplayDonationAmounts() {
return displayDonationAmounts;
}
public void setDisplayDonationAmounts(final Object displayAmounts) {
this.displayDonationAmounts = booleanOrNull(displayAmounts);
}
public Boolean getDisplayQuantity() {
return displayQuantity;
}
public void setDisplayQuantity(final Object displayQuantity) {
this.displayQuantity = booleanOrNull(displayQuantity);
}
public Boolean getDisplayPhoneNumber() {
return displayPhoneNumber;
}
public void setDisplayPhoneNumber(final Object displayPhoneNumber) {
this.displayPhoneNumber = booleanOrNull(displayPhoneNumber);
}
public Boolean getBypassHostedConfirmation() {
return bypassHostedConfirmation;
}
public void setBypassHostedConfirmation(final Object bypassHostedConfirmation) {
this.bypassHostedConfirmation = booleanOrNull(bypassHostedConfirmation);
}
public String getUnitName() {
return unitName;
}
public void setUnitName(final Object unitName) {
this.unitName = stringOrNull(unitName);
}
public String getPlanIntervalUnit() {
return planIntervalUnit;
}
public void setPlanIntervalUnit(final Object planIntervalUnit) {
this.planIntervalUnit = stringOrNull(planIntervalUnit);
}
public Integer getPlanIntervalLength() {
return planIntervalLength;
}
public void setPlanIntervalLength(final Object planIntervalLength) {
this.planIntervalLength = integerOrNull(planIntervalLength);
}
public String getTrialIntervalUnit() {
return trialIntervalUnit;
}
public void setTrialIntervalUnit(final Object trialIntervalUnit) {
this.trialIntervalUnit = stringOrNull(trialIntervalUnit);
}
public Integer getTotalBillingCycles() {
return totalBillingCycles;
}
public void setTotalBillingCycles(final Object totalBillingCycles) {
this.totalBillingCycles = integerOrNull(totalBillingCycles);
}
public Boolean getTrialRequiresBillingInfo() {
return this.trialRequiresBillingInfo;
}
public void setTrialRequiresBillingInfo(final Object trialRequiresBillingInfo) {
this.trialRequiresBillingInfo = booleanOrNull(trialRequiresBillingInfo);
}
public Integer getTrialIntervalLength() {
return trialIntervalLength;
}
public void setTrialIntervalLength(final Object trialIntervalLength) {
this.trialIntervalLength = integerOrNull(trialIntervalLength);
}
public String getAccountingCode() {
return accountingCode;
}
public void setAccountingCode(final Object accountingCode) {
this.accountingCode = stringOrNull(accountingCode);
}
public String getSetupFeeAccountingCode() {
return setupFeeAccountingCode;
}
public void setSetupFeeAccountingCode(final Object setupFeeAccountingCode) {
this.setupFeeAccountingCode = stringOrNull(setupFeeAccountingCode);
}
public DateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(final Object createdAt) {
this.createdAt = dateTimeOrNull(createdAt);
}
public DateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(final Object updatedAt) {
this.updatedAt = dateTimeOrNull(updatedAt);
}
public RecurlyUnitCurrency getUnitAmountInCents() {
return unitAmountInCents;
}
public void setUnitAmountInCents(final Object unitAmountInCents) {
this.unitAmountInCents = RecurlyUnitCurrency.build(unitAmountInCents);
}
public RecurlyUnitCurrency getSetupFeeInCents() {
return setupFeeInCents;
}
public void setSetupFeeInCents(final Object setupFeeInCents) {
this.setupFeeInCents = RecurlyUnitCurrency.build(setupFeeInCents);
}
public AddOns getAddOns() {
return this.addOns;
}
public void setAddOns(final AddOns addOns) {
this.addOns = addOns;
}
public RevenueScheduleType getSetupFeeRevenueScheduleType() {
return setupFeeRevenueScheduleType;
}
public void setSetupFeeRevenueScheduleType(final Object setupFeeRevenueScheduleType) {
this.setupFeeRevenueScheduleType = enumOrNull(RevenueScheduleType.class, setupFeeRevenueScheduleType, true);
}
public RevenueScheduleType getRevenueScheduleType() {
return revenueScheduleType;
}
public void setRevenueScheduleType(final Object revenueScheduleType) {
this.revenueScheduleType = enumOrNull(RevenueScheduleType.class, revenueScheduleType, true);
}
public Boolean getAutoRenew() {
return this.autoRenew;
}
public void setAutoRenew(final Object autoRenew) {
this.autoRenew = booleanOrNull(autoRenew);
}
public Boolean getTaxExempt() {
return this.taxExempt;
}
public void setTaxExempt(final Object taxExempt) {
this.taxExempt = booleanOrNull(taxExempt);
}
public String getTaxCode() {
return this.taxCode;
}
public void setTaxCode(final Object taxCode) {
this.taxCode = stringOrNull(taxCode);
}
public Boolean getAllowAnyItemOnSubscriptions() {
return this.allowAnyItemOnSubscriptions;
}
public void setAllowAnyItemOnSubscriptions(final Object allowAnyItemOnSubscriptions) {
this.allowAnyItemOnSubscriptions = booleanOrNull(allowAnyItemOnSubscriptions);
}
public String getDunningCampaignId() {
return dunningCampaignId;
}
public void setDunningCampaignId(final Object dunningCampaignId) {
this.dunningCampaignId = stringOrNull(dunningCampaignId);
}
public CustomFields getCustomFields() {
return customFields = customFields;
}
public void setCustomFields(final CustomFields customFields) {
this.customFields = customFields;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Plan");
sb.append("{addOns=").append(addOns);
sb.append(", pricingModel='").append(pricingModel).append('\'');
sb.append(", planCode='").append(planCode).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", successLink='").append(successLink).append('\'');
sb.append(", cancelLink='").append(cancelLink).append('\'');
sb.append(", displayDonationAmounts=").append(displayDonationAmounts);
sb.append(", displayQuantity=").append(displayQuantity);
sb.append(", displayPhoneNumber=").append(displayPhoneNumber);
sb.append(", bypassHostedConfirmation=").append(bypassHostedConfirmation);
sb.append(", unitName='").append(unitName).append('\'');
sb.append(", planIntervalUnit='").append(planIntervalUnit).append('\'');
sb.append(", planIntervalLength=").append(planIntervalLength);
sb.append(", trialIntervalLength=").append(trialIntervalLength);
sb.append(", trialIntervalUnit='").append(trialIntervalUnit).append('\'');
sb.append(", totalBillingCycles").append(totalBillingCycles);
sb.append(", trialRequiresBillingInfo='").append(trialRequiresBillingInfo).append('\'');
sb.append(", accountingCode='").append(accountingCode).append('\'');
sb.append(", setupFeeAccountingCode='").append(setupFeeAccountingCode).append('\'');
sb.append(", createdAt=").append(createdAt);
sb.append(", updatedAt=").append(updatedAt);
sb.append(", unitAmountInCents=").append(unitAmountInCents);
sb.append(", rampIntervals=").append(rampIntervals);
sb.append(", setupFeeInCents=").append(setupFeeInCents);
sb.append(", revenueScheduleType=").append(revenueScheduleType);
sb.append(", setupFeeRevenueScheduleType=").append(setupFeeRevenueScheduleType);
sb.append(", autoRenew=").append(autoRenew);
sb.append(", taxExempt=").append(taxExempt);
sb.append(", taxCode=").append(taxCode);
sb.append(", allowAnyItemOnSubscriptions=").append(allowAnyItemOnSubscriptions);
sb.append(", customFields=").append(customFields);
sb.append('}');
return sb.toString();
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final Plan plan = (Plan) o;
if (bypassHostedConfirmation != plan.bypassHostedConfirmation) {
return false;
}
if (displayPhoneNumber != plan.displayPhoneNumber) {
return false;
}
if (accountingCode != null ? !accountingCode.equals(plan.accountingCode) : plan.accountingCode != null) {
return false;
}
if (addOns != null ? !addOns.equals(plan.addOns) : plan.addOns != null) {
return false;
}
if (autoRenew != null ? !autoRenew.equals(plan.autoRenew) : plan.autoRenew != null) {
return false;
}
if (cancelLink != null ? !cancelLink.equals(plan.cancelLink) : plan.cancelLink != null) {
return false;
}
if (createdAt != null ? createdAt.compareTo(plan.createdAt) != 0: plan.createdAt != null) {
return false;
}
if (description != null ? !description.equals(plan.description) : plan.description != null) {
return false;
}
if (displayDonationAmounts != null ? !displayDonationAmounts.equals(plan.displayDonationAmounts) : plan.displayDonationAmounts != null) {
return false;
}
if (displayQuantity != null ? !displayQuantity.equals(plan.displayQuantity) : plan.displayQuantity != null) {
return false;
}
if (name != null ? !name.equals(plan.name) : plan.name != null) {
return false;
}
if (planCode != null ? !planCode.equals(plan.planCode) : plan.planCode != null) {
return false;
}
if (pricingModel != null ? !pricingModel.equals(plan.pricingModel) : plan.pricingModel != null) {
return false;
}
if (rampIntervals != null ? !rampIntervals.equals(plan.rampIntervals) : plan.rampIntervals != null) {
return false;
}
if (planIntervalLength != null ? !planIntervalLength.equals(plan.planIntervalLength) : plan.planIntervalLength != null) {
return false;
}
if (planIntervalUnit != null ? !planIntervalUnit.equals(plan.planIntervalUnit) : plan.planIntervalUnit != null) {
return false;
}
if (revenueScheduleType != null ? !revenueScheduleType.equals(plan.revenueScheduleType) : plan.revenueScheduleType != null) {
return false;
}
if (setupFeeInCents != null ? !setupFeeInCents.equals(plan.setupFeeInCents) : plan.setupFeeInCents != null) {
return false;
}
if (setupFeeRevenueScheduleType != null ? !setupFeeRevenueScheduleType.equals(plan.setupFeeRevenueScheduleType) : plan.setupFeeRevenueScheduleType != null) {
return false;
}
if (successLink != null ? !successLink.equals(plan.successLink) : plan.successLink != null) {
return false;
}
if (trialIntervalLength != null ? !trialIntervalLength.equals(plan.trialIntervalLength) : plan.trialIntervalLength != null) {
return false;
}
if (trialIntervalUnit != null ? !trialIntervalUnit.equals(plan.trialIntervalUnit) : plan.trialIntervalUnit != null) {
return false;
}
if (trialRequiresBillingInfo != null ? !trialRequiresBillingInfo.equals(plan.trialRequiresBillingInfo) : plan.trialRequiresBillingInfo != null) {
return false;
}
if (unitAmountInCents != null ? !unitAmountInCents.equals(plan.unitAmountInCents) : plan.unitAmountInCents != null) {
return false;
}
if (unitName != null ? !unitName.equals(plan.unitName) : plan.unitName != null) {
return false;
}
if (updatedAt != null ? updatedAt.compareTo(plan.updatedAt) != 0: plan.updatedAt != null) {
return false;
}
if (totalBillingCycles != null ? totalBillingCycles.compareTo(plan.totalBillingCycles) != 0: plan.totalBillingCycles != null) {
return false;
}
if (setupFeeAccountingCode != null ? setupFeeAccountingCode.compareTo(plan.setupFeeAccountingCode) != 0: plan.setupFeeAccountingCode != null) {
return false;
}
if (taxExempt != null ? taxExempt.compareTo(plan.taxExempt) != 0: plan.taxExempt != null) {
return false;
}
if (taxCode != null ? taxCode.compareTo(plan.taxCode) != 0: plan.taxCode != null) {
return false;
}
if (allowAnyItemOnSubscriptions != null ? allowAnyItemOnSubscriptions.compareTo(plan.allowAnyItemOnSubscriptions) != 0: plan.allowAnyItemOnSubscriptions != null) {
return false;
}
if (customFields != null ? !customFields.equals(plan.customFields) : plan.customFields != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(
addOns,
planCode,
name,
pricingModel,
rampIntervals,
description,
successLink,
cancelLink,
displayDonationAmounts,
displayQuantity,
displayPhoneNumber,
bypassHostedConfirmation,
unitName,
planIntervalUnit,
planIntervalLength,
trialIntervalUnit,
trialIntervalLength,
totalBillingCycles,
accountingCode,
setupFeeAccountingCode,
createdAt,
updatedAt,
unitAmountInCents,
setupFeeInCents,
revenueScheduleType,
setupFeeRevenueScheduleType,
trialRequiresBillingInfo,
autoRenew,
taxExempt,
taxCode,
allowAnyItemOnSubscriptions,
customFields
);
}
}
| 45,563
|
https://github.com/Narshe1412/Code-Institute-Data-Centric-Project/blob/master/src/app/model/ITimeRecord.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Code-Institute-Data-Centric-Project
|
Narshe1412
|
TypeScript
|
Code
| 9
| 21
|
export interface TimeRecord {
timestamp: number;
amount: number;
}
| 50,165
|
https://github.com/paulbuechner/chakra-ui/blob/master/packages/transition/src/scale-fade.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
chakra-ui
|
paulbuechner
|
TypeScript
|
Code
| 238
| 700
|
import { cx, __DEV__ } from "@chakra-ui/utils"
import {
AnimatePresence,
HTMLMotionProps,
motion,
Variants as _Variants,
} from "framer-motion"
import * as React from "react"
import {
TransitionDefaults,
Variants,
withDelay,
WithTransitionConfig,
} from "./transition-utils"
interface ScaleFadeOptions {
/**
* The initial scale of the element
* @default 0.95
*/
initialScale?: number
/**
* If `true`, the element will transition back to exit state
*/
reverse?: boolean
}
const variants: Variants<ScaleFadeOptions> = {
exit: ({ reverse, initialScale, transition, transitionEnd, delay }) => ({
opacity: 0,
...(reverse
? { scale: initialScale, transitionEnd: transitionEnd?.exit }
: { transitionEnd: { scale: initialScale, ...transitionEnd?.exit } }),
transition:
transition?.exit ?? withDelay.exit(TransitionDefaults.exit, delay),
}),
enter: ({ transitionEnd, transition, delay }) => ({
opacity: 1,
scale: 1,
transition:
transition?.enter ?? withDelay.enter(TransitionDefaults.enter, delay),
transitionEnd: transitionEnd?.enter,
}),
}
export const scaleFadeConfig: HTMLMotionProps<"div"> = {
initial: "exit",
animate: "enter",
exit: "exit",
variants: variants as _Variants,
}
export interface ScaleFadeProps
extends ScaleFadeOptions,
WithTransitionConfig<HTMLMotionProps<"div">> {}
export const ScaleFade = React.forwardRef<HTMLDivElement, ScaleFadeProps>(
(props, ref) => {
const {
unmountOnExit,
in: isOpen,
reverse = true,
initialScale = 0.95,
className,
transition,
transitionEnd,
delay,
...rest
} = props
const show = unmountOnExit ? isOpen && unmountOnExit : true
const animate = isOpen || unmountOnExit ? "enter" : "exit"
const custom = { initialScale, reverse, transition, transitionEnd, delay }
return (
<AnimatePresence custom={custom}>
{show && (
<motion.div
ref={ref}
className={cx("chakra-offset-slide", className)}
{...scaleFadeConfig}
animate={animate}
custom={custom}
{...rest}
/>
)}
</AnimatePresence>
)
},
)
if (__DEV__) {
ScaleFade.displayName = "ScaleFade"
}
| 28,511
|
https://github.com/Ron423c/chromium/blob/master/components/arc/enterprise/snapshot_session_controller.cc
|
Github Open Source
|
Open Source
|
BSD-3-Clause-No-Nuclear-License-2014, BSD-3-Clause
| 2,022
|
chromium
|
Ron423c
|
C++
|
Code
| 422
| 1,712
|
// Copyright 2020 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.
#include "components/arc/enterprise/snapshot_session_controller.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/time/time.h"
#include "components/session_manager/core/session_manager.h"
#include "components/user_manager/user_manager.h"
namespace arc {
namespace data_snapshotd {
namespace {
// The maximum duration of all required apps being installed.
const base::TimeDelta kDuration = base::TimeDelta::FromMinutes(5);
// This class tracks a user session lifetime and notifies its observers about
// the appropriate session state changes.
class SnapshotSessionControllerImpl final
: public SnapshotSessionController,
public session_manager::SessionManagerObserver {
public:
explicit SnapshotSessionControllerImpl(
std::unique_ptr<ArcAppsTracker> apps_tracker);
SnapshotSessionControllerImpl(const SnapshotSessionControllerImpl&) = delete;
SnapshotSessionControllerImpl& operator=(
const SnapshotSessionControllerImpl&) = delete;
~SnapshotSessionControllerImpl() override;
// SnapshotSessionController overrides:
void AddObserver(Observer* observer) override;
void RemoveObserver(Observer* observer) override;
const base::OneShotTimer* get_timer_for_testing() const override {
return &duration_timer_;
}
// session_manager::SessionManagerObserver overrides:
void OnSessionStateChanged() override;
private:
// Calls StartSession() is MGS is active.
bool MaybeStartSession();
void StartSession();
void StopSession();
// Callbacks to be passed to |apps_tracker_|.
void OnAppInstalled(int percent);
void OnPolicyCompliant();
// Called back once the session duration exceeds the maximum duration.
void OnTimerFired();
void NotifySnapshotSessionStarted();
void NotifySnapshotSessionStopped();
void NotifySnapshotSessionFailed();
void NotifySnapshotAppInstalled(int percent);
void NotifySnapshotSessionPolicyCompliant();
// Should be non-null when tracking apps.
std::unique_ptr<ArcAppsTracker> apps_tracker_;
base::OneShotTimer duration_timer_;
base::ObserverList<Observer> observers_;
// True, if ARC is compliant with policy report received.
// Note: the value never flips back to false.
bool is_policy_compliant_ = false;
base::WeakPtrFactory<SnapshotSessionControllerImpl> weak_ptr_factory_{this};
};
} // namespace
// static
std::unique_ptr<SnapshotSessionController> SnapshotSessionController::Create(
std::unique_ptr<ArcAppsTracker> apps_tracker) {
return std::make_unique<SnapshotSessionControllerImpl>(
std::move(apps_tracker));
}
const base::OneShotTimer* SnapshotSessionController::get_timer_for_testing()
const {
return nullptr;
}
SnapshotSessionController::~SnapshotSessionController() = default;
SnapshotSessionControllerImpl::SnapshotSessionControllerImpl(
std::unique_ptr<ArcAppsTracker> apps_tracker)
: apps_tracker_(std::move(apps_tracker)) {
session_manager::SessionManager::Get()->AddObserver(this);
// Start tracking apps for active MGS.
ignore_result(MaybeStartSession());
}
SnapshotSessionControllerImpl::~SnapshotSessionControllerImpl() {
session_manager::SessionManager::Get()->RemoveObserver(this);
}
void SnapshotSessionControllerImpl::AddObserver(Observer* observer) {
observers_.AddObserver(observer);
}
void SnapshotSessionControllerImpl::RemoveObserver(Observer* observer) {
observers_.RemoveObserver(observer);
}
void SnapshotSessionControllerImpl::OnSessionStateChanged() {
if (!MaybeStartSession())
StopSession();
}
bool SnapshotSessionControllerImpl::MaybeStartSession() {
if (user_manager::UserManager::Get() &&
user_manager::UserManager::Get()->IsLoggedInAsPublicAccount()) {
StartSession();
return true;
}
return false;
}
void SnapshotSessionControllerImpl::StartSession() {
DCHECK(!duration_timer_.IsRunning());
DCHECK(apps_tracker_);
duration_timer_.Start(
FROM_HERE, kDuration,
base::BindOnce(&SnapshotSessionControllerImpl::OnTimerFired,
weak_ptr_factory_.GetWeakPtr()));
apps_tracker_->StartTracking(
base::BindRepeating(&SnapshotSessionControllerImpl::OnAppInstalled,
weak_ptr_factory_.GetWeakPtr()),
base::BindOnce(&SnapshotSessionControllerImpl::OnPolicyCompliant,
weak_ptr_factory_.GetWeakPtr()));
NotifySnapshotSessionStarted();
}
void SnapshotSessionControllerImpl::StopSession() {
if (is_policy_compliant_) {
NotifySnapshotSessionStopped();
} else {
DCHECK(duration_timer_.IsRunning());
duration_timer_.Stop();
apps_tracker_.reset();
NotifySnapshotSessionFailed();
}
}
void SnapshotSessionControllerImpl::OnAppInstalled(int percent) {
NotifySnapshotAppInstalled(percent);
}
void SnapshotSessionControllerImpl::OnPolicyCompliant() {
DCHECK(duration_timer_.IsRunning());
is_policy_compliant_ = true;
apps_tracker_.reset();
duration_timer_.Stop();
NotifySnapshotSessionPolicyCompliant();
}
void SnapshotSessionControllerImpl::OnTimerFired() {
DCHECK(!is_policy_compliant_);
apps_tracker_.reset();
NotifySnapshotSessionFailed();
}
void SnapshotSessionControllerImpl::NotifySnapshotSessionStarted() {
for (auto& observer : observers_)
observer.OnSnapshotSessionStarted();
}
void SnapshotSessionControllerImpl::NotifySnapshotSessionStopped() {
for (auto& observer : observers_)
observer.OnSnapshotSessionStopped();
}
void SnapshotSessionControllerImpl::NotifySnapshotSessionFailed() {
for (auto& observer : observers_)
observer.OnSnapshotSessionFailed();
}
void SnapshotSessionControllerImpl::NotifySnapshotAppInstalled(int percent) {
for (auto& observer : observers_)
observer.OnSnapshotAppInstalled(percent);
}
void SnapshotSessionControllerImpl::NotifySnapshotSessionPolicyCompliant() {
for (auto& observer : observers_)
observer.OnSnapshotSessionPolicyCompliant();
}
} // namespace data_snapshotd
} // namespace arc
| 2,803
|
https://github.com/Shashi-rk/azure-sdk-for-java/blob/master/sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/fluent/models/MicrosoftGraphWorkbookIcon.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
azure-sdk-for-java
|
Shashi-rk
|
Java
|
Code
| 435
| 1,201
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.authorization.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.HashMap;
import java.util.Map;
/** workbookIcon. */
@Fluent
public final class MicrosoftGraphWorkbookIcon {
@JsonIgnore private final ClientLogger logger = new ClientLogger(MicrosoftGraphWorkbookIcon.class);
/*
* Represents the index of the icon in the given set.
*/
@JsonProperty(value = "index")
private Integer index;
/*
* Represents the set that the icon is part of. The possible values are:
* Invalid, ThreeArrows, ThreeArrowsGray, ThreeFlags, ThreeTrafficLights1,
* ThreeTrafficLights2, ThreeSigns, ThreeSymbols, ThreeSymbols2,
* FourArrows, FourArrowsGray, FourRedToBlack, FourRating,
* FourTrafficLights, FiveArrows, FiveArrowsGray, FiveRating, FiveQuarters,
* ThreeStars, ThreeTriangles, FiveBoxes.
*/
@JsonProperty(value = "set")
private String set;
/*
* workbookIcon
*/
@JsonIgnore private Map<String, Object> additionalProperties;
/**
* Get the index property: Represents the index of the icon in the given set.
*
* @return the index value.
*/
public Integer index() {
return this.index;
}
/**
* Set the index property: Represents the index of the icon in the given set.
*
* @param index the index value to set.
* @return the MicrosoftGraphWorkbookIcon object itself.
*/
public MicrosoftGraphWorkbookIcon withIndex(Integer index) {
this.index = index;
return this;
}
/**
* Get the set property: Represents the set that the icon is part of. The possible values are: Invalid, ThreeArrows,
* ThreeArrowsGray, ThreeFlags, ThreeTrafficLights1, ThreeTrafficLights2, ThreeSigns, ThreeSymbols, ThreeSymbols2,
* FourArrows, FourArrowsGray, FourRedToBlack, FourRating, FourTrafficLights, FiveArrows, FiveArrowsGray,
* FiveRating, FiveQuarters, ThreeStars, ThreeTriangles, FiveBoxes.
*
* @return the set value.
*/
public String set() {
return this.set;
}
/**
* Set the set property: Represents the set that the icon is part of. The possible values are: Invalid, ThreeArrows,
* ThreeArrowsGray, ThreeFlags, ThreeTrafficLights1, ThreeTrafficLights2, ThreeSigns, ThreeSymbols, ThreeSymbols2,
* FourArrows, FourArrowsGray, FourRedToBlack, FourRating, FourTrafficLights, FiveArrows, FiveArrowsGray,
* FiveRating, FiveQuarters, ThreeStars, ThreeTriangles, FiveBoxes.
*
* @param set the set value to set.
* @return the MicrosoftGraphWorkbookIcon object itself.
*/
public MicrosoftGraphWorkbookIcon withSet(String set) {
this.set = set;
return this;
}
/**
* Get the additionalProperties property: workbookIcon.
*
* @return the additionalProperties value.
*/
@JsonAnyGetter
public Map<String, Object> additionalProperties() {
return this.additionalProperties;
}
/**
* Set the additionalProperties property: workbookIcon.
*
* @param additionalProperties the additionalProperties value to set.
* @return the MicrosoftGraphWorkbookIcon object itself.
*/
public MicrosoftGraphWorkbookIcon withAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}
@JsonAnySetter
void withAdditionalProperties(String key, Object value) {
if (additionalProperties == null) {
additionalProperties = new HashMap<>();
}
additionalProperties.put(key, value);
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| 3,843
|
https://github.com/Bekmurod3388/shuaro/blob/master/resources/views/admin/facultets/edit.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
shuaro
|
Bekmurod3388
|
PHP
|
Code
| 149
| 627
|
@extends('admin.master')
@section('content')
<div class="col-md-12">
<div class="card">
<div class="card-header">
<div class="row">
<div class="col-10"><h1 class="card-title">Fakultetni yangilash</h1></div>
</div>
<hr>
<div class="card-body">
@if ($errors->any())
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<form action="{{route('admin.facultets.update',$post->id)}}" method="POST" id="myForm">
@csrf
@method('PUT')
<div class="form-group">
<label for="description_ru">Fakultet</label>
<input type="text" name="name" class="form-control" id="header_ru" placeholder="Fakultet"
value="{{$post->name}}">
</div>
<button type="submit" id="alert" class="btn btn-primary">Saqlash</button>
<input type="reset" class="btn btn-danger" value="Tozalash">
</form>
</div>
</div>
</div>
</div>
@endsection
@section('script')
<script>
let facultets = @json($facultets);
$(document).on('click', '#alert', function (e) {
e.preventDefault();
let cnt = 0;
var value = $('#header_ru').val();
if (facultets.length == 0) $('#myForm').submit();
for (let i = 0; i < facultets.length; i++) {
if (value == facultets[i].name && value != @json($post->name)) {
cnt++;
}
}
if (cnt > 0) {
swal({
icon: 'error',
title: 'Xatolik',
text: 'Bu fakultet oldin kiritilgan',
confirmButtonText: 'Continue',
})
$('#header_ru').val(@json($post->name));
} else $('#myForm').submit();
});
</script>
@endsection
| 49,817
|
https://github.com/deepakkus/jijigram/blob/master/vendor/wokster/yii2-owl-carousel-widget/OwlWidget.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
jijigram
|
deepakkus
|
PHP
|
Code
| 62
| 291
|
<?php
/**
* Created by internetsite.com.ua
* User: Tymofeiev Maksym
* Date: 12.05.2017
* Time: 18:39
*/
namespace wokster\owlcarousel;
use yii\base\Widget;
use yii\bootstrap\Html;
use yii\helpers\Json;
class OwlWidget extends Widget
{
public $plaginOptions = [];
public $theme = false;
public function init()
{
parent::init();
ob_start();
}
public function run()
{
$bundle = OwlWidgetAssets::register($this->view);
if($this->theme)
$bundle->css[] = 'assets/owl.theme.'.$this->theme.'.min.css';
$this->view->registerJs("$('#".$this->id."').owlCarousel(".Json::encode($this->plaginOptions).");");
return Html::tag('div',ob_get_clean(),['class'=>($this->theme)?'owl-theme owl-carousel':'owl-carousel','id'=>$this->id]);
}
}
| 33,065
|
https://github.com/NetsoftHoldings/growl/blob/master/Plugins/Displays/Brushed/GrowlBrushedDisplay.h
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
growl
|
NetsoftHoldings
|
Objective-C
|
Code
| 37
| 121
|
//
// GrowlBrushedDisplay.h
// Display Plugins
//
// Created by Ingmar Stein on 12/01/2004.
// Copyright 2004–2011 The Growl Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <GrowlPlugins/GrowlDisplayPlugin.h>
@class NSPreferencePane;
@interface GrowlBrushedDisplay : GrowlDisplayPlugin {
}
@end
| 36,606
|
https://github.com/extralucide/qams/blob/master/atomik/app/includes/Project.class.php
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
qams
|
extralucide
|
PHP
|
Code
| 2,133
| 9,815
|
<?php
/**
* QAMS Framework
* Copyright (c) 2009-2010 Olivier Appere
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package Project.class
* @author Olivier Appere
* @copyright 2009-2013 (c) Olivier Appere
* @license http://www.opensource.org/licenses/mit-license.php
* @link
*/
/**
* Handle project
*
* @package Project.class
*/
class Project {
private $db;
private $project_id;
private $sub_project_id;
public $aircraft_id;
private $aircraft_name;
private $project_name;
private $sub_project_name;
private $company_id;
private $company;
private $folder;
private $workspace;
public $name_serial;
public $nb_serial;
private $which_week;
public $id;
public $name;
public $description;
public $abstract;
public $part_number;
public $dal;
public $scope;
public $manager_id;
public $photo_file;
public $thumbnail;
public $list;
public $parent;
public function getWorkspace(){
return($this->workspace);
}
public function getFolder(){
return($this->folder);
}
public function getAircraft(){
return($this->aircraft_name);
}
public function getAircraftId(){
return($this->aircraft_id);
}
public function getCompany(){
return($this->company);
}
public function get($id){
Atomik::needed('Aircraft.class');
if ($id !=""){
$sql_query = "SELECT projects.aircraft_id,".
"projects.project,".
"projects.description,".
"projects.folder,".
"projects.workspace,".
"aircrafts.name as aircraft, ".
"enterprises.name as company ".
"FROM projects ".
"LEFT OUTER JOIN aircrafts ON projects.aircraft_id = aircrafts.id ".
"LEFT OUTER JOIN enterprises ON aircrafts.company_id = enterprises.id ".
"WHERE projects.id=".$id;
// echo $sql_query;
$result = A('db:'.$sql_query);
$img_path = dirname(__FILE__).DIRECTORY_SEPARATOR.
"..".DIRECTORY_SEPARATOR.
"..".DIRECTORY_SEPARATOR.
"assets".DIRECTORY_SEPARATOR."images".DIRECTORY_SEPARATOR."systems".DIRECTORY_SEPARATOR;
$this->photo_file=Atomik::asset("assets/images/systems/coeur.png");
$this->thumbnail=Atomik::asset("assets/images/systems/coeur_tb.png");
if ($result != false){
$row = $result->fetch(PDO::FETCH_ASSOC);
$this->project_id = $id;
$this->id=$id;
$this->folder=$row['folder'];
$this->workspace=$row['workspace'];
$this->project_name=$row['aircraft']." ".$row['project'];
$this->aircraft_id=$row['aircraft_id'];
$this->aircraft_name=$row['aircraft'];
$this->company=$row['company'];
$this->description=isset($row['description'])?$row['description']:"";
}
else{
$this->project_id = $id;
$this->id=$id;
$this->folder="";
$this->workspace="";
$this->project_name="";
$this->aircraft_id="";
$this->aircraft_name="";
$this->company="";
$this->description="";
}
}
else{
/* try aircraft at least */
$this->project_name = Aircraft::getAircraftName($this->aircraft_id);
}
}
public function getProjectId(){
return($this->project_id);
}
public function getSubProject($id){
// $row = Atomik_Db::find('lrus','id='.$id);
if (($id != "")&&($id != 0)){
$sql_query = "SELECT projects.aircraft_id,".
"projects.project as project_name,".
"lrus.id,".
"lrus.project,".
"lrus.lru,".
"lrus.manager_id,".
"description_lru as description,".
"abstract,".
"part_number,".
"dal,".
"scope.scope,".
"aircrafts.name as aircraft, ".
"parent_id FROM lrus ".
"LEFT OUTER JOIN projects ON projects.id = lrus.project ".
"LEFT OUTER JOIN aircrafts ON projects.aircraft_id = aircrafts.id ".
"LEFT OUTER JOIN scope ON scope.id = lrus.scope_id ".
"LEFT OUTER JOIN bug_users ON bug_users.id = lrus.manager_id ".
" WHERE lrus.id=".$id;
$result = A('db:'.$sql_query);
if ($result !== false){
$row = $result->fetch(PDO::FETCH_ASSOC);
$this->aircraft_id=$row['aircraft_id'];
$this->project_id = $row['project'];
$this->sub_project_id = $row['id'];
$this->sub_project_name=$row['lru'];
$this->project_name=$row['project_name'];
$this->aircraft_name=$row['aircraft'];
$this->description=isset($row['description'])?$row['description']:"";
$this->abstract=isset($row['abstract'])?$row['abstract']:"";
$this->part_number=isset($row['part_number'])?$row['part_number']:"";
$this->dal=isset($row['dal'])?$row['dal']:"";
$this->scope=isset($row['scope'])?$row['scope']:"";
$this->manager_id=isset($row['manager_id'])?$row['manager_id']:"";
$this->parent=$row['parent_id'];
}
else{
$this->aircraft_id="";
$this->project_id = "";
$this->sub_project_id = "";
$this->sub_project_name="";
$this->project_name="";
$this->aircraft_name="";
$this->description="";
$this->abstract="";
$this->part_number="";
$this->dal="";
$this->scope="";
$this->manager_id="";
$this->parent="";
}
if($this->scope == "Software"){
$this->photo_file=Atomik::asset("assets/images/SW.png");
$this->thumbnail=Atomik::asset("assets/images/SW.png");
}
else if($this->scope == "PLD"){
$this->photo_file=Atomik::asset("assets/images/fpga.jpg");
$this->thumbnail=Atomik::asset("assets/images/fpga.jpg");
}
else{
$this->photo_file=Atomik::asset("assets/images/systems/board.png");
$this->thumbnail=Atomik::asset("assets/images/systems/board_tb.png");
}
}
}
public function __construct($context=null) {
Atomik::needed("Db.class");
$this->db = new Db;
if($context != null){
$this->company_id = isset($context['company_id'])?$context['company_id']:"";
$this->aircraft_id = isset($context['aircraft_id'])?$context['aircraft_id']:"";
$this->project_id = isset($context['project_id'])?$context['project_id']:"";
$this->sub_project_id = isset($context['sub_project_id'])?$context['sub_project_id']:"";
$this->review_id = isset($context['review_id'])?$context['review_id']:"";
if ($this->project_id != ""){
$this->get($this->project_id);
$this->getSubProject($this->sub_project_id);
}
}
else {
$this->company_id = "";
$this->aircraft_id = (Atomik::has('session/current_aircraft_id')?Atomik::get('session/current_aircraft_id'):"");
$this->project_id = "";
$this->sub_project_id = "";
$this->review_id = "";
}
$this->description = "";
$this->photo_file=Atomik::asset("assets/images/systems/coeur.png");
$this->thumbnail=Atomik::asset("assets/images/systems/coeur_tb.png");
}
public function getUsers(){
Atomik::needed('Tool.class');
Atomik::needed('User.class');
$which_aircraft = Tool::setFilter("user_join_project.project_id",$this->project_id);
$which_project = Tool::setFilter("projects.aircraft_id",$this->aircraft_id);
$sql_query = "SELECT DISTINCT bug_users.id,fname,lname,function ".
"FROM bug_users ".
"LEFT OUTER JOIN user_join_project ON bug_users.id = user_join_project.user_id ".
"LEFT OUTER JOIN projects ON projects.id = user_join_project.project_id ".
" WHERE bug_users.id IS NOT NULL ".
$which_aircraft.
$which_project.
" ORDER BY `bug_users`.`lname` ASC";
$result = A("db:".$sql_query);
if ($result !== false){
$list = $result->fetchAll();
if (User::getCompanyUserLogged() != "ECE"){
foreach($list as $id => &$user):
$user['fname'] = str_rot13($user['fname']);
$user['lname'] = str_rot13($user['lname']);
$user['function'] = str_rot13($user['function']);
endforeach;
}
}
else{
$list=array();
}
return($list);
}
public static function getProject($aircraft_id="",
$company_id="",
$nb_projects=0){
Atomik::needed('Tool.class');
Atomik::needed('User.class');
$which_company = Tool::setFilter("aircrafts.id",$aircraft_id);
$which_aircraft = Tool::setFilter("enterprises.id",$company_id);
$sql_query = "SELECT ".
"projects.id, ".
"project, ".
"projects.description, ".
"aircrafts.name as aircraft, ".
"enterprises.name as company ".
"FROM projects ".
"LEFT OUTER JOIN aircrafts ON aircrafts.id = projects.aircraft_id ".
"LEFT OUTER JOIN enterprises ON aircrafts.company_id = enterprises.id ".
"WHERE projects.id IS NOT NULL ".
$which_company.
$which_aircraft.
" ORDER BY company ASC,aircraft ASC,`projects`.`project` ASC";
$list_data = A("db:".$sql_query);
$list = $list_data->fetchAll(PDO::FETCH_ASSOC);
$nb_projects = count($list);
/* Get pictures */
$system_w_photo = new Project;
if (User::getCompanyUserLogged() != "ECE"){
foreach($list as $id => &$system):
$system_w_photo->get($system['id']);
$system['photo_file'] = $system_w_photo->photo_file;
$system['thumbnail'] = $system_w_photo->thumbnail;
$system['project'] = str_rot13($system['project']);
$system['description'] = str_rot13($system['description']);
endforeach;
}
else{
foreach($list as $id => &$system):
$system_w_photo->get($system['id']);
$system['photo_file'] = $system_w_photo->photo_file;
$system['thumbnail'] = $system_w_photo->thumbnail;
endforeach;
}
return($list);
}
public function setProject($project_id){
$this->project_id = $project_id;
}
public function setSubProject($sub_project_id){
$this->sub_project_id = $sub_project_id;
}
public function getProjectName(){
return($this->project_name);
}
public function getSubProjectName(){
return($this->sub_project_name);
}
public function getBaseline(){
require_once("Tool.class.php");
$filter = Tool::setFilterWhere("baseline_join_project.project_id",$this->project_id);
$sql_query = "SELECT baselines.id as id,".
"baselines.description,".
"baselines.date,".
"lru,".
"projects.project ".
"FROM baseline_join_project ".
"LEFT OUTER JOIN lrus ON lrus.id = baseline_join_project.lru_id ".
"LEFT OUTER JOIN projects ON projects.id = baseline_join_project.project_id ".
"LEFT OUTER JOIN baselines ON baselines.id = baseline_join_project.baseline_id ".
$filter.
" ORDER BY date DESC, project ASC, lru ASC, description ASC ";
$result = $this->db->db_query($sql_query);
$list = $result->fetchAll(PDO::FETCH_ASSOC);
return($list);
}
public static function getSubProjectAcronym($id){
$row = Atomik_Db::find('lrus','id='.$id);
$acronym = $row['lru'];
if (User::getCompanyUserLogged() != "ECE"){
$acronym = str_rot13($acronym);
}
return ($acronym);
}
public function getSubProjectList(){
Atomik::needed("Tool.class");
Atomik::needed("User.class");
$which_project = Tool::setFilter("list_lrus.project",$this->project_id);
if (($this->project_id== NULL) || ($this->project_id == 0)){
$which_project = "";
}
else {
$which_project = "AND (list_lrus.project = {$this->project_id} OR list_lrus.project = 0)";
}
$which_aircraft = Tool::setFilter("aircrafts.id",$this->aircraft_id);
$which_company = Tool::setFilter("enterprises.id",$this->company_id);
$sql_query = "SELECT list_lrus.id, ".
"list_lrus.lru, ".
"parent_item.lru as parent_lru, ".
"list_lrus.abstract, ".
"list_lrus.part_number, ".
"list_lrus.dal, ".
"list_lrus.manager_id, ".
"scope.abrvt as scope, ".
"bug_users.lname as manager, ".
"list_lrus.description_lru as description, ".
"projects.project, ".
"aircrafts.name as aircraft, ".
"parent_id ".
"FROM lrus list_lrus INNER JOIN (".
"SELECT lrus.id,lru FROM lrus ".
"INNER JOIN projects ON projects.id = lrus.project ".
"INNER JOIN aircrafts ON projects.aircraft_id = aircrafts.id {$which_aircraft} ".
") parent_item ON parent_item.id = list_lrus.parent_id ".
"LEFT OUTER JOIN projects ON projects.id = list_lrus.project ".
"LEFT OUTER JOIN aircrafts ON projects.aircraft_id = aircrafts.id {$which_aircraft}".
"LEFT OUTER JOIN enterprises ON enterprises.id = aircrafts.company_id {$which_company}".
"LEFT OUTER JOIN scope ON scope.id = list_lrus.scope_id ".
"LEFT OUTER JOIN bug_users ON bug_users.id = list_lrus.manager_id ".
"WHERE list_lrus.id IS NOT NULL ".
$which_project.
" ORDER BY `aircrafts`.`name` ASC,`scope` ASC,`projects`.`project` ASC,`list_lrus`.`parent_id` ASC,`list_lrus`.`lru` ASC";
// echo $sql_query."<br/>";
$result = A('db:'.$sql_query);
if ($result !== false){
$list = $result->fetchAll(PDO::FETCH_ASSOC);
// var_dump($list);
$item_w_photo = new Project;
if (User::getCompanyUserLogged() != "ECE"){
foreach($list as $id => &$item):
$item['project'] = str_rot13($item['project']);
$item['lru'] = str_rot13($item['lru']);
$item['parent_lru'] = str_rot13($item['parent_lru']);
$item['description'] = str_rot13($item['description']);
$item['abstract'] = str_rot13($item['abstract']);
endforeach;
}
foreach($list as $id => &$item):
$item_w_photo->getSubProject($item['id']);
$item['photo_file'] = $item_w_photo->photo_file;
$item['thumbnail'] = $item_w_photo->thumbnail;
/* Looking for items with multiple parents */
$sql_query = "SELECT lrus.id FROM lrus LEFT OUTER JOIN lru_join_project ON lru_join_project.item_id = lrus.id WHERE lru_join_project.item_id = {$item['id']} AND lrus.id != lrus.parent_id";
$result = A('db:'.$sql_query);
if ($result !== false){
$row = $result->fetchAll(PDO::FETCH_ASSOC);
// var_dump($row);
if ($row !== false){
if (count($row)>0){
$item['parent_lru'] = $item['lru'];
}
}
}
endforeach;
}
else{
$list = array();
}
return($list);
}
public static function getParentsList($item_id){
$sql_query = "SELECT lru_join_project.id as link_id,lrus.id as id,lru,description_lru as description FROM lrus LEFT OUTER JOIN lru_join_project ON lru_join_project.parent_id = lrus.id ".
"WHERE lru_join_project.item_id = {$item_id}";
$sql_query .= " UNION SELECT NULL,parent_item.id as id,parent_item.lru,parent_item.description FROM lrus list_lrus INNER JOIN (SELECT id,parent_id,lru,description_lru as description FROM lrus) parent_item ON parent_item.id = list_lrus.parent_id ".
"WHERE list_lrus.id = {$item_id} AND list_lrus.id != list_lrus.parent_id";
// echo $sql_query;
$result = A('db:'.$sql_query);
if ($result !== false){
$list = $result->fetchAll(PDO::FETCH_ASSOC);
if ($list !== false){
}
else{
$list = null;
}
}
else{
$list = null;
}
return($list);
}
public function getAllParentsList($item_id){
$sql_query = "SELECT lru_join_project.id as link_id,lrus.id as id,lru,description_lru as description FROM lrus LEFT OUTER JOIN lru_join_project ON lru_join_project.parent_id = lrus.id ".
"WHERE lru_join_project.item_id = {$item_id}";
$sql_query .= " UNION SELECT NULL,parent_item.id as id,parent_item.lru,parent_item.description FROM lrus list_lrus INNER JOIN (SELECT id,parent_id,lru,description_lru as description FROM lrus) parent_item ON parent_item.id = list_lrus.parent_id ".
"WHERE list_lrus.id = {$item_id} AND list_lrus.id != list_lrus.parent_id";
// echo $sql_query;
$result = A('db:'.$sql_query);
if ($result !== false){
$list = $result->fetchAll(PDO::FETCH_ASSOC);
if ($list !== false){
}
else{
$list = null;
}
}
else{
$list = null;
}
return($list);
}
public static function getSelectProject($selected,$onchange="inactive",$aircraft_id="",$company_id=""){
$html='<label for="show_project">System:</label>';
$html.='<select class="combobox"';
if ($onchange=="active") {
$html .= 'onchange="this.form.submit()"';
}
$html .= ' name="show_project">';
$html_tmp = "";
$nb_projects = 0;
$list_project = Project::getProject($aircraft_id,$company_id,&$nb_projects);
foreach($list_project as $row):
$html_tmp .= '<option value="'.$row['id'].'"';
if ($row['id'] == $selected){
$html_tmp .= " SELECTED ";
}
$html_tmp .="/>".$row['aircraft']." ".$row['project'];
endforeach;
if ($nb_projects > 1){
$html .= '<option value=""/> --All--';
$html .= $html_tmp;
}
else{
/* do not display -- All -- because only one project exists */
$html .= $html_tmp;
}
$html .='</select>';
return($html);
}
public static function getSelectAircraft($company_id,$selected,$onchange="inactive"){
$html='<label for="show_aircraft">Aircraft:</label>';
$html.='<select class="combobox"';
if ($onchange=="active") {
$html .= 'onchange="this.form.submit()"';
}
$html .= ' name="show_aircraft">';
$html .= '<option value=""/> --All--';
Atomik::needed('Aircraft.class');
foreach(Aircraft::getAircrafts($company_id) as $row):
$html .= '<option value="'.$row['id'].'"';
if ($row['id'] == $selected){
$html .= " SELECTED ";
}
$html .=">".$row['aircraft'];
endforeach;
$html .='</select>';
return($html);
}
public static function getSelectSubProject($project,$selected="",$onchange="inactive"){
$html ='<label for="show_lru">'.A('menu/equipment').':</label>';
$html.='<select class="combobox"';
if ($onchange=="active") {
$html .= 'onchange="this.form.submit()"';
}
$html.= ' name="show_lru">';
$html.= '<option value=""/> --All--';
foreach($project->getSubProjectList() as $row):
$html .= '<option value="'.$row['id'].'"';
if ($row['id'] == $selected){
$html .= " SELECTED ";
}
if ($row['parent_lru'] == $row['lru']){
$html .= ">".$row['scope']." ".$row['lru'];
}
else{
$html .= ">".$row['scope']." ".$row['parent_lru']." ".$row['lru'];
}
endforeach;
$html .='</select>';
return($html);
}
public static function getSelectBaseline($project,$selected,$onchange="inactive"){
$html ='<label for="show_baseline">Baseline:</label>';
$html.='<select class="combobox"';
if ($onchange=="active") {
$html .= 'onchange="this.form.submit()"';
}
$html.= ' name="show_baseline">';
$html.= '<option value=""/> --All--';
foreach($project->getBaseline() as $row):
$html .= '<option value="'.$row['id'].'"';
if ($row['id'] == $selected){
$html .= " SELECTED ";
}
$html .=">".$row['project']." ".$row['lru']." ".$row['description'];
endforeach;
$html .='</select>';
return($html);
}
function get_project_name ($project_id){
if ($project_id != "") {
$sql_query = "SELECT project FROM projects WHERE id = ".$project_id;
$result = $this->db->db_query($sql_query);
$project_row = $result->fetch(PDO::FETCH_OBJ);
$name = $project_row->project;
}
else {
$name = "";
}
return($name);
}
function get_sub_project_name ($sub_project_id){
if (($sub_project_id != "")&&($sub_project_id != 0)){
$sql_query = "SELECT lru FROM lrus WHERE id = ".$sub_project_id;
$result = $this->db->db_query($sql_query);
$sub_project_row = $result->fetch(PDO::FETCH_OBJ);
$name = $sub_project_row->lru;
}
else {
$name = "";
}
return($name);
}
private function get_list_project ($select_week=""){
$sql_query = "SELECT DISTINCT (projects.id), projects.project as name FROM projects ".
"LEFT OUTER JOIN actions ON actions.project = projects.id WHERE actions.criticality = 14 ".$this->which_week;
return($sql_query);
}
private static function getListDownstreamItems($parent_id,$up=false){
if ($up === false){
$sql_query = "SELECT lrus.id,lru,description_lru as description,part_number as pn,abrvt as scope FROM lrus LEFT OUTER JOIN scope ON scope.id = lrus.scope_id WHERE parent_id = {$parent_id} AND lrus.id != parent_id";
$sql_query .= " UNION SELECT lrus.id,lru,description_lru as description,part_number as pn,abrvt as scope FROM lrus LEFT OUTER JOIN lru_join_project ON lru_join_project.item_id = lrus.id LEFT OUTER JOIN scope ON scope.id = lrus.scope_id WHERE lru_join_project.parent_id = {$parent_id} AND lrus.id != lrus.parent_id";
}
else{
$sql_query = "SELECT lrus.id,lru,description_lru as description,part_number as pn,abrvt as scope FROM lrus LEFT OUTER JOIN scope ON scope.id = lrus.scope_id WHERE project = {$parent_id} AND lrus.id = parent_id";
}
$result = A("db:".$sql_query);
// echo $sql_query."<br/>";
if ($result != false){
$list = $result->fetchAll(PDO::FETCH_OBJ);
}
else{
$list = array();
}
return($list);
}
private function display_downstream_data($id,$fhandle,$up=false){
$downstream_items_list = Project::getListDownstreamItems($id,$up);
if ($downstream_items_list !== false){
foreach ($downstream_items_list as $item) :
fputs($fhandle,'<node name="'.$item->scope.' '.$item->lru.' ('.$item->pn.')" id="'.$item->id.'" connectionname="" connectioncolor="#526e88" namecolor="#f" bgcolor="#d9e3ed" bgcolor2="#f" namebgcolor="#d9e3ed" namebgcolor2="#526e88" bordercolor="#526e88">');
fputs($fhandle,Tool::cleanDescription($item->description));
$this->display_downstream_data($item->id,&$fhandle);
fputs($fhandle,'</node>');
endforeach;
}
}
private function echo_map(&$node, $selected) {
$output = "";
$x = $node['x'];
$y = $node['y'];
$output .= "<a href=\"\" onclick=\"window.top.window.ouvrir('".Atomik::url('edit_eqpt',array('id'=>$node['id']))."','_blank')\">";
$output .= "<div style=\"position:absolute;left:{$x};top:{$y};width:{$node['w']};height:{$node['h']};" . ($selected == $node['id'] ? "background-color:red;filter:alpha(opacity=40);opacity:0.4;" : "") . "\"> </div></a>\n";
for ($i = 0; $i < count($node['childs']); $i++) {
$output .= $this->echo_map($node['childs'][$i], $selected);
}
$output .= "<a href='".Atomik::url('edit_eqpt',array('id'=>$node['id']))."'>open</a>";
return($output);
}
public function createDiagram($diagram_filename){
require_once 'diagram/class.diagram.php';
require_once 'diagram/class.diagram-ext.php';
Atomik::needed('Tool.class');
$output = "";
$diagram_file = dirname(__FILE__).DIRECTORY_SEPARATOR.
"..".DIRECTORY_SEPARATOR.
"..".DIRECTORY_SEPARATOR.
"..".DIRECTORY_SEPARATOR.
'result'.DIRECTORY_SEPARATOR.$diagram_filename.'.xml';
$fhandle = fopen($diagram_file,'w');
fputs($fhandle,'<?xml version="1.0" encoding="UTF-8"?>');
fputs($fhandle,'<diagram bgcolor="#f" bgcolor2="#d9e3ed">');
/* current system */
fputs($fhandle,'<node name="'.$this->project_name.'" id="'.$this->id.'" connectionname="" connectioncolor="#526e88" namecolor="#f" bgcolor="#d9e3ed" bgcolor2="#f" namebgcolor="#d9e3ed" namebgcolor2="#526e88" bordercolor="#526e88">');
fputs($fhandle,Tool::cleanDescription($this->description));
/*
* find downstream items
*/
$this->display_downstream_data($this->id,&$fhandle,true);
fputs($fhandle,'</node>');
/* */
fputs($fhandle,'</diagram>');
fclose($fhandle);
$diagram = new DiagramExtended($diagram_file);
$diagram_display = new Diagram(realpath($diagram_file));
$diagram_png="../result/".$diagram_filename.'.png';
$diagram_display->Draw($diagram_png);
$selected = (isset($_GET['id']) ? $_GET['id'] : $id);
$diagram_node_position = $diagram->getNodePositions();
$output .= $this->echo_map($diagram_node_position, $selected);
return ($output);
}
/*
* deprecated functions
*/
function get_amount_of_tasks ($project_id) {
$sql_query = "SELECT SUM(actions.duration) AS counter FROM projects ".
"LEFT OUTER JOIN actions ON actions.project = projects.id ".
" WHERE projects.id = {$project_id} AND actions.criticality = 14 ".$this->which_week;
//echo "TEST: ".$sql_query."<br>";
$result = do_query($sql_query);
$nb_remarks=mysql_fetch_object($result) ;
return($nb_remarks->counter);
}
function get_amount_of_tasks_with_status ($project_id,$status_id="8") {
$sql_query = "SELECT SUM(actions.duration) AS counter FROM projects ".
"LEFT OUTER JOIN actions ON actions.project = projects.id ".
" WHERE projects.id = {$project_id} AND actions.status = {$status_id} {$which_lru}";
//echo "TEST: ".$sql_query."<br>";
$result = do_query($sql_query);
$nb_remarks=mysql_fetch_object($result) ;
return($nb_remarks->counter);
}
function get_stat_tasks($select_week="") {
$this->which_week = Task::filter_week($select_week);
$sql_query = $this->get_list_project ();
//echo "TEST: ".$sql_query."<br>";
$result_response = do_query($sql_query);
/* amount of rows */
$this->nb=mysql_num_rows($result_response);
if ($this->nb != 0) {
//$data[] = array();
//$this->peer_reviewer_tab[] = array();
$this->index_poster = 0;
while($row = mysql_fetch_object($result_response)) {
$poster = $row->name; //filter($row->fname)." ".filter($row->lname);
//$this->poster_tab[$poster]=$row->duration;
$data[$this->index_poster] = $poster;
$nb[$this->index_poster] = $this->get_amount_of_tasks($row->id);
//$nb_closed[$this->index_poster] = $this->get_amount_of_actions($project_id,$lru_id,$row->id,9);
$this->poster_nb_tab[$poster]=$nb[$this->index_poster];
//$poster.= ": ".$row->duration;
//echo $poster."<br/>";//":".$nb[$index_poster]."<br/>";
$this->index_poster++;
} //ends sub-while loop
//$data=array("toto","titi","tata");
$this->name_serial = urlencode(serialize($data));
$this->nb_serial = urlencode(serialize($nb));
//$this->nb_closed_serial = urlencode(serialize($nb_closed));
}
}
}
| 35,803
|
https://github.com/gabrielhubner/situacaoDeEmergencia/blob/master/src/formulario.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
situacaoDeEmergencia
|
gabrielhubner
|
JavaScript
|
Code
| 97
| 372
|
import React from 'react';
import { View, Button, Text } from 'react-native';
const Formulario = ({ navigation }) => (
<View>
<Text>Incêndio</Text>
<CheckBox value={true} />
</View>
<View >
<Text>Deslizamento de Terra</Text>
<CheckBox value={false} />
</View>
<View>
<Text>Enxente</Text>
<CheckBox value={true} />
</View>
<View>
<Text>Tornado</Text>
<CheckBox value={true} />
</View>
<View>
<TextField label={'Nome'} highlightColor={'#FFFFFF'} textColor={'#ffffff'} />
<TextField label={'Insira o local'} highlightColor={'#FFFFFF'} textColor={'#ffffff'} />
<TextField label={'Celular'} highlightColor={'#FFFFFF'} textColor={'#ffffff'} />
<TextField label={'Digite o máximo de detalhe possível, o que está acontecendo'} highlightColor={'#FFFFFF'} textColor={'#ffffff'} />
</View>
<Button
title="Ajuda"
onPress={() => navigation.navigate('mapa') }
/>
);
Formulario.navigationOptions = {
title: 'Formulario',
}
export default Formulario;
| 13,164
|
https://github.com/Vonage/vonage-node-sdk/blob/master/packages/applications/lib/types/ApplicationClassParameters.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
vonage-node-sdk
|
Vonage
|
TypeScript
|
Code
| 34
| 82
|
import { AuthOpts } from '@vonage/auth';
import { AuthInterface } from '@vonage/auth';
import { VetchOptions } from '@vonage/vetch';
/**
* @deprecated
*/
export type ApplicationClassParameters = AuthOpts &
VetchOptions & {
auth?: AuthInterface;
};
| 39,692
|
https://github.com/Gradientz/assets-builder/blob/master/src/example.scss
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
assets-builder
|
Gradientz
|
SCSS
|
Code
| 7
| 21
|
$example: "test";
.test {
content: $example;
}
| 50,956
|
https://github.com/syhunt/community-scx/blob/master/src/PenTools/Scripts/encode/url.full.lua
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
community-scx
|
syhunt
|
Lua
|
Code
| 5
| 23
|
function Encode(s)
return ctk.url.encodefull(s)
end
| 10,335
|
https://github.com/gaoht/house/blob/master/java/classes/cn/testin/analysis/am.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
house
|
gaoht
|
Java
|
Code
| 2,335
| 7,385
|
package cn.testin.analysis;
import android.content.Context;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
public class am
{
public static String a(Context paramContext)
{
Object localObject3 = null;
Object localObject2;
if ((a()) && (al.b(paramContext, "android.permission.WRITE_EXTERNAL_STORAGE")))
{
localObject2 = paramContext.getExternalFilesDir(null);
localObject1 = localObject2;
if (localObject2 == null) {
ar.f("External dir is null");
}
}
for (Object localObject1 = localObject2;; localObject1 = null)
{
localObject2 = localObject1;
if (localObject1 == null) {
localObject2 = paramContext.getFilesDir();
}
paramContext = (Context)localObject3;
if (localObject2 != null) {
paramContext = ((File)localObject2).getAbsolutePath() + "/" + "testin_ab";
}
return paramContext;
}
}
/* Error */
public static String a(String paramString)
{
// Byte code:
// 0: new 43 java/io/File
// 3: dup
// 4: aload_0
// 5: invokespecial 64 java/io/File:<init> (Ljava/lang/String;)V
// 8: astore_0
// 9: aload_0
// 10: invokevirtual 67 java/io/File:exists ()Z
// 13: istore_1
// 14: iload_1
// 15: ifne +24 -> 39
// 18: iconst_0
// 19: ifeq +11 -> 30
// 22: new 69 java/lang/NullPointerException
// 25: dup
// 26: invokespecial 70 java/lang/NullPointerException:<init> ()V
// 29: athrow
// 30: aconst_null
// 31: areturn
// 32: astore_0
// 33: aload_0
// 34: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 37: aconst_null
// 38: areturn
// 39: new 75 java/io/BufferedReader
// 42: dup
// 43: new 77 java/io/FileReader
// 46: dup
// 47: aload_0
// 48: invokespecial 80 java/io/FileReader:<init> (Ljava/io/File;)V
// 51: invokespecial 83 java/io/BufferedReader:<init> (Ljava/io/Reader;)V
// 54: astore_2
// 55: aload_2
// 56: astore_0
// 57: new 37 java/lang/StringBuilder
// 60: dup
// 61: invokespecial 41 java/lang/StringBuilder:<init> ()V
// 64: astore 4
// 66: aload_2
// 67: astore_0
// 68: aload_2
// 69: invokevirtual 86 java/io/BufferedReader:readLine ()Ljava/lang/String;
// 72: astore_3
// 73: aload_3
// 74: ifnull +39 -> 113
// 77: aload_2
// 78: astore_0
// 79: aload 4
// 81: aload_3
// 82: invokevirtual 51 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 85: pop
// 86: goto -20 -> 66
// 89: astore_3
// 90: aload_2
// 91: astore_0
// 92: aload_3
// 93: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 96: aload_2
// 97: ifnull -67 -> 30
// 100: aload_2
// 101: invokevirtual 89 java/io/BufferedReader:close ()V
// 104: aconst_null
// 105: areturn
// 106: astore_0
// 107: aload_0
// 108: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 111: aconst_null
// 112: areturn
// 113: aload_2
// 114: astore_0
// 115: new 91 java/lang/String
// 118: dup
// 119: aload 4
// 121: invokevirtual 58 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 124: iconst_2
// 125: invokestatic 97 android/util/Base64:decode (Ljava/lang/String;I)[B
// 128: invokespecial 100 java/lang/String:<init> ([B)V
// 131: astore_3
// 132: aload_2
// 133: ifnull +7 -> 140
// 136: aload_2
// 137: invokevirtual 89 java/io/BufferedReader:close ()V
// 140: aload_3
// 141: areturn
// 142: astore_0
// 143: aload_0
// 144: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 147: goto -7 -> 140
// 150: astore_2
// 151: aconst_null
// 152: astore_0
// 153: aload_0
// 154: ifnull +7 -> 161
// 157: aload_0
// 158: invokevirtual 89 java/io/BufferedReader:close ()V
// 161: aload_2
// 162: athrow
// 163: astore_0
// 164: aload_0
// 165: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 168: goto -7 -> 161
// 171: astore_2
// 172: goto -19 -> 153
// 175: astore_3
// 176: aconst_null
// 177: astore_2
// 178: goto -88 -> 90
// Local variable table:
// start length slot name signature
// 0 181 0 paramString String
// 13 2 1 bool boolean
// 54 83 2 localBufferedReader java.io.BufferedReader
// 150 12 2 localObject1 Object
// 171 1 2 localObject2 Object
// 177 1 2 localObject3 Object
// 72 10 3 str1 String
// 89 4 3 localIOException1 java.io.IOException
// 131 10 3 str2 String
// 175 1 3 localIOException2 java.io.IOException
// 64 56 4 localStringBuilder StringBuilder
// Exception table:
// from to target type
// 22 30 32 java/io/IOException
// 57 66 89 java/io/IOException
// 68 73 89 java/io/IOException
// 79 86 89 java/io/IOException
// 115 132 89 java/io/IOException
// 100 104 106 java/io/IOException
// 136 140 142 java/io/IOException
// 0 14 150 finally
// 39 55 150 finally
// 157 161 163 java/io/IOException
// 57 66 171 finally
// 68 73 171 finally
// 79 86 171 finally
// 92 96 171 finally
// 115 132 171 finally
// 0 14 175 java/io/IOException
// 39 55 175 java/io/IOException
}
/* Error */
public static void a(String paramString1, String paramString2)
{
// Byte code:
// 0: aconst_null
// 1: astore 5
// 3: aconst_null
// 4: astore 4
// 6: aload 5
// 8: astore_3
// 9: aload_1
// 10: invokevirtual 105 java/lang/String:getBytes ()[B
// 13: iconst_2
// 14: invokestatic 109 android/util/Base64:encodeToString ([BI)Ljava/lang/String;
// 17: astore 6
// 19: aload 5
// 21: astore_3
// 22: new 43 java/io/File
// 25: dup
// 26: aload_0
// 27: invokespecial 64 java/io/File:<init> (Ljava/lang/String;)V
// 30: astore_1
// 31: aload 5
// 33: astore_3
// 34: aload_1
// 35: invokevirtual 112 java/io/File:getParentFile ()Ljava/io/File;
// 38: invokevirtual 67 java/io/File:exists ()Z
// 41: ifne +14 -> 55
// 44: aload 5
// 46: astore_3
// 47: aload_1
// 48: invokevirtual 112 java/io/File:getParentFile ()Ljava/io/File;
// 51: invokevirtual 115 java/io/File:mkdirs ()Z
// 54: pop
// 55: aload 5
// 57: astore_3
// 58: aload_1
// 59: invokevirtual 112 java/io/File:getParentFile ()Ljava/io/File;
// 62: invokevirtual 67 java/io/File:exists ()Z
// 65: istore_2
// 66: iload_2
// 67: ifne +22 -> 89
// 70: iconst_0
// 71: ifeq +11 -> 82
// 74: new 69 java/lang/NullPointerException
// 77: dup
// 78: invokespecial 70 java/lang/NullPointerException:<init> ()V
// 81: athrow
// 82: return
// 83: astore_0
// 84: aload_0
// 85: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 88: return
// 89: aload 5
// 91: astore_3
// 92: new 117 java/io/BufferedWriter
// 95: dup
// 96: new 119 java/io/FileWriter
// 99: dup
// 100: aload_1
// 101: invokespecial 120 java/io/FileWriter:<init> (Ljava/io/File;)V
// 104: invokespecial 123 java/io/BufferedWriter:<init> (Ljava/io/Writer;)V
// 107: astore_1
// 108: aload_1
// 109: aload 6
// 111: invokevirtual 126 java/io/BufferedWriter:write (Ljava/lang/String;)V
// 114: new 37 java/lang/StringBuilder
// 117: dup
// 118: invokespecial 41 java/lang/StringBuilder:<init> ()V
// 121: ldc -128
// 123: invokevirtual 51 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 126: aload_0
// 127: invokevirtual 51 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 130: invokevirtual 58 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 133: invokestatic 31 cn/testin/analysis/ar:f (Ljava/lang/String;)V
// 136: aload_1
// 137: ifnull -55 -> 82
// 140: aload_1
// 141: invokevirtual 131 java/io/BufferedWriter:flush ()V
// 144: aload_1
// 145: invokevirtual 132 java/io/BufferedWriter:close ()V
// 148: return
// 149: astore_0
// 150: aload_0
// 151: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 154: return
// 155: astore_1
// 156: aload 4
// 158: astore_0
// 159: aload_0
// 160: astore_3
// 161: aload_1
// 162: invokestatic 135 cn/testin/analysis/ar:a (Ljava/lang/Throwable;)V
// 165: aload_0
// 166: ifnull -84 -> 82
// 169: aload_0
// 170: invokevirtual 131 java/io/BufferedWriter:flush ()V
// 173: aload_0
// 174: invokevirtual 132 java/io/BufferedWriter:close ()V
// 177: return
// 178: astore_0
// 179: aload_0
// 180: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 183: return
// 184: astore_0
// 185: aload_3
// 186: ifnull +11 -> 197
// 189: aload_3
// 190: invokevirtual 131 java/io/BufferedWriter:flush ()V
// 193: aload_3
// 194: invokevirtual 132 java/io/BufferedWriter:close ()V
// 197: aload_0
// 198: athrow
// 199: astore_1
// 200: aload_1
// 201: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 204: goto -7 -> 197
// 207: astore_0
// 208: aload_1
// 209: astore_3
// 210: goto -25 -> 185
// 213: astore_3
// 214: aload_1
// 215: astore_0
// 216: aload_3
// 217: astore_1
// 218: goto -59 -> 159
// Local variable table:
// start length slot name signature
// 0 221 0 paramString1 String
// 0 221 1 paramString2 String
// 65 2 2 bool boolean
// 8 202 3 localObject1 Object
// 213 4 3 localIOException java.io.IOException
// 4 153 4 localObject2 Object
// 1 89 5 localObject3 Object
// 17 93 6 str String
// Exception table:
// from to target type
// 74 82 83 java/io/IOException
// 140 148 149 java/io/IOException
// 9 19 155 java/io/IOException
// 22 31 155 java/io/IOException
// 34 44 155 java/io/IOException
// 47 55 155 java/io/IOException
// 58 66 155 java/io/IOException
// 92 108 155 java/io/IOException
// 169 177 178 java/io/IOException
// 9 19 184 finally
// 22 31 184 finally
// 34 44 184 finally
// 47 55 184 finally
// 58 66 184 finally
// 92 108 184 finally
// 161 165 184 finally
// 189 197 199 java/io/IOException
// 108 136 207 finally
// 108 136 213 java/io/IOException
}
public static boolean a()
{
return Environment.getExternalStorageState().equals("mounted");
}
/* Error */
public static byte[] a(InputStream paramInputStream)
{
// Byte code:
// 0: aconst_null
// 1: astore_3
// 2: aload_0
// 3: ifnonnull +7 -> 10
// 6: aload_3
// 7: astore_0
// 8: aload_0
// 9: areturn
// 10: new 149 java/util/zip/GZIPInputStream
// 13: dup
// 14: aload_0
// 15: invokespecial 152 java/util/zip/GZIPInputStream:<init> (Ljava/io/InputStream;)V
// 18: astore_1
// 19: aload_1
// 20: astore_0
// 21: aload_1
// 22: invokestatic 154 cn/testin/analysis/am:b (Ljava/io/InputStream;)[B
// 25: astore_2
// 26: aload_2
// 27: astore_0
// 28: aload_1
// 29: ifnull -21 -> 8
// 32: aload_1
// 33: invokevirtual 155 java/util/zip/GZIPInputStream:close ()V
// 36: aload_2
// 37: areturn
// 38: astore_0
// 39: aload_0
// 40: invokestatic 135 cn/testin/analysis/ar:a (Ljava/lang/Throwable;)V
// 43: aload_2
// 44: areturn
// 45: astore_2
// 46: aconst_null
// 47: astore_1
// 48: aload_1
// 49: astore_0
// 50: aload_2
// 51: invokestatic 135 cn/testin/analysis/ar:a (Ljava/lang/Throwable;)V
// 54: aload_3
// 55: astore_0
// 56: aload_1
// 57: ifnull -49 -> 8
// 60: aload_1
// 61: invokevirtual 155 java/util/zip/GZIPInputStream:close ()V
// 64: aconst_null
// 65: areturn
// 66: astore_0
// 67: aload_0
// 68: invokestatic 135 cn/testin/analysis/ar:a (Ljava/lang/Throwable;)V
// 71: aconst_null
// 72: areturn
// 73: astore_1
// 74: aconst_null
// 75: astore_0
// 76: aload_0
// 77: ifnull +7 -> 84
// 80: aload_0
// 81: invokevirtual 155 java/util/zip/GZIPInputStream:close ()V
// 84: aload_1
// 85: athrow
// 86: astore_0
// 87: aload_0
// 88: invokestatic 135 cn/testin/analysis/ar:a (Ljava/lang/Throwable;)V
// 91: goto -7 -> 84
// 94: astore_1
// 95: goto -19 -> 76
// 98: astore_2
// 99: goto -51 -> 48
// Local variable table:
// start length slot name signature
// 0 102 0 paramInputStream InputStream
// 18 43 1 localGZIPInputStream java.util.zip.GZIPInputStream
// 73 12 1 localObject1 Object
// 94 1 1 localObject2 Object
// 25 19 2 arrayOfByte byte[]
// 45 6 2 localIOException1 java.io.IOException
// 98 1 2 localIOException2 java.io.IOException
// 1 54 3 localObject3 Object
// Exception table:
// from to target type
// 32 36 38 java/io/IOException
// 10 19 45 java/io/IOException
// 60 64 66 java/io/IOException
// 10 19 73 finally
// 80 84 86 java/io/IOException
// 21 26 94 finally
// 50 54 94 finally
// 21 26 98 java/io/IOException
}
/* Error */
public static byte[] a(byte[] paramArrayOfByte)
{
// Byte code:
// 0: aload_0
// 1: ifnonnull +5 -> 6
// 4: aconst_null
// 5: areturn
// 6: new 158 java/io/ByteArrayOutputStream
// 9: dup
// 10: aload_0
// 11: arraylength
// 12: invokespecial 161 java/io/ByteArrayOutputStream:<init> (I)V
// 15: astore 4
// 17: new 163 java/util/zip/GZIPOutputStream
// 20: dup
// 21: aload 4
// 23: invokespecial 166 java/util/zip/GZIPOutputStream:<init> (Ljava/io/OutputStream;)V
// 26: astore_2
// 27: aload_2
// 28: astore_1
// 29: aload_2
// 30: aload_0
// 31: iconst_0
// 32: aload_0
// 33: arraylength
// 34: invokevirtual 169 java/util/zip/GZIPOutputStream:write ([BII)V
// 37: aload_2
// 38: astore_1
// 39: aload_2
// 40: invokevirtual 172 java/util/zip/GZIPOutputStream:finish ()V
// 43: aload_2
// 44: astore_1
// 45: aload 4
// 47: invokevirtual 173 java/io/ByteArrayOutputStream:flush ()V
// 50: aload_2
// 51: astore_1
// 52: aload 4
// 54: invokevirtual 176 java/io/ByteArrayOutputStream:toByteArray ()[B
// 57: astore_3
// 58: aload_2
// 59: ifnull +7 -> 66
// 62: aload_2
// 63: invokevirtual 177 java/util/zip/GZIPOutputStream:close ()V
// 66: aload 4
// 68: invokevirtual 178 java/io/ByteArrayOutputStream:close ()V
// 71: aload_3
// 72: areturn
// 73: astore_0
// 74: aload_0
// 75: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 78: aload_3
// 79: areturn
// 80: astore_3
// 81: aconst_null
// 82: astore_2
// 83: aload_2
// 84: astore_1
// 85: aload_3
// 86: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 89: aload_2
// 90: ifnull +7 -> 97
// 93: aload_2
// 94: invokevirtual 177 java/util/zip/GZIPOutputStream:close ()V
// 97: aload 4
// 99: invokevirtual 178 java/io/ByteArrayOutputStream:close ()V
// 102: aload_0
// 103: areturn
// 104: astore_1
// 105: aload_1
// 106: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 109: aload_0
// 110: areturn
// 111: astore_0
// 112: aconst_null
// 113: astore_1
// 114: aload_1
// 115: ifnull +7 -> 122
// 118: aload_1
// 119: invokevirtual 177 java/util/zip/GZIPOutputStream:close ()V
// 122: aload 4
// 124: invokevirtual 178 java/io/ByteArrayOutputStream:close ()V
// 127: aload_0
// 128: athrow
// 129: astore_1
// 130: aload_1
// 131: invokevirtual 73 java/io/IOException:printStackTrace ()V
// 134: goto -7 -> 127
// 137: astore_0
// 138: goto -24 -> 114
// 141: astore_3
// 142: goto -59 -> 83
// Local variable table:
// start length slot name signature
// 0 145 0 paramArrayOfByte byte[]
// 28 57 1 localGZIPOutputStream1 java.util.zip.GZIPOutputStream
// 104 2 1 localIOException1 java.io.IOException
// 113 6 1 localObject Object
// 129 2 1 localIOException2 java.io.IOException
// 26 68 2 localGZIPOutputStream2 java.util.zip.GZIPOutputStream
// 57 22 3 arrayOfByte byte[]
// 80 6 3 localIOException3 java.io.IOException
// 141 1 3 localIOException4 java.io.IOException
// 15 108 4 localByteArrayOutputStream ByteArrayOutputStream
// Exception table:
// from to target type
// 62 66 73 java/io/IOException
// 66 71 73 java/io/IOException
// 17 27 80 java/io/IOException
// 93 97 104 java/io/IOException
// 97 102 104 java/io/IOException
// 17 27 111 finally
// 118 122 129 java/io/IOException
// 122 127 129 java/io/IOException
// 29 37 137 finally
// 39 43 137 finally
// 45 50 137 finally
// 52 58 137 finally
// 85 89 137 finally
// 29 37 141 java/io/IOException
// 39 43 141 java/io/IOException
// 45 50 141 java/io/IOException
// 52 58 141 java/io/IOException
}
public static byte[] b(InputStream paramInputStream)
{
ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
byte[] arrayOfByte = new byte[' '];
for (;;)
{
int i = paramInputStream.read(arrayOfByte, 0, arrayOfByte.length);
if (i == -1) {
break;
}
localByteArrayOutputStream.write(arrayOfByte, 0, i);
}
localByteArrayOutputStream.flush();
return localByteArrayOutputStream.toByteArray();
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/cn/testin/analysis/am.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| 47,522
|
https://github.com/udoprog/condo/blob/master/examples/src/test/java/eu/toolchain/condo/CondoTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
condo
|
udoprog
|
Java
|
Code
| 151
| 571
|
package eu.toolchain.condo;
import com.google.common.base.Throwables;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import java.util.concurrent.ForkJoinPool;
import java.util.function.Predicate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class CondoTest {
final Entity entity = new Entity("John");
private InMemoryDatabase database;
private Condo<DatabaseMetadata> condo;
private Service service;
@Before
public void setUp() {
database = new InMemoryDatabase();
condo = CoreCondo.buildDefault();
service = new Service(new Database_Condo(condo, database));
}
@Test
public void testWriteNever() {
service.put("hello", entity);
/* operation takes 50ms, this will _probably_ never pass */
assertNull(database.read("hello"));
}
@Test
public void testWriteWait() throws Exception {
service.put("hello", entity);
condo.waitOnce(m -> m instanceof DatabaseMetadata.Write);
assertEquals(entity, database.read("hello"));
}
@Test
public void testWaitForSpecificEntity() throws Exception {
ForkJoinPool.commonPool().execute(() -> {
service.put("hello", entity);
});
final Predicate<DatabaseMetadata> writeWorld = writeEntity("world");
condo.mask(writeWorld);
service.put("world", entity);
condo.waitOnce(writeEntity("hello"));
assertEquals(entity, database.read("hello"));
assertNull(database.read("world"));
condo.pump(writeWorld).waitOnce(writeWorld);
assertEquals(entity, database.read("hello"));
assertEquals(entity, database.read("world"));
}
static Predicate<DatabaseMetadata> writeEntity(final String id) {
return m -> m instanceof DatabaseMetadata.Write && ((DatabaseMetadata.Write) m).id().equals(id);
}
}
| 38,868
|
https://github.com/NovaLabsNovaPass/hardware/blob/master/firmware/NovaPass/Disp.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
hardware
|
NovaLabsNovaPass
|
C++
|
Code
| 148
| 657
|
#include "Disp.h"
extern U8G2_SH1106_128X64_NONAME_1_SW_I2C u8g2;
void Disp::Setup(void) {
uint8_t ypos;
u8g2.begin(); // display
}
void Disp::Writeln(uint8_t line_no, String str) {
char cbuf[32];
str.toCharArray(cbuf,32);
if (line_no < DISP_MAXL) {
strncpy(lines[line_no],cbuf,DISP_MAXCH);
}
}
void Disp::Writeln(uint8_t line_no, char *cp) {
if (line_no < DISP_MAXL) {
strncpy(lines[line_no],cp,DISP_MAXCH);
}
}
void Disp::Writeln(uint8_t line_no, const char *cp) {
if (line_no < DISP_MAXL) {
strncpy(lines[line_no],cp,DISP_MAXCH);
}
}
void Disp::WriteStr(uint8_t line_no, String s) {
if (line_no < DISP_MAXL) {
s.toCharArray(lines[line_no],DISP_MAXCH);
}
}
void Disp::Show(void) {
uint8_t i,starty;
for (i = 0; i < DISP_MAXL; i++) {
SerialUSB.println(lines[i]);
}
u8g2.firstPage();
do {
u8g2.setFont(u8g2_font_helvB10_tf);
starty = 12;
for (i = 0; i < DISP_MAXL; i++, starty += 12) {
if (lines[i]) {
if (strlen(lines[i]) > 16)
u8g2.setFont(u8g2_font_helvB08_tf);
else
u8g2.setFont(u8g2_font_helvB10_tf);
u8g2.drawStr(0,starty,lines[i]);
}
}
} while ( u8g2.nextPage() );
}
void Disp::Clear(void) {
uint8_t i;
for (i = 0; i < DISP_MAXL; i++) {
lines[i][0] = (char)0;
}
u8g2.clearDisplay();
}
| 11,558
|
https://github.com/OndernemerspleinLab/PatternLibrary/blob/master/source/css/scss/atoms/typography/_text.scss
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
PatternLibrary
|
OndernemerspleinLab
|
SCSS
|
Code
| 224
| 802
|
html {
font-size: 100%;
@include mqGreaterThan(small) {
font-size: 100%/16*17;
}
@include mqGreaterThan(large) {
font-size: 100%/16*18;
}
}
/* Text-Related Elements */
p {
margin-bottom: 1em;
}
/* Blockquote (is gelijk aan _tip.scss) */
blockquote {
font-style: italic;
border-left: 4px solid getColor(grijs default);
color: getColor(grijs default);
padding-left: 1em;
margin: 1em 0;
}
/* Horizontal Rule */
hr {
border: 0;
height: 2px;
background: getColor(grijs light);
margin: $doubleSpace 0;
}
abbr {
border-bottom: 1px dotted getColor(grijs default);
cursor: help;
}
//Intro text
.intro {
font-size: getFontSize(introText);
font-style: italic;
display: block;
clear: both;
color: getColor(hemelblauw darkest);
$marginMap: multiplyProps(getFontSize(h2), 2);
@include setPropWithMq(greater, margin-bottom, $marginMap);
}
//Info text
.infoText {
font-style: italic;
margin-bottom: 1em;
font-size: getFontSize(small);
&--source {
@include mqGreaterThan(smallMedium) {
float: left;
max-width: 65%;
}
}
&--date {
@include mqGreaterThan(smallMedium) {
float: right;
span {
display: block;
}
}
@include mqGreaterThan(extraLarge) {
span {
display: inline;
}
}
}
&--afzender {
border-top: 4px solid getColor(grijs border);
padding-top: 0.75em;
margin-bottom: 0.75em;
color: getColor(grijs grijs6);
}
}
//Source Block
.sourceBlock {
padding: 1rem 0;
ul {
margin-left: 0;
.verticalItem:first-child {
margin-left: 0;
}
.partnerLogo {
height: 2.75rem;
}
}
}
.textLine {
display: block;
}
.highlight--blue {
color: getColor(hemelblauw default);
}
.highlight--purple {
color: getColor(paars default);
}
.highlight--green {
color: getColor(mosgroen default);
}
// Only for development purposes!
.yellow-marker {
background-color: yellow;
}
.yellow-line {
border-bottom: 10px yellow solid;
}
| 18,889
|
https://github.com/jingcao80/Elastos/blob/master/Sources/Elastos/LibCore/tests/bak/ICU/ICUTest/test.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
Elastos
|
jingcao80
|
C++
|
Code
| 365
| 1,694
|
#include "test.h"
#include <stdio.h>
#include <Elastos.CoreLibrary.h>
#include <elautoptr.h>
using namespace Elastos;
using namespace Elastos::Core;
CTest::CTest()
{
CICUUtil::AcquireSingleton((IICUUtil**)&icuhep);
}
void assertNotNull(String str)
{
if (!str.IsNull())
{
PFL_EX("expected~~~~")
} else {
PFL_EX("Unexpected~~~~")
}
}
int CTest::test_getISOLanguages(int argc, char* argv[])
{
// Check that corrupting our array doesn't affect other callers.
AutoPtr<ArrayOf<String> > languages ;
icuhep->GetISOLanguages((ArrayOf<String> **)&languages);
assertNotNull((*languages)[0]);
(*languages)[0] = String(NULL);
icuhep->GetISOLanguages((ArrayOf<String> **)&languages);
assertNotNull((*languages)[0]);
return 0;
}
int CTest::test_getISOCountries(int argc, char* argv[])
{
// Check that corrupting our array doesn't affect other callers.
AutoPtr<ArrayOf<String> > countries ;
icuhep->GetISOCountries((ArrayOf<String> **)&countries);
assertNotNull((*countries)[0]);
(*countries)[0] = String(NULL);
icuhep->GetISOCountries((ArrayOf<String> **)&countries);
assertNotNull((*countries)[0]);
return 0;
}
int CTest::test_getAvailableLocales(int argc, char* argv[])
{
// Check that corrupting our array doesn't affect other callers.
AutoPtr<ArrayOf<ILocale*> > locales;
icuhep->GetAvailableLocales((ArrayOf<ILocale *> **)&locales);
if ((*locales)[0])
{
PFL_EX("expected ~~~")
} else {
PFL_EX("Unexpected ~~~")
}
(*locales)[0] = NULL;
icuhep->GetAvailableLocales((ArrayOf<ILocale *> **)&locales);
if ((*locales)[0])
{
PFL_EX("expected ~~~")
} else {
PFL_EX("Unexpected ~~~")
}
return 0;
}
void assertEqualsLocale(ILocale * one ,ILocale * two)
{
Boolean flag = FALSE;
one->Equals(two,&flag);
PFL_EX("flag : %d " , flag)
// assert(flag);
}
int CTest::test_localeFromString(int argc, char* argv[])
{
// localeFromString is pretty lenient. Some of these can't be round-tripped
// through Locale.toString.
AutoPtr<ILocaleHelper> lochep;
CLocaleHelper::AcquireSingleton((ILocaleHelper**)&lochep);
AutoPtr<ILocale> enloc;
AutoPtr<ILocale> usloc;
lochep->GetENGLISH((ILocale**)&enloc);
lochep->GetUS((ILocale**)&usloc);
AutoPtr<ILocale> enloc2;
AutoPtr<ILocale> usloc2;
icuhep->LocaleFromString(String("en") , (ILocale**)&enloc2);
assertEqualsLocale(enloc , enloc2);
icuhep->LocaleFromString(String("en_") , (ILocale**)&enloc2);
assertEqualsLocale(enloc , enloc2);
icuhep->LocaleFromString(String("en__") , (ILocale**)&enloc2);
assertEqualsLocale(enloc , enloc2);
icuhep->LocaleFromString(String("en_US") , (ILocale**)&usloc2);
assertEqualsLocale(usloc , usloc2);
icuhep->LocaleFromString(String("en_US_") , (ILocale**)&usloc2);
assertEqualsLocale(usloc , usloc2);
CLocale::New(String(""),String("US") , String("") ,(ILocale**)&usloc);
icuhep->LocaleFromString(String("_US") , (ILocale**)&usloc2);
assertEqualsLocale(usloc , usloc2);
icuhep->LocaleFromString(String("_US_") , (ILocale**)&usloc2);
assertEqualsLocale(usloc , usloc2);
CLocale::New(String(""),String("") , String("POSIX"), (ILocale**)&usloc);
icuhep->LocaleFromString(String("__POSIX") , (ILocale**)&usloc2);
assertEqualsLocale(usloc , usloc2);
CLocale::New(String("aa"),String("BB") , String("CC"), (ILocale**)&usloc);
icuhep->LocaleFromString(String("aa_BB_CC") , (ILocale**)&usloc2);
assertEqualsLocale(usloc , usloc2);
return 0;
}
void assertEquals(String one, String two , AutoPtr<IICUUtil> icuhep)
{
String addstr , scrstr;
icuhep->AddLikelySubtags(String("en_US") , &addstr);
icuhep->GetScript(addstr , &scrstr);
Boolean flag = one.Equals(scrstr);
PFL_EX("flag : %d " , flag)
// assert( flag );
}
int CTest::test_getScript_addLikelySubtags(int argc, char* argv[])
{
assertEquals(String("Latn"), String("en_US"),icuhep);
assertEquals(String("Hebr"), String("he") , icuhep);
assertEquals(String("Hebr"), String("he_IL") , icuhep);
assertEquals(String("Hebr"), String("iw") , icuhep);
assertEquals(String("Hebr"), String("iw_IL") , icuhep);
return 0;
}
int CTest::test_11152(int argc, char* argv[])
{
AutoPtr<ILocale> locale;
String name;
ECode ec = CLocale::New(String("en"), String("US"), String("POSIX"), (ILocale**)&locale);
assert(ec == NOERROR);
ec = locale->GetDisplayName(&name);
assert(ec == NOERROR);
PFL_EX("name : %s", name.string())
}
| 1,772
|
https://github.com/apache/netbeans/blob/master/enterprise/maven.jaxws/src/org/netbeans/modules/maven/jaxws/wizards/JaxWsClientCreator.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
netbeans
|
apache
|
Java
|
Code
| 594
| 2,375
|
/*
* 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.netbeans.modules.maven.jaxws.wizards;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.modules.maven.api.execute.RunConfig;
import org.netbeans.modules.maven.api.execute.RunUtils;
import org.netbeans.modules.maven.jaxws.MavenModelUtils;
import org.netbeans.modules.maven.jaxws.MavenWebService;
import org.netbeans.modules.maven.jaxws.WSUtils;
import org.netbeans.modules.websvc.api.support.ClientCreator;
import java.io.IOException;
import java.util.Collections;
import org.netbeans.api.progress.ProgressUtils;
import org.netbeans.api.project.Project;
import org.netbeans.modules.maven.jaxws.MavenJAXWSSupportImpl;
import org.netbeans.modules.maven.model.ModelOperation;
import org.netbeans.modules.maven.model.Utilities;
import org.netbeans.modules.maven.model.pom.POMModel;
import org.netbeans.modules.websvc.jaxws.light.api.JAXWSLightSupport;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.NbBundle;
/**
*
* @author Milan Kuchtiak
*/
public class JaxWsClientCreator implements ClientCreator {
private Project project;
private WizardDescriptor wiz;
/**
* Creates a new instance of WebServiceClientCreator
*/
public JaxWsClientCreator(Project project, WizardDescriptor wiz) {
this.project = project;
this.wiz = wiz;
}
@Override
public void createClient() throws IOException {
JAXWSLightSupport jaxWsSupport = JAXWSLightSupport.getJAXWSLightSupport(project.getProjectDirectory());
String wsdlUrl = (String)wiz.getProperty(WizardProperties.WSDL_DOWNLOAD_URL);
String filePath = (String)wiz.getProperty(WizardProperties.WSDL_FILE_PATH);
//Boolean useDispatch = (Boolean) wiz.getProperty(ClientWizardProperties.USEDISPATCH);
//if (wsdlUrl==null) wsdlUrl = "file:"+(filePath.startsWith("/")?filePath:"/"+filePath); //NOI18N
if(wsdlUrl == null) {
wsdlUrl = FileUtil.toFileObject(FileUtil.normalizeFile(new File(filePath))).toURL().toExternalForm();
}
FileObject localWsdlFolder = jaxWsSupport.getWsdlFolder(true);
boolean hasSrcFolder = false;
File srcFile = new File (FileUtil.toFile(project.getProjectDirectory()),"src"); //NOI18N
if (srcFile.exists()) {
hasSrcFolder = true;
} else {
hasSrcFolder = srcFile.mkdirs();
}
if (localWsdlFolder != null) {
FileObject wsdlFo = retrieveWsdl(wsdlUrl, localWsdlFolder,
hasSrcFolder);
if (wsdlFo != null) {
final boolean isJaxWsLibrary = MavenModelUtils.hasJaxWsAPI(project);
final String relativePath = FileUtil.getRelativePath(localWsdlFolder, wsdlFo);
final String clientName = wsdlFo.getName();
Preferences prefs = ProjectUtils.getPreferences(project, MavenWebService.class, true);
if (prefs != null) {
// remember original wsdlUrl for Client
prefs.put(MavenWebService.CLIENT_PREFIX+WSUtils.getUniqueId(wsdlFo.getName(), jaxWsSupport.getServices()), wsdlUrl);
}
if (!isJaxWsLibrary) {
try {
MavenModelUtils.addMetroLibrary(project);
MavenModelUtils.addJavadoc(project);
} catch (Exception ex) {
Logger.getLogger(
JaxWsClientCreator.class.getName()).log(
Level.INFO, "Cannot add Metro libbrary to pom file", ex); //NOI18N
}
}
final String wsdlLocation = wsdlUrl;
ModelOperation<POMModel> operation = new ModelOperation<POMModel>() {
@Override
public void performOperation(POMModel model) {
String packageName = (String) wiz.getProperty(WizardProperties.WSDL_PACKAGE_NAME);
org.netbeans.modules.maven.model.pom.Plugin plugin =
WSUtils.isEJB(project) ?
MavenModelUtils.addJaxWSPlugin(model, "2.0") : //NOI18N
MavenModelUtils.addJaxWSPlugin(model);
MavenModelUtils.addWsimportExecution(plugin, clientName,
relativePath,wsdlLocation, packageName);
if (WSUtils.isWeb(project)) { // expecting web project
MavenModelUtils.addWarPlugin(model, true);
} else { // J2SE Project
MavenModelUtils.addWsdlResources(model);
}
}
};
Utilities.performPOMModelOperations(project.getProjectDirectory().getFileObject("pom.xml"),
Collections.singletonList(operation));
// execute wsimport goal
RunConfig cfg = RunUtils.createRunConfig(FileUtil.toFile(
project.getProjectDirectory()),
project,
"JAX-WS:wsimport", //NOI18N
Collections.singletonList("compile")); //NOI18N
RunUtils.executeMaven(cfg);
}
}
}
private FileObject retrieveWsdl( final String wsdlUrl,
final FileObject localWsdlFolder, final boolean hasSrcFolder )
{
final FileObject[] wsdlFo = new FileObject[1];
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
wsdlFo[0] = WSUtils.retrieveResource(
localWsdlFolder,
(hasSrcFolder ?
new URI(MavenJAXWSSupportImpl.CATALOG_PATH) :
new URI("jax-ws-catalog.xml")), //NOI18N
new URI(wsdlUrl));
} catch (URISyntaxException ex) {
//ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
String mes = NbBundle.getMessage(JaxWsClientCreator.class,
"ERR_IncorrectURI", wsdlUrl); // NOI18N
NotifyDescriptor desc = new NotifyDescriptor.Message(mes,
NotifyDescriptor.Message.ERROR_MESSAGE);
DialogDisplayer.getDefault().notify(desc);
} catch (UnknownHostException ex) {
//ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
String mes = NbBundle.getMessage(JaxWsClientCreator.class,
"ERR_UnknownHost", ex.getMessage()); // NOI18N
NotifyDescriptor desc = new NotifyDescriptor.Message(mes,
NotifyDescriptor.Message.ERROR_MESSAGE);
DialogDisplayer.getDefault().notify(desc);
} catch (IOException ex) {
//ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
String mes = NbBundle.getMessage(JaxWsClientCreator.class,
"ERR_WsdlRetrieverFailure", wsdlUrl); // NOI18N
NotifyDescriptor desc = new NotifyDescriptor.Message(mes,
NotifyDescriptor.Message.ERROR_MESSAGE);
DialogDisplayer.getDefault().notify(desc);
}
}
};
AtomicBoolean isCancelled = new AtomicBoolean();
ProgressUtils.runOffEventDispatchThread(runnable, NbBundle.getMessage(
JaxWsClientCreator.class, "LBL_RetrieveWSDL"), isCancelled, false); // NOI18N
if ( isCancelled.get() ){
return null;
}
return wsdlFo[0];
}
}
| 11,151
|
https://github.com/homberghp/toyexam/blob/master/trunk/40_exam/questions/multiset/settoquest.pl
|
Github Open Source
|
Open Source
|
Artistic-2.0
| 2,020
|
toyexam
|
homberghp
|
Perl
|
Code
| 122
| 493
|
#!/usr/bin/perl -w
my ($base,$dir,$correctchoice,$num,$source,%hash,$realcount);
$source="multiset2.txt";
$dir='multi';
$num=1;
$base='provinciesteden';
my @choices;
open(SRC,"$source") or die qq(cannot open file $source\n);
while (<SRC>){
chomp;
next if m/^#/;
if (m/^choices:/){
s/^choices://;
(@choices) = split ",";
} else {
($quest,$correctchoice)= split/;/;
if (defined($quest)){
if (defined($correctchoice)){
$hash{$quest}= $correctchoice;
}
}
}
}
close(SRC);
foreach my $key1 (keys %hash) {
my $qid = qq($dir-$base$num);
my $fname=qq($base${num}.tex);
open(FILE,">$fname") or die qq(cannot open $fname\n);
print FILE qq(\\begin{questionmult}{$qid}
\\NL{In welke provincie ligt $key1?}
\\DE{In welcher Provinz liegt $key1?}
\\EN{In which province lies $key1?}
\\begin{multicols}{3}
\\begin{choices}
);
for my $key2 (@choices) {
if ($hash{$key1} eq $key2 ) {
print FILE qq( \\correctchoice{$key2}\n);
} else {
print FILE qq( \\wrongchoice{$key2}\n);
}
}
print FILE qq( \\end{choices}
\\end{multicols}
\\end{questionmult});
$num++;
print qq($key1 => $hash{$key1}\n);
close(FILE);
}
| 9,072
|
https://github.com/HappyPiggy/ECS_Charles/blob/master/Assets/Entitas/Editor/Plugins.meta
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
ECS_Charles
|
HappyPiggy
|
Unity3D Asset
|
Code
| 16
| 77
|
fileFormatVersion: 2
guid: 95d5777ce9d837b4e9d57843c38ff97f
folderAsset: yes
timeCreated: 1533636356
licenseType: Free
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
| 8,716
|
https://github.com/jfitz/BASIC-1973/blob/master/test/statement/print_using_ns/data/print_using_ns.bas
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
BASIC-1973
|
jfitz
|
Visual Basic
|
Code
| 39
| 82
|
10 REM TEST PRINT USING
20 LET A = 3.14159
21 LET B = 2.7184
30 PRINT "PRINT USING WITH COMMA"
31 PRINT USING "###.##", A
40 PRINT "PRINT USING WITH SEMICOLON"
41 PRINT USING "###.##"; A
99 END
| 37,843
|
https://github.com/boost-entropy-golang/buildbuddy/blob/master/app/footer/footer.tsx
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
buildbuddy
|
boost-entropy-golang
|
TypeScript
|
Code
| 62
| 292
|
import React from "react";
export default class FooterComponent extends React.Component {
render() {
return (
<div className="footer">
<span>© {new Date().getFullYear()} Iteration, Inc.</span>
<a href="https://buildbuddy.io/terms" target="_blank">
Terms
</a>
<a href="https://buildbuddy.io/privacy" target="_blank">
Privacy
</a>
<a href="https://buildbuddy.io" target="_blank">
BuildBuddy
</a>
<a href="mailto:hello@buildbuddy.io" target="_blank">
Contact us
</a>
<a href="https://slack.buildbuddy.io" target="_blank">
Slack
</a>
<a href="https://twitter.com/buildbuddy_io" target="_blank">
Twitter
</a>
<a href="https://github.com/buildbuddy-io/buildbuddy/" target="_blank">
GitHub
</a>
</div>
);
}
}
| 21,510
|
https://github.com/xavierherron/inaturalist/blob/master/app/webpack/observations/show/ducks/quality_metrics.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
inaturalist
|
xavierherron
|
JavaScript
|
Code
| 110
| 263
|
import inatjs from "inaturalistjs";
const SET_QUALITY_METRICS = "obs-show/quality_metrics/SET_QUALITY_METRICS";
export default function reducer( state = [], action ) {
switch ( action.type ) {
case SET_QUALITY_METRICS:
return action.metrics;
default:
// nothing to see here
}
return state;
}
export function setQualityMetrics( metrics ) {
return {
type: SET_QUALITY_METRICS,
metrics
};
}
export function fetchQualityMetrics( options = {} ) {
return ( dispatch, getState ) => {
const observation = options.observation || getState( ).observation;
if ( !observation ) { return null; }
const params = { id: observation.id, ttl: -1 };
return inatjs.observations.qualityMetrics( params ).then( response => {
dispatch( setQualityMetrics( response.results ) );
} ).catch( e => { } );
};
}
| 6,312
|
https://github.com/MjingGithub/concurrency-practice-demo/blob/master/src/main/java/com/mjing/concurrency/cacheDemo/Computable.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
concurrency-practice-demo
|
MjingGithub
|
Java
|
Code
| 13
| 43
|
package com.mjing.concurrency.cacheDemo;
public interface Computable<A,V> {
V compute(A arg) throws InterruptedException ;
}
| 2,481
|
https://github.com/longkun234/cloudpaas/blob/master/cloudpaas-admin-ui/src/test/java/com/cloudpaas/admin/ui/system/biz/MenuBizTest.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
cloudpaas
|
longkun234
|
Java
|
Code
| 182
| 1,013
|
/**
*
*/
package com.cloudpaas.admin.ui.system.biz;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.alibaba.fastjson.JSON;
import com.cloudpaas.admin.ui.AdminUIApplication;
import com.cloudpaas.admin.ui.base.BaseBiz;
import com.cloudpaas.admin.ui.constants.ApiConstants;
import com.cloudpaas.admin.ui.utils.RestTemplateUtils;
import com.cloudpaas.common.constants.CommonConstants;
import com.cloudpaas.common.model.Menu;
import com.cloudpaas.common.model.User;
import com.cloudpaas.common.result.ObjectResponse;
import com.cloudpaas.common.vo.MenuTreeVo;
import com.google.common.collect.Maps;
/**
* @author 大鱼
*
* @date 2019年8月19日 下午2:52:08
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = AdminUIApplication.class)
@AutoConfigureMockMvc //测试接口用
public class MenuBizTest extends BaseBiz<Menu>{
protected MockMvc mockMvc;
@Autowired
protected WebApplicationContext context;
@Autowired
private MenuBiz menuBiz;
@Before
public void testBefore(){
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
System.out.println("测试前");
}
@After
public void testAfter(){
System.out.println("测试后");
}
@Test
public void MenuSelectOneTest(){
ParameterizedTypeReference<ObjectResponse<Menu>> responseBodyType = new ParameterizedTypeReference<ObjectResponse<Menu>>() {};
Map<String, Object> params = Maps.newHashMap();
params.put("id", "14");
HttpEntity<User> httpEntity = new HttpEntity<User>(getHttpHeaders());
ObjectResponse<Menu> result = RestTemplateUtils.exchange(getBaseUrl()+ApiConstants.API_MENU_SINGLE_URL+"{id}",
HttpMethod.GET, httpEntity, responseBodyType,params)
.getBody();
Menu entity = result.getData();
System.out.print(JSON.toJSONString(entity));
}
@Test
public void MenuGetTreeTest(){
List<MenuTreeVo> menus = menuBiz.getMenuTree();
System.out.println(JSON.toJSONString(menus));
}
@Test
public void MenuGetByIdTest(){
Menu menu = menuBiz.getMenuByID(1);
System.out.println(JSON.toJSONString(menu));
}
/* (non-Javadoc)
* @see com.cloudpaas.admin.ui.base.BaseBiz#getSID()
*/
@Override
public String getSID() {
// TODO Auto-generated method stub
return CommonConstants.ADMIN_SERVICE_ID;
}
}
| 30,874
|
https://github.com/scalalab/scalalab/blob/master/source/src/main/java/scalaExec/gui/MathDialogs/MinInDerDialog.java
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
scalalab
|
scalalab
|
Java
|
Code
| 459
| 1,512
|
package scalaExec.gui.MathDialogs;
import scalaExec.Interpreter.GlobalValues;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class MinInDerDialog extends JFrame {
JTextArea fCode = new JTextArea("def fx( x: Array[Double]) = { \n // Code of function, use x(0) as x argument, e.g. cos(x(0)) instead of cos(x) \n \n }\n" +
"def dfx(x: Array[Double]) = { \n" +
" // code for the derivative of the function, use x(0) as x argument, e.g. sin(x(0)) instead of sin(x) \n \n }\n ");
JTextArea genCode;
JTextField fXLow = new JTextField(10);
JTextField fXStep = new JTextField(10);
JTextField fXUp = new JTextField(10);
JButton buttonGenerateCode = new JButton("Generate Code");
JButton plotButton = new JButton(" Plot ");
JPanel functionPanel = new JPanel(), limitsPanel = new JPanel(), buttonsPanel = new JPanel();
JTextArea fTol;
String codeStr, tolStr;
public MinInDerDialog() {
setTitle("Minimum of a single variable function in an interval, derivative is specified");
fCode.setFont(GlobalValues.defaultTextFont);
tolStr = "def tolx(x: Array[Double]) = { Math.abs(x(0))*1.0e-6+1.0e-6 }";
fTol = new JTextArea(tolStr);
fTol.setFont(GlobalValues.defaultTextFont);
plotButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String expr = fCode.getText();
// extract the function name
int startIdx = expr.indexOf("def") + 4; // after def
int endIdx = expr.indexOf('(');
String fname = expr.substring(startIdx, endIdx);
double lowX = Double.parseDouble(fXLow.getText());
double stepX = Double.parseDouble(fXStep.getText());
double upX = Double.parseDouble(fXUp.getText());
codeStr = expr + "\n\nvar x = Inc(" + lowX + "," + stepX + "," + upX + "); \n" +
"var xlen = x.length \n" +
"var y = new Array[Double](xlen) \n" +
"var yt = new Array[Double](1) \n" +
"for (k<-0 to xlen-1) { yt(0)=x(k); y(k) = " + fname + "(yt);}\n" +
"plot(x,y);";
GlobalValues.scalalabMainFrame.scalalabConsole.interpretLine(codeStr);
}
});
buttonGenerateCode.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String expr = fCode.getText();
double lowX = Double.parseDouble(fXLow.getText());
double stepX = Double.parseDouble(fXStep.getText());
double upX = Double.parseDouble(fXUp.getText());
String codeStr = " var x = new Array[Double](1); \n var a = new Array[Double](1); \n var b = new Array[Double](1); \n " +
"var mininClass = new MininClassTemplate(); \n" +
"a(0) = " + lowX + ";\n" +
"b(0) = " + upX + ";\n" +
"var m = Analytic_problems.mininder(a, b, mininClass); \n" +
"System.out.println(\"Minimum is \"+a(0)); " +
"// the wrapper class declaration follows \n" +
"\n\n class MininClassTemplate extends AnyRef with AP_mininder_methods { \n" +
expr +
tolStr +
"\n }";
if (genCode != null) {
functionPanel.remove(genCode);
}
if (fTol != null) {
functionPanel.remove(fTol);
}
genCode = new JTextArea(codeStr);
fTol = new JTextArea(tolStr);
genCode.setFont(GlobalValues.defaultTextFont);
functionPanel.add(genCode);
functionPanel.add(fTol);
pack();
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
}
});
functionPanel.add(new JLabel("y = f(x) = "));
functionPanel.add(fCode);
functionPanel.add(fTol);
limitsPanel.add(new JLabel("xMin (deltaX) xMax"));
JPanel xAxisPanel = new JPanel();
xAxisPanel.add(fXLow);
xAxisPanel.add(fXStep);
xAxisPanel.add(fXUp);
limitsPanel.add(xAxisPanel);
buttonsPanel.add(plotButton);
buttonsPanel.add(buttonGenerateCode);
setLayout(new BorderLayout());
add("North", functionPanel);
add("Center", limitsPanel);
add("South", buttonsPanel);
}
}
| 9,274
|
https://github.com/justlep/bitwig/blob/master/bitwigApiStubs/OscInvalidArgumentTypeException.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
bitwig
|
justlep
|
JavaScript
|
Code
| 9
| 22
|
/* API Version - 2.3.1 */
function OscInvalidArgumentTypeException() {}
| 44,476
|
https://github.com/diaksizz/Adisatya/blob/master/accounts/models.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Adisatya
|
diaksizz
|
Python
|
Code
| 86
| 390
|
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Admin(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
nama = models.CharField(max_length=200, null=True)
alamat = models.CharField(max_length=200, null=True)
no_hp = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
profile_pict = models.ImageField(null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.nama
class Client(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
nama = models.CharField(max_length=200, null=True)
no_hp = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
instansi = models.CharField(max_length=200, null=True, blank=True)
alamat = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.nama
| 36,827
|
https://github.com/ranand-twilio/Authy-API-Samples/blob/master/generateQRCode.sh
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
Authy-API-Samples
|
ranand-twilio
|
Shell
|
Code
| 49
| 189
|
clear
echo Generate a QR Code for 3rd party authenticator app
echo
echo Request
echo curl -X POST "https://api.authy.com/protected/json/users/\$AUTHY_ID/secret"
echo -H "X-Authy-API-Key: \$AUTHY_API_KEY"
echo -d label="LabelHere"
echo -d qr_size="300"
echo
echo
echo Response
curl -X POST "https://api.authy.com/protected/json/users/$AUTHY_ID/secret" \
-H "X-Authy-API-Key: $AUTHY_API_KEY" \
-d label="LabelHere" \
-d qr_size="300"| jq
echo
| 39,459
|
https://github.com/firefly1250/Cassie_CFROST/blob/master/Cassie_Example/+cassie/+constraints/average_pitch.m
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,020
|
Cassie_CFROST
|
firefly1250
|
MATLAB
|
Code
| 68
| 228
|
function [ average_pitch_fun ] = average_pitch( nlp )
%average_pitch constraint for average_pitch
% Creates SymFunction for a average_pitch constraint
%
% Author: Ross Hartley
% Date: 2018-03-19
% Compute function for average_pitch constraint
X = cell(1,nlp.NumNode);
for i = 1:nlp.NumNode
X{i} = SymVariable(['x',num2str(i)],[nlp.Plant.numState,1]);
if i == 1
average_pitch = X{i}(5);
else
average_pitch = average_pitch + X{i}(5);
end
end
average_pitch = average_pitch/nlp.NumNode;
average_pitch_fun = SymFunction(['average_pitch_', nlp.Plant.Name], average_pitch, X);
end
| 47,239
|
https://github.com/DEFRA/water-abstraction-service/blob/master/migrations/sqls/20191101101124-billing-tables-down.sql
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, OGL-UK-3.0
| 2,023
|
water-abstraction-service
|
DEFRA
|
SQL
|
Code
| 174
| 494
|
drop table if exists water.billing_transactions;
drop table if exists water.billing_invoice_licences;
drop table if exists water.billing_batch_invoices;
drop table if exists water.billing_invoices;
drop table if exists water.billing_batch_charge_versions;
drop table if exists water.billing_batches;
drop type if exists water.charge_type;
drop type if exists water.charge_batch_type;
------------------------------
-- update uuid to varchar type
------------------------------
-- drop the foreign key constraints
alter table if exists water.charge_agreements
drop constraint charge_agreements_charge_element_id_fkey;
alter table if exists water.charge_elements
drop constraint charge_elements_charge_version_id_fkey;
alter table if exists water.charge_agreements
alter column charge_agreement_id set data type varchar using charge_agreement_id::varchar,
alter column charge_element_id set data type varchar using charge_element_id::varchar;
alter table if exists water.charge_versions
alter column charge_version_id set data type varchar using charge_version_id::varchar;
alter table if exists water.charge_elements
alter column charge_version_id set data type varchar using charge_version_id::varchar,
alter column charge_element_id set data type varchar using charge_element_id::varchar;
-- reinstate the foreign key relationships
alter table if exists water.charge_agreements
add constraint charge_agreements_charge_element_id_fkey
foreign key (charge_element_id)
references water.charge_elements (charge_element_id)
match simple
on delete cascade;
alter table if exists water.charge_elements
add constraint charge_elements_charge_version_id_fkey
foreign key (charge_version_id)
references water.charge_versions (charge_version_id)
match simple
on delete cascade;
| 20,317
|
https://github.com/reels-research/iOS-Private-Frameworks/blob/master/ProactiveSupport.framework/_PASZoneSupport.h
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
iOS-Private-Frameworks
|
reels-research
|
C
|
Code
| 202
| 744
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/ProactiveSupport.framework/ProactiveSupport
*/
@interface _PASZoneSupport : NSObject
+ (id)copyArray:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)copyData:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)copyDate:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)copyDictionary:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)copyNumber:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)copySet:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)copyString:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)copyUUID:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)deepCopyObject:(id)arg1 toZone:(struct _NSZone { }*)arg2 strategy:(struct { unsigned int x1 : 1; unsigned int x2 : 1; unsigned int x3 : 1; unsigned int x4 : 1; unsigned int x5 : 1; unsigned int x6 : 1; })arg3;
+ (id)mutableCopyArray:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)mutableCopyData:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)mutableCopyDictionary:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)mutableCopySet:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)mutableCopyString:(id)arg1 toZone:(struct _NSZone { }*)arg2;
+ (id)newMutableArrayInZone:(struct _NSZone { }*)arg1;
+ (id)newMutableArrayInZone:(struct _NSZone { }*)arg1 capacity:(unsigned long long)arg2;
+ (id)newMutableDataInZone:(struct _NSZone { }*)arg1;
+ (id)newMutableDataInZone:(struct _NSZone { }*)arg1 capacity:(unsigned long long)arg2;
+ (id)newMutableDataInZone:(struct _NSZone { }*)arg1 length:(unsigned long long)arg2;
+ (id)newMutableDictionaryInZone:(struct _NSZone { }*)arg1;
+ (id)newMutableDictionaryInZone:(struct _NSZone { }*)arg1 capacity:(unsigned long long)arg2;
+ (id)newMutableSetInZone:(struct _NSZone { }*)arg1;
+ (id)newMutableSetInZone:(struct _NSZone { }*)arg1 capacity:(unsigned long long)arg2;
+ (id)newMutableStringInZone:(struct _NSZone { }*)arg1;
+ (id)newMutableStringInZone:(struct _NSZone { }*)arg1 capacity:(unsigned long long)arg2;
@end
| 25,774
|
https://github.com/William-Owen/KISO/blob/master/src/components/app/DisplayCurrency/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
KISO
|
William-Owen
|
JavaScript
|
Code
| 7
| 16
|
import DisplayCurrency from "./DisplayCurrency"
export default DisplayCurrency
| 49,094
|
https://github.com/lemastero/lotos/blob/master/examples/src/main/scala/lotos/examples/LFStackTest.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
lotos
|
lemastero
|
Scala
|
Code
| 148
| 481
|
package lotos.examples
import java.util.concurrent.atomic.AtomicReference
import cats.effect.{ExitCode, IO, IOApp}
import lotos.model.{Consistency, Gen, TestConfig}
import lotos.testing.LotosTest
import lotos.testing.syntax._
import scala.concurrent.duration._
case class Node[T](value: T, next: Node[T] = null)
class LFStack[T] extends Serializable {
val stack: AtomicReference[Node[T]] = new AtomicReference[Node[T]]()
def push(item: T): Unit = {
var oldHead: Node[T] = null
var newHead = Node(item)
do {
oldHead = stack.get();
newHead = newHead.copy(next = oldHead)
} while (!stack.compareAndSet(oldHead, newHead))
}
def pop: Option[T] = {
var oldHead: Node[T] = null
var newHead: Node[T] = null
do {
oldHead = stack.get()
if (oldHead == null)
return None
newHead = oldHead.next
} while (!stack.compareAndSet(oldHead, newHead))
Some(oldHead.value)
}
}
object LFStackTest extends IOApp {
val stackSpec =
spec(new LFStack[Int])
.withMethod(method("push").param("item")(Gen.int(10)))
.withMethod(method("pop"))
val cfg = TestConfig(
parallelism = 2,
scenarioLength = 10,
scenarioRepetition = 100,
scenarioCount = 10
)
def run(args: List[String]): IO[ExitCode] =
for {
_ <- LotosTest.forSpec(stackSpec, cfg, Consistency.linearizable)
} yield ExitCode.Success
}
| 4,585
|
https://github.com/pedromdev/mongoose-jest-setup/blob/master/src/configurations/mongodb.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
mongoose-jest-setup
|
pedromdev
|
JavaScript
|
Code
| 56
| 192
|
const MongoMemoryServer = require('mongodb-memory-server').default;
let mongod;
if (process.env.NODE_ENV === 'test') {
mongod = new MongoMemoryServer({
autoStart: false
});
}
module.exports = {
getMongoD() {
return mongod;
},
async getConnectionUri() {
if (process.env.NODE_ENV === 'test') {
if (!mongod.isRunning) {
console.log('Starting MongoDB Memory Server...');
await mongod.start();
}
return await mongod.getConnectionString();
} else {
return process.env.MONGODB_URI;
}
}
};
| 38,995
|
https://github.com/upbeatNow/CAD_Printer/blob/master/printFormsApp1/printFormsApp1/Plot/JoinStyle.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
CAD_Printer
|
upbeatNow
|
C#
|
Code
| 50
| 122
|
//
// Copyright © 2014 Parrish Husband (parrish.husband@gmail.com)
// The MIT License (MIT) - See LICENSE.txt for further details.
//
namespace PiaNO
{
/// <summary>
/// 连接样式
/// </summary>
public enum JoinStyle
{
Miter = 0,
Bevel = 1,
Round = 2,
Diamond = 3,
FromObject = 5
}
}
| 23,395
|
https://github.com/Joze01/caprisMinsal/blob/master/NextLevelSeven-master/NextLevelSeven-master/NextLevelSeven-master/NextLevelSeven/Parsing/Elements/EncodingFieldParser.cs
|
Github Open Source
|
Open Source
|
ISC, BSD-2-Clause
| 2,018
|
caprisMinsal
|
Joze01
|
C#
|
Code
| 99
| 286
|
using System.Collections.Generic;
using System.Linq;
using NextLevelSeven.Core;
using NextLevelSeven.Diagnostics;
namespace NextLevelSeven.Parsing.Elements
{
/// <summary>Represents the special field at MSH-2, which contains encoding characters for a message.</summary>
internal sealed class EncodingFieldParser : StaticValueFieldParser
{
/// <summary>Create an encoding field.</summary>
/// <param name="ancestor"></param>
public EncodingFieldParser(Parser ancestor)
: base(ancestor, 1, 2)
{
}
/// <summary>Get or set encoding characters.</summary>
public override string Value
{
get => Ancestor.DescendantDivider[1];
set => throw new ElementException(ErrorCode.ElementValueCannotBeChanged);
}
/// <summary>Get or set this field's encoding characters.</summary>
public override IEnumerable<string> Values
{
get { return Value.Select(c => new string(c, 1)); }
set => throw new ElementException(ErrorCode.ElementValueCannotBeChanged);
}
}
}
| 24,314
|
https://github.com/JarLob/EventStore/blob/master/src/EventStore.Core/Index/AddResult.cs
|
Github Open Source
|
Open Source
|
Apache-2.0, CC0-1.0
| 2,022
|
EventStore
|
JarLob
|
C#
|
Code
| 32
| 94
|
using System.Collections.Generic;
namespace EventStore.Core.Index {
public class AddResult {
public readonly IndexMap NewMap;
public readonly bool CanMergeAny;
public AddResult(IndexMap newMap, bool canMergeAny) {
NewMap = newMap;
CanMergeAny = canMergeAny;
}
}
}
| 40,878
|
https://github.com/AustinKladke/6.00.1x-MIT-CS-Python/blob/master/Week1/problem3.py
|
Github Open Source
|
Open Source
|
MIT
| null |
6.00.1x-MIT-CS-Python
|
AustinKladke
|
Python
|
Code
| 107
| 304
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 29 15:09:52 2021
@author: akladke
"""
overall_lst = []
s = 'azcbobobegghakl'
for i in range(len(s)):
sub_str = s[i:]
sub_str_lst = [] # List gets reset after inner loop is broken out of
current_sub_str = "" # String gets reset after inner loop is broken out of
for j in range(len(sub_str)):
if j + 1 < len(sub_str) and sub_str[j] <= sub_str[j+1]:
current_sub_str += sub_str[j]
else:
current_sub_str += sub_str[j]
if len(current_sub_str) != 0:
sub_str_lst.append(current_sub_str)
overall_lst.append(sub_str_lst)
break
max_str = ""
for i in overall_lst:
if len(i[0]) > len(max_str):
max_str = i[0]
print("Longest substring in alphabetical order: " + max_str)
| 1,075
|
https://github.com/CS151-Group-12/Smart-Group-Financial/blob/master/server/database/createTable.sql
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Smart-Group-Financial
|
CS151-Group-12
|
SQL
|
Code
| 242
| 627
|
CREATE TABLE `User` (
`userID` INT NOT NULL,
`email` VARCHAR(45) NOT NULL,
`password` VARCHAR(60) NOT NULL
);
CREATE TABLE `Event` (
`eventID` INT NOT NULL,
`name` VARCHAR(45) NOT NULL,
`location` VARCHAR(45) NOT NULL,
`startDate` VARCHAR(45) NOT NULL,
`endDate` VARCHAR(45) NOT NULL
);
CREATE TABLE `User` (`userID` INT NOT NULL);
CREATE TABLE `Party` (
`partyID` INT NOT NULL,
`name` VARCHAR(45) NOT NULL
);
CREATE TABLE `Location` (
`locationID` INT NOT NULL,
`city` VARCHAR(45) NOT NULL,
`zipCode` INT NOT NULL,
`state` VARCHAR(45) NOT NULL
);
CREATE TABLE `User-Contribute-Event` (
`eventID` INT NOT NULL,
`userID` INT NOT NULL,
`category` INT NOT NULL,
`amount` INT NOT NULL
);
CREATE TABLE `Event-HappenAt-Locatio` (
`eventID` INT NOT NULL,
`locationID` INT NOT NULL
);
CREATE TABLE `Party-Has-Event` (
`eventID` INT NOT NULL,
`partyID` INT NOT NULL
);
CREATE TABLE `User-Create-Event` (
`userID` INT NOT NULL,
`eventID` INT NOT NULL
);
CREATE TABLE `User-Join-Party` (
`userID` INT NOT NULL,
`partyID` INT NOT NULL
);
CREATE TABLE `User-Form-Party` (
`userID` INT NOT NULL,
`partyID` INT NOT NULL
);
CREATE TABLE `Party-Has-Event` (
`eventID` INT NOT NULL,
`partyID` INT NOT NULL
);
CREATE TABLE `User-Create-Event` (
`userID` INT NOT NULL,
`eventID` INT NOT NULL
);
CREATE TABLE `User-Join-Party` (
`userID` INT NOT NULL,
`partyID` INT NOT NULL
);
CREATE TABLE `User-Form-Party` (
`userID` INT NOT NULL,
`partyID` INT NOT NULL
);
CREATE TABLE `User-Owe-User` (
`receipientID` INT NOT NULL,
`payerID` INT NOT NULL,
`amount` INT NOT NULL,
`eventID` INT NOT NULL
);
| 15,381
|
https://github.com/aclements/perflock/blob/master/cmd/perflock/lock.go
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
perflock
|
aclements
|
Go
|
Code
| 232
| 659
|
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import "sync"
type PerfLock struct {
l sync.Mutex
q []*Locker
}
type Locker struct {
C <-chan bool
c chan<- bool
shared bool
woken bool
msg string
}
func (l *PerfLock) Enqueue(shared, nonblocking bool, msg string) *Locker {
ch := make(chan bool, 1)
locker := &Locker{ch, ch, shared, false, msg}
// Enqueue.
l.l.Lock()
defer l.l.Unlock()
l.setQ(append(l.q, locker))
if nonblocking && !locker.woken {
// Acquire failed. Dequeue.
l.setQ(l.q[:len(l.q)-1])
return nil
}
return locker
}
func (l *PerfLock) Dequeue(locker *Locker) {
l.l.Lock()
defer l.l.Unlock()
for i, o := range l.q {
if locker == o {
copy(l.q[i:], l.q[i+1:])
l.setQ(l.q[:len(l.q)-1])
return
}
}
panic("Dequeue of non-enqueued Locker")
}
func (l *PerfLock) Queue() []string {
var q []string
l.l.Lock()
defer l.l.Unlock()
for _, locker := range l.q {
q = append(q, locker.msg)
}
return q
}
func (l *PerfLock) setQ(q []*Locker) {
l.q = q
if len(q) == 0 {
return
}
wake := func(locker *Locker) {
if locker.woken == false {
locker.woken = true
locker.c <- true
}
}
if q[0].shared {
// Wake all shared acquires at the head of the queue.
for _, locker := range q {
if !locker.shared {
break
}
wake(locker)
}
} else {
wake(q[0])
}
}
| 7,118
|
https://github.com/RamziGaagai/RobustMP/blob/master/Optimizer/Geodesic_Opt/setup_geodesic_MPC.m
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
RobustMP
|
RamziGaagai
|
MATLAB
|
Code
| 225
| 1,048
|
function setup_geodesic_MPC(n,N,W,dW,n_W)
%%%%% Inputs %%%%%
%n: state-space dimension
%N: Chebyshev polynomial order
%W, dW: W and dW matrix functions
%n_W: states that W is a function of
%%%%% Outputs %%%%%
%geo_Prob: Tomlab problem structure
%T_e: evaluation matrix for geodesic curve
%T_dot_e: evaluation matrix for geodesic curve velocity
%% Define constants
K = 2*N;
K_e = 3; %beginning, middle, endpoint
%Optimization variables: chebyshev coefficients for geodesic
%{c_0^1...c_N^1},...,{c_0^1...c_N^n}
%% Obtain Chebyschev Pseudospectral Numerics
%CGL points and quadrature weights
[t,w] = clencurt(K);
[t_e,~] = clencurt(K_e-1);
%compute Cheby basis at all points
[T, T_dot] = ...
compute_cheby(K,N,t);
[T_e, T_dot_e] = ...
compute_cheby(K_e-1,N,t_e);
%% Geodesic endpoint constraints
[phi_start, ~] = compute_cheby(0,N,-1);
[phi_end, ~] = compute_cheby(0,N,1);
A_start = kron(eye(n),phi_start');
A_end = kron(eye(n),phi_end');
Aeq = sparse([A_start;
A_end]);
%% For evaluating x_k, x_dot_k
Phi = zeros(n,n*(N+1),K+1);
Phi_dot = zeros(n,n*(N+1),K+1);
for k = 1:K+1
Phi(:,:,k) = kron(eye(n),T(:,k)');
Phi_dot(:,:,k) = 2*kron(eye(n),T_dot(:,k)');
end
%use to evaluate cost derivative
Ti = zeros(n*(N+1),K+1,length(n_W));
In = eye(n);
for j = 1:length(n_W)
i = n_W(j);
Ti(:,:,j) = kron(In(:,i),T);
end
%% Setup cost and gradient functions
global GEO_X_MPC;
GEO_X_MPC = zeros(n,K+1);
global GEO_MXDOT_MPC;
GEO_MXDOT_MPC = zeros(n,K+1);
% Cost function
geo_cost_fnc = @(vars) Geodesic_cost_MPC(vars,w,n,...
K,W,Phi,Phi_dot);
%Gradient function
geo_grad_fnc = @(vars) Geodesic_grad_MPC(vars,w,...
K,N,n,Ti,W,dW,Phi,Phi_dot,n_W);
Name = 'Geodesic_MPC';
geo_Prob = conAssign(geo_cost_fnc,geo_grad_fnc,[],[],...
[],[],Name,zeros(n*(N+1),1),[],0,...
Aeq,zeros(2*n,1),zeros(2*n,1),[],[],[],[],[],[]);
geo_Prob.SOL.optPar(10) = 1e-6;
geo_Prob.SOL.optPar(11) = 1e-6;
geo_warm = struct('sol',0,'result',[]);
% Assemble geodesic struct for MPC
global geodesic_MPC;
geodesic_MPC = struct('geo_Prob',geo_Prob,'W',W,'geodesic_N',N,'T_e',T_e,'T_dot_e',T_dot_e,...
'geo_Aeq',Aeq,'warm',geo_warm,'solver','npsol');
end
| 10,630
|
https://github.com/zzzzzzzs/ApacheSpark-Self-Study/blob/master/SparkCore/src/main/java/spark/core/rdd/Spark19_RDD_Case.scala
|
Github Open Source
|
Open Source
|
MIT
| null |
ApacheSpark-Self-Study
|
zzzzzzzs
|
Scala
|
Code
| 58
| 239
|
package spark.core.rdd
import org.apache.spark.{SparkConf, SparkContext}
object Spark19_RDD_Case {
def main(args: Array[String]): Unit = {
val sparkConf = new SparkConf().setMaster("local[*]").setAppName("RDD")
val sc = new SparkContext(sparkConf)
// TODO 小练习:将List(List(1,2),3,List(4,5))进行扁平化操作
val list = List(
List(1,2),3,List(4,5)
)
val rdd = sc.makeRDD(list)
rdd.flatMap(
data => {
data match {
case list:List[_] => list
case d => List(d)
}
}
).collect.foreach(println)
sc.stop
}
}
| 16,953
|
https://github.com/limanmana/python-/blob/master/函数/位置参数默认参数键值对参数.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
python-
|
limanmana
|
Python
|
Code
| 92
| 566
|
# 参数的几种类型
# 位置参数。 一个标识符做形参。位置参数普通和常用。
# def get_max(q,w,e): #这是形参
# max_num = q
# if w > max_num:
# max_num = w
# if e > max_num:
# max_num = e
#
# return max_num
# get_max(3, 8, 7) #这是实参
# # 默认参数。带默认值的参数。step=1
# for i in range(1,10):
# print(i)
# def n(e,w,step=1):
# i = e
# while i<w:
#
# print(i)
# i+=step
#
# n(1,10,k)
# 上例中的step=1 就是一个默认参数。函数调用时是默认值。如果实参传值的话,传的值可以默认参数,那么这个参数的值就会覆盖参数默认值。
# 参数的顺序:默认参数必须要在位置参数之后。
# 默认值一般定义为你想要的默认信息,数字类型参数默认可以定为0,字符串参数默认值'',布尔默认值一般False。
# 键值对参数(函数调用传实参时)
def print_stu_info(name,sex,score):
print('姓名{},性别{},分数{}'.format(name, sex, score))
print_stu_info('小明','male',90) #位置参数
# #键值对参数 (namae='小明',sex=90)
# 当参数比较多,超过五个十个的时候,用位置参数容易混淆出错。
# 实参 键=值,这样就能准确给形参赋值
| 49,034
|
https://github.com/ErnestoVivas/X-HD/blob/master/ADoCSM/Modelica_Library/AixLib/Fluid/FMI/Conversion/Validation/AirToOutletFlowReversal.mo
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
X-HD
|
ErnestoVivas
|
Modelica
|
Code
| 269
| 1,411
|
within AixLib.Fluid.FMI.Conversion.Validation;
model AirToOutletFlowReversal
"Validation model for air to outlet converter with flow reversal enabled"
extends AixLib.Fluid.FMI.Conversion.Validation.AirToOutlet(
allowFlowReversal = true);
BoundaryCondition bouAirNoC(
redeclare package Medium = AixLib.Media.Air (
X_default={0.015, 0.985}))
"Boundary condition" annotation (Placement(
transformation(extent={{40,50},{60,70}})));
BoundaryCondition bouAirWithC(
redeclare package Medium = AixLib.Media.Air (
X_default={0.015, 0.985},
extraPropertiesNames={"CO2"}))
"Boundary condition" annotation (Placement(
transformation(extent={{40,10},{60,30}})));
BoundaryCondition bouDryAirNoC(
redeclare package Medium = Modelica.Media.Air.SimpleAir)
"Boundary condition" annotation (Placement(
transformation(extent={{40,-40},{60,-20}})));
BoundaryCondition bouDryAirWithC(
redeclare package Medium = Modelica.Media.Air.SimpleAir (
extraPropertiesNames={"CO2"}))
"Boundary condition" annotation (Placement(
transformation(extent={{40,-80},{60,-60}})));
protected
model BoundaryCondition
extends Modelica.Blocks.Icons.Block;
replaceable package Medium = Modelica.Media.Interfaces.PartialMedium
"Medium in the component";
final parameter Boolean use_p_in=false
"= true to use a pressure from connector, false to output Medium.p_default";
Adaptors.Inlet bouInlAirNoC(
redeclare package Medium = Medium,
allowFlowReversal=true,
use_p_in=false) "Boundary condition for air inlet"
annotation (Placement(transformation(extent={{-60,-10},{-40,10}})));
Sources.Boundary_pT bou(
redeclare package Medium = Medium,
nPorts=1,
p=Medium.p_default + 1000,
T=298.15,
C=fill(0.7, Medium.nC)) "Boundary condition"
annotation (Placement(transformation(extent={{60,-10},{40,10}})));
Interfaces.Inlet inlet(
use_p_in=use_p_in,
redeclare package Medium = Medium,
allowFlowReversal=true)
"Fluid inlet"
annotation (Placement(transformation(extent={{-120,-10},{-100,10}})));
FixedResistances.PressureDrop res(
redeclare package Medium = Medium,
m_flow_nominal=0.1,
dp_nominal=1000,
linearized=true) "Flow resistance"
annotation (Placement(transformation(extent={{-10,-10},{10,10}})));
equation
connect(bouInlAirNoC.inlet, inlet)
annotation (Line(points={{-61,0},{-110,0}}, color={0,0,255}));
connect(res.port_b, bou.ports[1])
annotation (Line(points={{10,0},{10,0},{40,0}}, color={0,127,255}));
connect(res.port_a, bouInlAirNoC.port_b)
annotation (Line(points={{-10,0},{-10,0},{-40,0}}, color={0,127,255}));
end BoundaryCondition;
equation
connect(bouAirNoC.inlet, conAirNoC.outlet)
annotation (Line(points={{39,60},{21,60}}, color={0,0,255}));
connect(bouAirWithC.inlet, conAirWithC.outlet)
annotation (Line(points={{39,20},{21,20}}, color={0,0,255}));
connect(bouDryAirNoC.inlet, conDryAirNoC.outlet)
annotation (Line(points={{39,-30},{21,-30}}, color={0,0,255}));
connect(bouDryAirWithC.inlet, conDryAirWithC.outlet)
annotation (Line(points={{39,-70},{21,-70}}, color={0,0,255}));
annotation (Documentation(info="<html>
<p>
This example is identical to
<a href=\"modelica://AixLib.Fluid.FMI.Conversion.Validation.AirToOutlet\">
AixLib.Fluid.FMI.Conversion.Validation.AirToOutlet</a>,
except that it has reverse flow.
This tests whether the fluid properties from
the upstream media are correctly converted to
the output signals of
<a href=\"modelica://AixLib.Fluid.FMI.Conversion.AirToOutlet\">
AixLib.Fluid.FMI.Conversion.AirToOutlet</a>.
</p>
</html>", revisions="<html>
<ul>
<li>
June 29, 2016 by Michael Wetter:<br/>
First implementation.
</li>
</ul>
</html>"),
__Dymola_Commands(file="modelica://AixLib/Resources/Scripts/Dymola/Fluid/FMI/Conversion/Validation/AirToOutletFlowReversal.mos"
"Simulate and plot"),
experiment(Tolerance=1e-6, StopTime=1.0));
end AirToOutletFlowReversal;
| 43,294
|
https://github.com/gurugio/paip-lisp/blob/master/lisp/mycin-r.lisp
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
paip-lisp
|
gurugio
|
Common Lisp
|
Code
| 314
| 720
|
;;;; -*- Mode: Lisp; Syntax: Common-Lisp -*-
;;;; Code from Paradigms of AI Programming
;;;; Copyright (c) 1991 Peter Norvig
;;;; File mycin-r.lisp: Sample parameter list and rulebase for mycin.
(requires "mycin")
;;; Parameters for patient:
(defparm name patient t "Patient's name: " t read-line)
(defparm sex patient (member male female) "Sex:" t)
(defparm age patient number "Age:" t)
(defparm burn patient (member no mild serious)
"Is ~a a burn patient? If so, mild or serious?" t)
(defparm compromised-host patient yes/no
"Is ~a a compromised host?")
;;; Parameters for culture:
(defparm site culture (member blood)
"From what site was the specimen for ~a taken?" t)
(defparm days-old culture number
"How many days ago was this culture (~a) obtained?" t)
;;; Parameters for organism:
(defparm identity organism
(member pseudomonas klebsiella enterobacteriaceae
staphylococcus bacteroides streptococcus)
"Enter the identity (genus) of ~a:" t)
(defparm gram organism (member acid-fast pos neg)
"The gram stain of ~a:" t)
(defparm morphology organism (member rod coccus)
"Is ~a a rod or coccus (etc.):")
(defparm aerobicity organism (member aerobic anaerobic))
(defparm growth-conformation organism
(member chains pairs clumps))
(clear-rules)
(defrule 52
if (site culture is blood)
(gram organism is neg)
(morphology organism is rod)
(burn patient is serious)
then .4
(identity organism is pseudomonas))
(defrule 71
if (gram organism is pos)
(morphology organism is coccus)
(growth-conformation organism is clumps)
then .7
(identity organism is staphylococcus))
(defrule 73
if (site culture is blood)
(gram organism is neg)
(morphology organism is rod)
(aerobicity organism is anaerobic)
then .9
(identity organism is bacteroides))
(defrule 75
if (gram organism is neg)
(morphology organism is rod)
(compromised-host patient is yes)
then .6
(identity organism is pseudomonas))
(defrule 107
if (gram organism is neg)
(morphology organism is rod)
(aerobicity organism is aerobic)
then .8
(identity organism is enterobacteriaceae))
(defrule 165
if (gram organism is pos)
(morphology organism is coccus)
(growth-conformation organism is chains)
then .7
(identity organism is streptococcus))
| 47,114
|
https://github.com/lucee/lucee-dockerfiles/blob/master/supporting/prewarm.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
lucee-dockerfiles
|
lucee
|
Shell
|
Code
| 95
| 337
|
#!/bin/sh
set -e
LUCEE_MINOR=$1
if [ "$LUCEE_MINOR" = "5.2" ]; then
# legacy warmup support for Lucee 5.2 only
/usr/local/tomcat/bin/catalina.sh start
while [ ! -f "/opt/lucee/web/logs/application.log" ] ; do sleep 2; done
while [ ! -d "/opt/lucee/server/lucee-server/deploy" ] ; do sleep 2; done
sleep 1
/usr/local/tomcat/bin/catalina.sh stop
sleep 3
rm -rf /opt/lucee/web/logs/*
/usr/local/tomcat/bin/catalina.sh start
while [ ! -f "/opt/lucee/web/logs/application.log" ] ; do sleep 2; done
while [ ! -d "/opt/lucee/server/lucee-server/deploy" ] ; do sleep 2; done
sleep 1
/usr/local/tomcat/bin/catalina.sh stop
sleep 3
rm -rf /opt/lucee/web/logs/*
else
# native warmup support
export LUCEE_ENABLE_WARMUP=true
/usr/local/tomcat/bin/catalina.sh run
fi
| 1,353
|
https://github.com/nobuyo/stone/blob/master/src/chap14/JavaLoader.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
stone
|
nobuyo
|
Java
|
Code
| 67
| 230
|
package chap14;
import stone.StoneException;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
public class JavaLoader {
protected ClassLoader loader;
protected ClassPool cpool;
public JavaLoader() {
cpool = new ClassPool(null);
cpool.appendSystemPath();
loader = new ClassLoader(this.getClass().getClassLoader()) {};
}
public Class<?> load(String className, String method) {
// System.out.println(method);
CtClass cc = cpool.makeClass(className);
try {
cc.addMethod(CtMethod.make(method, cc));
return cc.toClass(loader, null);
} catch (CannotCompileException e) {
throw new StoneException(e.getMessage());
}
}
}
| 35,385
|
https://github.com/J-Pster/unit-tests/blob/master/tests/getCharacter.spec.js
|
Github Open Source
|
Open Source
|
MIT
| null |
unit-tests
|
J-Pster
|
JavaScript
|
Code
| 388
| 939
|
/* eslint-disable max-len */
/* eslint-disable no-unused-vars */
const getCharacter = require('../src/getCharacter');
/*
Essa função recebe como parâmetro o nome de um personagem e retorna um objeto com seu nome, classe e frases.
O retorno será de acordo com a seguinte relação:
Parâmetro | Nome | Classe | Frases
----------------------------------------------------------------------------------
Arya | Arya Stark | Rogue | 'Not today', 'A girl has no name.'
Brienne | Brienne Tarth | Knight | 'Im No Lady, Your Grace.', 'I, Brienne Of Tarth, Sentence You To Die.'
Melissandre | Melissandre | Necromancer | 'Death By Fire Is The Purest Death.', 'For The Night Is Dark And Full Of Terrors.'
- Se o parâmetro não estiver na tabela, a função retorna undefined.
- Se o parâmetro estiver, a função retorna um objeto no formato abaixo:
{
name: 'Nome do Personagem',
class: 'Classe do Personagem' ,
phrases: ['frase1', 'frase2']
}
- OBS.: O parâmetro não é CASE SENSITIVE, portanto Arya, ArYa e ARYA tem o mesmo resultado.
Elabore testes para verificar se a função está funcionando de acordo com o proposto.
Parâmetros:
- Uma string.
Comportamento:
- getCharacter('Arya');
Retorno:
{
name: 'Arya Stark',
class: 'Rogue',
phrases: [ 'Not today', 'A girl has no name.' ]
}
*/
describe('9 - Implemente os casos de teste da função `getCharacter`', () => {
it('Verifica se a função `getCharacter` retorna o objeto do personagem corretamente.', () => {
// ESCREVA SEUS TESTES ABAIXO:
// Teste se a função, quando não recebe nenhum parâmetro, retorna undefined.
expect(getCharacter()).toBeUndefined();
// Teste se a função retorna o objeto correto para o parâmetro 'Arya',
let aryaCorrect = {
name: 'Arya Stark',
class: 'Rogue',
phrases: [ 'Not today', 'A girl has no name.' ]
}
expect(getCharacter('Arya')).toEqual(expect.objectContaining(aryaCorrect))
// Teste se a função retorna o objeto correto para o parâmetro 'Brienne',
let brienneCorrect = {
name: 'Brienne Tarth',
class: 'Knight',
phrases: ['Im No Lady, Your Grace.', 'I, Brienne Of Tarth, Sentence You To Die.'],
}
expect(getCharacter('Brienne')).toEqual(expect.objectContaining(brienneCorrect))
// Teste se a função retorna o objeto correto para o parâmetro 'Melissandre',
let melissandreCorrect = {
name: 'Melissandre',
class: 'Necromancer',
phrases: ['Death By Fire Is The Purest Death.', 'For The Night Is Dark And Full Of Terrors.'],
}
expect(getCharacter('Melissandre')).toEqual(expect.objectContaining(melissandreCorrect))
// Teste se os parâmetros não são Case Sensitive.
expect(getCharacter('Arya')).toEqual(getCharacter('arya'));
// Teste se ao passar um nome que não está na tabela, a função retorna undefined.
expect(getCharacter('SeuJosé')).toBeUndefined();
});
});
| 48,118
|
https://github.com/mukhtarbayerouniversity/fairensics/blob/master/fairensics/methods/disparate_impact.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
fairensics
|
mukhtarbayerouniversity
|
Python
|
Code
| 1,590
| 5,011
|
"""Wrapper and functions for DisparateImpact remover from fair-classification.
The base class _DisparateImpact implements predict function for both methods.
The classes AccurateDisparateImpact and FairDisparateImpact inherit from
_DisparateImpact and implement fit() functions with different input signatures
and algorithms for minimization.
Original code:
https://github.com/mbilalzafar/fair-classification
"""
import warnings
from copy import deepcopy
import numpy as np
from aif360.algorithms import Transformer
from aif360.datasets.binary_label_dataset import BinaryLabelDataset
from scipy.optimize import minimize
from .fairness_warnings import FairnessBoundsWarning, DataSetSkewedWarning
from .utils import (
add_intercept,
get_protected_attributes_dict,
get_one_hot_encoding,
LossFunctions,
)
from ..fairensics_utils import get_unprotected_attributes
class _DisparateImpact(Transformer):
"""Base class for the two methods removing disparate impact.
Example:
https://github.com/nikikilbertus/fairensics/blob/master/examples/2_1_fair-classification-disparate-impact-example.ipynb
"""
def __init__(self, loss_function, warn):
"""
Args:
loss_function (str): loss function string from utils.LossFunctions.
warn (bool): if true, warnings are raised on certain bounds.
"""
super(_DisparateImpact, self).__init__()
self._warn = warn
self._params = {}
self._initialized = False
self._loss_function = LossFunctions.get_loss_function(loss_function)
def predict(self, dataset: BinaryLabelDataset):
"""Make predictions.
Args:
dataset: either AIF360 data set or np.ndarray.
For AIF360 data sets, protected features will be ignored.
For np.ndarray, only unprotected features should be included.
Returns:
Either AIF360 data set or np.ndarray if dataset is np.ndarray.
"""
if not self._initialized:
raise ValueError("Model not initialized. Run `fit` first.")
# TODO: ok?
if isinstance(dataset, np.ndarray):
return np.sign(np.dot(add_intercept(dataset), self._params["w"]))
dataset_new = dataset.copy(deepcopy=True)
dataset_new.labels = np.sign(
np.dot(
add_intercept(get_unprotected_attributes(dataset)),
self._params["w"],
)
)
# Map the dataset labels to back to their original values.
temp_labels = dataset.labels.copy()
temp_labels[(dataset_new.labels == 1.0)] = dataset.favorable_label
temp_labels[(dataset_new.labels == -1.0)] = dataset.unfavorable_label
dataset_new.labels = temp_labels.copy()
if self._warn:
bound_warnings = FairnessBoundsWarning(dataset, dataset_new)
bound_warnings.check_bounds()
return dataset_new
@staticmethod
def _get_cov_thresh_dict(cov_thresh, protected_attribute_names):
"""Return dict with covariance threshold for each protected attribute.
Each attribute gets the same threshold (cov_thresh).
Args:
cov_thresh (float): the covariance threshold.
protected_attribute_names (list(str)): list of protected attribute
names.
Returns:
sensitive_attrs_to_cov_thresh (dict):
dict of form {"sensitive_attribute_name_1":cov_thresh, ...}.
"""
sensitive_attrs_to_cov_thresh = {}
for sens_attr_name in protected_attribute_names:
sensitive_attrs_to_cov_thresh[sens_attr_name] = cov_thresh
return sensitive_attrs_to_cov_thresh
class AccurateDisparateImpact(_DisparateImpact):
"""Minimize loss subject to fairness constraints.
Loss "L" defines whether a logistic regression or a liner SVM is trained.
Minimize
L(w)
Subject to
cov(sensitive_attributes, true_labels, predictions) <
sensitive_attrs_to_cov_thresh
Where:
predictions: the distance to the decision boundary
"""
def __init__(self, loss_function=LossFunctions.NAME_LOG_REG, warn=True):
super(AccurateDisparateImpact, self).__init__(
loss_function=loss_function, warn=warn
)
def fit(
self,
dataset: BinaryLabelDataset,
sensitive_attrs_to_cov_thresh=0,
sensitive_attributes=None,
):
"""Fit the model.
Args:
dataset: AIF360 data set
sensitive_attrs_to_cov_thresh (float or dict): dictionary as
returned by _get_cov_thresh_dict(). If a single float is passed
the dict is generated using the _get_cov_thresh_dict() method.
sensitive_attributes (list(str)): names of protected attributes to
apply constraints to.
"""
if self._warn:
dataset_warning = DataSetSkewedWarning(dataset)
dataset_warning.check_dataset()
# constraints are only applied to the selected sensitive attributes
# if no list is provided, constraints are applied to all protected
if sensitive_attributes is None:
sensitive_attributes = dataset.protected_attribute_names
# if sensitive_attrs_to_cov_thresh is not a dict, each sensitive
# attribute gets the same threshold
if not isinstance(sensitive_attrs_to_cov_thresh, dict):
sensitive_attrs_to_cov_thresh = self._get_cov_thresh_dict(
sensitive_attrs_to_cov_thresh,
dataset.protected_attribute_names,
)
# fair-classification takes the protected attributes as dict
protected_attributes_dict = get_protected_attributes_dict(
dataset.protected_attribute_names, dataset.protected_attributes
)
# map labels to -1 and 1
temp_labels = dataset.labels.copy()
temp_labels[(dataset.labels == dataset.favorable_label)] = 1.0
temp_labels[(dataset.labels == dataset.unfavorable_label)] = -1.0
self._params["w"] = self._train_model_sub_to_fairness(
add_intercept(get_unprotected_attributes(dataset)),
temp_labels.ravel(),
protected_attributes_dict,
sensitive_attributes,
sensitive_attrs_to_cov_thresh,
)
self._initialized = True
return self
def _train_model_sub_to_fairness(
self,
x,
y,
x_control,
sensitive_attrs,
sensitive_attrs_to_cov_thresh,
max_iter=10000,
):
""" Optimize the loss function under fairness constraints.
Args:
x (np.ndarray): 2D array of unprotected features and intercept.
y (np.ndarray): 1D array of labels.
x_control (dict): dict of protected attributes as returned by
get_protected_attributes_dict().
max_iter (int): maximum iterations for solver.
sensitive_attrs, sensitive_attrs_to_cov_thresh: see fit() method.
Returns:
w (np.ndarray): 1D array of the learned weights.
TODO: sensitive_attrs is redundant. sensitive_attrs_to_cov_thresh
should only contain features for which constraints are applied.
"""
constraints = self._get_fairness_constraint_list(
x, y, x_control, sensitive_attrs, sensitive_attrs_to_cov_thresh
)
x0 = np.random.rand(x.shape[1])
w = minimize(
fun=self._loss_function,
x0=x0,
args=(x, y),
method="SLSQP",
options={"maxiter": max_iter},
constraints=constraints,
)
if not w.success:
warnings.warn(
"Optimization problem did not converge. "
"Check the solution returned by the optimizer:"
)
print(w)
return w.x
def _get_fairness_constraint_list(
self, x, y, x_control, sensitive_attrs, sensitive_attrs_to_cov_thresh
):
"""Get list of constraints for fairness. See fit method for details.
Returns:
constraints (list(str)): fairness constraints in cvxpy format.
https://www.cvxpy.org/api_reference/cvxpy.constraints.html#
"""
constraints = []
for attr in sensitive_attrs:
attr_arr = x_control[attr]
attr_arr_transformed, index_dict = get_one_hot_encoding(attr_arr)
if index_dict is None: # binary attribute
thresh = sensitive_attrs_to_cov_thresh[attr]
c = {
"type": "ineq",
"fun": self._test_sensitive_attr_constraint_cov,
"args": (x, y, attr_arr_transformed, thresh, False),
}
constraints.append(c)
else: # categorical attribute, need to set the cov threshs
for attr_val, ind in index_dict.items():
attr_name = attr_val
thresh = sensitive_attrs_to_cov_thresh[attr][attr_name]
t = attr_arr_transformed[:, ind]
c = {
"type": "ineq",
"fun": self._test_sensitive_attr_constraint_cov,
"args": (x, y, t, thresh, False),
}
constraints.append(c)
return constraints
@staticmethod
def _test_sensitive_attr_constraint_cov(
model, x_arr, y_arr_dist_boundary, x_control, thresh, verbose
):
"""
The covariance is computed b/w the sensitive attr val and the distance
from the boundary. If the model is None, we assume that the
y_arr_dist_boundary contains the distance from the decision boundary.
If the model is not None, we just compute a dot product or model and
x_arr for the case of SVM, we pass the distance from boundary because
the intercept in internalized for the class and we have compute the
distance using the project function.
This function will return -1 if the constraint specified by thresh
parameter is not satisfied otherwise it will return +1 if the return
value is >=0, then the constraint is satisfied.
"""
assert x_arr.shape[0] == x_control.shape[0]
if len(x_control.shape) > 1: # make sure we just have one column
assert x_control.shape[1] == 1
if model is None:
arr = y_arr_dist_boundary # simply the output labels
else:
arr = np.dot(
model, x_arr.T
) # the sign of this is the output label
arr = np.array(arr, dtype=np.float64)
cov = np.dot(x_control - np.mean(x_control), arr) / len(x_control)
# <0 if covariance > thresh -- condition is not satisfied
ans = thresh - abs(cov)
if verbose is True:
print("Covariance is", cov)
print("Diff is:", ans)
print()
return ans
class FairDisparateImpact(_DisparateImpact):
"""Minimize disparate impact subject to accuracy constraints.
Loss "L" defines whether a logistic regression or a liner svm is trained.
Minimize
cov(sensitive_attributes, predictions)
Subject to
L(w) <= (1-gamma)L(w*)
Where
L(w*): is the loss of the unconstrained classifier
predictions: the distance to the decision boundary
"""
def __init__(self, loss_function=LossFunctions.NAME_LOG_REG, warn=True):
super(FairDisparateImpact, self).__init__(
loss_function=loss_function, warn=warn
)
def fit(
self,
dataset: BinaryLabelDataset,
sensitive_attributes=None,
sep_constraint=False,
gamma=0,
):
"""Fits the model.
Args:
dataset: AIF360 data set.
sensitive_attributes (list(str)): names of protected attributes to
apply constraints to.
sep_constraint (bool): apply fine grained accuracy constraint.
gamma (float): trade off for accuracy for sep_constraint.
"""
if self._warn:
dataset_warning = DataSetSkewedWarning(dataset)
dataset_warning.check_dataset()
# constraints are only applied to the selected sensitive attributes
# if no list is provided, constraints for all protected attributes
if sensitive_attributes is None:
sensitive_attributes = dataset.protected_attribute_names
# fair-classification takes the protected attributes as dict
protected_attributes_dict = get_protected_attributes_dict(
dataset.protected_attribute_names, dataset.protected_attributes
)
# map labels to -1 and 1
temp_labels = dataset.labels.copy()
temp_labels[(dataset.labels == dataset.favorable_label)] = 1.0
temp_labels[(dataset.labels == dataset.unfavorable_label)] = -1.0
self._params["w"] = self._train_model_sub_to_acc(
add_intercept(get_unprotected_attributes(dataset)),
temp_labels.ravel(),
protected_attributes_dict,
sensitive_attributes,
sep_constraint,
gamma,
)
self._initialized = True
return self
def _train_model_sub_to_acc(
self,
x,
y,
x_control,
sensitive_attrs,
sep_constraint,
gamma=None,
max_iter=10000,
):
"""Optimize fairness subject to accuracy constraints.
WARNING: Only first protected attribute is considered as constraint.
All others are ignored.
Args:
x (np.ndarray): 2D array of unprotected features and intercept.
y (np.ndarray): 1D array of labels.
x_control (dict): dict of protected attributes as returned by
get_protected_attributes_dict().
max_iter (int): maximum number of iterations for solver
sep_constraint, sensitive_attrs, gamma: see fit() method
Returns:
w (np.ndarray): 1D, the learned weight vector for the classifier.
"""
def cross_cov_abs_optm_func(weight_vec, x_in, x_control_in_arr):
cross_cov = x_control_in_arr - np.mean(x_control_in_arr)
cross_cov *= np.dot(weight_vec, x_in.T)
return float(abs(sum(cross_cov))) / float(x_in.shape[0])
x0 = np.random.rand(x.shape[1])
# get the initial loss without constraints
w = minimize(
fun=self._loss_function,
x0=x0,
args=(x, y),
method="SLSQP",
options={"maxiter": max_iter},
)
old_w = deepcopy(w.x)
constraints = self._get_accuracy_constraint_list(
x, y, x_control, w, gamma, sep_constraint, sensitive_attrs
)
if len(x_control) > 1:
warnings.warn(
"Only the first protected attribute is considered "
"with this constraint."
)
# TODO: only the first protected attribute is passed
# optimize for fairness under the unconstrained accuracy loss
w = minimize(
fun=cross_cov_abs_optm_func,
x0=old_w,
args=(x, x_control[sensitive_attrs[0]]),
method="SLSQP",
options={"maxiter": max_iter},
constraints=constraints,
)
if not w.success:
warnings.warn(
"Optimization problem did not converge. "
"Check the solution returned by the optimizer:"
)
print(w)
return w.x
def _get_accuracy_constraint_list(
self, x, y, x_control, w, gamma, sep_constraint, sensitive_attrs
):
"""Constraint list for accuracy constraint.
Args:
x, y, x_control, gamma, sep_constraint, sensitive_attrs: see
_train_model_sub_to_acc method.
w (scipy.optimize.OptimizeResult): the learned weights of the
unconstrained classifier.
Returns:
constraints (list(str)): accuracy constraints in cvxpy format.
https://www.cvxpy.org/api_reference/cvxpy.constraints.html#
TODO: Currently, only the first protected attribute is considered.
The code should be extended to more than one sensitive_attr.
"""
def constraint_gamma_all(w_, x_, y_, initial_loss_arr):
# gamma_arr = np.ones_like(y) * gamma # set gamma for everyone
new_loss = self._loss_function(w_, x_, y_)
old_loss = sum(initial_loss_arr)
return ((1.0 + gamma) * old_loss) - new_loss
def constraint_protected_people(w_, x_, _y):
# don't confuse the protected here with the sensitive feature
# protected/non-protected values protected here means that these
# points should not be misclassified to negative class
return np.dot(w_, x_.T) # if positive, constraint is satisfied
def constraint_unprotected_people(w_, _ind, old_loss, x_, y_):
new_loss = self._loss_function(w_, np.array([x_]), np.array(y_))
return ((1.0 + gamma) * old_loss) - new_loss
predicted_labels = np.sign(np.dot(w.x, x.T))
unconstrained_loss_arr = self._loss_function(
w.x, x, y, return_arr=True
)
constraints = []
if sep_constraint: # separate gamma for different people
for i in range(0, len(predicted_labels)):
# TODO: use favorable_label instead of 1.0
# TODO: extend here to allow more than one sensitive attribute
if (
predicted_labels[i] == 1.0
and x_control[sensitive_attrs[0]][i] == 1.0
):
c = {
"type": "ineq",
"fun": constraint_protected_people,
"args": (x[i], y[i]),
}
constraints.append(c)
else:
c = {
"type": "ineq",
"fun": constraint_unprotected_people,
"args": (i, unconstrained_loss_arr[i], x[i], y[i]),
}
constraints.append(c)
else: # same gamma for everyone
c = {
"type": "ineq",
"fun": constraint_gamma_all,
"args": (x, y, unconstrained_loss_arr),
}
constraints.append(c)
return constraints
| 14,386
|
https://github.com/philip1337/ecorp-matrix-viewer/blob/master/src/node/src/main/java/net/MasterPackets.java
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
ecorp-matrix-viewer
|
philip1337
|
Java
|
Code
| 61
| 163
|
package net;
import message.HeloMessage;
public class MasterPackets {
public static HeloMessage CreateHelo(int version, String magic, int width,
int height, long time, String vmVersion, String vmName, String hostname) {
HeloMessage msg = new HeloMessage();
msg.version_ = version;
msg.magic_ = magic;
msg.width = width;
msg.height = height;
msg.time_ = time;
msg.vmVersion_ = vmVersion;
msg.vmName_ = vmName;
msg.hostname_ = hostname;
return msg;
}
}
| 3,732
|
https://github.com/KPGY/frontend16/blob/master/node_modules/html2canvas/dist/types/css/ITypeDescriptor.d.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
frontend16
|
KPGY
|
TypeScript
|
Code
| 26
| 60
|
import { CSSValue } from './syntax/parser';
import { Context } from '../core/context';
export interface ITypeDescriptor<T> {
name: string;
parse: (context: Context, value: CSSValue) => T;
}
| 37,518
|
https://github.com/aqfaridi/Competitve-Programming-Codes/blob/master/SPOJ/SPOJ/PQUEUE.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
Competitve-Programming-Codes
|
aqfaridi
|
C++
|
Code
| 91
| 417
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <deque>
#include <utility>
using namespace std;
deque<pair<int,int> > q;
int main()
{
int t,n,pos,count,priority,num,posnum;
bool b;
scanf("%d",&t);
while(t--)
{
count = 0;
q.clear();
scanf("%d %d",&n,&pos);
for(int i=0;i<n;i++)
{
scanf("%d",&priority);
//storing priority with corresp position
q.push_back(make_pair(priority,i));
}
while(q.size())
{
b = false;
for(int j=1;j<q.size();j++)
{
if((q.front()).first < q[j].first)
{
q.push_back(q.front());
q.pop_front();
b = true;
break;
}
}
if(!b)
{
count++;
if((q.front()).second == pos)
break;
q.pop_front();//size decreases
}
/**
for(int x=0;x<q.size();x++)
cout<<"("<<q[x].first<<" "<<q[x].second<<"),"<<" ";
cout<<endl;
**/
}
printf("%d\n",count);
}
return 0;
}
| 39,957
|
https://github.com/xliangwu/com.caveup.machine_learn/blob/master/yinbaojian/crawl_content_chrome2.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
com.caveup.machine_learn
|
xliangwu
|
Python
|
Code
| 167
| 854
|
import csv
import re
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
def crawl_content(url):
try:
chrome_options = Options()
chrome_options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(url)
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located(
(By.CLASS_NAME, "MsoNormalTable"))
)
table_ele = driver.find_element_by_class_name("MsoNormalTable")
print(table_ele.text)
return table_ele.get_attribute('outerHTML')
finally:
driver.quit()
except BaseException as e:
print(url, '\t', "无法访问此网站", e)
return ""
if __name__ == '__main__':
all_files = [
"ybjhDocPcjgView_hainan_7.csv",
"ybjhDocPcjgView_guangxi_24.csv",
"ybjhDocPcjgView_guizhou_22.csv",
"ybjhDocPcjgView_hebei_26.csv",
"ybjhDocPcjgView_heilongjiang_32.csv",
"ybjhDocPcjgView_henan_63.csv",
"ybjhDocPcjgView_hubei_40.csv",
"ybjhDocPcjgView_hunan_75.csv",
"ybjhDocPcjgView_jiangsu_62.csv",
"ybjhDocPcjgView_jiangxi_48.csv",
"ybjhDocPcjgView_jilin_34.csv",
"ybjhDocPcjgView_liaoning_22.csv",
"ybjhDocPcjgView_neimenggu_27.csv",
"ybjhDocPcjgView_ningbo_23.csv"]
for file in all_files:
area = file.split("_")[1]
print("process file:{}->{} ".format(file, area))
contents = []
with open("../" + file, 'r', newline='', encoding='utf-8') as csv_file:
reader = csv.reader(csv_file)
index = 0
for row in reader:
if (len(row)) <= 0:
break
if(index>=180):
break
url = r'http://www.cbirc.gov.cn' + row[0]
page_content = crawl_content(url)
contents.append(page_content)
print(index, "->>>done")
index = index + 1
time.sleep(2)
with open("ybjhDocPcjgView_" + area + "_content" + ".html", 'w', encoding="utf-8", newline='') as f:
for content in contents:
f.write(content)
f.write("\n")
| 50,046
|
https://github.com/FireTS/rbxts-visualize/blob/master/src/index.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
rbxts-visualize
|
FireTS
|
TypeScript
|
Code
| 499
| 1,706
|
import Object from "@rbxts/object-utils";
import { RunService, Workspace } from "@rbxts/services";
import { ConfigureSettings, HandleAdornments, Swappable } from "types";
export class Visualizer {
private config: ConfigureSettings = {
enabled: true,
color: new Color3(1, 1, 1),
alwaysOnTop: true,
vectorRadius: 0.1,
pointRadius: 0.1,
lineRadius: 0.02,
lineInnerRadius: 0,
transparency: 0.5,
cframeLength: 1,
cacheAdornments: true,
vectorLine: false,
};
private swappable = new Array<Swappable>();
private vectors = this.createSwappable<ConeHandleAdornment | CylinderHandleAdornment>();
private points = this.createSwappable<SphereHandleAdornment>();
private lines = this.createSwappable<CylinderHandleAdornment>();
private createHandleAdornment<T extends HandleAdornments>(className: T) {
const instance = new Instance(className);
instance.Transparency = this.config.transparency;
instance.AlwaysOnTop = this.config.alwaysOnTop;
instance.Color3 = this.config.color;
instance.Visible = true;
instance.ZIndex = 2;
instance.Adornee = Workspace.Terrain;
instance.Parent = Workspace.Terrain;
return instance;
}
private createSwappable<T extends Instance>() {
const swappable = {
used: new Array<T>(),
unused: new Array<T>(),
};
this.swappable.push(swappable);
return swappable;
}
private pop<T extends Instance>(swappable: Swappable<T>) {
return this.config.cacheAdornments ? swappable.unused.pop() : undefined;
}
private step() {
for (const swappable of this.swappable) {
for (const unused of swappable.unused) {
unused.Destroy();
}
swappable.unused = swappable.used;
swappable.used = [];
}
}
/**
* A utility class for drawing different datatypes in 3d space.
*/
constructor(settings?: Partial<ConfigureSettings>) {
if (settings) this.configure(settings);
if (RunService.IsServer()) {
RunService.Heartbeat.Connect(() => this.step());
} else {
RunService.RenderStepped.Connect(() => this.step());
}
}
/**
* Override the default Visualizer settings.
*/
configure(settings: Partial<ConfigureSettings>) {
Object.assign(this.config, settings);
}
/**
* Render a direction Vector3
* @param origin The origin of the vector.
* @param direction The direction of the vector.
* @param color An optional color.
*/
vector(origin: Vector3, direction: Vector3, color = this.config.color) {
if (!this.config.enabled || !Visualize.config.enabled) return;
let adornment = this.pop(this.vectors);
if (!adornment) {
const adornmentType = this.config.vectorLine ? "CylinderHandleAdornment" : "ConeHandleAdornment";
adornment = this.createHandleAdornment(adornmentType);
}
const offset = this.config.vectorLine ? direction.Magnitude / 2 : 0;
adornment.Height = math.max(direction.Magnitude, 1);
adornment.Radius = this.config.vectorRadius;
adornment.CFrame = CFrame.lookAt(origin, origin.add(direction)).mul(new CFrame(0, 0, -offset));
adornment.Color3 = color;
this.vectors.used.push(adornment);
}
/**
* Render a single position as a point
* @param origin The point's location.
* @param color An optional color.
*/
point(origin: Vector3, color = this.config.color) {
if (!this.config.enabled || !Visualize.config.enabled) return;
let adornment = this.pop(this.points);
if (!adornment) {
adornment = this.createHandleAdornment("SphereHandleAdornment");
}
adornment.Radius = this.config.pointRadius;
adornment.CFrame = new CFrame(origin);
adornment.Color3 = color;
this.points.used.push(adornment);
}
/**
* Draw a line between two points
* @param start The start of the line.
* @param finish The end of the line.
* @param color An optional color.
*/
line(start: Vector3, finish: Vector3, color = this.config.color) {
if (!this.config.enabled || !Visualize.config.enabled) return;
let adornment = this.pop(this.lines);
if (!adornment) {
adornment = this.createHandleAdornment("CylinderHandleAdornment");
}
adornment.Height = start.sub(finish).Magnitude;
adornment.Radius = this.config.lineRadius;
adornment.InnerRadius = this.config.lineInnerRadius;
adornment.CFrame = CFrame.lookAt(start, finish).mul(new CFrame(0, 0, -start.sub(finish).Magnitude / 2));
adornment.Color3 = color;
this.lines.used.push(adornment);
}
/**
* Render a CFrame.
* Equivalent to: Visualize.vector(pos, lookVector, color)
* @param cframe The CFrame to render.
* @param color An optional color.
*/
cframe(cframe: CFrame, color = this.config.color) {
this.vector(cframe.Position, cframe.LookVector.mul(this.config.cframeLength), color);
}
}
/**
* A global visualizer instance for convenience.
*
* Disabling the global visualizer will disable all Visualizer instances.
*/
export const Visualize = new Visualizer();
| 28,388
|
https://github.com/andrewosh/hypercontainer/blob/master/lib/docker.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
hypercontainer
|
andrewosh
|
JavaScript
|
Code
| 699
| 2,001
|
var path = require('path')
var from = require('from2')
var cuid = require('cuid')
var proc = require('child_process')
var pump = require('pumpify')
var tar = require('tar-stream')
var sub = require('subleveldown')
var Swarm = require('discovery-swarm')
var Docker = require('dockerode')
var mkdirp = require('mkdirp')
var hyperdrive = require('hyperdrive')
var filesystem = require('./filesystem')
var conf = require('../conf')
var debug = require('debug')(conf.name)
function DockerEngine (db, opts) {
if (!(this instanceof DockerEngine)) return new DockerEngine(db, opts)
this.opts = opts || {}
this.db = db
this.drive = hyperdrive(db)
this.docker = new Docker()
}
DockerEngine.prototype.run = function (image, opts, cb) {
// check if the image is in the hyperdrive, else boot it from Docker Hub
var self = this
var archive = this.drive.createArchive(image)
var id = cuid()
console.log('booting from drive with id:', id, 'and img:', image)
self._bootFromArchive(archive, id, opts, cb)
}
DockerEngine.prototype._bootFromArchive = function (archive, id, opts, cb) {
var mnt = path.join(conf.containerDir, id, 'mnt')
var data = path.join(conf.containerDir, id, 'data')
// TODO: async?
mkdirp.sync(mnt)
var swarm = Swarm()
swarm.listen()
swarm.join(archive.key)
swarm.on('connection', function (conn) {
conn.pipe(archive.replicate()).pipe(conn)
})
function createImageStream (entry, offset) {
var total = entry.length - offset
debug('name:', entry.name, 'total:', total)
var cursor = archive.createByteCursor(entry.name, offset)
var read = 0
var done = false
// TODO: this can be optimized a lot
return from(function (size, next) {
if (done) return next(null, null)
cursor.next(function (err, buf) {
if (err) return next(err)
if (!buf) {
return next(null, null)
}
read += buf.length
if (read > total) {
done = true
var sliced = buf.slice(0, read - total)
debug('returning buffer of length:', sliced.length, 'read:', read)
return next(null, sliced)
}
debug('returning buffer of length:', buf.length, 'read:', read)
return next(null, buf)
})
})
}
function createIndexStream () {
return archive.list()
}
filesystem(sub(this.db, id), mnt, data, {
createImageStream: createImageStream,
createIndexStream: createIndexStream,
log: debug,
uid: process.getuid(),
gid: process.getgid()
}, function (err, fs) {
if (err) throw err
debug('filesystem index loaded. booting vm...')
fs.readdir('/', function (err, files) {
console.log('files are:', files)
if (err) throw err
files = files
.filter(function (file) {
return file !== '.' && file !== '..' && file !== 'proc' && file !== 'dev'
})
.map(function (file) {
return '-v ' + path.resolve(path.join(conf.containerDir, id, 'mnt', file)) + ':/' + file + ' '
})
.join('').trim().split(/\s+/)
var entrypoint = opts.cmd || '/bin/bash'
var command = ['run', '-it', '--entrypoint', entrypoint]
command = command.concat(['--net', opts.net || 'bridge'])
.concat(files).concat('tianon/true')
if (opts.env) {
var vars = [].concat(opts.env || [])
var env = []
vars.forEach(function (v) {
env.push('-e', v)
})
command = command.concat(env)
}
var spawn = function () {
proc.spawn('docker', command, {stdio: 'inherit'}).on('exit', function () {
console.log('EXITING')
return cb()
})
}
var ns = new Buffer('nameserver 8.8.8.8\nnameserver 8.8.4.4\n')
fs.open('/etc/resolv.conf', 1, function (err, fd) {
if (err < 0) return spawn()
fs.write('/etc/resolv.conf', 0, ns.length, ns, fd, function (err) {
if (err < 0) return spawn()
fs.release('/etc/resolv.conf', fd, spawn)
})
})
})
})
}
DockerEngine.prototype._bootFromHub = function (id, image, opts, cb) {
var containerOpts = Object.assign({ Image: image }, opts)
this.docker.createContainer(containerOpts, function (err, container) {
if (err) return cb(err)
container.attach({ stream: true, stdout: true, stderr: true }, function (err, stream) {
if (err) return cb(err)
return cb(null, stream)
})
})
}
DockerEngine.prototype.ps = function (opts, cb) {
// list all running docker containers (just a thin wrapper around `docker ps`)
this.docker.listContainers(opts, function (err, containers) {
if (err) return cb(err)
return cb(null, containers)
})
}
/**
* Create an image from a container (specified by ID)
*/
DockerEngine.prototype.create = function (id, opts, cb) {
var self = this
console.log('id:', id)
var container = this.docker.getContainer(id)
console.log('container:', container)
if (container) {
var archive = self.drive.createArchive()
container.export(function (err, stream) {
if (err) return cb(err)
var extract = tar.extract()
extract.on('entry', function (header, stream, callback) {
header.name = '/' + header.name
var fileStream = pump(stream, archive.createFileWriteStream(header))
fileStream.on('finish', function () {
return callback()
})
fileStream.on('error', function (err) {
return callback(err)
})
fileStream.resume()
})
var archiveStream = pump(stream, extract)
archiveStream.on('finish', function () {
archive.finalize(function (err) {
if (err) return cb(err)
if (opts.seed) {
return _seed(archive, cb)
}
return cb(null, archive.key.toString('hex'))
})
})
archiveStream.on('error', function (err) {
return cb(err)
})
archiveStream.resume()
})
} else {
return cb(new Error('container does not exist'))
}
function _seed (archive, cb) {
var swarm = Swarm()
swarm.listen()
swarm.join(archive.key)
swarm.on('connection', function (conn) {
conn.pipe(archive.replicate()).pipe(conn)
})
return cb(null, archive.key.toString('hex'))
}
}
module.exports = DockerEngine
| 32,362
|
https://github.com/digideskio/geoportal-server-harvester/blob/master/geoportal-connectors/geoportal-harvester-ags/src/main/java/com/esri/geoportal/harvester/ags/AgsApplication.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
geoportal-server-harvester
|
digideskio
|
Java
|
Code
| 196
| 625
|
/*
* Copyright 2016 Esri, 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.
*/
package com.esri.geoportal.harvester.ags;
import com.esri.geoportal.harvester.api.base.DataCollector;
import com.esri.geoportal.harvester.api.base.DataPrintStreamOutput;
import com.esri.geoportal.commons.meta.xml.SimpleDcMetaBuilder;
import com.esri.geoportal.harvester.api.ProcessInstance.Listener;
import com.esri.geoportal.harvester.api.base.SimpleInitContext;
import com.esri.geoportal.harvester.api.defs.EntityDefinition;
import com.esri.geoportal.harvester.api.defs.Task;
import com.esri.geoportal.harvester.api.specs.InputBroker;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
/**
* AgsApplication.
*/
public class AgsApplication {
public static void main(String[] args) throws Exception {
DataPrintStreamOutput destination = new DataPrintStreamOutput(System.out);
for (String sUrl: args) {
ArrayList<Listener> listeners = new ArrayList<>();
SimpleDcMetaBuilder metaBuilder = new SimpleDcMetaBuilder();
AgsConnector connector = new AgsConnector(metaBuilder);
URL start = new URL(sUrl);
EntityDefinition def = new EntityDefinition();
AgsBrokerDefinitionAdaptor adaptor = new AgsBrokerDefinitionAdaptor(def);
adaptor.setHostUrl(start);
InputBroker hv = connector.createBroker(def);
hv.initialize(new SimpleInitContext(new Task(null,hv,null),listeners));
DataCollector dataCollector = new DataCollector(hv, Arrays.asList(new DataPrintStreamOutput[]{destination}),listeners);
dataCollector.collect();
}
}
}
| 42,644
|
https://github.com/kuantingchen04/google-test-template/blob/master/run.sh
|
Github Open Source
|
Open Source
|
RSA-MD
| null |
google-test-template
|
kuantingchen04
|
Shell
|
Code
| 1
| 11
|
./build/test/unittest_all
| 17,317
|
https://github.com/mariamelfeky/Ottica-Store/blob/master/resources/views/lenseBrand/edit.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Ottica-Store
|
mariamelfeky
|
Blade
|
Code
| 88
| 496
|
@extends('layouts.admin')
@section('content')
<div class="container">
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h2 mb-0 text-black-800">Edit Brand</h1>
<a href="{{route('lenseBrand.index')}}" class="btn btn-icons btn-rounded btn-outline-info"><i class="fas fa-list fa-sm text-blue-80 "></i> All Lenses Brands</a>
</div>
{!! Form::model($brand,['route' =>['lenseBrand.update',$brand],'enctype'=>'multipart/form-data','method' => 'put']) !!}
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">Brand</span>
</div>
{!! Form::text('name',null,['class'=>'form-control','aria-label'=>'name', 'aria-describedby'=>'basic-addon1','placeholder'=>'Brand Name']) !!}
</div>
<div><span class="text">{{$errors->first('name')}}</span></div>
<div class="input-group mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" name="image" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile01">Choose Image</label>
</div>
</div>
<div>
<span>{{$errors->first('image')}}</span></div>
<div style="text-align: center ">
{!! Form::submit('Update',['class'=>'btn btn-primary center-block btn-lg']) !!}
{!! Form::close() !!}
</div>
</div>
</body>
</html>
@endsection
| 20,687
|
https://github.com/ischubert/gym-physx/blob/master/tests/test_box_env.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
gym-physx
|
ischubert
|
Python
|
Code
| 2,340
| 9,151
|
# %%
"""
Tests for the PhysxPushingEnv
"""
import os
import glob
import json
import pickle
import time
import numpy as np
import matplotlib.pyplot as plt
import pytest
import gym
from stable_baselines3 import HER, DDPG, SAC, TD3
from gym_physx.envs.shaping import PlanBasedShaping
from gym_physx.generators.plan_generator import PlanFromDiskGenerator
def test_pushing_obstacle():
"""
Make sure that pushing_obstacle behaves as expected
"""
with open(os.path.join(
os.path.dirname(__file__), "expected_observations_obstacle.json"
), "r") as in_file:
expected = json.load(in_file)
env = gym.make(
'gym_physx:physx-pushing-v0',
plan_based_shaping=PlanBasedShaping(
shaping_mode=None,
width=None
),
fixed_initial_config=None,
fixed_finger_initial_position=None,
plan_generator=None,
komo_plans=False,
action_uncertainty=0.0,
config_files="pushing_obstacle"
)
env._controlled_reset( # pylint: disable=protected-access
finger_position=[0, 1],
box_position=[0, 0.5],
goal_position=[1.5, 1.5]
)
actions = [
[0, -.01, 0],
[-.01, 0, 0],
[0, -.01, 0],
[.01, 0, 0],
[0, -.01, 0],
[.01, 0, 0],
[0, .01, 0],
[0, 0, .01],
[0, .01, 0],
[0, 0, -.01],
[.01, 0, 0],
[0, .01, -0.02],
[-.01, 0, 0],
[0, -.01, 0]
]
durations = [
100, 70, 10, 70, 30, 20, 40,
20, 10, 20, 100, 60, 80, 20
]
observations = []
for action, duration in zip(actions, durations):
for _ in range(duration):
# time.sleep(0.05)
obs, _, _, _ = env.step(action)
observations.append(list(obs["observation"]))
assert np.all(np.abs(np.array(observations) - np.array(expected)) < 1e-3)
def test_compare_manhattan_planner_to_saved():
"""
Make sure that the manhattan planner for n_keyframes=0 works as expected
"""
data_path = os.path.join(os.path.dirname(__file__), 'test_plans')
env = gym.make(
'gym_physx:physx-pushing-v0',
plan_based_shaping=PlanBasedShaping(
shaping_mode="relaxed",
width=None
),
fixed_initial_config=None,
fixed_finger_initial_position=None,
plan_generator=None,
komo_plans=False,
action_uncertainty=0.0,
config_files="pushing",
)
with open(os.path.join(
data_path, "saved_plans_manhattan_n_keyframes_0.pkl"
), 'rb') as data_stream:
saved_data = pickle.load(data_stream)
for element in saved_data:
finger_pos, box_pos, target_pos, plan = element
obs = env._controlled_reset(
finger_position=finger_pos,
box_position=box_pos,
goal_position=target_pos
)
assert np.all(
plan == obs['desired_goal']
)
@pytest.mark.parametrize("n_trials", [20])
@pytest.mark.parametrize("from_disk", [True, False])
def test_plan_generator_from_file(n_trials, from_disk):
"""
Test the plan generator class that provides plans
loaded from the disk
"""
# load test files
data_path = os.path.join(os.path.dirname(__file__), 'test_plans')
# generate generator object
plan_dim = 6
plan_len = 50
# either let generator load plans from disk
if from_disk:
file_list = glob.glob(
os.path.join(
data_path,
"plans_*.pkl"
)
)
num_plans_per_file = 1000
plan_array = None
flattened = False
# or load plans beforehand and provide it to the generator as object
else:
file_list = None
num_plans_per_file = None
with open(os.path.join(data_path, "buffered_plans.pkl"), 'rb') as data_stream:
plan_array = pickle.load(data_stream)
flattened = True
generator = PlanFromDiskGenerator(
plan_dim,
plan_len,
file_list=file_list,
num_plans_per_file=num_plans_per_file,
plan_array=plan_array,
flattened=flattened
)
# Assert (again; done in __init__() as well) that files are in the expected format
generator.test_consistency()
env_gen = gym.make(
'gym_physx:physx-pushing-v0',
plan_based_shaping=PlanBasedShaping(shaping_mode='relaxed'),
fixed_initial_config=None,
plan_generator=generator
)
env_plan = gym.make(
'gym_physx:physx-pushing-v0',
plan_based_shaping=PlanBasedShaping(shaping_mode='relaxed'),
fixed_initial_config=None,
plan_generator=None
)
trials = []
for _ in range(n_trials):
obs_gen = env_gen.reset()
plan_gen = obs_gen['desired_goal'].reshape(generator.plan_len, generator.plan_dim)
finger_position = plan_gen[0, :2]
box_position = plan_gen[0, 3:5]
goal_position = plan_gen[-1, 3:5]
obs_plan = env_plan._controlled_reset( # pylint: disable=protected-access
finger_position,
box_position,
goal_position
)
# assert that the saved plan and the recomputed plan are approximately consistent
trials.append(
np.mean(
np.abs(obs_gen['desired_goal'] - obs_plan['desired_goal'])
) < 0.05
)
assert np.mean(trials) >= 0.9
def test_observations(view=False, n_trials=5):
"""
Test the consistency of all observations
"""
shaping_objects = [
PlanBasedShaping(shaping_mode=strategy, gamma=gamma)
for strategy, gamma in zip(
[None, 'relaxed', 'potential_based'],
[None, None, 0.9]
)
]
with open(os.path.join(
os.path.dirname(__file__),
'expected_rewards.json'
), 'r') as data:
expected_rewards = json.load(data)["expected_rewards"]
for shaping_object, expected_reward in zip(
shaping_objects,
expected_rewards
):
for _ in range(n_trials):
env = gym.make(
'gym_physx:physx-pushing-v0',
plan_based_shaping=shaping_object
)
if view:
view = env.render()
states, achieved_goals, desired_goals, rewards, dones, infos = [], [], [], [], [], []
obs = env._controlled_reset( # pylint: disable=protected-access
[-0.3, 0],
[-0.6, -0.6],
[0.6, 0.6]
)
states.append(obs["observation"])
achieved_goals.append(obs["achieved_goal"])
desired_goals.append(obs["desired_goal"])
actions = [
[-0.05, 0, 0],
[0, -0.05, 0],
[0.05, 0, 0],
[0, -0.05, 0],
[0.05, 0, 0],
[0, 0.05, 0],
]
durations = [15, 13, 25, 5, 5, 26]
assert len(actions) == len(durations)
for action, duration in zip(actions, durations):
for timestep in range(duration):
obs, reward, done, info = env.step(action)
states.append(obs["observation"])
achieved_goals.append(obs["achieved_goal"])
desired_goals.append(obs["desired_goal"])
rewards.append(reward)
dones.append(done)
infos.append(info)
# This also checks for all subspaces
assert env.observation_space.contains(obs)
assert env.action_space.contains(action)
if view and (timestep % 10 == 0 or duration-timestep < 3):
fig = plt.figure()
axis = fig.gca(projection='3d')
axis.set_title("Dims 0 to 2")
axis.plot(
np.array(states)[:, 0],
np.array(states)[:, 1],
np.array(states)[:, 2],
marker='v',
label='states 0-2'
)
if shaping_object.shaping_mode is not None:
axis.plot(
np.array(achieved_goals)[:, 0],
np.array(achieved_goals)[:, 1],
np.array(achieved_goals)[:, 2],
label='achieved goals 0-2'
)
axis.plot(
np.array(desired_goals).reshape(
(-1, env.plan_length, env.dim_plan))[-1, :, 0],
np.array(desired_goals).reshape(
(-1, env.plan_length, env.dim_plan))[-1, :, 1],
np.array(desired_goals).reshape(
(-1, env.plan_length, env.dim_plan))[-1, :, 2],
label='latest plan 0-2'
)
axis.legend()
plt.show()
plt.show()
fig = plt.figure()
axis = fig.gca(projection='3d')
axis.set_title("Dims 3 to 5")
axis.plot(
np.array(states)[:, 3],
np.array(states)[:, 4],
np.array(states)[:, 5],
marker='v',
label='states 3-5'
)
if shaping_object.shaping_mode is not None:
axis.plot(
np.array(achieved_goals)[:, 3],
np.array(achieved_goals)[:, 4],
np.array(achieved_goals)[:, 5],
label='achieved goals 3-5',
)
axis.plot(
np.array(desired_goals).reshape(
(-1, env.plan_length, env.dim_plan))[-1, :, 3],
np.array(desired_goals).reshape(
(-1, env.plan_length, env.dim_plan))[-1, :, 4],
np.array(desired_goals).reshape(
(-1, env.plan_length, env.dim_plan))[-1, :, 5],
label='latest plan 3-5'
)
else:
axis.plot(
np.array(achieved_goals)[:, 0],
np.array(achieved_goals)[:, 1],
len(achieved_goals)*[0],
label='achieved goals 0-1',
marker='v'
)
axis.plot(
np.array(desired_goals)[:, 0],
np.array(desired_goals)[:, 1],
len(desired_goals)*[0],
marker='*',
label='desired goals 0-1'
)
axis.legend()
plt.show()
assert len(np.array(states).shape) == 2
assert np.array(states).shape[-1] == 10
for desired_goal in desired_goals:
assert np.all(desired_goals[0] == desired_goal)
if shaping_object.shaping_mode is not None:
assert len(np.array(achieved_goals).shape) == 2
assert np.array(achieved_goals).shape[-1] == 6
assert len(np.array(desired_goals).shape) == 2
assert np.array(desired_goals).shape[-1] == 50*6
assert np.all(np.array(states)[
:, :6] == np.array(achieved_goals))
else:
assert len(np.array(achieved_goals).shape) == 2
assert np.array(achieved_goals).shape[-1] == 2
assert len(np.array(desired_goals).shape) == 2
assert np.array(desired_goals).shape[-1] == 2
assert np.all(np.array(states)[
:, 3:5] == np.array(achieved_goals))
if shaping_object.shaping_mode == "potential_based":
previous_achieved_goals = np.array(achieved_goals)[:-1]
else:
previous_achieved_goals = None
computed_rewards = env.compute_reward(
np.array(achieved_goals)[1:],
np.array(desired_goals)[1:],
None,
previous_achieved_goal=previous_achieved_goals
)
if view and (timestep % 10 == 0 or duration-timestep < 3):
plt.plot(rewards, marker='1', markersize=20)
plt.plot(computed_rewards, marker='2', markersize=20)
plt.plot(expected_reward)
plt.legend([
'Collected rewards',
'Computed Rewards',
"Appr. Expected Rewards"
])
plt.show()
assert len(np.array(rewards).shape) == 1
assert len(computed_rewards.shape) == 1
assert computed_rewards.shape[0] == np.array(
rewards).shape[0]
assert np.all(computed_rewards == np.array(rewards))
assert len(np.array(expected_reward).shape) == 1
assert computed_rewards.shape[0] == np.array(
expected_reward).shape[0]
assert np.all(
np.abs(
(np.array(expected_reward) - np.array(rewards))
) < 5e-2
)
def test_stable_baselines_her():
"""
Test the gym API by running the stable_baselines3 HER implementation
https://github.com/DLR-RM/stable-baselines3 as reference.
This test does not check for performance.
"""
for model_class in [DDPG, SAC, TD3]:
# Create env without shaping
env = gym.make('gym_physx:physx-pushing-v0')
# The environment does not have a time limit itself, but
# this can be provided using the TimeLimit wrapper
env = gym.wrappers.TimeLimit(env, max_episode_steps=500)
model = HER(
'MlpPolicy',
env,
model_class,
verbose=1,
device='cpu'
)
model.learn(2100)
def test_simulation(n_trials=5, view=False):
"""
Test if the sequence of actions defined below
indeed reaches the goal, and whether the rewards are
as expected for all 3 shaping options.
Parts of this is redundant with test_observations(), but
redundancy does not hurt when testing.
"""
shaping_objects = [
PlanBasedShaping(shaping_mode=strategy, gamma=gamma)
for strategy, gamma in zip(
[None, 'relaxed', 'potential_based'],
[None, None, 0.9]
)
]
with open(os.path.join(
os.path.dirname(__file__),
'expected_rewards.json'
), 'r') as data:
expected_rewards = json.load(data)["expected_rewards"]
expected_success = expected_rewards[0]
for shaping_object, expected_reward in zip(
shaping_objects, expected_rewards
):
env = gym.make(
'gym_physx:physx-pushing-v0',
plan_based_shaping=shaping_object
)
if view:
view = env.render()
for _ in range(n_trials):
rewards = []
successes = []
env._controlled_reset( # pylint: disable=protected-access
[-0.3, 0],
[-0.6, -0.6],
[0.6, 0.6]
)
env.config.frame('target').setContact(0)
actions = [
[-0.05, 0, 0],
[0, -0.05, 0],
[0.05, 0, 0],
[0, -0.05, 0],
[0.05, 0, 0],
[0, 0.05, 0],
]
durations = [15, 13, 25, 5, 5, 26]
assert len(actions) == len(durations)
for action, duration in zip(actions, durations):
for _ in range(duration):
_, reward, _, info = env.step(action)
if view:
time.sleep(0.02)
print(f'reward={reward}')
rewards.append(reward)
successes.append(info["is_success"])
assert np.all(
np.abs(
(np.array(expected_reward) - np.array(rewards))
) < 5e-2
)
assert np.all(
np.array(successes).astype(float) == np.array(expected_success)
)
def test_friction(view=False):
"""
Test the effects of friction if angle of attack is not
aligned with the center of mass
"""
env = gym.make('gym_physx:physx-pushing-v0')
if view:
view = env.render()
successes = []
for _ in range(20):
for reset_pos, expected in zip(
[
[0.5, 0.],
[0.5, 0.1],
[0.5, -0.1]
],
[
[
-0.5, 0., 0.14, -0.75723034, -0.00260414,
0.64451677, 0.9986539, 0.00936635, -0.00884138, 0.05024423
],
[
-0.5, 0.1, 0.14, -0.68895733, -0.07530067,
0.64443678, 0.94599276, 0.01166595, -0.0064683, 0.32391319
],
[
-0.5, -0.1, 0.14, -0.66184765, 0.10549879,
0.64465803, 0.94096258, 0.00520798, -0.0121258, -0.33825325
]
]
):
if view:
time.sleep(2)
env._controlled_reset( # pylint: disable=protected-access
reset_pos,
[0., 0.],
[-0.6, -0.6]
)
action = [-0.05, 0., 0.]
for _ in range(20):
observation, _, _, _ = env.step(action)
if view:
time.sleep(0.02)
print(observation['observation'])
successes.append(np.linalg.norm(
observation['observation']-expected) < 1e-8)
assert np.all(successes)
def test_reset():
"""
Make sure that after a random reset, box and finger are
never in collision
"""
env = gym.make('gym_physx:physx-pushing-v0')
for _ in range(5000):
# reset to random finger, box, and target pos
env.reset()
# allowed states are in at least one of the planar
# coordinates further away from each other than $MIN_DIST
assert any(
np.abs(
env.config.frame(
"finger"
).getPosition()[:2] - env.config.frame(
"box"
).getPosition()[:2]
) > 0.21
)
@pytest.mark.parametrize("n_trials", [50])
@pytest.mark.parametrize("komo_plans", [False, True])
@pytest.mark.parametrize("n_keyframes", [0, 1])
def test_planning_module(n_trials, komo_plans, n_keyframes):
# MAKE SURE BOX IS NEVER PENETRATED
"""
Test whether the planning module returns feasible and dense
plans with acceptable costs
"""
# n_keyframes > 0 only implemented for komo_plans=False
if n_keyframes > 0 and komo_plans:
return 0
env = gym.make(
'gym_physx:physx-pushing-v0',
# using relaxed reward shaping only to enforce that the
# environment plans automatically
plan_based_shaping=PlanBasedShaping(shaping_mode='relaxed'),
komo_plans=komo_plans,
n_keyframes=n_keyframes,
plan_length=50*(1+n_keyframes)
)
height_offset = env.config.frame(
"finger"
).getPosition()[2] - env.config.getJointState()[2]
acceptable_costs_count = 0
for _ in range(n_trials):
observation = env.reset()
plan = observation["desired_goal"]
# Assert that the observation is included in observation space
assert env.observation_space.contains(observation)
# Should be already included in the assertion above
assert env.observation_space["desired_goal"].contains(plan)
# reshape plan into [time, dims]
plan = plan.reshape(env.plan_length, env.dim_plan)
# Make sure every line of the plan is included in achieved_goal space
for achieved_goal in plan:
assert env.observation_space["achieved_goal"].contains(
achieved_goal)
# ensure acceptable costs
costs = env.komo.getConstraintViolations() if komo_plans else 0
acceptable_costs_count += int(costs < 50)
# ensure that initial state of the plan is consistent with env state
assert np.all(np.abs(
observation["observation"][:6] - plan[0]
) < env.plan_max_stepwidth * 2)
# ensure that the initial state of the plan is consistent with achieved_goal
assert np.all(np.abs(
observation["achieved_goal"][:6] - plan[0]
) < env.plan_max_stepwidth * 2)
# ensure initial plan state consistent with internal joint state...
assert np.all(np.abs(
env.config.getJointState()[:3] - plan[0, :3]
) < env.plan_max_stepwidth * 2)
# ...and consistent with internal box state
assert np.all(np.abs(
env.config.frame('box').getPosition() - plan[0, 3:]
) < env.plan_max_stepwidth * 2)
# ensure that final state of plan reaches goal
assert np.all(np.abs(
env.config.frame('target').getPosition() - plan[-1, 3:]
) < env.plan_max_stepwidth * 2)
# enusure (again) that planned finger positions are within the env's limits
assert all(np.abs(
plan[:, :2]
).flatten() <= env.maximum_xy_for_finger)
assert np.all(
plan[:, 2] >= env.minimum_rel_z_for_finger -
env.plan_max_stepwidth/2
)
assert np.all(
plan[:, 2] <= env.maximum_rel_z_for_finger +
env.plan_max_stepwidth/2
)
# ensure that finger is never "inside" box
for state in plan:
assert (
(
# either the finger has to be outside the box...
# (only take inner disk of radius 0.2 here for simplicity)
np.linalg.norm(
state[:2] - state[3:5]
) > 0.18 # account for the box's border radius of 0.05
) or (
# or the finger's z coordinate is above the box
(state[2] + height_offset) - state[5] > 0.1 + 0.06
# account for height offset between joint and config coords
)
)
# ensure sufficient plan density and a smooth trajectory
assert all(
np.linalg.norm(
plan[1:] - plan[:-1],
axis=-1
) <= 2 * np.sqrt(2)*env.plan_max_stepwidth*150/env.plan_length
)
# A certain amount of plans have to have acceptable cost
assert acceptable_costs_count/n_trials >= 48/50
with open(
os.path.join(os.path.dirname(__file__), 'fixed_reset.json'),
'r'
) as infile:
fixed_reset_data = json.load(infile)
@pytest.mark.parametrize("n_episodes", [5])
@pytest.mark.parametrize(
"shaping_object",
[
PlanBasedShaping(shaping_mode=strategy, gamma=gamma)
for strategy, gamma in zip(
[None, 'relaxed', 'potential_based'],
[None, None, 0.9]
)
]
)
@pytest.mark.parametrize(
"fixed_initial_config",
[
None,
{
'finger_position': [-0.8, -0.1],
'box_position': [-0.5, 0.],
'goal_position': [0.5, 0.]
},
{
'finger_position': [-0.8, -0.1],
'box_position': [-0.5, 0.],
'goal_position': [0.5, 0.],
'static_plan': np.array(fixed_reset_data['reference_plan'])
},
]
)
def test_fixed_initial_config(n_episodes, shaping_object, fixed_initial_config):
"""
Test setting in which the environment is reset to the same config
(i.e. same finger+box position and same goal) after each reset
"""
assert shaping_object.shaping_mode in [None, 'relaxed', 'potential_based']
env = gym.make(
'gym_physx:physx-pushing-v0',
plan_based_shaping=shaping_object,
fixed_initial_config=fixed_initial_config
)
if fixed_initial_config is None:
assert not isinstance(env.observation_space, gym.spaces.Box)
assert isinstance(env.observation_space, gym.spaces.Dict)
else:
assert isinstance(env.observation_space, gym.spaces.Box)
assert not isinstance(env.observation_space, gym.spaces.Dict)
for _ in range(n_episodes):
obs = env.reset()
collected_rewards = []
desired_goals = []
achieved_goals = []
for __ in range(21):
assert env.observation_space.contains(obs)
if fixed_initial_config is None:
assert obs['observation'].shape == (10,)
if shaping_object.shaping_mode is not None:
assert obs['achieved_goal'].shape == (6,)
assert obs['desired_goal'].shape == (300,)
else:
assert obs['achieved_goal'].shape == (2,)
assert obs['desired_goal'].shape == (2,)
else:
assert obs.shape == (10,)
if shaping_object.shaping_mode is None:
assert env.current_desired_goal.shape == (2,)
assert np.all(env.current_desired_goal ==
fixed_initial_config["goal_position"])
else:
assert env.current_desired_goal.shape == (300,)
assert np.all(env.current_desired_goal == env.static_plan)
if 'static_plan' in fixed_initial_config:
# In this case env.static_plan has to be strictly equal to the reference
assert np.all(env.static_plan ==
fixed_initial_config['static_plan'])
assert np.all(env.static_plan == np.array(
fixed_reset_data['reference_plan']))
assert np.all(env.current_desired_goal == np.array(
fixed_reset_data['reference_plan']))
else:
# In this case the equality only is approximate
# (limited by the accuracy of the planner)
assert np.mean(
np.abs(env.static_plan -
np.array(fixed_reset_data['reference_plan']))
) < 5e-3
obs, reward, _, _ = env.step([0.05, 0, 0])
collected_rewards.append(reward)
desired_goals.append(env.current_desired_goal)
achieved_goals.append(env.current_achieved_goal)
reference_rewards = np.array(
fixed_reset_data[str(shaping_object.shaping_mode)])
if shaping_object.shaping_mode == 'potential_based':
reference_rewards = reference_rewards[1:]
collected_rewards = collected_rewards[1:]
computed_rewards = env.compute_reward(
np.array(achieved_goals)[1:],
np.array(desired_goals)[1:],
None,
previous_achieved_goal=np.array(achieved_goals)[:-1]
)
else:
computed_rewards = env.compute_reward(
np.array(achieved_goals),
np.array(desired_goals),
None
)
# Computed rewards always have to be strictly consistent
assert np.all(np.array(collected_rewards) == computed_rewards)
if fixed_initial_config is not None:
# Reference rewards have to be...
if 'static_plan' in fixed_initial_config:
# ..striclty consistent if the reference plan was used
if shaping_object.shaping_mode is not None:
assert np.all(
env.current_desired_goal == np.array(
fixed_initial_config['static_plan'])
)
assert np.all(
np.abs(np.array(collected_rewards) - reference_rewards) < 1e-15
)
# ...appr. consistent if the plan was re-computed
assert np.mean(
np.abs(np.array(collected_rewards) - reference_rewards)
) < 5e-3
@pytest.mark.parametrize("n_episodes", [10])
@pytest.mark.parametrize(
"shaping_object",
[PlanBasedShaping(shaping_mode=None, gamma=None)]
)
@pytest.mark.parametrize("fixed_finger_initial_position", [True, False])
def test_fixed_initial_finger_position(n_episodes, shaping_object, fixed_finger_initial_position):
assert shaping_object.shaping_mode in [None, 'relaxed', 'potential_based']
env = gym.make(
'gym_physx:physx-pushing-v0',
plan_based_shaping=shaping_object,
fixed_initial_config=None,
fixed_finger_initial_position=fixed_finger_initial_position
)
finger_positions = []
for _ in range(n_episodes):
obs = env.reset()
finger_positions.append(obs['observation'][:2])
finger_positions = np.array(finger_positions)
assert finger_positions.shape == (n_episodes, 2)
if fixed_finger_initial_position:
assert np.max(finger_positions) == 0
else:
assert not np.max(finger_positions) == 0
@pytest.mark.parametrize("n_episodes", [100])
@pytest.mark.parametrize("action_noise", [0.0, 0.1])
def test_success_rate_of_open_loop_manhattan_plans(n_episodes, action_noise):
env = gym.make(
'gym_physx:physx-pushing-v0',
# using relaxed reward shaping only to enforce that the
# environment plans automatically
plan_based_shaping=PlanBasedShaping(
shaping_mode="relaxed",
width=0.5
),
fixed_initial_config=None,
fixed_finger_initial_position=True,
plan_length=50,
komo_plans=False,
action_uncertainty=action_noise
)
# (almost) open-loop plan execution
last_rewards = []
for _ in range(n_episodes):
obs = env.reset()
for _ in range(100):
plan = obs['desired_goal'].reshape(env.plan_length, env.dim_plan)
closest_ind = np.argmin(np.linalg.norm(plan - obs['achieved_goal'][None, :], axis=-1))
if closest_ind+1 < len(plan):
action = plan[closest_ind + 1, :3] - plan[closest_ind, :3]
obs, reward, done, info = env.step(action)
else:
break
last_rewards.append(reward)
if action_noise == 0:
assert np.mean(last_rewards) > 0.6
else:
assert np.mean(last_rewards) < 0.4
# %%
| 9,868
|
https://github.com/archeranimesh/HeadFirstPython/blob/master/SRC/Chapter_02-List-Data/04_panic.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
HeadFirstPython
|
archeranimesh
|
Python
|
Code
| 66
| 178
|
phrase = "Don't panic!"
plist = list(phrase)
print(phrase)
print(plist)
# remove the last 4 char "nic!"
for i in range(4):
plist.pop()
# Remove the first char, D
plist.pop(0)
# Remove the ', list is ont pa
plist.remove("'")
# Swap last 2 character, list is ont ap
plist.extend([plist.pop(), plist.pop()])
# Shifts the space by 1 index, list is on tap
plist.insert(2, plist.pop(3))
new_phrase = "".join(plist)
print(plist)
print(new_phrase)
| 31,067
|
https://github.com/mpsitech/wdbe-WhizniumDBE/blob/master/japiwdbe/DpchEngWdbeAck.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
wdbe-WhizniumDBE
|
mpsitech
|
Java
|
Code
| 51
| 152
|
/**
* \file DpchEngWdbeAck.java
* Wdbe Java API package ack engine dispatch block
* \copyright (C) 2018-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
package apiwdbe;
public class DpchEngWdbeAck extends DpchEngWdbe {
public DpchEngWdbeAck() {
super(VecWdbeVDpch.DPCHENGWDBEACK);
};
};
| 46,623
|
https://github.com/AnnaFilinova/project1/blob/master/venv/Lib/site-packages/bokeh/server/static/js/types/models/widgets/spinner.d.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
project1
|
AnnaFilinova
|
TypeScript
|
Code
| 132
| 472
|
import { NumericInputView, NumericInput } from "./numeric_input";
import * as p from "../../core/properties";
export declare class SpinnerView extends NumericInputView {
model: Spinner;
protected wrapper_el: HTMLDivElement;
protected btn_up_el: HTMLButtonElement;
protected btn_down_el: HTMLButtonElement;
private _handles;
private _counter;
private _interval;
buttons(): Generator<HTMLButtonElement>;
initialize(): void;
connect_signals(): void;
render(): void;
get precision(): number;
remove(): void;
_start_incrementation(sign: 1 | -1): void;
_stop_incrementation(): void;
_btn_mouse_down(evt: MouseEvent): void;
_btn_mouse_up(): void;
_btn_mouse_leave(): void;
_input_mouse_wheel(evt: WheelEvent): void;
_input_key_down(evt: KeyboardEvent): void;
adjust_to_precision(value: number): number;
increment(step: number): void;
change_input(): void;
}
export declare namespace Spinner {
type Attrs = p.AttrsOf<Props>;
type Props = NumericInput.Props & {
value_throttled: p.Property<number | null>;
step: p.Property<number>;
page_step_multiplier: p.Property<number>;
wheel_wait: p.Property<number>;
};
}
export interface Spinner extends Spinner.Attrs {
}
export declare class Spinner extends NumericInput {
properties: Spinner.Props;
__view_type__: SpinnerView;
constructor(attrs?: Partial<Spinner.Attrs>);
static init_Spinner(): void;
}
//# sourceMappingURL=spinner.d.ts.map
| 16,026
|
https://github.com/SnitavetsIV/MysteryShopper/blob/master/ui/app/mock.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
MysteryShopper
|
SnitavetsIV
|
JavaScript
|
Code
| 227
| 747
|
(function (appModule) {
angular.module('app-mock', ['ngMockE2E'])
.run(function ($httpBackend) {
//LOCAL STORAGE
var userData = [
{
id: 1,
username: 'Admin',
password: 'Admin',
userType: 'Admin'
},
{
id: 2,
username: 'MySh',
password: 'MySh',
userType: 'Shopper'
},
{
id: 3,
username: 'CoMa',
password: 'CoMa',
userType: 'Manager'
}
];
//START Guest module
$httpBackend.whenPOST('/api/auth').respond(function (method, url, data, headers) {
data = JSON.parse(data);
if (!data.username || !data.password) {
return [404];
}
for (var i = 0; i < userData.length; i++) {
var user = userData[i];
if (user.username === data.username &&
user.password === data.password) {
return [200, {userType: user.userType, token: 'blablabla' + user.username}];
}
}
return [404];
});
$httpBackend.whenGET('/api/auth').respond(function (method, url, data, headers) {
data = JSON.parse(data);
if (!data.token) {
return [404];
} else {
//need to check is token exist in db
if (data.token.startsWith("blablabla")) {
return [202];
}
}
return [404];
});
$httpBackend.whenPOST('/api/user').respond(function (method, url, data, headers) {
data = JSON.parse(data);
if (data.username && data.password && data.userType) {
var nextId = 0;
for (var i = 0; i < userData.length; i++) {
if (userData[i].username == data.username) {
return [409, {message: 'Username already exist'}];
}
if (userData[i].id > nextId) {
nextId = userData[i].id;
}
}
if (data.userType != 'shopper' && data.userType != 'manager') {
return [403];
}
nextId++;
userData.push({
id: nextId,
username: data.username,
password: data.password,
userType: data.userType
});
return [200];
} else {
return [404];
}
});
//END Guest module
$httpBackend.whenGET(/\.html/).passThrough();
});
appModule.requires.push('app-mock');
}(angular.module('app')));
| 20,737
|
https://github.com/lyh-ADT/Shoots/blob/master/Shoots/test/shooter.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Shoots
|
lyh-ADT
|
Python
|
Code
| 86
| 370
|
import unittest
from Shoots.bin.map import Map
from Shoots.bin.shooter import Shooter
from Shoots.bin.info import Info
class TestCanSeeMethod(unittest.TestCase):
def test_vertical(self):
m = Map(2)
m.map = [
[Map.ROAD, Map.ROAD],
[Map.ROAD, Map.ROAD]
]
s1 = Shooter(m)
s2 = Shooter(m)
s1.position = (0, 0)
s1.face = Info.FACE_DONW
s2.position = (1, 0)
s2.face = Info.FACE_LEFT
self.assertTrue(s1.can_see(s2))
self.assertFalse(s2.can_see(s1))
def test_horizon(self):
m = Map(2)
m.map = [
[Map.ROAD, Map.ROAD],
[Map.ROAD, Map.ROAD]
]
s1 = Shooter(m)
s2 = Shooter(m)
s1.position = (0, 0)
s1.face = Info.FACE_RIGHT
s2.position = (0, 1)
s2.face = Info.FACE_DONW
self.assertTrue(s1.can_see(s2))
self.assertFalse(s2.can_see(s1))
| 40,476
|
https://github.com/W-YXN/MyNOIPProjects/blob/master/cut.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
MyNOIPProjects
|
W-YXN
|
C++
|
Code
| 86
| 224
|
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
long long ans = 0;
int main()
{
priority_queue<int, vector<int>, greater<int> > q;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
int tmp;
cin >> tmp;
q.push(tmp);
}
while (!q.empty())
{
int a = q.top();
q.pop();
if (!q.empty())
{
int b = q.top();
q.pop();
int cnt = a + b;
ans += (a + b);
q.push(cnt);
}
}
cout << ans << endl;
return 0;
}
| 13,995
|
https://github.com/ESSICS/openxal-fx/blob/master/xaos.tools.module/src/test/java/se/europeanspallationsource/xaos/tools/lang/PublicOuterSubClass2.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
openxal-fx
|
ESSICS
|
Java
|
Code
| 12
| 51
|
package se.europeanspallationsource.xaos.tools.lang;
@SuppressWarnings( "ClassWithoutLogger" )
public class PublicOuterSubClass2 extends PackageOuterClass {
}
| 17,732
|
https://github.com/ichisadashioko/EPiServer.Forms.Samples/blob/master/Implementation/Elements/DateTimeElementBlock.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
EPiServer.Forms.Samples
|
ichisadashioko
|
C#
|
Code
| 455
| 1,669
|
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.DataAnnotations;
using EPiServer.Forms.Core;
using EPiServer.Forms.Core.Internal;
using EPiServer.Forms.Core.Models.Internal;
using EPiServer.Forms.EditView;
using EPiServer.Forms.EditView.DataAnnotations;
using EPiServer.Forms.EditView.Models.Internal;
using EPiServer.Forms.Helpers.Internal;
using EPiServer.Forms.Implementation.Elements.BaseClasses;
using EPiServer.Forms.Implementation.Validation;
using EPiServer.Forms.Samples.EditView;
using EPiServer.Forms.Samples.EditView.SelectionFactory;
using EPiServer.Forms.Samples.Implementation.Models;
using EPiServer.Forms.Samples.Implementation.Validation;
using EPiServer.Shell.ObjectEditing;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
namespace EPiServer.Forms.Samples.Implementation.Elements
{
/// <summary>
/// DateTime element for EpiForm (support Visitor picking Time, Date, or both Date and Time)
/// </summary>
[ContentType(GUID = "{3CC0755E-E50B-4AF4-92DF-C0F7625D526F}", GroupName = ConstantsFormsUI.FormElementGroup, Order = 2230)]
[AvailableValidatorTypesAttribute(Include = new Type[] { typeof(RequiredValidator) })]
public class DateTimeElementBlock : InputElementBlockBase, IElementCustomFormatValue, IElementRequireClientResources
{
[SelectOne(SelectionFactoryType = typeof(DateTimePickerTypeSelectionFactory))]
[Display(GroupName = SystemTabNames.Content, Order = -6000)]
public virtual int PickerType { get; set; }
/// <summary>
/// Always use a custom Validator to validate this datetime element (along with builtin Validator like RequiredValidator)
/// <remarks>The datetime custom Validator is not visible to Editor (in EditView), but it still works to validate element value</remarks>
/// </summary>
[Display(GroupName = SystemTabNames.Content, Order = -5000)]
public override string Validators
{
get
{
var pickerValidator = GetValidatorTypeForPicker((DateTimePickerType)PickerType).FullName;
var validators = this.GetPropertyValue(content => content.Validators);
if (string.IsNullOrEmpty(validators))
{
return pickerValidator;
}
else
{
return string.Concat(validators, EPiServer.Forms.Constants.RecordSeparator, pickerValidator);
}
}
set
{
this.SetPropertyValue(content => content.Validators, value);
}
}
/// <summary>
/// Base on DateTimePicker type, we use appropriate Validator.
/// </summary>
private Type GetValidatorTypeForPicker(DateTimePickerType pickerType)
{
switch (pickerType)
{
case DateTimePickerType.DatePicker:
return typeof(DateValidator);
case DateTimePickerType.TimePicker:
return typeof(TimeValidator);
case DateTimePickerType.DateTimePicker:
return typeof(DateTimeValidator);
default:
return null;
}
}
/// <inheritdoc />
public virtual object GetFormattedValue()
{
// NOTE: submittedValue is YYYY-MM-DDTHH:mmTZD(ISO-8601), might need to transform to date only (yyyy/MM/dd) or time only (hh:mm)
var submittedValue = this.GetSubmittedValue();
if (submittedValue == null)
{
return null;
}
var valueString = submittedValue.ToString();
DateTime dateTimeValue;
if (!DateTime.TryParse(valueString, out dateTimeValue))
{
return valueString;
}
var dateTimeSegments = dateTimeValue.ToString("s", CultureInfo.InvariantCulture).Split(new char[] { 'T' }, StringSplitOptions.RemoveEmptyEntries);
var pickerType = (DateTimePickerType)this.PickerType;
switch (pickerType)
{
case DateTimePickerType.TimePicker:
return dateTimeSegments[1];
case DateTimePickerType.DatePicker:
return dateTimeSegments[0];
default:
return valueString;
}
}
/// <inheritdoc />
public override ElementInfo GetElementInfo()
{
var baseInfo = base.GetElementInfo();
var dateTimeElementInfo = new DateTimeElementInfo
{
Type = baseInfo.Type,
FriendlyName = baseInfo.FriendlyName,
CustomBinding = true,
PickerType = ((DateTimePickerType)this.PickerType).ToString().ToLower()
};
return dateTimeElementInfo;
}
public IEnumerable<Tuple<string, string>> GetExtraResources()
{
var publicVirtualPath = ModuleHelper.GetPublicVirtualPath(Constants.ModuleName);
return new List<Tuple<string, string>>() {
new Tuple<string, string>("script", publicVirtualPath + "/ClientResources/ViewMode/datetimepicker.modified.js"),
new Tuple<string, string>("script", publicVirtualPath + "/ClientResources/ViewMode/DateTimeElementBlock.js")
};
}
/// <summary>
/// convert datetime string with format YYYY-MM-DDTHH:mmTZD(ISO-8601) -> [yyyy-MM-dd hh:mm tt] OR [hh:mm:ss] -> [hh:mm tt]
/// </summary>
/// <returns></returns>
public override string GetDefaultValue()
{
var result = base.GetDefaultValue();// datetime string with format [YYYY-MM-DDTHH:mmTZD](ISO-8601) OR [YYYY-MM-DD] OR [hh:mm:ss]
if (!string.IsNullOrEmpty(this.GetErrorMessage()))
{
return result;
}
var pickerType = (DateTimePickerType)this.PickerType;
DateTime dateTimeValue;
if (!DateTime.TryParse(result, out dateTimeValue))
{
return result;
}
switch (pickerType)
{
case DateTimePickerType.TimePicker:
return dateTimeValue.ToString("hh:mm tt");
case DateTimePickerType.DateTimePicker:
return DateTimeOffset.Parse(result).ToString("yyyy-MM-dd hh:mm tt"); //ignore offset
default:
return result;
}
}
}
}
| 36,247
|
https://github.com/khangaikhuu-mstars/mstars-exercises/blob/master/anar/react/my-react-delivery-menu/src/App.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
mstars-exercises
|
khangaikhuu-mstars
|
JavaScript
|
Code
| 62
| 176
|
import './App.css';
import { BrowserRouter, Route } from 'react-router-dom';
import { Container } from 'react-bootstrap';
import Header from './Header'
import Home from './Home'
import Orders from './Orders'
import Delivery from './Delivery'
function App() {
return (
<BrowserRouter>
<Container>
<Route path="/" component={Header} />
<Route exact path={'/'} component={Home} />
<Route path={'/orders'} component={Orders} />
<Route path={'/delivery'} component={Delivery} />
</Container>
</BrowserRouter>
);
}
export default App;
| 9,551
|
https://github.com/felix-seifert/network-programming-project/blob/master/frontend/src/screens/PlaceCreateScreen.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
network-programming-project
|
felix-seifert
|
JavaScript
|
Code
| 206
| 787
|
import React, { PureComponent } from "react";
import TextField from "@material-ui/core/TextField/TextField";
import Button from "@material-ui/core/Button";
import { withStyles } from "@material-ui/styles";
import { toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { Redirect } from "react-router-dom";
import { createPlace } from "../rest/VisitedPlacesService";
toast.configure();
const styles = () => ({
textField: {
marginTop: "1rem",
},
});
class CreateFinancialRequestScreen extends PureComponent {
constructor(props) {
super(props);
this.state = {
city: null,
countryCode: null,
fromDate: null,
toDate: null,
visitorId: "soid",
};
}
handleTextFieldChange = (event) => {
console.log(event.target.id);
this.setState({ [event.target.id]: event.target.value });
};
handleCreate = () => {
createPlace(this.state)
.then(() => {
toast.success("Requested created successfully");
})
.catch(() => {
toast.error("Something went wrong!");
});
};
render() {
if (localStorage.getItem("token") === null) {
return <Redirect to="/" />;
}
const { classes } = this.props;
return (
<div>
<div style={{ display: "inline-block", marginTop: "5rem" }}>
<h2>Create Place</h2>
<form style={{ margin: "4rem" }}>
<TextField
className={classes.textField}
fullWidth={true}
id="countryCode"
label="Country Code"
onChange={this.handleTextFieldChange}
/>
<TextField
className={classes.textField}
fullWidth={true}
id="city"
label="City"
onChange={this.handleTextFieldChange}
/>
<TextField
className={classes.textField}
fullWidth={true}
id="fromDate"
label="Form Date"
type={"date"}
onChange={this.handleTextFieldChange}
InputLabelProps={{
shrink: true,
}}
/>
<TextField
className={classes.textField}
fullWidth={true}
id="toDate"
label="To Date"
type={"date"}
onChange={this.handleTextFieldChange}
InputLabelProps={{
shrink: true,
}}
/>
<Button
className={classes.textField}
variant="contained"
color="primary"
onClick={this.handleCreate}
>
Create Place
</Button>
</form>
</div>
</div>
);
}
}
CreateFinancialRequestScreen.propTypes = {};
export default withStyles(styles)(CreateFinancialRequestScreen);
| 20,992
|
https://github.com/Cindia-blue/openair-cn-lixh/blob/master/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/build.make
|
Github Open Source
|
Open Source
|
BSD-3-Clause, LicenseRef-scancode-unknown-license-reference, Apache-2.0, BSD-2-Clause, BSD-2-Clause-Views
| 2,019
|
openair-cn-lixh
|
Cindia-blue
|
Makefile
|
Code
| 614
| 6,218
|
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 3.10
# Delete rule output on recipe failure.
.DELETE_ON_ERROR:
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build
# Include any dependencies generated for this target.
include extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/depend.make
# Include the progress variables for this target.
include extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/progress.make
# Include the compile flags for this target's objects.
include extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/flags.make
extensions/rt_busypeers/lex.rtbusy_conf.c: ../extensions/rt_busypeers/rtbusy_conf.l
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --blue --bold --progress-dir=/home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_1) "Generating lex.rtbusy_conf.c"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/flex -Prtbusy_conf -o/home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/lex.rtbusy_conf.c /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers/rtbusy_conf.l
extensions/rt_busypeers/rtbusy_conf.tab.c: ../extensions/rt_busypeers/rtbusy_conf.y
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --blue --bold --progress-dir=/home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_2) "Generating rtbusy_conf.tab.c, rtbusy_conf.tab.h"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/bison --name-prefix=rtbusy_conf --defines --output-file=/home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/rtbusy_conf.tab.c /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers/rtbusy_conf.y
extensions/rt_busypeers/rtbusy_conf.tab.h: extensions/rt_busypeers/rtbusy_conf.tab.c
@$(CMAKE_COMMAND) -E touch_nocreate extensions/rt_busypeers/rtbusy_conf.tab.h
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/flags.make
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o: ../extensions/rt_busypeers/rtbusy.c
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_3) "Building C object extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -o CMakeFiles/rt_busypeers.dir/rtbusy.c.o -c /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers/rtbusy.c
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.i: cmake_force
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/rt_busypeers.dir/rtbusy.c.i"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -E /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers/rtbusy.c > CMakeFiles/rt_busypeers.dir/rtbusy.c.i
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.s: cmake_force
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/rt_busypeers.dir/rtbusy.c.s"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -S /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers/rtbusy.c -o CMakeFiles/rt_busypeers.dir/rtbusy.c.s
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o.requires:
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o.requires
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o.provides: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o.requires
$(MAKE) -f extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/build.make extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o.provides.build
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o.provides
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o.provides.build: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/flags.make
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o: extensions/rt_busypeers/lex.rtbusy_conf.c
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_4) "Building C object extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -I /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers -o CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o -c /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/lex.rtbusy_conf.c
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.i: cmake_force
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.i"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -I /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers -E /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/lex.rtbusy_conf.c > CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.i
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.s: cmake_force
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.s"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -I /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers -S /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/lex.rtbusy_conf.c -o CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.s
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o.requires:
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o.requires
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o.provides: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o.requires
$(MAKE) -f extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/build.make extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o.provides.build
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o.provides
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o.provides.build: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/flags.make
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o: extensions/rt_busypeers/rtbusy_conf.tab.c
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --progress-dir=/home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_5) "Building C object extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -I /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers -o CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o -c /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/rtbusy_conf.tab.c
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.i: cmake_force
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Preprocessing C source to CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.i"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -I /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers -E /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/rtbusy_conf.tab.c > CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.i
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.s: cmake_force
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green "Compiling C source to assembly CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.s"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && /usr/bin/cc $(C_DEFINES) $(C_INCLUDES) $(C_FLAGS) -I /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers -S /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/rtbusy_conf.tab.c -o CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.s
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o.requires:
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o.requires
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o.provides: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o.requires
$(MAKE) -f extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/build.make extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o.provides.build
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o.provides
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o.provides.build: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o
# Object files for target rt_busypeers
rt_busypeers_OBJECTS = \
"CMakeFiles/rt_busypeers.dir/rtbusy.c.o" \
"CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o" \
"CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o"
# External object files for target rt_busypeers
rt_busypeers_EXTERNAL_OBJECTS =
extensions/rt_busypeers.fdx: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o
extensions/rt_busypeers.fdx: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o
extensions/rt_busypeers.fdx: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o
extensions/rt_busypeers.fdx: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/build.make
extensions/rt_busypeers.fdx: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/link.txt
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --green --bold --progress-dir=/home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/CMakeFiles --progress-num=$(CMAKE_PROGRESS_6) "Linking C shared module ../rt_busypeers.fdx"
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && $(CMAKE_COMMAND) -E cmake_link_script CMakeFiles/rt_busypeers.dir/link.txt --verbose=$(VERBOSE)
# Rule to build all files generated by this target.
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/build: extensions/rt_busypeers.fdx
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/build
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/requires: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy.c.o.requires
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/requires: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/lex.rtbusy_conf.c.o.requires
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/requires: extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/rtbusy_conf.tab.c.o.requires
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/requires
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/clean:
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers && $(CMAKE_COMMAND) -P CMakeFiles/rt_busypeers.dir/cmake_clean.cmake
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/clean
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/depend: extensions/rt_busypeers/lex.rtbusy_conf.c
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/depend: extensions/rt_busypeers/rtbusy_conf.tab.c
extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/depend: extensions/rt_busypeers/rtbusy_conf.tab.h
cd /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build && $(CMAKE_COMMAND) -E cmake_depends "Unix Makefiles" /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/extensions/rt_busypeers /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers /home/lixh/v0.1.0/openair-cn/build/git_submodules/freeDiameter/build/extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/DependInfo.cmake --color=$(COLOR)
.PHONY : extensions/rt_busypeers/CMakeFiles/rt_busypeers.dir/depend
| 720
|
https://github.com/phad92/cac-v1/blob/master/resources/views/livewire/member/create-index.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
cac-v1
|
phad92
|
PHP
|
Code
| 361
| 1,656
|
<form wire:submit.prevent="processForm" class="needs-validation">
@include('layouts.partials.utils')
@yield('success')
@yield('errors')
@csrf
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="first_name">First name<sub class="text-danger">*</sub></label>
<input type="text" class="form-control" wire:model="first_name" id="first_name" placeholder="First name" >
@error('first_name')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
<div class="col-md-6 mb-3">
<label for="last_name">Last name <sub class="text-danger">*</sub> </label>
<input type="text" class="form-control" wire:model="last_name" id="last_name" placeholder="Last name" >
@error('last_name')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb3">
<div class="form-group">
<label for="dob" class="col-form-label">Date of Birth <sub class="text-danger">*</sub> </label>
<input class="form-control" type="date" wire:model="dob" id="dob" >
@error('dob')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
<div class="col-md-3 mb-3">
<div class="form-group">
<label class="col-form-label">Gender <sub class="text-danger">*</sub> </label>
<select class="form-control" wire:model="gender" >
<option value="">Choose Gender</option>
@foreach (['male', 'female'] as $gender)
<option value='{{ $gender }}'>{{ $gender }} </option>
@endforeach
</select>
@error('gender')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
<div class="col-md-6 mb-3">
<label for="phone">Phone Number<sub class="text-danger">*</sub><small class="text-info">(Active)</small></label>
<input type="text" class="form-control" wire:model="phone" id="phone" placeholder="Phone Number" >
@error('phone')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="email">Email Address</label>
<input type="text" class="form-control" wire:model="email" id="email" placeholder="Email Address">
@error('email')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
<div class="col-md-6 mb-3">
<label for="occupation">Occupation <sub class="text-danger">*</sub></label>
<input type="text" class="form-control" wire:model="occupation" id="occupation" placeholder="Occupation" >
@error('occupation')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="location">Location <sub class="text-danger">*</sub> </label>
<input type="text" class="form-control" wire:model="location" id="location" placeholder="Location" >
@error('location')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
<div class="col-md-6 mb-3">
<label for="hometown">Home Town</label>
<input type="text" class="form-control" wire:model="hometown" id="hometown" placeholder="Home Town">
@error('hometown')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
<div class="form-row">
<div class="col-md-4 mb-3">
<div class="form-group">
<label class="col-form-label">Marital Status</label>
<select class="form-control" wire:model="marital_status">
<option value="">Choose Status</option>
@foreach (['married', 'single'] as $status)
<option value='{{ $status }}'>{{ ucfirst($status) }} </option>
@endforeach
</select>
@error('marital_status')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
<div class="col-md-4 mb-3">
<label for="spouse">Spouse Name</label>
<input type="text" class="form-control" wire:model="spouse" id="spouse" placeholder="Spouse Name" >
@error('spouse')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
<div class="col-md-4 mb-3">
<label for="no_of_children">Number of Children</label>
<input type="number" class="form-control" wire:model="no_of_children" min="0" id="no_of_children" placeholder="Number of Children" >
@error('no_of_children')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
<div class="float-right">
<button class="btn btn-flat btn-primary mr-2" type="submit">Submit Form</button>
<button class="btn btn-flat btn-default" type="button">Cancel</button>
</div>
</form>
| 16,164
|
https://github.com/Bvdldf/ABP/blob/master/modules/PurchaseOrder/actions/PaxHeader/GetTaxes.php
|
Github Open Source
|
Open Source
|
PHP-3.0, Apache-2.0, ECL-2.0
| null |
ABP
|
Bvdldf
|
PHP
|
Code
| 4
| 26
|
30 mtime=1556800944.261386113
24 SCHILY.fflags=extent
| 26,885
|
https://github.com/majweb/xml/blob/master/database/factories/OrderFactory.php
|
Github Open Source
|
Open Source
|
MIT
| null |
xml
|
majweb
|
PHP
|
Code
| 113
| 422
|
<?php
namespace Database\Factories;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Order>
*/
class OrderFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
return [
'filename' => Str::random(10).'.xml',
'order_number' => $this->faker->unique()->numberBetween($min = 1000, $max = 9000).'-order' ,
'order_date' => $this->faker->dateTime($max = 'now', $timezone = null),
'expected_delivery_date' => $this->faker->dateTime($max = 'now', $timezone = null),
'document_function_code' => $this->faker->numberBetween($min = 1, $max = 1000),
'buyer_iln' => $this->faker->numberBetween($min = 0000000000000, $max = 9999999999999),
'seller_iln' => $this->faker->numberBetween($min = 0000000000000, $max = 9999999999999),
'delivery_point_iln' => $this->faker->numberBetween($min = 0000000000000, $max = 9999999999999),
'date_of_issue' => $this->faker->dateTime($max = 'now', $timezone = null),
'status' => $this->faker->randomElement($array = array ('Nowe','Potwierdzone','Zafakturowane'))
];
}
}
| 17,733
|
https://github.com/arangodb/arangodb/blob/master/arangod/Agency/AsyncAgencyComm.h
|
Github Open Source
|
Open Source
|
Apache-2.0, BSD-3-Clause, ICU, Zlib, GPL-1.0-or-later, OpenSSL, ISC, LicenseRef-scancode-gutenberg-2020, MIT, GPL-2.0-only, CC0-1.0, BSL-1.0, LicenseRef-scancode-autoconf-simple-exception, LicenseRef-scancode-pcre, Bison-exception-2.2, LicenseRef-scancode-public-domain, JSON, BSD-2-Clause, LicenseRef-scancode-unknown-license-reference, Unlicense, BSD-4-Clause, Python-2.0, LGPL-2.1-or-later
| 2,023
|
arangodb
|
arangodb
|
C++
|
Code
| 905
| 2,997
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2023 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Lars Maier
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <fuerte/message.h>
#include <deque>
#include <memory>
#include <mutex>
#include <velocypack/Builder.h>
#include <velocypack/Slice.h>
#include "Agency/AgencyComm.h"
#include "Agency/AgencyCommon.h"
#include "Agency/PathComponent.h"
#include "Basics/ResultT.h"
#include "Basics/debugging.h"
#include "Futures/Future.h"
#include "Network/Methods.h"
#include "Network/Utils.h"
namespace arangodb {
struct AsyncAgencyCommResult {
arangodb::fuerte::Error error;
std::unique_ptr<arangodb::fuerte::Response> response;
[[nodiscard]] bool ok() const noexcept {
return arangodb::fuerte::Error::NoError == this->error;
}
[[nodiscard]] bool fail() const noexcept { return !ok(); }
VPackSlice slice() const {
TRI_ASSERT(response != nullptr);
return response->slice();
}
std::shared_ptr<velocypack::Buffer<uint8_t>> copyPayload() const {
TRI_ASSERT(response != nullptr);
return response->copyPayload();
}
std::shared_ptr<velocypack::Buffer<uint8_t>> stealPayload() const {
TRI_ASSERT(response != nullptr);
return response->stealPayload();
}
std::string payloadAsString() const {
TRI_ASSERT(response != nullptr);
return response->payloadAsString();
}
std::size_t payloadSize() const {
TRI_ASSERT(response != nullptr);
return response->payloadSize();
}
arangodb::fuerte::StatusCode statusCode() const {
TRI_ASSERT(response != nullptr);
return response->statusCode();
}
[[nodiscard]] Result asResult() const {
using namespace arangodb::network;
if (!ok()) {
return Result{fuerteToArangoErrorCode(error), to_string(error)};
} else {
auto code = statusCode();
auto internalCode = fuerteStatusToArangoErrorCode(code);
if (internalCode == TRI_ERROR_NO_ERROR) {
return Result(internalCode);
}
return Result{internalCode, fuerteStatusToArangoErrorMessage(code)};
}
}
};
// Work around a spurious compiler warning in GCC 9.3 with our maintainer mode
// switched off. And since warnings are considered to be errors, we must
// switch the warning off:
#if defined(__GNUC__) && \
(__GNUC__ > 9 || (__GNUC__ == 9 && __GNUC_MINOR__ >= 2))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
struct AgencyReadResult : public AsyncAgencyCommResult {
AgencyReadResult(
AsyncAgencyCommResult&& result,
std::shared_ptr<arangodb::cluster::paths::Path const> valuePath)
: AsyncAgencyCommResult(std::move(result)),
_value(nullptr),
_valuePath(std::move(valuePath)) {}
VPackSlice value() {
if (this->_value.start() == nullptr) {
this->_value = slice().at(0).get(_valuePath->vec());
}
return this->_value;
}
private:
VPackSlice _value;
std::shared_ptr<arangodb::cluster::paths::Path const> _valuePath;
};
#if defined(__GNUC__) && \
(__GNUC__ > 9 || (__GNUC__ == 9 && __GNUC_MINOR__ >= 2))
#pragma GCC diagnostic pop
#endif
class AsyncAgencyComm;
class AsyncAgencyCommManager final {
public:
static std::unique_ptr<AsyncAgencyCommManager> INSTANCE;
static void initialize(ArangodServer& server) {
INSTANCE = std::make_unique<AsyncAgencyCommManager>(server);
}
static bool isEnabled() { return INSTANCE != nullptr; }
static AsyncAgencyCommManager& getInstance();
explicit AsyncAgencyCommManager(ArangodServer&);
void addEndpoint(std::string const& endpoint);
void updateEndpoints(std::vector<std::string> const& endpoints);
std::deque<std::string> endpoints() const {
std::unique_lock<std::mutex> guard(_lock);
return _endpoints;
}
std::string endpointsString() const;
auto getSkipScheduler() const -> bool { return _skipScheduler; };
void setSkipScheduler(bool v) { _skipScheduler = v; };
std::string getCurrentEndpoint();
void reportError(std::string const& endpoint);
void reportRedirect(std::string const& endpoint,
std::string const& redirectTo);
network::ConnectionPool* pool() const { return _pool; }
void pool(network::ConnectionPool* pool) { _pool = pool; }
ArangodServer& server();
uint64_t nextRequestId() {
return _nextRequestId.fetch_add(1, std::memory_order_relaxed);
}
bool isStopping() const { return _isStopping; }
void setStopping(bool stopping) { _isStopping = stopping; }
private:
std::atomic<bool> _isStopping = false;
std::atomic<bool> _skipScheduler = true;
ArangodServer& _server;
mutable std::mutex _lock;
std::deque<std::string> _endpoints;
network::ConnectionPool* _pool = nullptr;
std::atomic<uint64_t> _nextRequestId = 0;
};
struct SetTransientOptions {
bool skipScheduler = false;
network::Timeout timeout = std::chrono::seconds{20};
};
class AsyncAgencyComm final {
public:
using FutureResult = arangodb::futures::Future<AsyncAgencyCommResult>;
using FutureReadResult = arangodb::futures::Future<AgencyReadResult>;
[[nodiscard]] FutureResult getValues(
std::string const& path,
std::optional<network::Timeout> timeout = {}) const;
[[nodiscard]] FutureReadResult getValues(
std::shared_ptr<arangodb::cluster::paths::Path const> const& path,
std::optional<network::Timeout> timeout = {}) const;
[[nodiscard]] FutureResult poll(network::Timeout timeout,
uint64_t index) const;
[[nodiscard]] futures::Future<consensus::index_t> getCurrentCommitIndex()
const;
template<typename T>
[[nodiscard]] FutureResult setValue(
network::Timeout timeout,
std::shared_ptr<arangodb::cluster::paths::Path const> const& path,
T const& value, uint64_t ttl = 0) {
return setValue(timeout, path->str(), value, ttl);
}
template<typename T>
[[nodiscard]] FutureResult setValue(network::Timeout timeout,
std::string const& path, T const& value,
uint64_t ttl = 0) {
VPackBuffer<uint8_t> transaction;
{
VPackBuilder trxBuilder(transaction);
VPackArrayBuilder env(&trxBuilder);
{
VPackArrayBuilder trx(&trxBuilder);
{
VPackObjectBuilder ops(&trxBuilder);
{
VPackObjectBuilder op(&trxBuilder, path);
trxBuilder.add("op", VPackValue("set"));
trxBuilder.add("new", value);
if (ttl > 0) {
trxBuilder.add("ttl", VPackValue(ttl));
}
}
}
}
}
return sendWriteTransaction(timeout, std::move(transaction));
}
[[nodiscard]] FutureResult deleteKey(
network::Timeout timeout,
std::shared_ptr<arangodb::cluster::paths::Path const> const& path) const;
[[nodiscard]] FutureResult deleteKey(network::Timeout timeout,
std::string const& path) const;
[[nodiscard]] FutureResult sendWriteTransaction(
network::Timeout timeout, velocypack::Buffer<uint8_t>&& body) const;
[[nodiscard]] FutureResult sendReadTransaction(
network::Timeout timeout, velocypack::Buffer<uint8_t>&& body) const;
[[nodiscard]] FutureResult sendPollTransaction(network::Timeout timeout,
uint64_t index) const;
[[nodiscard]] FutureResult sendTransaction(
network::Timeout timeout, AgencyReadTransaction const&) const;
[[nodiscard]] FutureResult sendTransaction(
network::Timeout timeout, AgencyWriteTransaction const&) const;
[[nodiscard]] FutureResult setTransientValue(
std::string const& key, arangodb::velocypack::Slice const& slice,
SetTransientOptions const& opts = {});
enum class RequestType {
READ, // send the transaction again in the case of no response
WRITE, // does not send the transaction again but instead tries to do
// inquiry with the given ids
CUSTOM, // talk to the leader and always return the result, even on timeout
// or redirect
};
using ClientId = std::string;
[[nodiscard]] FutureResult sendWithFailover(
arangodb::fuerte::RestVerb method, std::string_view url,
network::Timeout timeout, RequestType type,
std::vector<ClientId> clientIds,
velocypack::Buffer<uint8_t>&& body) const;
[[nodiscard]] FutureResult sendWithFailover(
arangodb::fuerte::RestVerb method, std::string_view url,
network::Timeout timeout, RequestType type,
std::vector<ClientId> clientIds, AgencyTransaction const& trx) const;
[[nodiscard]] FutureResult sendWithFailover(
arangodb::fuerte::RestVerb method, std::string_view url,
network::Timeout timeout, RequestType type,
velocypack::Buffer<uint8_t>&& body) const;
[[nodiscard]] FutureResult sendWithFailover(arangodb::fuerte::RestVerb method,
std::string_view url,
network::Timeout timeout,
RequestType type,
uint64_t index) const;
AsyncAgencyComm() : _manager(AsyncAgencyCommManager::getInstance()) {}
explicit AsyncAgencyComm(AsyncAgencyCommManager& manager)
: _manager(manager) {}
auto withSkipScheduler(bool v) -> AsyncAgencyComm& {
_skipScheduler = v;
return *this;
}
private:
bool _skipScheduler = false;
AsyncAgencyCommManager& _manager;
};
} // namespace arangodb
| 19,549
|
https://github.com/toilatester/sample-automation-frameworks-across-languages/blob/master/java/ta-cucumber-test/src/test/java/com/mh/ta/test/SearchStoryTestPassed.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
sample-automation-frameworks-across-languages
|
toilatester
|
Java
|
Code
| 29
| 173
|
package com.mh.ta.test;
import com.mh.ta.core.base.BaseCucumberTestNG;
import cucumber.api.CucumberOptions;
@CucumberOptions(features = "src/test/resources/features/SearchWithPassed.feature", glue = { "com.mh.ta.test.stepdefs",
"com.mh.ta.core.base" }, plugin = { "com.mh.ta.core.report.CucumberReportListener",
"json:target/cucumber-report.json", "html:target/cucumber-report/SearchStory" })
public class SearchStoryTestPassed extends BaseCucumberTestNG {
}
| 45,227
|
https://github.com/goofmint/OnsenUI-Tab-Nav/blob/master/src/NewsDetail.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
OnsenUI-Tab-Nav
|
goofmint
|
Vue
|
Code
| 40
| 209
|
<template>
<v-ons-page>
<h2>ニュース詳細</h2>
<p style="text-align: center">
<v-ons-button @click="popPage" style="margin: 6px 0">戻る</v-ons-button>
<v-ons-button @click="toHomeDetail" style="margin: 6px 0">ホーム詳細へ</v-ons-button>
</p>
</v-ons-page>
</template>
<script>
export default {
key: 'NewsDetail',
methods: {
popPage() {
this.$emit('pop-page');
},
toHomeDetail() {
this.$emit('push-page', {page: 'HomeDetail'});
}
}
}
</script>
| 10,116
|
https://github.com/joseortizd/event-handler-corporate/blob/master/lib/index.d.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
event-handler-corporate
|
joseortizd
|
TypeScript
|
Code
| 24
| 65
|
import { EventModel } from "./business/models/event.model";
import { eventHandler } from "./business/event-subscriber/eventHandler";
export declare function publishEvent(event: EventModel): Promise<boolean>;
export declare function subscribeEvent(handler: eventHandler): void;
| 33,910
|
https://github.com/keitakurita/slack_tools/blob/master/tests/test_notify.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
slack_tools
|
keitakurita
|
Python
|
Code
| 86
| 424
|
import pytest
import jupyter_slack
def test_notify():
jupyter_slack.notify_self("hello world")
def test_context_manager_no_exception():
with jupyter_slack.Monitor("test no exception", time=False):
pass
def test_context_manager_no_exception_time():
with jupyter_slack.Monitor("test no exception timed", time=True):
pass
def test_context_manager_exception():
with pytest.raises(ValueError, match="AAAAA"):
with jupyter_slack.Monitor("test exception", time=False):
raise ValueError("AAAAA")
def test_context_manager_exception_tb():
def external_fn():
raise ValueError("AAAAA")
def error_fn():
def inner_error_fn():
external_fn()
inner_error_fn()
with pytest.raises(ValueError):
with jupyter_slack.Monitor("test exception", time=False, send_full_traceback=True):
error_fn()
def test_decorater_exception_tb():
def external_fn():
raise ValueError("AAAAA")
@jupyter_slack.Monitor("test decorator exception", send_full_traceback=True)
def error_fn():
def inner_error_fn():
external_fn()
inner_error_fn()
with pytest.raises(ValueError):
error_fn()
def test_silent():
with jupyter_slack.Monitor("silent! this should not be sent", silent=True):
pass
| 34,402
|
https://github.com/deg/batik/blob/master/batik-ext/src/main/java/org/w3c/dom/events/KeyboardEvent.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
batik
|
deg
|
Java
|
Code
| 952
| 2,311
|
/*
* Copyright (c) 2006 World Wide Web Consortium,
*
* (Massachusetts Institute of Technology, European Research Consortium for
* Informatics and Mathematics, Keio University). All Rights Reserved. This
* work is distributed under the W3C(r) Software License [1] 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.
*
* [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
package org.w3c.dom.events;
import org.w3c.dom.views.AbstractView;
/**
* The <code>KeyboardEvent</code> interface provides specific contextual
* information associated with keyboard devices. Each keyboard event
* references a key using an identifier. Keyboard events are commonly
* directed at the element that has the focus.
* <p> The <code>KeyboardEvent</code> interface provides convenient attributes
* for some common modifiers keys: <code>KeyboardEvent.ctrlKey</code>,
* <code>KeyboardEvent.shiftKey</code>, <code>KeyboardEvent.altKey</code>,
* <code>KeyboardEvent.metaKey</code>. These attributes are equivalent to
* use the method
* <code>KeyboardEvent.getModifierState(keyIdentifierArg)</code> with
* "Control", "Shift", "Alt", or "Meta" respectively.
* <p> To create an instance of the <code>KeyboardEvent</code> interface, use
* the <code>DocumentEvent.createEvent("KeyboardEvent")</code> method call.
* <p>See also the <a href='http://www.w3.org/TR/2006/WD-DOM-Level-3-Events-20060413'>
Document Object Model (DOM) Level 3 Events Specification
</a>.
* @since DOM Level 3
*/
public interface KeyboardEvent extends UIEvent {
// KeyLocationCode
/**
* The key activation is not distinguished as the left or right version
* of the key, and did not originate from the numeric keypad (or did not
* originate with a virtual key corresponding to the numeric keypad).
* Example: the 'Q' key on a PC 101 Key US keyboard.
*/
int DOM_KEY_LOCATION_STANDARD = 0x00;
/**
* The key activated is in the left key location (there is more than one
* possible location for this key). Example: the left Shift key on a PC
* 101 Key US keyboard.
*/
int DOM_KEY_LOCATION_LEFT = 0x01;
/**
* The key activation is in the right key location (there is more than
* one possible location for this key). Example: the right Shift key on
* a PC 101 Key US keyboard.
*/
int DOM_KEY_LOCATION_RIGHT = 0x02;
/**
* The key activation originated on the numeric keypad or with a virtual
* key corresponding to the numeric keypad. Example: the '1' key on a PC
* 101 Key US keyboard located on the numeric pad.
*/
int DOM_KEY_LOCATION_NUMPAD = 0x03;
/**
* <code>keyIdentifier</code> holds the identifier of the key. The key
* identifiers are defined in Appendix A.2 "". Implementations that are
* unable to identify a key must use the key identifier
* <code>"Unidentified"</code>.
*/
String getKeyIdentifier();
/**
* The <code>keyLocation</code> attribute contains an indication of the
* location of they key on the device, as described in .
*/
int getKeyLocation();
/**
* <code>true</code> if the control (Ctrl) key modifier is activated.
*/
boolean getCtrlKey();
/**
* <code>true</code> if the shift (Shift) key modifier is activated.
*/
boolean getShiftKey();
/**
* <code>true</code> if the alternative (Alt) key modifier is activated.
* <p ><b>Note:</b> The Option key modifier on Macintosh systems must be
* represented using this key modifier.
*/
boolean getAltKey();
/**
* <code>true</code> if the meta (Meta) key modifier is activated.
* <p ><b>Note:</b> The Command key modifier on Macintosh systems must be
* represented using this key modifier.
*/
boolean getMetaKey();
/**
* This methods queries the state of a modifier using a key identifier.
* See also .
* @param keyIdentifierArg A modifier key identifier. Common modifier
* keys are <code>"Alt"</code>, <code>"AltGraph"</code>,
* <code>"CapsLock"</code>, <code>"Control"</code>, <code>"Meta"</code>
* , <code>"NumLock"</code>, <code>"Scroll"</code>, or
* <code>"Shift"</code>.
* <p ><b>Note:</b> If an application wishes to distinguish between
* right and left modifiers, this information could be deduced using
* keyboard events and <code>KeyboardEvent.keyLocation</code>.
* @return <code>true</code> if it is modifier key and the modifier is
* activated, <code>false</code> otherwise.
*/
boolean getModifierState(String keyIdentifierArg);
/**
* The <code>initKeyboardEvent</code> method is used to initialize the
* value of a <code>KeyboardEvent</code> object and has the same
* behavior as <code>UIEvent.initUIEvent()</code>. The value of
* <code>UIEvent.detail</code> remains undefined.
* @param typeArg Refer to the <code>UIEvent.initUIEvent()</code> method
* for a description of this parameter.
* @param canBubbleArg Refer to the <code>UIEvent.initUIEvent()</code>
* method for a description of this parameter.
* @param cancelableArg Refer to the <code>UIEvent.initUIEvent()</code>
* method for a description of this parameter.
* @param viewArg Refer to the <code>UIEvent.initUIEvent()</code> method
* for a description of this parameter.
* @param keyIdentifierArg Specifies
* <code>KeyboardEvent.keyIdentifier</code>.
* @param keyLocationArg Specifies <code>KeyboardEvent.keyLocation</code>
* .
* @param modifiersList A <a href='http://www.w3.org/TR/2004/REC-xml-20040204/#NT-S'>white space</a> separated
* list of modifier key identifiers to be activated on this
* object.
*/
void initKeyboardEvent(String typeArg,
boolean canBubbleArg,
boolean cancelableArg,
AbstractView viewArg,
String keyIdentifierArg,
int keyLocationArg,
String modifiersList);
/**
* The <code>initKeyboardEventNS</code> method is used to initialize the
* value of a <code>KeyboardEvent</code> object and has the same
* behavior as <code>UIEvent.initUIEventNS()</code>. The value of
* <code>UIEvent.detail</code> remains undefined.
* @param namespaceURI Refer to the <code>UIEvent.initUIEventNS()</code>
* method for a description of this parameter.
* @param typeArg Refer to the <code>UIEvent.initUIEventNS()</code>
* method for a description of this parameter.
* @param canBubbleArg Refer to the <code>UIEvent.initUIEventNS()</code>
* method for a description of this parameter.
* @param cancelableArg Refer to the <code>UIEvent.initUIEventNS()</code>
* method for a description of this parameter.
* @param viewArg Refer to the <code>UIEvent.initUIEventNS()</code>
* method for a description of this parameter.
* @param keyIdentifierArg Refer to the
* <code>KeyboardEvent.initKeyboardEvent()</code> method for a
* description of this parameter.
* @param keyLocationArg Refer to the
* <code>KeyboardEvent.initKeyboardEvent()</code> method for a
* description of this parameter.
* @param modifiersList A <a href='http://www.w3.org/TR/2004/REC-xml-20040204/#NT-S'>white space</a> separated
* list of modifier key identifiers to be activated on this
* object. As an example, <code>"Control Alt"</code> will activated
* the control and alt modifiers.
*/
void initKeyboardEventNS(String namespaceURI,
String typeArg,
boolean canBubbleArg,
boolean cancelableArg,
AbstractView viewArg,
String keyIdentifierArg,
int keyLocationArg,
String modifiersList);
}
| 23,343
|
https://github.com/Valentine1996/FamilyTime/blob/master/src/main/java/com/familytime/notification/model/service/NotificationService.java
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
FamilyTime
|
Valentine1996
|
Java
|
Code
| 106
| 256
|
/** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *
* *
* @copyright 2016 (c), by Valentine
*
* @author <a href="mailto:valentunnamisnuk@gmail.com">Valentyn Namisnyk</a>
*
* @date 2016-09-05 10:43 :: 2016-09-05 10:46
*
* @address /Ukraine/Ivano-Frankivsk/Rozhniw
* *
*///*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *
package com.familytime.notification.model.service;
import com.familytime.notification.model.entity.Contact;
import com.familytime.notification.model.entity.Message;
public interface NotificationService {
/**
* Send message.
*
* @param from Contact of sender
* @param to Contact of recipient.
* @param message Message for sending.
*/
void send( Contact from, Contact to, Message message);
}
| 26,264
|
https://github.com/david-driscoll/Swashbuckle.AspNetCore/blob/master/test/Swashbuckle.AspNetCore.SwaggerGen.Test/Annotations/XmlCommentsSchemaFilterTests.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Swashbuckle.AspNetCore
|
david-driscoll
|
C#
|
Code
| 152
| 623
|
using System;
using System.Collections.Generic;
using System.Xml.XPath;
using System.Reflection;
using Newtonsoft.Json.Serialization;
using Xunit;
using Swashbuckle.AspNetCore.Swagger;
namespace Swashbuckle.AspNetCore.SwaggerGen.Test
{
public class XmlCommentsSchemaFilterTests
{
[Theory]
[InlineData(typeof(XmlAnnotatedType), "summary for XmlAnnotatedType")]
[InlineData(typeof(XmlAnnotatedWithNestedType.NestedType), "summary for NestedType")]
[InlineData(typeof(XmlAnnotatedGenericType<string>), "summary for XmlAnnotatedGenericType")]
public void Apply_SetsDescription_FromClassSummaryTag(
Type type,
string expectedDescription)
{
var schema = new Schema
{
Properties = new Dictionary<string, Schema>()
};
var filterContext = FilterContextFor(type);
Subject().Apply(schema, filterContext);
Assert.Equal(expectedDescription, schema.Description);
}
[Theory]
[InlineData(typeof(XmlAnnotatedType), "Property", "summary for Property")]
[InlineData(typeof(XmlAnnotatedSubType), "BaseProperty", "summary for BaseProperty")]
[InlineData(typeof(XmlAnnotatedGenericType<string>), "GenericProperty", "summary for GenericProperty")]
public void Apply_SetsPropertyDescriptions_FromPropertySummaryTag(
Type type,
string propertyName,
string expectedDescription)
{
var schema = new Schema
{
Properties = new Dictionary<string, Schema>()
{
{ propertyName, new Schema() }
}
};
var filterContext = FilterContextFor(type);
Subject().Apply(schema, filterContext);
Assert.Equal(expectedDescription, schema.Properties[propertyName].Description);
}
private SchemaFilterContext FilterContextFor(Type type)
{
var jsonObjectContract = new DefaultContractResolver().ResolveContract(type);
return new SchemaFilterContext(type, (jsonObjectContract as JsonObjectContract), null);
}
private XmlCommentsSchemaFilter Subject()
{
var xmlComments = GetType().GetTypeInfo()
.Assembly
.GetManifestResourceStream("Swashbuckle.AspNetCore.SwaggerGen.Test.TestFixtures.XmlComments.xml");
return new XmlCommentsSchemaFilter(new XPathDocument(xmlComments));
}
}
}
| 40,500
|
https://github.com/Matthew-Lancaster/matthew-lancaster/blob/master/SCRIPTER CODE -- VB6/VB6/VB-NT/00_Best_VB_01/#0 GRAPHIC PATTERN ANIMATION/PolyGons Roy Jenner/Sample_Display.frm
|
Github Open Source
|
Open Source
|
Unlicense
| null |
matthew-lancaster
|
Matthew-Lancaster
|
Visual Basic
|
Code
| 54
| 153
|
VERSION 5.00
Begin VB.Form Display2
Caption = "Form1"
ClientHeight = 5010
ClientLeft = 11175
ClientTop = 315
ClientWidth = 6615
LinkTopic = "Form1"
ScaleHeight = 5010
ScaleWidth = 6615
Visible = 0 'False
End
Attribute VB_Name = "Display2"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
| 13,516
|
https://github.com/MatthiasSchilder/DotSpatial/blob/master/Source/Core/DotSpatial.Controls/LayoutMap.cs
|
Github Open Source
|
Open Source
|
MIT, LGPL-2.0-or-later
| 2,023
|
DotSpatial
|
MatthiasSchilder
|
C#
|
Code
| 981
| 2,802
|
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using DotSpatial.Data;
using NetTopologySuite.Geometries;
namespace DotSpatial.Controls
{
/// <summary>
/// A layout control that draws the content from a map control so that it can be printed.
/// </summary>
public class LayoutMap : LayoutElement
{
#region Fields
private Bitmap _buffer;
private Envelope _envelope;
private bool _extentChanged = true;
private Map _mapControl;
private RectangleF _oldRectangle;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LayoutMap"/> class.
/// </summary>
/// <param name="mapControl">The map control that generates the printable content.</param>
/// <exception cref="ArgumentNullException">Throws if mapControl is null.</exception>
public LayoutMap(Map mapControl)
{
_mapControl = mapControl ?? throw new ArgumentNullException(nameof(mapControl));
Name = "Map";
Envelope viewExtentEnvelope = new(_mapControl.ViewExtents.ToEnvelope());
if (_mapControl.ExtendBuffer)
{
// if ExtendBuffer, Envelope must be three times smaller
viewExtentEnvelope.ExpandBy(-viewExtentEnvelope.Width / _mapControl.MapFrame.ExtendBufferCoeff, -viewExtentEnvelope.Height / _mapControl.MapFrame.ExtendBufferCoeff);
}
_envelope = viewExtentEnvelope;
ResizeStyle = ResizeStyle.NoScaling;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the geographic envelope to be shown by the layout.
/// </summary>
[Browsable(false)]
public virtual Envelope Envelope
{
get
{
return _envelope;
}
set
{
if (value.Width / value.Height < Size.Width / Size.Height)
{
double yCenter = value.MinY + (value.Height / 2.0);
double deltaY = (value.Width / Size.Width * Size.Height) / 2.0;
_envelope = new Envelope(value.MinX, value.MaxX, yCenter - deltaY, yCenter + deltaY);
}
else
{
double xCenter = value.MinX + (value.Width / 2.0);
double deltaX = (value.Height / Size.Height * Size.Width) / 2.0;
_envelope = new Envelope(xCenter - deltaX, xCenter + deltaX, value.MinY, value.MaxY);
}
_extentChanged = true;
OnThumbnailChanged();
OnInvalidate();
}
}
/// <summary>
/// Gets or sets the map control that generates the printable content.
/// </summary>
[Browsable(false)]
public Map MapControl
{
get
{
return _mapControl;
}
set
{
_mapControl = value ?? throw new ArgumentNullException(nameof(value));
}
}
/// <summary>
/// Gets or sets the scale of the map.
/// </summary>
[Browsable(true)]
[Category("Map")]
public virtual long Scale
{
get
{
if (_mapControl.Layers.Count < 1)
return 100000;
if (Resizing)
return 100000;
return Convert.ToInt64((UnitMeterConversion() * _envelope.Width * 39.3700787 * 100D) / Size.Width);
}
set
{
if (_mapControl.Layers.Count < 1)
return;
double xtl = Envelope.MinX;
double ytl = Envelope.MaxY;
Envelope.Init(xtl, xtl + ((value * Size.Width) / (UnitMeterConversion() * 39.3700787 * 100D)), ytl - ((value * Size.Height) / (UnitMeterConversion() * 39.3700787 * 100D)), ytl);
}
}
#endregion
#region Methods
/// <summary>
/// This gets called to instruct the element to draw itself in the appropriate spot of the graphics object.
/// </summary>
/// <param name="g">The graphics object to draw to.</param>
/// <param name="printing">Boolean, true if the drawing is printing to an actual page.</param>
public override void Draw(Graphics g, bool printing)
{
if (printing == false)
{
if (MapControl.Layers.Count <= 0 || Convert.ToInt32(Size.Width) <= 0 || Convert.ToInt32(Size.Height) <= 0)
return;
if (_buffer != null && ((_buffer.Width != Convert.ToInt32(Size.Width * 96 / 100) || _buffer.Height != Convert.ToInt32(Size.Height * 96 / 100)) || _extentChanged))
{
_extentChanged = false;
_buffer.Dispose();
_buffer = null;
}
if (_buffer == null)
{
_buffer = new Bitmap(Convert.ToInt32(Size.Width * 96 / 100), Convert.ToInt32(Size.Height * 96 / 100), PixelFormat.Format32bppArgb);
_buffer.SetResolution(96, 96);
Graphics graph = Graphics.FromImage(_buffer);
MapControl.Print(graph, new Rectangle(0, 0, _buffer.Width, _buffer.Height), _envelope.ToExtent());
graph.Dispose();
}
g.DrawImage(_buffer, Rectangle);
}
else
{
MapControl.Print(g, new Rectangle(Location.X, Location.Y, Convert.ToInt32(Size.Width), Convert.ToInt32(Size.Height)), _envelope.ToExtent());
}
}
/// <summary>
/// Pans the map.
/// </summary>
/// <param name="x">The amount to pan the map in the X-axis in map coord.</param>
/// <param name="y">The amount to pan the map in the Y-axis in map coord.</param>
public virtual void PanMap(double x, double y)
{
Envelope = new Envelope(Envelope.MinX - x, Envelope.MaxX - x, Envelope.MinY - y, Envelope.MaxY - y);
}
/// <summary>
/// Zooms the map element in by 10%.
/// </summary>
public virtual void ZoomInMap()
{
double tenPerWidth = (Envelope.MaxX - Envelope.MinX) / 20;
double tenPerHeight = (Envelope.MaxY - Envelope.MinY) / 20; // todo jany_ why uses maxy tenperwidth instead of height?
Envelope envl = new(Envelope.MinX + tenPerWidth, Envelope.MaxX - tenPerWidth, Envelope.MinY + tenPerHeight, Envelope.MaxY - tenPerWidth); // TODO jany_ can we assign this direct or do we lose MinX etc?
Envelope = envl;
}
/// <summary>
/// Zooms the map element out by 10%.
/// </summary>
public virtual void ZoomOutMap()
{
double tenPerWidth = (Envelope.MaxX - Envelope.MinX) / 20;
double tenPerHeight = (Envelope.MaxY - Envelope.MinY) / 20; // todo jany_ why uses maxy tenperwidth instead of height?
Envelope envl = new(Envelope.MinX - tenPerWidth, Envelope.MaxX + tenPerWidth, Envelope.MinY - tenPerHeight, Envelope.MaxY + tenPerWidth); // TODO jany_ can we assign this direct or do we lose MinX etc?
Envelope = envl;
}
/// <summary>
/// Zooms the map to the fullextent of all available layers.
/// </summary>
public virtual void ZoomToFullExtent()
{
Envelope = MapControl.Extent.ToEnvelope();
}
/// <summary>
/// Zooms the map to the extent of the current view.
/// </summary>
public virtual void ZoomViewExtent()
{
Envelope viewExtentEnvelope = new(_mapControl.ViewExtents.ToEnvelope());
if (_mapControl.ExtendBuffer)
{
// if ExtendBuffer, Envelope must be three times smaller
viewExtentEnvelope.ExpandBy(-viewExtentEnvelope.Width / _mapControl.MapFrame.ExtendBufferCoeff, -viewExtentEnvelope.Height / _mapControl.MapFrame.ExtendBufferCoeff);
}
Envelope = viewExtentEnvelope;
}
/// <summary>
/// Updates the size of the control.
/// </summary>
protected override void OnSizeChanged()
{
if (!Resizing)
{
// If the size has never been set before we set the maps extent to that of the map
if (_oldRectangle.Width == 0 && _oldRectangle.Height == 0)
{
ZoomViewExtent();
}
else
{
double dx = Envelope.Width / _oldRectangle.Width;
double dy = Envelope.Height / _oldRectangle.Height;
double xtl = Envelope.MinX;
double ytl = Envelope.MaxY;
double width = Envelope.Width + ((Rectangle.Width - _oldRectangle.Width) * dx);
double height = Envelope.Height + ((Rectangle.Height - _oldRectangle.Height) * dy);
Envelope = new Envelope(xtl, xtl + width, ytl - height, ytl); // set a new envelope so the buffer gets recreated
}
_oldRectangle = new RectangleF(LocationF, Size);
}
base.OnSizeChanged();
}
private double UnitMeterConversion()
{
if (_mapControl.Layers.Count == 0) return 1;
if (_mapControl.Layers[0].DataSet?.Projection == null) return 1;
if (_mapControl.Layers[0].DataSet.Projection.IsLatLon)
return _mapControl.Layers[0].DataSet.Projection.GeographicInfo.Unit.Radians * 6354101.943;
return _mapControl.Layers[0].DataSet.Projection.Unit.Meters;
}
#endregion
}
}
| 3,996
|
https://github.com/klemenm81/reflection/blob/master/libjobject/exceptions/MethodWithNArgumentsNotFound.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
reflection
|
klemenm81
|
C
|
Code
| 50
| 163
|
#pragma once
#include "Exception.h"
#include <string>
class MethodWithNArgumentsNotFound : public Exception {
private:
std::string m_errorMsg;
public:
MethodWithNArgumentsNotFound(const char *methodName, size_t nArguments) : m_errorMsg(
std::string("Method ") +
std::string(methodName) +
std::string(" with ") +
std::to_string(nArguments) +
std::string(" arguments not found.")
) {
}
const char* Message() const {
return m_errorMsg.c_str();
}
};
| 31,481
|
https://github.com/se-kiss/api-gateway/blob/master/src/search/search.dto.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
api-gateway
|
se-kiss
|
TypeScript
|
Code
| 101
| 275
|
import { InputType, Field } from '@nestjs/graphql';
@InputType()
export class SearchArgs {
@Field(() => String)
text: string;
@Field(() => Number)
from: number;
@Field(() => Number)
size: number;
@Field(() => [String], { nullable: true, defaultValue: [] })
tags?: string[];
@Field(() => [String], { nullable: true, defaultValue: [] })
types?: string[];
}
@InputType()
export class SearchBody {
@Field(() => String)
playlistId: string;
@Field(() => String)
name: string;
@Field(() => String)
ownerName: string;
@Field(() => [String])
tags: string[];
@Field(() => String)
type: string;
@Field(() => String, { nullable: true })
description?: string;
}
@InputType()
export class DeleteArgs {
@Field(() => String)
playlistId: string;
}
| 18,348
|
https://github.com/HODEIM/ListaTareas/blob/master/resources/views/verbusquedatarea.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
ListaTareas
|
HODEIM
|
PHP
|
Code
| 33
| 170
|
@extends('buscarTarea')
@section('verbusqueda')
<div>
<table class="table table-hover table-striped m-auto fondoTabla">
<thead>
<tr>
<th><h2>Tarea:</h2></th>
</tr>
</thead>
<tbody>
@foreach ( $tarea as $resultado)
{{csrf_field()}}
<tr>
<td>
<h5>{{ $resultado->nombre }}</h5>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
| 25,422
|
https://github.com/Ivan-Zaitsau/java-extensions/blob/master/Collections/src/zjava/collection/HugeListSupport.java
|
Github Open Source
|
Open Source
|
MIT
| null |
java-extensions
|
Ivan-Zaitsau
|
Java
|
Code
| 76
| 173
|
package zjava.collection;
/**
* Marker interface which indicates that list can handle more than
* <tt>Integer.MAX_VALUE</tt> elements and provides means of accessing
* elements beyond this limit.
*
* @since Zjava 1.0
*
* @author Ivan Zaitsau
*
* @see HugeList
*/
public interface HugeListSupport<E> extends HugeArraySupport<E> {
/**
* Provides means of accessing list elements above <tt>Integer.MAX_VALUE</tt> limit.
*
* @return <tt>HugeList</tt> object, used to work with lists of huge capacity
*/
HugeList<E> asHuge();
}
| 17,016
|
https://github.com/nh-live/dgraph-sql/blob/master/src/main/java/com/ke/search/parser/GraphqlBuilder.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
dgraph-sql
|
nh-live
|
Java
|
Code
| 1,607
| 6,023
|
package com.ke.search.parser;
import com.ke.search.antlr.GraphSQLBaseVisitor;
import com.ke.search.antlr.GraphSQLParser;
import com.ke.search.exception.ParseException;
import java.util.*;
/**
* @author zhaoxiang
*/
public class GraphqlBuilder extends GraphSQLBaseVisitor<Void> {
private ParseState parseState;
private QueryMode queryMode = QueryMode.COMMON;
private SubQuery current;
private List<SubQuery> query = new ArrayList<>();
private Map<String, SubQuery> m = new HashMap<>();
/** Check node and variable name conflicts */
private Set<String> variables;
private Set<String> nodes = new HashSet<>();
private Stack<FilterTree> filterTree = new Stack<>();
private Map<String, String> compare = new HashMap<>();
private String name;
private String attr;
private String var;
private Set<FilterTree> temp;
private boolean opt;
public GraphqlBuilder() {
compare.put("=", "eq");
compare.put(">", "gt");
compare.put("<", "lt");
compare.put(">=", "ge");
compare.put("<=", "le");
}
/**
* SQL statement processing order: from -> groupby -> where -> Select -> orderby -> limit
*/
@Override
public Void visitQuery(GraphSQLParser.QueryContext ctx) {
visit(ctx.fromClause());
if (ctx.groupBy() != null) {
visit(ctx.groupBy());
}
if(ctx.selectClause().OPT() != null) {
opt = true;
}
if (ctx.whereClause() != null) {
visit(ctx.whereClause());
}
if(opt) {
processFiltersOpt();
} else {
processFilters();
}
visit(ctx.selectClause());
if (ctx.havingClause() != null) {
visit(ctx.havingClause());
}
if (ctx.orderBy() != null) {
visit(ctx.orderBy());
}
if (ctx.limitClause() != null) {
visit(ctx.limitClause());
}
if (variables != null && queryMode == QueryMode.COMMON) {
queryMode = QueryMode.VARIABLE;
}
return null;
}
@Override
public Void visitEdge(GraphSQLParser.EdgeContext ctx) {
SubQuery last = current;
String name = null;
current = new SubQuery();
current.father = last;
last.child = current;
query.add(current);
if(ctx.edgeType() != null) {
name = current.edgeType = ctx.edgeType().getText();
}
if (ctx.edgeName() != null) {
name = current.alias = ctx.edgeName().getText();
}
if(name != null){
if (m.containsKey(name)) {
throw new ParseException(ctx.edgeType().getStart(), "Edge %s already defined", name);
}
m.put(name, current);
}
return null;
}
@Override
public Void visitNode(GraphSQLParser.NodeContext ctx) {
String name;
if(current == null){
current = new SubQuery();
query.add(current);
}
if(ctx.nodeName() != null) {
name = ctx.nodeName().getText();
if (m.containsKey(name)) {
throw new ParseException(ctx.nodeName().getStart(), "Node %s already defined", name);
}
nodes.add(name);
current.name = name;
m.put(name, current);
}
if (ctx.nodeLabel() != null) {
current.label = ctx.nodeLabel().getText();
}
return null;
}
@Override
public Void visitName(GraphSQLParser.NameContext ctx) {
name = var = ctx.getText();
if (!m.containsKey(name)) {
throw new ParseException(ctx.getStart(), "Node or Edge %s not defined", name);
}
if (nodes.contains(name)) {
attr = "uid";
} else {
attr = m.get(name).edgeType;
}
return null;
}
@Override
public Void visitEdgeName(GraphSQLParser.EdgeNameContext ctx) {
visit(ctx.name());
if (nodes.contains(name)) {
throw new ParseException(ctx.getStart(), "Expect an Edge but get a Node %s", name);
}
return null;
}
@Override
public Void visitNodeName(GraphSQLParser.NodeNameContext ctx) {
visit(ctx.name());
if (!nodes.contains(name)) {
throw new ParseException(ctx.getStart(), "Expect a Node but get an Edge %s", name);
}
return null;
}
@Override
public Void visitNamedAttribute(GraphSQLParser.NamedAttributeContext ctx) {
visit(ctx.name());
attr = ctx.attribute().getText();
var = ctx.getText();
return null;
}
@Override
public Void visitGroupBy(GraphSQLParser.GroupByContext ctx) {
parseState = ParseState.GROUPBY;
visit(ctx.predicate());
if (ctx.predicate().namedAttribute() != null && !nodes.contains(name)) {
throw new ParseException(ctx.getStart(), "Can't group by Edge's attribute");
}
if (ctx.predicate().edgeName() != null) {
queryMode = QueryMode.GROUPBYEDGE;
m.get(name).father.groupByAttr = attr;
} else {
m.get(name).groupByAttr = attr;
}
return null;
}
@Override
public Void visitWhereClause(GraphSQLParser.WhereClauseContext ctx) {
parseState = ParseState.WHERE;
visitChildren(ctx);
return null;
}
@Override
public Void visitNotNull(GraphSQLParser.NotNullContext ctx) {
visit(ctx.predicate());
filterTree.push(new FilterTree(String.format("has(%s)", attr), name));
return null;
}
@Override
public Void visitStringFunc(GraphSQLParser.StringFuncContext ctx) {
visit(ctx.namedAttribute());
String func;
String funcName = ctx.funcName().getText();
if (ctx.NUMERIC_LITERAL() != null) {
func = String.format("%s(%s,%s,%s)", funcName, attr, ctx.STRING_LITERAL().getText(), ctx.NUMERIC_LITERAL().getText());
} else {
func = String.format("%s(%s,%s)", funcName, attr, ctx.STRING_LITERAL().getText());
}
if ("regexp".equals(funcName)) {
func = func.replace("'", "/");
}
filterTree.push(new FilterTree(func, name));
return null;
}
@Override
public Void visitComparision(GraphSQLParser.ComparisionContext ctx) {
visit(ctx.commonItem());
String cmp = String.format("%s(%s,%s)", compare.get(ctx.op.getText()), attr, ctx.literal_value().getText());
FilterTree ft = new FilterTree(cmp, name);
filterTree.push(ft);
if(nodes.contains(name) && ctx.commonItem().namedAttribute() != null) {
String value = String.format("%s(val(%s),%s)", compare.get(ctx.op.getText()), var, ctx.literal_value().getText());
ft.setTmp(value, var, attr);
addTemp(ft);
}
return null;
}
private String getVarName(String... args) {
return String.join(".", args);
}
private void addTemp(FilterTree filterTree) {
if(temp == null) {
temp = new HashSet<>();
}
temp.add(filterTree);
}
private void addVariable(String name, String varName, String attr) {
if (variables == null) {
variables = new HashSet<>();
}
SubQuery query = m.get(name);
if (!variables.contains(varName)) {
variables.add(varName);
if(nodes.contains(name)) {
if (query.groupByAttr != null && queryMode == QueryMode.GROUPBYEDGE){
if (query.varFunc == null) {
query.varFunc = String.format("uid(%s)", varName);
}
}
query.addVariable(String.format("%s as %s", varName, attr));
} else {
query.addFacetVariable(String.format("%s as %s", varName, attr));
}
}
}
@Override
public Void visitLogicalAnd(GraphSQLParser.LogicalAndContext ctx) {
visitChildren(ctx);
filterTree.push(FilterTree.logicalAnd(filterTree.pop(), filterTree.pop()));
return null;
}
@Override
public Void visitLogicalOr(GraphSQLParser.LogicalOrContext ctx) {
visitChildren(ctx);
filterTree.push(FilterTree.logicalOr(filterTree.pop(), filterTree.pop()));
if ("".equals(filterTree.peek().name)) {
throw new ParseException(ctx.getStart(), "Can't connect two filters on different Nodes or Edges with logicalOr");
}
return null;
}
@Override
public Void visitLogicalNot(GraphSQLParser.LogicalNotContext ctx) {
visitChildren(ctx);
if ("".equals(filterTree.peek().name)) {
throw new ParseException(ctx.getStart(), "Can't connect filter on different Nodes or Edges with logicalNot");
}
filterTree.push(FilterTree.logicalNot(filterTree.pop()));
return null;
}
private void addFilterTree(FilterTree ft) {
if (nodes.contains(ft.name)) {
m.get(ft.name).addFilters(ft);
} else {
m.get(ft.name).addFacetFilters(ft);
}
}
private void removeTmp(FilterTree ft) {
if(ft.children.size() != 0) {
for(FilterTree c : ft.children) {
removeTmp(c);
}
} else if(ft.compare) {
temp.remove(ft);
}
}
private void processFilters() {
for(SubQuery sq : query) {
if(sq.label != null) {
if(filterTree.empty()) {
filterTree.push(new FilterTree(String.format("type(%s)", sq.label), sq.name));
} else {
filterTree.push(FilterTree.logicalAnd(new FilterTree(String.format("type(%s)", sq.label), sq.name), filterTree.pop()));
}
}
}
FilterTree ft = filterTree.pop();
switch (ft.op) {
case NONE: case NOT: case OR:
addFilterTree(ft);
break;
case AND:
for (FilterTree c : ft.children) {
addFilterTree(c);
}
break;
default:
}
}
private void processFiltersOpt() {
for(SubQuery sq : query) {
if(sq.label != null) {
FilterTree ft = new FilterTree(String.format("type(%s)", sq.label), sq.name);
ft.setTmp(String.format("eq(val(%s),%s)", sq.name + ".dgraph.type", sq.label), sq.name + ".dgraph.type", "dgraph.type");
addTemp(ft);
if(filterTree.empty()) {
filterTree.push(ft);
} else {
filterTree.push(FilterTree.logicalAnd(ft, filterTree.pop()));
}
}
}
FilterTree ft = filterTree.pop();
SubQuery subQuery;
switch (ft.op) {
case NONE:
if(ft.compare) {
removeTmp(ft);
}
addFilterTree(ft);
break;
case NOT: case OR:
throw new ParseException("There must be a source function");
case AND:
for (FilterTree c : ft.children) {
subQuery = m.get(c.name);
if (c.compare && subQuery.hasSrcFunc) {
subQuery.addVarFilters(c);
} else {
if (c.compare && c.op == FilterOp.NONE) {
subQuery.hasSrcFunc = true;
removeTmp(c);
}
addFilterTree(c);
}
}
break;
default:
}
if(temp != null) {
for(FilterTree filterTree : temp){
filterTree.value = filterTree.tmpValue;
addVariable(filterTree.name, filterTree.tmpVarName, filterTree.tmpAttr);
}
}
}
@Override
public Void visitShortestPath(GraphSQLParser.ShortestPathContext ctx) {
query.get(0).addArgs("property", ctx.property().id().getText());
List<String> shortest = new ArrayList<>();
for (GraphSQLParser.ShortestOptionsContext args : ctx.shortestOptions()) {
shortest.add(args.getText());
}
queryMode = QueryMode.SHORTEST;
query.get(0).addArgs("shortest", String.join(", ", shortest));
return null;
}
@Override
public Void visitNdegree(GraphSQLParser.NdegreeContext ctx) {
queryMode = QueryMode.NDEGREE;
query.get(0).addArgs("depth", ctx.depthArgs().getText());
return null;
}
@Override
public Void visitSelectCommon(GraphSQLParser.SelectCommonContext ctx) {
visit(ctx.commonItem());
if(ctx.alias() != null) {
attr = String.format("%s:%s", ctx.alias().getText(), attr);
}
if(nodes.contains(name)){
m.get(name).addAttr(attr);
} else {
m.get(name).addFacet(attr);
}
return null;
}
@Override
public Void visitCountFunc(GraphSQLParser.CountFuncContext ctx) {
visit(ctx.countItem());
if ("*".equals(attr)) {
throw new ParseException(ctx.getStart(), "%s is illegal", ctx.getText());
}
var = getVarName("count", var);
if(ctx.countItem().name() != null && !nodes.contains(name)) {
name = m.get(name).father.name;
}
boolean hasVar = parseState == ParseState.HAVING || parseState == ParseState.ORDER || (m.get(name).groupByAttr != null && queryMode == QueryMode.GROUPBYEDGE);
if(hasVar) {
addVariable(name, var, String.format("count(%s)", attr));
attr = String.format("val(%s)", var);
} else {
attr = String.format("count(%s)", attr);
}
return null;
}
@Override
public Void visitAggregation(GraphSQLParser.AggregationContext ctx) {
visit(ctx.commonItem());
if(m.get(name).empty) {
throw new ParseException(ctx.getStart(), "Too many nested aggregation");
}
if(m.get(name).groupByAttr == null) {
addVariable(name, var, attr);
attr = String.format("%s(val(%s))", ctx.aggr.getText(), var);
var = getVarName(ctx.aggr.getText(), var);
if(m.get(name).father == null) {
queryMode = QueryMode.ROOT;
m.get(name).empty = true;
} else {
addVariable(m.get(name).father.name, var, attr);
attr = String.format("val(%s)", var);
name = m.get(name).father.name;
}
} else {
var = getVarName(ctx.aggr.getText(), var);
attr = String.format("%s(%s)", ctx.aggr.getText(), attr);
if(queryMode == QueryMode.GROUPBYEDGE) {
addVariable(name, var, attr);
attr = String.format("val(%s)", var);
}
}
return null;
}
@Override
public Void visitHavingClause(GraphSQLParser.HavingClauseContext ctx) {
parseState = ParseState.HAVING;
visitChildren(ctx);
FilterTree ft = filterTree.pop();
switch (ft.op) {
case NONE:
case NOT:
case OR:
m.get(ft.name).addVarFilters(ft);
break;
case AND:
for (FilterTree c : ft.children) {
m.get(c.name).addVarFilters(c);
}
break;
default:
}
return null;
}
@Override
public Void visitOrderBy(GraphSQLParser.OrderByContext ctx) {
parseState = ParseState.ORDER;
return visitChildren(ctx);
}
@Override
public Void visitOrderItem(GraphSQLParser.OrderItemContext ctx) {
visit(ctx.commonItem());
String order = String.format("order%s:%s", ctx.order.getText().toLowerCase(), attr);
if (nodes.contains(name)) {
m.get(name).addOrderAndPage(order);
} else {
m.get(name).addFacet(order);
}
return null;
}
@Override
public Void visitLimitArgs(GraphSQLParser.LimitArgsContext ctx) {
m.get(name).addOrderAndPage(ctx.getText());
return null;
}
// Construct graphql+- query
String translate() {
int count, end;
StringBuilder s = new StringBuilder();
switch (queryMode) {
case SHORTEST:
query.get(0).write(s, "{ S as var(").writeSrcFunc(s).write(s, ")").writeFilter(s);
query.get(1).write(s, " T as var(").writeSrcFunc(s).write(s, ")").writeFilter(s);
query.get(0).write(s," path as shortest(from:uid(S), to:uid(T)").writeArgs(s, ", ", "shortest");
query.get(1).write(s, "){ ").writeEdge(s).write(s, " }");
query.get(0).write(s," path(func: uid(path)){ ").writeArgs(s, "","property").write(s," } }");
break;
case NDEGREE:
query.get(0).write(s,"{ query(").writeSrcFunc(s).write(s, ")").writeFilter(s);
query.get(0).write(s,"@recurse(").writeArgs(s, "","depth").write(s, ") { expand(_all_) } }");
break;
case COMMON:
current = query.get(0);
current.write(s, "{ query(").writeSrcFunc(s).writeOrderAndPage(s,", %s").write(s, ")");
current.writeFilter(s).writeGroupBy(s).write(s, "{ ").writeAttrs(s);
end = query.size()-1;
while (end >= 0 && !query.get(end).hasAttribute()){
end--;
}
count = 1;
while (count <= end){
current = query.get(count);
current.write(s, " ").writeEdge(s).writeFacetFilter(s).writeFacets(s);
current.writeFilter(s).writeGroupBy(s).writeOrderAndPage(s, "(%s)");
current.write(s, "{ ").writeAttrs(s);
count++;
}
for (int i = count + 1; i > 0; i--){
s.append(" }");
}
break;
default:
current = query.get(0);
s.append("{ ");
if(current.hasAttribute() && queryMode == QueryMode.VARIABLE){
s.append(current.name).append("_ as ");
current.addVarFilters(new FilterTree(String.format("uid(%s_)", current.name), current.name));
}
current.write(s, "var(").writeSrcFunc(s).write(s,")").writeFilter(s).writeGroupBy(s);
current.write(s, "{ ").writeVariables(s);
end = query.size()-1;
while (end >= 0 && query.get(end).variables == null){
end--;
}
count = 1;
while ( count <= end){
current = query.get(count);
s.append(" ");
if(current.hasAttribute() && queryMode == QueryMode.VARIABLE){
s.append(current.name).append("_ as ");
current.addVarFilters(new FilterTree(String.format("uid(%s_)", current.name), current.name));
}
current.writeEdge(s).writeFacetVariables(s);
current.writeGroupBy(s).writeFilter(s).write(s, "{ ").writeVariables(s);
count++;
}
for (int i = count; i > 0; i--){
s.append(" }");
}
switch (queryMode) {
case GROUPBYEDGE:
current.write(s, " query(").writeVarFunc(s).writeOrderAndPage(s, ", %s");
current.child.writeOrderAndPage(s, ", %s").write(s, ")");
current.writeVarFilter(s).write(s, "{ ").writeAttrs(s).write(s, " ");
current.child.writeAttrs(s).write(s, " } }");
break;
case ROOT:
query.get(0).write(s, " query(){ ").writeAttrs(s).write(s, " } }");
break;
case VARIABLE:
count = 0;
current = query.get(0);
while (!current.hasAttribute()){
count++;
current = query.get(count);
}
int lastCount = count;
current.write(s, " query(").writeVarFunc(s).writeGroupBy(s).writeOrderAndPage(s, ", %s").write(s, ")");
current.writeVarFilter(s).write(s, "{ ").writeAttrs(s);
count++;
end = query.size()-1;
while (end >= 0 && !query.get(end).hasAttribute()){
end--;
}
while (count <= end) {
current =query.get(count);
current.write(s, " ").writeEdge(s).writeFacetFilter(s).writeFacets(s);
current.writeVarFilter(s).writeGroupBy(s).writeOrderAndPage(s, "(%s)").write(s, "{ ").writeAttrs(s);
count++;
}
for (int i = count-lastCount+1; i > 0; i--){
s.append(" }");
}
break;
default:
}
}
return s.toString().replace("'", "\"");
}
}
| 15,299
|
https://github.com/qbox/drone/blob/master/vendor/github.com/drone/mq/stomp/option_test.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
drone
|
qbox
|
Go
|
Code
| 261
| 849
|
package stomp
import (
"bytes"
"testing"
)
func TestOptions(t *testing.T) {
opt := WithAck("auto")
msg := NewMessage()
msg.Apply(opt)
if !bytes.Equal(msg.Ack, AckAuto) {
t.Errorf("Want WiathAck to apply ack header")
}
opt = WithCredentials("janedoe", "password")
msg = NewMessage()
msg.Apply(opt)
if string(msg.User) != "janedoe" {
t.Errorf("Want WithCredentials to apply username header")
}
if string(msg.Pass) != "password" {
t.Errorf("Want WithCredentials to apply password header")
}
opt = WithExpires(1234)
msg = NewMessage()
msg.Apply(opt)
if !bytes.Equal(msg.Expires, []byte("1234")) {
t.Errorf("Want WithExpires to apply expires header")
}
opt = WithHeader("foo", "bar")
msg = NewMessage()
msg.Apply(opt)
if v := msg.Header.Get([]byte("foo")); string(v) != "bar" {
t.Errorf("Want WithHeader to add header keypair")
}
opt = WithHeader("id", "123")
msg = NewMessage()
msg.Apply(opt)
if v := msg.Header.Get([]byte("id")); string(v) != "" {
t.Errorf("Want WithHeader to reject reserved header")
}
opt = WithHeaders(map[string]string{"baz": "boo", "id": "123"})
msg = NewMessage()
msg.Apply(opt)
if v := msg.Header.Get([]byte("baz")); string(v) != "boo" {
t.Errorf("Want WithHeaders to add header keypairs")
}
if v := msg.Header.Get([]byte("id")); string(v) != "" {
t.Errorf("Want WithHeaders to reject reserved header")
}
opt = WithPersistence()
msg = NewMessage()
msg.Apply(opt)
if !bytes.Equal(msg.Persist, PersistTrue) {
t.Errorf("Want WithPersistence to apply persist header")
}
opt = WithPrefetch(2)
msg = NewMessage()
msg.Apply(opt)
if !bytes.Equal(msg.Prefetch, []byte("2")) {
t.Errorf("Want WithPrefetch to apply persist header")
}
opt = WithReceipt()
msg = NewMessage()
msg.Apply(opt)
if len(msg.Receipt) == 0 {
t.Errorf("Want WithReceipt to apply receipt header")
}
opt = WithRetain("last")
msg = NewMessage()
msg.Apply(opt)
if !bytes.Equal(msg.Retain, RetainLast) {
t.Errorf("Want WithRetain to apply retain header")
}
opt = WithSelector("ram > 2")
msg = NewMessage()
msg.Apply(opt)
if !bytes.Equal(msg.Selector, []byte("ram > 2")) {
t.Errorf("Want WithRetain to apply retain header")
}
}
| 28,068
|
https://github.com/enterstudio/plivo-salesforce/blob/master/src/classes/PlivoTransferResponse.cls
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
plivo-salesforce
|
enterstudio
|
Apex
|
Code
| 66
| 148
|
public class PlivoTransferResponse {
public Integer server_code ;
public String message ;
public List<String> call_uuids ;
public String error ;
public String api_id ;
public PlivoTransferResponse() {
// empty
}
public override String toString() {
return 'GenericResponse [\n serverCode=' + server_code + ',\n message='
+ message + ',\n call uuids=' + call_uuids + ',\n error=' + error + ',\n apiId=' + api_id + '\n]';
}
}
| 9,533
|
https://github.com/calvinm298/Slogo/blob/master/src/commands/AskWith.java
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
Slogo
|
calvinm298
|
Java
|
Code
| 55
| 187
|
package commands;
import java.util.ArrayList;
import java.util.List;
import Turtle.Turtle;
public class AskWith extends Command{
private final static int numParams = 2;
@Override
double execute(List<CommandNode> children, Turtle t) {
double retVal = 0;
CommandNode bracketNode1 = children.get(0);
CommandNode bracketNode2 = children.get(1);
if(bracketNode1.execute(t)==1) {
retVal =bracketNode2.execute(t);
}
return retVal;
}
@Override
int getNumberOfParameters() {
return numParams;
}
}
| 13,738
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.