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/NightOfTwelve/iOS-Cracked-Apps/blob/master/DumpedClasses/Taobao/YWFetchedResultsController.h
Github Open Source
Open Source
MIT
2,018
iOS-Cracked-Apps
NightOfTwelve
Objective-C
Code
361
1,737
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" #import "NSFetchedResultsControllerDelegate.h" #import "YWDBFadeArrayDataSource.h" @class NSArray, NSDictionary, NSFetchedResultsController, NSMutableArray, NSMutableDictionary, NSString, YWIMCore, YWMemoryCache; @interface YWFetchedResultsController : NSObject <YWDBFadeArrayDataSource, NSFetchedResultsControllerDelegate> { _Bool _disableFRCChangeTransaction; _Bool _bHasInsert; _Bool _bHasDelete; NSDictionary *_bridgeProperties; NSString *_frcCacheName; YWIMCore *_imCore; CDUnknownBlockType _didResetContentBlock; CDUnknownBlockType _willChangeContentBlock; CDUnknownBlockType _didChangeContentBlock; CDUnknownBlockType _objectDidChangeBlock; CDUnknownBlockType _sectionDidChangeBlock; id <YWFetchedResultsControllerDelegate> _delegate; YWMemoryCache *_convertCache; NSMutableDictionary *_internalUserInfo; NSMutableDictionary *_externalUserInfo; NSFetchedResultsController *_frc; CDUnknownBlockType _makeNSFRCBlock; CDUnknownBlockType _convertObjectBlock; CDUnknownBlockType _revertObjectBlock; Class _sectionInfoSubclass; Class _objectClass; NSMutableArray *_FRCChangeTransaction; } + (id)fetchedResultsControllerForObjectClass:(Class)arg1 imCore:(id)arg2; + (void)onLoginIdChanged:(id)arg1; @property(nonatomic) _Bool bHasDelete; // @synthesize bHasDelete=_bHasDelete; @property(nonatomic) _Bool bHasInsert; // @synthesize bHasInsert=_bHasInsert; @property(retain, nonatomic) NSMutableArray *FRCChangeTransaction; // @synthesize FRCChangeTransaction=_FRCChangeTransaction; @property(nonatomic) _Bool disableFRCChangeTransaction; // @synthesize disableFRCChangeTransaction=_disableFRCChangeTransaction; @property(copy, nonatomic) Class objectClass; // @synthesize objectClass=_objectClass; @property(copy, nonatomic) Class sectionInfoSubclass; // @synthesize sectionInfoSubclass=_sectionInfoSubclass; @property(copy, nonatomic) CDUnknownBlockType revertObjectBlock; // @synthesize revertObjectBlock=_revertObjectBlock; @property(copy, nonatomic) CDUnknownBlockType convertObjectBlock; // @synthesize convertObjectBlock=_convertObjectBlock; @property(copy, nonatomic) CDUnknownBlockType makeNSFRCBlock; // @synthesize makeNSFRCBlock=_makeNSFRCBlock; @property(readonly, nonatomic) NSFetchedResultsController *frc; // @synthesize frc=_frc; @property(readonly, copy, nonatomic) NSMutableDictionary *externalUserInfo; // @synthesize externalUserInfo=_externalUserInfo; @property(copy, nonatomic) NSMutableDictionary *internalUserInfo; // @synthesize internalUserInfo=_internalUserInfo; @property(retain, nonatomic) YWMemoryCache *convertCache; // @synthesize convertCache=_convertCache; @property(nonatomic) __weak id <YWFetchedResultsControllerDelegate> delegate; // @synthesize delegate=_delegate; @property(copy, nonatomic) CDUnknownBlockType sectionDidChangeBlock; // @synthesize sectionDidChangeBlock=_sectionDidChangeBlock; @property(copy, nonatomic) CDUnknownBlockType objectDidChangeBlock; // @synthesize objectDidChangeBlock=_objectDidChangeBlock; @property(copy, nonatomic) CDUnknownBlockType didChangeContentBlock; // @synthesize didChangeContentBlock=_didChangeContentBlock; @property(copy, nonatomic) CDUnknownBlockType willChangeContentBlock; // @synthesize willChangeContentBlock=_willChangeContentBlock; @property(copy, nonatomic) CDUnknownBlockType didResetContentBlock; // @synthesize didResetContentBlock=_didResetContentBlock; @property(nonatomic) __weak YWIMCore *imCore; // @synthesize imCore=_imCore; - (void).cxx_destruct; - (void)controller:(id)arg1 didChangeSection:(id)arg2 atIndex:(unsigned long long)arg3 forChangeType:(unsigned long long)arg4; - (void)controller:(id)arg1 didChangeObject:(id)arg2 atIndexPath:(id)arg3 forChangeType:(unsigned long long)arg4 newIndexPath:(id)arg5; - (void)controllerDidChangeContent:(id)arg1; - (void)controllerWillChangeContent:(id)arg1; - (void)resetContent; @property(readonly, copy, nonatomic) NSString *frcCacheName; // @synthesize frcCacheName=_frcCacheName; - (void)setFrc:(id)arg1 cacheName:(id)arg2; @property(readonly, copy, nonatomic) NSDictionary *bridgeProperties; // @synthesize bridgeProperties=_bridgeProperties; - (id)initWithNSFetchedResultsController:(id)arg1 convertObjectBlock:(CDUnknownBlockType)arg2 revertObjectBlock:(CDUnknownBlockType)arg3 imCore:(id)arg4; - (void)dealloc; - (id)init; - (id)_convertNSSectionInfo:(id)arg1; - (id)_revertToManagedObject:(id)arg1; - (id)_convertFromManagedObject:(id)arg1; - (id)bridgedObjectFromManagedObject:(id)arg1 forceUpdate:(_Bool)arg2; - (id)_convertManagedObject:(id)arg1 forceUpdate:(_Bool)arg2; - (id)_convertManagedObject:(id)arg1; - (void)onMemoryWarning:(id)arg1; - (id)dbBridgeProperties; - (id)dbRevertTargetObject:(id)arg1; - (id)dbConvertSourceObject:(id)arg1; - (id)dbSourceArray; - (void)removeAllBlocks; - (long long)sectionForSectionIndexTitle:(id)arg1 atIndex:(long long)arg2; - (id)indexPathForObject:(id)arg1; - (id)objectAtIndexPath:(id)arg1; @property(readonly, nonatomic) unsigned long long countOfFetchedObjects; @property(readonly, nonatomic) NSArray *fetchedObjects; - (id)_forceConvertedFetchedObjects; @property(readonly, nonatomic) NSArray *sectionIndexTitles; @property(readonly, nonatomic) NSArray *sections; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
45,046
https://github.com/SeguraChain/SeguraChain/blob/master/SeguraChain-Lib/Blockchain/Setting/BlockchainSetting.cs
Github Open Source
Open Source
MIT
null
SeguraChain
SeguraChain
C#
Code
1,628
4,011
using System.Collections.Generic; using System.Numerics; using SeguraChain_Lib.Blockchain.Mining.Object; using SeguraChain_Lib.Blockchain.Setting.Function; using SeguraChain_Lib.Blockchain.Sovereign.Database; using SeguraChain_Lib.Utility; namespace SeguraChain_Lib.Blockchain.Setting { /// <summary> /// Note 1: Once a value change, especially of the part about the Blockchain Settings & Properties part, the compatibility change. /// Note 2: Sovereign update(s), can provide the possibility to do few change(s) and keep the compatibility about previous data(s) generated pending of the life of this one. /// </summary> public class BlockchainSetting { #region Blockchain Settings & Properties. /// <summary> /// Wallet Settings. /// </summary> public const int WalletAddressWifLengthMin = 109; public const int WalletAddressWifLengthMax = 110; public const int WalletPublicKeyWifLength = 219; public const int WalletPrivateKeyWifLength = 119; /// <summary> /// Computations settings for wallet generator. /// </summary> public const int WalletPublicKeyByteArrayLength = 64; public const int WalletPrivateKeyWifByteArrayLength = 71; // I select that length just for fun. public const int WalletAddressByteArrayLength = 65; // The same. /// <summary> /// Signature Settings. /// </summary> public const string CurveName = "sect571r1"; public const string SignerName = "SHA512WITHECDSA"; public const string SignerNameNetwork = "SHA256WITHECDSA"; public const string CurveNameBitcoin = "secp256k1"; /// <summary> /// Transaction Settings. /// </summary> public const int TransactionVersion = 1; public const int TransactionMandatoryBlockRewardConfirmations = 10; public const int TransactionMandatoryMinBlockTransactionConfirmations = 2; // The minimum mandatory confirmations accepted on transactions. public const int TransactionMandatoryMaxBlockTransactionConfirmationsDays = 7; public const int TransactionMandatoryMaxBlockTransactionConfirmations = BlockExpectedPerDay * TransactionMandatoryMaxBlockTransactionConfirmationsDays; // The maximum mandatory confirmations accepted on transactions. Max amount of confirmations is around the amount of blocks mined in 7 days. public const int TransactionMandatoryMinBlockHeightStartConfirmation = 5; // The minimum mandatory block height start to target for a transaction. public const int TransactionMandatoryMaxBlockHeightStartConfirmation = BlockExpectedPerDay; // The maximum mandatory block height start to target for a transaction. public const int TransactionInvalidDelayRemove = 86_400; // Remove a transaction set has invalid after a delay of 86400 seconds. public const int TransactionHashSize = (sizeof(long) * 2) + 128; // block height long hex size + sha512 hex size size. /// <summary> /// Coin Settings. /// </summary> public const long CoinDecimal = 100_000_000; public const int CoinDecimalNumber = 8; public const long MinFeeTransaction = CoinDecimal / 500_000; public const long FeeTransactionPerKb = CoinDecimal / 500_000; public const long MinAmountTransaction = 1; /// <summary> /// Blockchain Settings. /// </summary> public const int MaxTransactionPerBlock = 300_000; public const int BlockRewardHalvingRange = 100_000; public static readonly BigInteger BlockRewardStatic = (10 * CoinDecimal); public const decimal BlockDevFeePercent = 0.005m; public static readonly BigInteger MaxSupply = 26_000_000 * CoinDecimal; /// <summary> /// Task transaction confirmation settings. /// </summary> public const int TaskVirtualWalletBalanceCheckpoint = 20; // Speed up tx confirmation process by save wallet balance calculated checkpoints. public const int TaskVirtualTransactionCheckpoint = 20; // Do not check again transactions signatures, data after 20 valid confirmations done. public const int TaskVirtualBlockCheckpoint = 50; // Increase speed of checking block transactions. #region Dev wallet Information settings. /// <summary> /// Sovereign Update Settings. /// </summary> public static string WalletAddressDevPublicKey(long timestampSovereignUpdate) => SovereignUpdateGetter.GetLastDevWalletPublicKey(timestampSovereignUpdate); public static string WalletAddressDev(long timestampSovereignUpdate) => SovereignUpdateGetter.GetLastDevWalletAddress(timestampSovereignUpdate); public const string DefaultWalletAddressDevPublicKey ="YMBT7sXubw9ksQfJNYWxZvqAzyNob3yM3HvoReNBvJ8nYK7HeVAKVRfaqi1douAkmsPC3Tc1gFZjXrCzc2iGSn7jCtiiaGMm3n9k2eMsx3y2x4tQQCyfM876q83H8EdC9y9sL7WUGqZaHxsZnwNJ9TrFqvTj58y4FnaSxZAu3aiPXvjB7rYJF9ckX8BKTAJZ9reMrZ92Wun1Y34eG2wkK8dzoph"; public const string DefaultWalletAddressDev ="5RX2c5yToFS3NGzsesrQ6o3ywwcw2KTi5qVD54DfLWpPxn2qexqH4Gcjwsmqom2GKDsU6oZcgATbgUvm4SkFfFHPKbs2kVBTq3Q6hQvEExSN5x"; #endregion /// <summary> /// Take in count halving. /// </summary> /// <param name="blockHeight">The block height for calculate halving.</param> /// <returns></returns> public static BigInteger BlockReward(long blockHeight) => ClassBlockRewardFunction.GetBlockRewardWithHalving(blockHeight); public static BigInteger BlockDevFee(long blockHeight) => ClassBlockRewardFunction.GetDevFeeWithHalving(blockHeight); public static BigInteger BlockRewardWithDevFee(long blockHeight) => (BlockReward(blockHeight) - BlockDevFee(blockHeight)); public const string BlockRewardName = "BLOCK"; // Block reward transaction name. public const int BlockTime = 60; // The block time scheduled in seconds. public const int BlockExpectedPerDay = (int)((24 * 60d) / (BlockTime / 60d)); // The average of blocks calculated from the scheduled Block Time and the amount of minutes in a single day. public const int BlockDifficultyRangeCalculation = BlockExpectedPerDay / 3; // Use previous blocks for generate the new block difficulty. public const int BlockDifficultyPrecision = 100_000; // The precision put on the difficulty factor calculated. public const int GenesisBlockHeight = 1; // The genesis block height. public static readonly BigInteger GenesisBlockAmount = 2_973_370 * CoinDecimal; // The genesis block amount reward has pre-mining. public const string GenesisBlockFinalTransactionHash ="DD93226470331793E1F0A22B08ADB95BF72B824E4CEE6EF48C68BEBCD3B49DAB50418AEA357A25371812BC3C498DF7548B6ACD2A99B589160B1394449212B5AB"; public const int GenesisBlockTransactionCount = 1; // The maximum of transaction inserted on the genesis block. public const int BlockAmountNetworkConfirmations = 2; // The minimum amount of network checks on blocks to do with peers, before to enable the task of confirmations on the block. public const int BlockAmountSlowNetworkConfirmations = 5; // This amount increment another amount of network checks, once this one is reach, the network counter increment and this one return back to 0. public const int BlockMiningUnlockShareTimestampMaxDelay = BlockTime; // The maximum of time allowed on a mining share timestamp received. The broadcasting of this one need to be enough fast to reach the majority of nodes. public const int BlockSyncAmountNetworkConfirmationsCheckpointPassed = 10; // If the block synced height is below the latest block height unlocked, the block synced network confirmations is automatically filled. /// <summary> /// Blockchain Properties. /// </summary> public const string CoinName = "XENOPHYTE"; public const string CoinMinName = "XENOP"; public const string BlockchainVersion = "01"; // Version of the blockchain used on Base58. public static readonly byte[] BlockchainVersionByteArray = ClassUtility.GetByteArrayFromHexString(BlockchainVersion); public const int BlockchainChecksum = 16; // Checksum size used on Base58. /// <summary> /// Used on some parts of the code: Encryption, network and more.. /// </summary> public static readonly byte[] BlockchainMarkKey = ClassUtility.GetByteArrayFromStringAscii(ClassUtility.GenerateSha3512FromString(new byte[] { 0x73, 0x61, 0x6d, 0x20, 0x73, 0x65, 0x67, 0x75, 0x72, 0x61 }.GetStringFromByteArrayAscii())); public const int BlockchainSha512HexStringLength = 128; public const int BlockchainSha256HexStringLength = 64; /// <summary> /// Block hash description size. /// </summary> public const int BlockHeightByteArrayLengthOnBlockHash = sizeof(long); public const int BlockDifficultyByteArrayLengthOnBlockHash = sizeof(double); public const int BlockCountTransactionByteArrayLengthOnBlockHash = sizeof(int); public const int BlockFinalTransactionHashByteArrayLengthOnBlockHash = 64; // SHA512 public const int BlockHashByteArraySize = BlockHeightByteArrayLengthOnBlockHash + BlockDifficultyByteArrayLengthOnBlockHash + BlockCountTransactionByteArrayLengthOnBlockHash + BlockFinalTransactionHashByteArrayLengthOnBlockHash + WalletAddressByteArrayLength; public const int BlockHashHexSize = BlockHashByteArraySize * 2; /// <summary> /// Average of mining luck calculated from block range mined. /// </summary> public const double BlockMiningStatsAvgPoorLuck = 0.85d; public const double BlockMiningStatsAvgNormalLuck = 1d; public const double BlockMiningStatsAvgLucky = 1.15d; public const double BlockMiningStatsAvgVeryLucky = 1.30d; public const double BlockMiningStatsAvgWarningLuck = 1.5d; #endregion #region Peer P2P Settings & Properties. /// <summary> /// The peer unique id hash, permit to support multiple peers with different id hash from the same hostname/ip. /// </summary> public const int PeerUniqueIdHashLength = 128; public const int PeerIvIterationCount = 1024; /// <summary> /// Peer P2P Settings can be changed on the node setting file. /// </summary> public const int PeerMaxNoPacketConnectionAttempt = 40; public const int PeerMaxInvalidPacket = 60; // Banned after 60 invalid packets. public const int PeerMaxDelayAwaitResponse = 10; // Await a response from a peer target pending maximum 10 seconds per requests sent. public const int PeerMaxDelayConnection = 10; // A maximum of 10 seconds on receive a packet. public const int PeerMaxTimestampDelayPacket = 360; // Await a maximum of 360 seconds on the timestamp of a packet, above the packet is considered has expired. public const int PeerMaxDelayKeepAliveStats = 60; // Keep alive packet stats of a peer pending 60 seconds. public const int PeerMaxEarlierPacketDelay = 600; // A maximum of 600 seconds is accepted on timestamp of packets. public const int PeerMaxDelayToConnectToTarget = 5; // A maximum of 5 seconds delay on connect to a peer. public const int PeerMaxAttemptConnection = 20; // After 20 retries to connect to a peer, the peer target is set has dead pending a certain amount of time. public const int PeerBanDelay = 30; // Ban delay pending 30 seconds. public const int PeerDeadDelay = 15; // Dead delay pending 15 seconds. public const int PeerMinValidPacket = 2; // Do not check packet signature after 2 valid packets sent. public const int PeerMaxWhiteListPacket = 1000; // Empty valid packet counter of a peer after to have ignoring packet signature 1000 of a peer. public const int PeerTaskSyncDelay = 10; public const int MaxPeerPerSyncTask = 50; public const int PeerMinAvailablePeerSync = 1; // The minimum of required peer(s). public const int PeerMaxAuthKeysExpire = 86_400 * 7; // Each week, internal auth keys of a peer are renewed. public const int PeerMaxPacketBufferSize = 8_192; public const int PeerMaxPacketSplitedSendSize = 1024; public const int PeerDelayDeleteDeadPeer = 600; public const int PeerMinPort = 1; public const int PeerMaxPort = 65_535; public const int PeerMaxNodeConnectionPerIp = 1000; public const int PeerMaxSemaphoreConnectAwaitDelay = 5_000; public const int PeerMaxRangeBlockToSyncPerRequest = 5; // Amount of blocks to sync per range. public const int PeerMaxRangeTransactionToSyncPerRequest = 5; // Amount of transactions to sync per range. public const bool PeerEnableSyncTransactionByRange = true; public const bool PeerEnableSovereignPeerVote = false; public const int PeerMaxTaskIncomingConnection = 200; /// <summary> /// The default P2P port. /// </summary> public const int PeerDefaultPort = 2400; public static readonly Dictionary<string, Dictionary<string, int>> BlockchainStaticPeerList = new Dictionary<string, Dictionary<string, int>>() { { "141.95.229.232", new Dictionary<string, int>() { { "D0BFF4A56F062828939E40E6DFD8A5EF58E28A10CB69E9E281C90802632D0345618CB5DA20736C2BAAC458A1EB5239F012621847B40F76C0CD10EA05CC4FD184", PeerDefaultPort } }} }; // This is a static peer list who can't be updated, it's usually used once a peer don't have any peer list saved. #endregion #region Peer API Settings. /// <summary> /// Peer API Settings. /// </summary> public const string PeerDefaultApiIp = "127.0.0.1"; public const int PeerDefaultApiPort = 2401; public const int PeerMaxApiConnectionPerIp = 1000; public const int PeerApiMaxConnectionDelay = 30; public const int PeerApiMaxEarlierPacketDelay = 60; public const int PeerApiMaxPacketDelay = 30; public const int PeerApiMaxRangeTransactionToSyncPerRequest = 10; // Amount of transactions to sync per range, by an API. public const int PeerApiSemaphoreDelay = 2_000; public const int PeerApiMaxRetryRequest = 5; #endregion #region Sovereign Object Getter class private static readonly ClassSovereignUpdateGetter SovereignUpdateGetter = new ClassSovereignUpdateGetter(); #endregion #region Mining Settings. /// <summary> /// Mining Settings. /// </summary> public static readonly BigInteger MiningMinDifficulty = 1000; public const int MiningMinInstructionsCount = 3; public static ClassMiningPoWaCSettingObject DefaultMiningPocSettingObject = new ClassMiningPoWaCSettingObject(true); public static ClassMiningPoWaCSettingObject CurrentMiningPoWaCSettingObject(long blockHeight) => SovereignUpdateGetter.GetLastSovereignUpdateMiningPocSettingObject(blockHeight); #endregion #region Other settings. public const string BlockchainSetupWikiPage = "https://github.com/SeguraChain/SeguraChain/wiki/Setup-your-own-Blockchain"; #endregion } }
15,320
https://github.com/craigdavies/vrm-assign-online/blob/master/acceptance-tests/src/test/scala/pages/PaymentPreventBackPageSteps.scala
Github Open Source
Open Source
MIT
2,015
vrm-assign-online
craigdavies
Scala
Code
46
201
package pages import cucumber.api.scala.EN import cucumber.api.scala.ScalaDsl import org.scalatest.Matchers import org.scalatest.concurrent.Eventually.PatienceConfig import org.scalatest.concurrent.Eventually.eventually import org.scalatest.selenium.WebBrowser._ import pages.vrm_assign.PaymentPreventBackPage.address import uk.gov.dvla.vehicles.presentation.common.helpers.webbrowser.WebBrowserDriver final class PaymentPreventBackPageSteps(implicit webDriver: WebBrowserDriver, timeout: PatienceConfig) extends ScalaDsl with EN with Matchers { def `is displayed` = { eventually { currentUrl should equal(address) }(timeout) this } }
46,935
https://github.com/johnpoth/camel-spring-boot/blob/master/components-starter/camel-avro-starter/src/test/java/org/apache/camel/dataformat/avro/springboot/test/AvroMarshalAndUnmarshallXmlTest.java
Github Open Source
Open Source
Apache-2.0
2,022
camel-spring-boot
johnpoth
Java
Code
309
1,107
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.dataformat.avro.springboot.test; import org.apache.camel.CamelContext; import org.apache.camel.CamelException; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.dataformat.avro.AvroDataFormat; import org.apache.camel.spring.boot.CamelAutoConfiguration; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.test.annotation.DirtiesContext; import org.apache.camel.test.spring.junit5.CamelSpringBootTest; @DirtiesContext @CamelSpringBootTest @SpringBootTest( classes = { CamelAutoConfiguration.class, AvroMarshalAndUnmarshallXmlTest.class }, properties = { "camel.springboot.routes-include-pattern=file:src/test/resources/routes/springDataFormat.xml"} ) public class AvroMarshalAndUnmarshallXmlTest { @Autowired private CamelContext context; @Autowired ProducerTemplate template; @EndpointInject("mock:reverse") MockEndpoint mock; @Test public void testMarshalAndUnmarshalWithDataFormat() throws Exception { marshalAndUnmarshal("direct:in", "direct:back"); } @Test public void testMarshalAndUnmarshalWithDSL1() throws Exception { marshalAndUnmarshal("direct:marshal", "direct:unmarshalA"); } @Test public void testMarshalAndUnmarshalWithDSL2() throws Exception { marshalAndUnmarshal("direct:marshal", "direct:unmarshalB"); } @Test public void testMarshalAndUnmarshalWithDSL3() throws Exception { try { context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:unmarshalC").unmarshal().avro(new CamelException("wrong schema")) .to("mock:reverse"); } }); fail("Expect the exception here"); } catch (Exception ex) { // expected } } private void marshalAndUnmarshal(String inURI, String outURI) throws Exception { Value input = Value.newBuilder().setValue("test body").build(); mock.reset(); mock.expectedMessageCount(1); mock.message(0).body().isInstanceOf(Value.class); mock.message(0).body().isEqualTo(input); Object marshalled = template.requestBody(inURI, input); template.sendBody(outURI, marshalled); mock.assertIsSatisfied(); Value output = mock.getReceivedExchanges().get(0).getIn().getBody(Value.class); assertEquals(input, output); } @Bean(name = "avro1") AvroDataFormat getAvroDataFormat() { AvroDataFormat avroDataFormat = new AvroDataFormat(); avroDataFormat.setInstanceClassName("org.apache.camel.dataformat.avro.springboot.test.Value"); return avroDataFormat; } }
34,523
https://github.com/keesvv/deno-hello-world/blob/master/src/middleware/ErrorHandler.ts
Github Open Source
Open Source
MIT
2,020
deno-hello-world
keesvv
TypeScript
Code
34
86
import { oak } from '../../deps.ts'; export async function ErrorHandler( context: oak.Context, next: () => Promise<void> ) { try { await next(); } catch (error) { context.response.status = error.status; context.response.body = error.message; } }
25,330
https://github.com/tburnett80/parishRegistrationForm/blob/master/ParishForms/ParishForms/ClientApp/app/components/auth/login.component.ts
Github Open Source
Open Source
MIT
null
parishRegistrationForm
tburnett80
TypeScript
Code
99
396
import { Component, OnInit, NgZone } from '@angular/core'; import { AdalService } from 'adal-angular4'; import { Router } from '@angular/router'; @Component({ selector: 'welcome', template: ` <div *ngIf="!IsAuthenticated" class="heading">Please login</div> <button *ngIf="!IsAuthenticated" class="btn btn-default" (click)="logIn()">Login</button> <div *ngIf="IsAuthenticated"> <h3>already logged in....</h3> </div> `, styles: [` .heading { padding-top:15px; padding-bottom:15px; }`] }) export class LoginComponent { constructor(private readonly adalService: AdalService, private readonly router: Router, private readonly zone: NgZone) { } get IsAuthenticated(): boolean { return this.adalService.userInfo && this.adalService.userInfo.authenticated; } ngOnInit() { this.adalService.handleWindowCallback(); if (this.adalService.userInfo && this.adalService.userInfo.profile) { console.log(this.adalService.userInfo); console.log("role: ", this.adalService.userInfo.profile.roles); } } logIn() { this.adalService.login(); } logOut() { this.adalService.logOut(); } }
38,218
https://github.com/hurricanerix/Unity3D/blob/master/Effects/ColorBlindness/ColorBlindness.shader
Github Open Source
Open Source
Apache-2.0
null
Unity3D
hurricanerix
GLSL
Code
249
595
Shader "Hidden/ColorBlindness" { // Copyright 2016 Richard Hawkins // // 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. Properties { _MainTex ("Base (RGB)", 2D) = "white" {} _bwBlend ("Black & White blend", Range (0, 1)) = 0 } SubShader { Pass { CGPROGRAM // Upgrade NOTE: excluded shader from DX11, Xbox360, OpenGL ES 2.0 because it uses unsized arrays #pragma exclude_renderers d3d11 xbox360 gles #pragma vertex vert_img #pragma fragment frag #include "UnityCG.cginc" uniform sampler2D _MainTex; uniform float _chValues[81]; uniform int _mode; float4 frag(v2f_img i) : COLOR { int o = 9 * _mode; float4 c = tex2D(_MainTex, i.uv); float4 result = float4(0.0, 0.0, 0.0, c.a); result.r = ((c.r * _chValues[o + 0]) + (c.g * _chValues[o + 1]) + (c.b * _chValues[o + 2])); result.g = ((c.r * _chValues[o + 3]) + (c.g * _chValues[o + 4]) + (c.b * _chValues[o + 5])); result.b = ((c.r * _chValues[o + 6]) + (c.g * _chValues[o + 7]) + (c.b * _chValues[o + 8])); return result; } ENDCG } } }
1,431
https://github.com/hashanchamikara/AzuraCast/blob/master/src/Message/AddNewMediaMessage.php
Github Open Source
Open Source
Apache-2.0
2,021
AzuraCast
hashanchamikara
PHP
Code
50
119
<?php namespace App\Message; use App\MessageQueue\QueueManager; class AddNewMediaMessage extends AbstractUniqueMessage { /** @var int The numeric identifier for the StorageLocation entity. */ public int $storage_location_id; /** @var string The relative path for the media file to be processed. */ public string $path; public function getQueue(): string { return QueueManager::QUEUE_MEDIA; } }
34,189
https://github.com/IntelliTect/EssentialCSharp/blob/master/src/Chapter09.Tests/Listing09.16.OverridingToString.Tests.cs
Github Open Source
Open Source
MIT
2,023
EssentialCSharp
IntelliTect
C#
Code
70
237
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter09.Listing09_16.Tests; using AddisonWesley.Michaelis.EssentialCSharp.Chapter09.Listing09_16; [TestClass] public class OverridingToStringTest { [TestMethod] public void Override_ToString_MatchesExpectedValue() { Angle angle1 = new(120, 20, 20, "AngleName"); Angle angle2 = new(320, 10, 10, null); string expected1 = $"AngleName: 120� 20' 20\""; string expected2 = $"320� 10' 10\""; string actual1 = angle1.ToString(); string actual2 = angle2.ToString(); // Different strings should be returned from ToString() depending on whether a name was provided Assert.AreEqual(actual1, expected1); Assert.AreEqual(actual2, expected2); } }
11,242
https://github.com/egoist/yurei/blob/master/src/js/app.js
Github Open Source
Open Source
MIT
null
yurei
egoist
JavaScript
Code
241
713
var $ = document.getElementById.bind(document); var $$ = document.querySelectorAll.bind(document); function render(tpl, data) { var html = $(tpl + '-template').innerHTML; var template = Handlebars.compile(html); var compiled = template(data); return compiled; }; function fetchList(opt, cb) { var page = opt.page || 1; qwest .before(function() { loading(); }) .get(api('repos/' + site.owner + '/' + site.repo + '/issues'), { per_page: site.per_page, page: page, access_token: site.access_token }) .then(function(data) { data.forEach(function(d) { var excerpt = trimHTML(marked(d.body), { limit: 200 }); if (site.show_excerpt) { d.excerpt = excerpt.html; } console.log(excerpt) }) return cb(data); }) .catch(function(e, response) { // Process the error var error = response.message $('output').innerHTML = '<div class="error">' + e + ' : ' + error + '</div>'; }); }; function fetchPost(opt, cb) { qwest .before(function() { loading(); }) .get(api('repos/' + site.owner + '/' + site.repo + '/issues/' + opt.number)) .then(function(post) { return cb(post); }); }; function loading() { var html = render('loading'); $('output').innerHTML = html; }; /* function buildParams(obj) { var arr = []; for (o in obj) { arr.push(o + '=' + obj[o]); } return '?' + arr.join('&'); }; */ (function() { var homeRouter = function(page) { //var html = render('home'); fetchList({}, function(posts) { var list = render('home-list', { posts: posts }); var html = list; $('output').innerHTML = html; }); }; var postRouter = function(number) { fetchPost({number: number}, function(post) { post.content = marked(post.body); var post = render('post', {post: post}); var html = post; $('output').innerHTML = html; }); }; Q.reg('home', homeRouter); Q.reg('post', postRouter); Q.init({ index: 'home' }); })();
11,792
https://github.com/alice-biometrics/petisco-task-manager/blob/master/taskmanager/src/modules/events/infrastructure/persistence/models/event_model.py
Github Open Source
Open Source
MIT
2,020
petisco-task-manager
alice-biometrics
Python
Code
36
118
from petisco.persistence.persistence import Persistence from sqlalchemy import Column, Integer, String, JSON Base = Persistence.get_base("taskmanager") class EventModel(Base): __tablename__ = "Event" id = Column("id", Integer, primary_key=True) event_id = Column("event_id", String(36)) type = Column("type", String(100)) data = Column("data", JSON)
16,868
https://github.com/samuel-dudik/StoneWork/blob/master/vpp/abx/vpp2101/abx/abx_if_attach.c
Github Open Source
Open Source
Apache-2.0
2,022
StoneWork
samuel-dudik
C
Code
1,152
4,323
/* * Copyright (c) 2019 PANTHEON.tech s.r.o. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <abx/abx_if_attach.h> #include <plugins/acl/exports.h> /** * Pool of ABX interface attachment objects */ abx_if_attach_t *abx_if_attach_pool; /** * A per interface vector of attached policies. Used in the data-plane */ u32 **abx_per_if; /** * Per interface values of ACL lookup context IDs. Used in the data-plane */ static u32 *abx_alctx_per_if; /** * ABX ACL module user id returned during the initialization */ static u32 abx_acl_user_id; /* * ACL plugin method vtable */ static acl_plugin_methods_t acl_plugin; /** * A DB of attachments; key={abx_index,sw_if_index} */ static uword *abx_if_attach_db; static u64 abx_if_attach_mk_key (u32 abx_index, u32 sw_if_index) { u64 key; key = abx_index; key = key << 32; key |= sw_if_index; return (key); } static abx_if_attach_t * abx_if_attach_db_find (u32 abx_index, u32 sw_if_index) { uword *p; u64 key; key = abx_if_attach_mk_key (abx_index, sw_if_index); p = hash_get (abx_if_attach_db, key); if (NULL != p) return (pool_elt_at_index (abx_if_attach_pool, p[0])); return (NULL); } static void abx_if_attach_db_add (u32 abx_index, u32 sw_if_index, abx_if_attach_t * aia) { u64 key; key = abx_if_attach_mk_key (abx_index, sw_if_index); hash_set (abx_if_attach_db, key, aia - abx_if_attach_pool); } static void abx_if_attach_db_del (u32 abx_index, u32 sw_if_index) { u64 key; key = abx_if_attach_mk_key (abx_index, sw_if_index); hash_unset (abx_if_attach_db, key); } static int abx_cmp_attach_for_sort (void *v1, void *v2) { const abx_if_attach_t *aia1; const abx_if_attach_t *aia2; aia1 = abx_if_attach_get (*(u32 *) v1); aia2 = abx_if_attach_get (*(u32 *) v2); return (aia1->aia_priority - aia2->aia_priority); } void abx_setup_acl_lc (u32 sw_if_index) { u32 *acl_vec = 0; u32 *aiai; abx_if_attach_t *aia; if (~0 == abx_alctx_per_if[sw_if_index]) return; vec_foreach (aiai, abx_per_if[sw_if_index]) { aia = abx_if_attach_get (*aiai); vec_add1 (acl_vec, aia->aia_acl); } acl_plugin.set_acl_vec_for_context (abx_alctx_per_if[sw_if_index], acl_vec); vec_free (acl_vec); } static int abx_if_enable_disable (u32 sw_if_index, u8 enable_disable) { vnet_feature_enable_disable ("ip4-unicast", "abx-ip4", sw_if_index, enable_disable, NULL, 0); vnet_feature_enable_disable ("ip4-multicast", "abx-ip4", sw_if_index, enable_disable, NULL, 0); vnet_feature_enable_disable ("ip6-unicast", "abx-ip6", sw_if_index, enable_disable, NULL, 0); vnet_feature_enable_disable ("ip6-multicast", "abx-ip6", sw_if_index, enable_disable, NULL, 0); return 0; } int abx_if_attach (u32 policy_id, u32 priority, u32 sw_if_index) { abx_if_attach_t *aia; abx_policy_t *ap; u32 api; api = abx_policy_find (policy_id); if (INDEX_INVALID == api) return (VNET_API_ERROR_NO_SUCH_ENTRY); ap = abx_policy_get (api); /* * check this is not a duplicate */ aia = abx_if_attach_db_find (policy_id, sw_if_index); if (NULL != aia) return (VNET_API_ERROR_ENTRY_ALREADY_EXISTS); /* * construct a new attachment object */ pool_get (abx_if_attach_pool, aia); aia->aia_priority = priority; aia->aia_acl = ap->ap_acl; aia->aia_abx = api; aia->aia_sw_if_index = sw_if_index; abx_if_attach_db_add (policy_id, sw_if_index, aia); /* * Insert the policy on the interfaces list. */ vec_validate_init_empty (abx_per_if, sw_if_index, NULL); vec_add1 (abx_per_if[sw_if_index], aia - abx_if_attach_pool); if (1 == vec_len (abx_per_if[sw_if_index])) { abx_if_enable_disable (sw_if_index, 1); /* if this is the first ABX policy, we need to acquire an ACL lookup context */ vec_validate_init_empty (abx_alctx_per_if, sw_if_index, ~0); abx_alctx_per_if[sw_if_index] = acl_plugin.get_lookup_context_index (abx_acl_user_id, sw_if_index, 0); } else { vec_sort_with_function (abx_per_if[sw_if_index], abx_cmp_attach_for_sort); } /* Prepare and set the list of ACLs for lookup within the context */ abx_setup_acl_lc (sw_if_index); return (0); } int abx_if_detach (u32 policy_id, u32 sw_if_index) { abx_if_attach_t *aia; u32 index; vnet_main_t *vnm = vnet_get_main (); vnet_sw_interface_t * sw_if; /* * check this is a valid interface */ if (pool_is_free_index (vnm->interface_main.sw_interfaces, sw_if_index)) return (VNET_API_ERROR_INVALID_SW_IF_INDEX); /* not a physical port? */ sw_if = vnet_get_sw_interface (vnm, sw_if_index); if (sw_if->type != VNET_SW_INTERFACE_TYPE_HARDWARE) return (VNET_API_ERROR_INVALID_SW_IF_INDEX); /* * check this is a valid attachment */ aia = abx_if_attach_db_find (policy_id, sw_if_index); if (NULL == aia) return (VNET_API_ERROR_NO_SUCH_ENTRY); /* * first remove from the interface's vector */ ASSERT (abx_per_if[sw_if_index]); index = vec_search (abx_per_if[sw_if_index], aia - abx_if_attach_pool); ASSERT (index != ~0); vec_del1 (abx_per_if[sw_if_index], index); if (0 == vec_len (abx_per_if[sw_if_index])) { abx_if_enable_disable (sw_if_index, 0); /* Return the lookup context, invalidate its id in our records */ acl_plugin.put_lookup_context_index (abx_alctx_per_if[sw_if_index]); abx_alctx_per_if[sw_if_index] = ~0; } else { vec_sort_with_function (abx_per_if[sw_if_index], abx_cmp_attach_for_sort); } /* Prepare and set the list of ACLs for lookup within the context */ abx_setup_acl_lc (sw_if_index); /* * remove the attachment from the DB */ abx_if_attach_db_del (policy_id, sw_if_index); /* * return the object */ pool_put (abx_if_attach_pool, aia); return (0); } static clib_error_t * abx_if_attach_cmd (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { u32 policy_id, sw_if_index; u32 is_del, priority; vnet_main_t *vnm; is_del = 0; sw_if_index = policy_id = ~0; vnm = vnet_get_main (); priority = 0; while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { if (unformat (input, "del")) is_del = 1; else if (unformat (input, "add")) is_del = 0; else if (unformat (input, "policy %d", &policy_id)) ; else if (unformat (input, "priority %d", &priority)) ; else if (unformat (input, "%U", unformat_vnet_sw_interface, vnm, &sw_if_index)) ; else return (clib_error_return (0, "unknown input '%U'", format_unformat_error, input)); } if (~0 == sw_if_index) return (clib_error_return (0, "invalid interface name")); if (~0 == policy_id) return (clib_error_return (0, "invalid policy ID:%d", policy_id)); if (~0 == abx_policy_find (policy_id)) return (clib_error_return (0, "invalid policy ID:%d", policy_id)); if (is_del) abx_if_detach (policy_id, sw_if_index); else abx_if_attach (policy_id, priority, sw_if_index); return (NULL); } /* *INDENT-OFF* */ /** * Attach an ABX policy to an interface. */ VLIB_CLI_COMMAND (abx_if_attach_cmd_node, static) = { .path = "abx attach", .function = abx_if_attach_cmd, .short_help = "abx attach [del] policy <index> priority <prio> <interface>", // this is not MP safe }; /* *INDENT-ON* */ static u8 * format_abx_if_attach (u8 * s, va_list * args) { abx_if_attach_t *aia = va_arg (*args, abx_if_attach_t *); abx_policy_t *ap; ap = abx_policy_get (aia->aia_abx); s = format (s, " abx-interface-attach: policy:%d priority:%d", ap->ap_id, aia->aia_priority); return (s); } static clib_error_t * abx_show_attach_cmd (vlib_main_t * vm, unformat_input_t * input, vlib_cli_command_t * cmd) { const abx_if_attach_t *aia; u32 sw_if_index, *aiai; vnet_main_t *vnm; sw_if_index = ~0; vnm = vnet_get_main (); while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT) { if (unformat (input, "%U", unformat_vnet_sw_interface, vnm, &sw_if_index)) ; else return (clib_error_return (0, "unknown input '%U'", format_unformat_error, input)); } if (~0 == sw_if_index) return (clib_error_return (0, "specify an interface")); vec_validate_init_empty (abx_per_if, sw_if_index, NULL); if (0 < vec_len (abx_per_if[sw_if_index])) { /* *INDENT-OFF* */ vec_foreach(aiai, abx_per_if[sw_if_index]) { aia = pool_elt_at_index(abx_if_attach_pool, *aiai); vlib_cli_output(vm, "%U", format_abx_if_attach, aia); } /* *INDENT-ON* */ } return (NULL); } /* *INDENT-OFF* */ VLIB_CLI_COMMAND (abx_show_attach_cmd_node, static) = { .path = "show abx attach", .function = abx_show_attach_cmd, .short_help = "show abx attach <interface>", .is_mp_safe = 1, }; /* *INDENT-ON* */ static clib_error_t * abx_if_bond_init (vlib_main_t * vm) { clib_error_t *acl_init_res = acl_plugin_exports_init (&acl_plugin); if (acl_init_res) return (acl_init_res); abx_acl_user_id = acl_plugin.register_user_module ("ABX plugin", "sw_if_index", NULL); return (NULL); } VLIB_INIT_FUNCTION (abx_if_bond_init); inline u32 get_abx_alctx_per_if(u32 sw_if_index) { /* * check this is a valid interface */ if (pool_is_free_index (vnet_get_main ()->interface_main.sw_interfaces, sw_if_index)) return INDEX_INVALID; if (vec_len (abx_alctx_per_if) < sw_if_index) return INDEX_INVALID; return abx_alctx_per_if[sw_if_index]; } inline void *get_abx_acl_main() { return acl_plugin.p_acl_main; } void abx_if_attach_walk (abx_if_attach_cb_t cb, void *ctx) { u32 aia; /* *INDENT-OFF* */ pool_foreach_index(aia, abx_if_attach_pool) { if (!cb(aia, ctx)) break; } /* *INDENT-ON* */ }
27,421
https://github.com/Henkoglobin/Plot3D.Mobile/blob/master/StandardLibrary/PatternHelpers/StrategyComparer.cs
Github Open Source
Open Source
Unlicense
2,021
Plot3D.Mobile
Henkoglobin
C#
Code
73
231
using System; using System.Collections.Generic; namespace StandardLibrary.PatternHelpers { public class StrategyComparer<T> : IEqualityComparer<T> { private readonly Func<T, T, bool> compare; private readonly Func<T, int> getHashCode; public bool Equals(T x, T y) { return this.compare(x, y); } public int GetHashCode(T obj) { return this.getHashCode(obj); } public StrategyComparer(Func<T, T, bool> compare) : this(compare, x => x.GetHashCode()) { } public StrategyComparer(Func<T, T, bool> compare, Func<T, int> getHashCode) { this.compare = compare; this.getHashCode = getHashCode; } } }
11,507
https://github.com/smartcommunitylab/sco.infanziadigitales/blob/master/ungiorno-console/src/app/Classes/service.ts
Github Open Source
Open Source
Apache-2.0
null
sco.infanziadigitales
smartcommunitylab
TypeScript
Code
49
138
import { Kid } from './kid'; import { Time } from "./time"; export class Service { servizio: string; fasce: Time[]; kids : string[]; normale :boolean; constructor(name:string, fasce: Time[], kids?:string[], normale?:boolean) { this.servizio = name.charAt(0).toUpperCase() + name.slice(1); this.fasce = fasce; this.kids = kids; this.normale = normale || false; } }
15,329
https://github.com/joaoseidel/message/blob/master/src/main/java/io/joaoseidel/message/domain/MessageType.java
Github Open Source
Open Source
MIT
null
message
joaoseidel
Java
Code
11
44
package io.joaoseidel.message.domain; public enum MessageType { EMAIL, SMS, PUSH, WHATSAPP }
49,070
https://github.com/roadhouse-dev/LocalDownloadManager/blob/master/library/src/androidTest/java/au/com/roadhouse/localdownloadmanager/PersistentQueueTest.java
Github Open Source
Open Source
Apache-2.0
null
LocalDownloadManager
roadhouse-dev
Java
Code
326
1,564
package au.com.roadhouse.localdownloadmanager; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; @RunWith(AndroidJUnit4.class) public class PersistentQueueTest { @Test public void testBlockingPersistence() throws Exception{ File queueFile = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "test.que"); queueFile.delete(); PersistentQueue<String> persistentQueue = new PersistentQueue<>(queueFile); persistentQueue.setBlocking(true); persistentQueue.add("test"); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 1); assertEquals(persistentQueue.peek(), "test"); queueFile.delete(); } @Test public void testNonBlockingPersistence() throws Exception{ File queueFile = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "test.que"); queueFile.delete(); PersistentQueue<String> persistentQueue = new PersistentQueue<>(queueFile); persistentQueue.setBlocking(false); persistentQueue.add("test"); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 1); assertEquals(persistentQueue.peek(), "test"); queueFile.delete(); } @Test public void testItemRemoval() { File queueFile = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "test.que"); queueFile.delete(); PersistentQueue<String> persistentQueue = new PersistentQueue<>(queueFile); persistentQueue.add("Hello"); persistentQueue.add("You"); assertEquals(persistentQueue.size(), 2); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 2); persistentQueue.remove("Hello"); assertEquals(persistentQueue.size(), 1); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 1); } @Test public void testRemove() { File queueFile = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "test.que"); queueFile.delete(); PersistentQueue<String> persistentQueue = new PersistentQueue<>(queueFile); persistentQueue.add("Hello"); persistentQueue.add("You"); assertEquals(persistentQueue.size(), 2); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 2); ; assertEquals(persistentQueue.remove(), "Hello"); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 1); assertEquals(persistentQueue.remove(), "You"); queueFile.delete(); persistentQueue = new PersistentQueue<>(queueFile); //Sanity check assertEquals(persistentQueue.size(), 0); try{ persistentQueue.remove(); } catch (Exception e){ return; } //Shouldn't get here assertTrue(false); } @Test public void testPeek() { File queueFile = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "test.que"); queueFile.delete(); PersistentQueue<String> persistentQueue = new PersistentQueue<>(queueFile); persistentQueue.add("Hello"); persistentQueue.add("You"); assertEquals(persistentQueue.size(), 2); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 2); assertEquals(persistentQueue.peek(), "Hello"); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 2); assertEquals(persistentQueue.peek(), "Hello"); } @Test public void testElement() { File queueFile = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "test.que"); queueFile.delete(); PersistentQueue<String> persistentQueue = new PersistentQueue<>(queueFile); persistentQueue.add("Hello"); persistentQueue.add("You"); assertEquals(persistentQueue.size(), 2); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 2); assertEquals(persistentQueue.element(), "Hello"); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 2); assertEquals(persistentQueue.element(), "Hello"); queueFile.delete(); persistentQueue = new PersistentQueue<>(queueFile); //Sanity check assertEquals(persistentQueue.size(), 0); try{ persistentQueue.element(); } catch (Exception e){ return; } //Shouldn't get here assertTrue(false); } @Test public void testClear() { File queueFile = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "test.que"); queueFile.delete(); PersistentQueue<String> persistentQueue = new PersistentQueue<>(queueFile); persistentQueue.add("Hello"); persistentQueue.add("You"); assertEquals(persistentQueue.size(), 2); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 2); persistentQueue.clear(); assertEquals(persistentQueue.size(), 0); persistentQueue.flushUpdates(); persistentQueue = new PersistentQueue<>(queueFile); assertEquals(persistentQueue.size(), 0); } }
28,099
https://github.com/Unni34/blueprints/blob/master/src/test/java/com/arangodb/blueprints/client/test/SimpleVertexTest.java
Github Open Source
Open Source
Apache-2.0
null
blueprints
Unni34
Java
Code
347
1,767
package com.arangodb.blueprints.client.test; import java.util.HashMap; import java.util.Map; import java.util.Vector; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.arangodb.ArangoException; import com.arangodb.ErrorNums; import com.arangodb.blueprints.client.ArangoDBException; import com.arangodb.blueprints.client.ArangoDBSimpleGraph; import com.arangodb.blueprints.client.ArangoDBSimpleVertex; public class SimpleVertexTest extends BaseTestCase { ArangoDBSimpleGraph graph = null; @Before public void setUp() { super.setUp(); try { graph = client.createGraph(graphName, vertices, edges); } catch (ArangoException e) { e.printStackTrace(); Assert.assertTrue(false); } } @Test public void test_CreateSimpleVertex() throws ArangoDBException { ArangoDBSimpleVertex vertex = client.createVertex(graph, null, null); Assert.assertNotNull(vertex); Assert.assertNotNull(vertex.getDocumentKey()); } @Test public void test_CreateAndGetSimpleVertex() throws ArangoDBException { ArangoDBSimpleVertex vertex = client.createVertex(graph, null, null); Assert.assertNotNull(vertex); Assert.assertNotNull(vertex.getDocumentKey()); ArangoDBSimpleVertex vertex2 = client.getVertex(graph, vertex.getDocumentKey()); Assert.assertNotNull(vertex2); Assert.assertNotNull(vertex2.getDocumentKey()); ArangoDBSimpleVertex vertex3 = client.getVertex(graph, vertex.getDocumentKey()); Assert.assertNotNull(vertex3); Assert.assertNotNull(vertex3.getDocumentKey()); } @Test public void test_CreateSimpleVertexWithName() throws ArangoDBException { ArangoDBSimpleVertex vertex = client.createVertex(graph, "egon", null); Assert.assertNotNull(vertex); Assert.assertNotNull(vertex.getDocumentKey()); Assert.assertEquals("egon", vertex.getDocumentKey()); } @Test public void test_CreateSimpleVertexWithProperties() throws ArangoDBException { Map<String, Object> properties = new HashMap<String, Object>(); properties.put("fisch", "mehl"); properties.put("counter", 5); ArangoDBSimpleVertex vertex = client.createVertex(graph, "egon", properties); Assert.assertNotNull(vertex); Assert.assertNotNull(vertex.getDocumentKey()); Assert.assertEquals("mehl", vertex.getProperty("fisch")); Assert.assertEquals(5, vertex.getProperty("counter")); } @Test public void test_ChangeSimpleVertex() throws ArangoDBException { double numericValue = 6.0; Map<String, Object> properties = new HashMap<String, Object>(); properties.put("fisch", "mehl"); properties.put("counter", 5); ArangoDBSimpleVertex vertex = client.createVertex(graph, "egon", properties); Assert.assertNotNull(vertex); Assert.assertNotNull(vertex.getDocumentKey()); Assert.assertEquals("mehl", vertex.getProperty("fisch")); Assert.assertEquals(5, vertex.getProperty("counter")); vertex.removeProperty("fisch"); vertex.setProperty("counter", numericValue); client.saveVertex(graph, vertex); Assert.assertNull(vertex.getProperty("fisch")); Assert.assertEquals(numericValue, vertex.getProperty("counter")); ArangoDBSimpleVertex vertex2 = client.getVertex(graph, vertex.getDocumentKey()); Assert.assertNotNull(vertex2); Assert.assertNotNull(vertex2.getDocumentKey()); Assert.assertNull(vertex2.getProperty("fisch")); Assert.assertEquals(numericValue, vertex2.getProperty("counter")); } @Test public void test_DeleteSimpleVertex() throws ArangoDBException { ArangoDBSimpleVertex vertex = client.createVertex(graph, "to_delete", null); Assert.assertNotNull(vertex); Assert.assertNotNull(vertex.getDocumentKey()); client.deleteVertex(graph, vertex); Assert.assertTrue(vertex.isDeleted()); try { vertex = client.getVertex(graph, "to_delete"); Assert.fail("ArangoDBException not thrown"); } catch (ArangoDBException e) { Assert.assertEquals(new Integer(ErrorNums.ERROR_ARANGO_DOCUMENT_NOT_FOUND), e.errorNumber()); } } @Test public void test_SetProperties() throws ArangoDBException { ArangoDBSimpleVertex vertex = client.createVertex(graph, "testProperties", null); Assert.assertNotNull(vertex); Assert.assertNotNull(vertex.getDocumentKey()); vertex.setProperty("key1", "abc##ääüü"); HashMap<String, Object> hm = new HashMap<String, Object>(); hm.put("test", "protest"); hm.put("hello", "world"); vertex.setProperty("key2", hm); HashMap<Object, Object> hm2 = new HashMap<Object, Object>(); hm2.put("test", "protest"); hm2.put(hm, "world"); // fail! try { vertex.setProperty("key3", hm2); Assert.fail("ArangoDBException not thrown"); } catch (ArangoDBException e) { Assert.assertEquals(new Integer(ErrorNums.ERROR_GRAPH_INVALID_PARAMETER), e.errorNumber()); } HashMap<Object, Object> hm3 = new HashMap<Object, Object>(); hm3.put("test", "protest"); hm3.put("hello", hm); vertex.setProperty("key4", hm3); Vector<Object> v = new Vector<Object>(); v.add("huhu"); vertex.setProperty("key5", v); v.add(hm); vertex.setProperty("key6", v); v.add(hm2); // fail! try { vertex.setProperty("key6", v); Assert.fail("ArangoDBException not thrown"); } catch (ArangoDBException e) { Assert.assertEquals(new Integer(ErrorNums.ERROR_GRAPH_INVALID_PARAMETER), e.errorNumber()); } client.saveVertex(graph, vertex); } }
35,137
https://github.com/Cyecize/Can-Sealers-Bulgaria/blob/master/templates/default/question-details.html.twig
Github Open Source
Open Source
MIT
2,020
Can-Sealers-Bulgaria
Cyecize
Twig
Code
119
424
{# @var dict \App\Service\Lang\ILanguagePack #} {# @var question \App\Entity\Question #} {% extends 'base.html.twig' %} {% block title %}{{ dict.websiteName }} - Въпрос{% endblock %} {% block body %} <div class="container rounded bg-container mt-container pb-container"> <h3>Въпрос от {{ question.fullName }}</h3> <small>{{ question.dateFormat }}</small> <hr> <div class="row"> <div class="col-lg-9"> <div class="p-2"> <ul class="list-group"> <li class="list-group-item">Име: {{ question.fullName }}</li> <li class="list-group-item">Тел. номер: {{ question.phoneNumber }}</li> {% if question.email %} <li class="list-group-item"> Email: <a href="mailto:{{ question.email }}">{{ question.email }}</a> </li> {% endif %} {% if question.user %} <li class="list-group-item"> Потр. Име: <a href="{{ path('show_user', {'username':question.user.username}) }}"> {{ question.user.username }} </a> </li> {% endif %} <br> </ul> <p>Въпрос: </p> <div class="raw-content border border-light rounded p-2">{{ question.message }}</div> </div> </div> </div> </div> {% endblock %}
48,764
https://github.com/githubsaturn/covid19-spread-simulator/blob/master/src/utils/Logger.ts
Github Open Source
Open Source
MIT
2,021
covid19-spread-simulator
githubsaturn
TypeScript
Code
30
98
export default class Logger { static log(s: string) { console.log(s) } static error(s: any) { console.log(s) } static dev(s: string) { if (process.env.REACT_APP_IS_DEBUG) { console.log('>>> ', s) } } }
921
https://github.com/Zenterio/opensourcelib/blob/master/citools/seed/src/main/groovy/com/zenterio/jenkins/configuration/Watcher.groovy
Github Open Source
Open Source
Apache-2.0
2,021
opensourcelib
Zenterio
Groovy
Code
50
190
package com.zenterio.jenkins.configuration import groovy.transform.AutoClone import groovy.transform.Canonical import groovy.transform.EqualsAndHashCode @Canonical @EqualsAndHashCode(callSuper=true, includeFields=true) @AutoClone class Watcher extends ContactInformation { public Watcher(String name, String email, EmailPolicy emailPolicy) { super(name, email, emailPolicy) } public Watcher inherit() { return new Watcher(this.name, this.email,this.emailPolicy.inherit()) } public static Watcher getTestData() { return new Watcher("Watcher", "watcher@mail.com", EmailPolicy.testData) } }
24,737
https://github.com/talsewell/cerberus/blob/master/tools/colours.sh
Github Open Source
Open Source
BSD-2-Clause
2,022
cerberus
talsewell
Shell
Code
60
198
#!/bin/bash if [[ "$OSTYPE" == "linux-gnu" ]]; then $@ else if [ "$1" = "lem" ]; then ($@) 2>&1 | sed -E -e "s,^ Warning.*,$(tput setaf 3)&$(tput sgr 0)," -e "s,^ (Error|Type error).*,$(tput setaf 1)&$(tput sgr 0),"; exit ${PIPESTATUS[0]} else ($@) | sed -E -e "s,^Warning.*,$(tput setaf 3)&$(tput sgr 0)," -e "s,^Error.*,$(tput setaf 1)&$(tput sgr 0),"; exit ${PIPESTATUS[0]} fi fi
30,495
https://github.com/hmoralesluis/netviral-2016-11-16/blob/master/src/App/AdminBundle/Resources/views/Product/audio_ebook.html.twig
Github Open Source
Open Source
MIT
2,020
netviral-2016-11-16
hmoralesluis
Twig
Code
424
1,773
{% extends 'AdminBundle::layout.html.twig' %} {% block title %}Main Infuence{% endblock %} {% block stylesheets %} <link href="{{ asset('bundles/admin/css/pages/search.css') }}" rel="stylesheet" type="text/css"/> <link rel="stylesheet" href="{{ asset('bundles/admin/plugins/data-tables/DT_bootstrap.css') }}"/> {% endblock %} {% block content %} <div class="row-fluid profile"> <div class="span12"> <!--BEGIN TABS--> <div class="tabbable tabbable-custom tabbable-full-width"> <ul class="nav nav-tabs"> <li class="active"><a href="#tab_1_1" data-toggle="tab">{% trans %}Audios{% endtrans %}</a></li> <li><a href="#tab_1_2" data-toggle="tab">{% trans %}Ebooks{% endtrans %}</a></li> </ul> <div class="tab-content"> <div class="tab-pane row-fluid active" id="tab_1_1"> {% if is_granted('ROLE_ADMIN') %} <div class="row-fluid"> <div class="span4"> <div class="booking-app"> <a href="{{ path('management_audio_new') }}"> <i class="icon-headphones pull-right"></i> <span class="pull-right">{% trans %}Registrar fichero de audio{% endtrans %}</span> </a> </div> </div> </div> <div class="space40"></div> {% endif %} <table class="table table-striped table-hover" id="audio"> <thead> <tr> <th align="center"></th> </tr> </thead> <tbody> {% for audio in audios %} <tr class="odd gradeX"> <td> <div class="row-fluid portfolio-block"> <div class="span5 portfolio-text"> <img src="{{ asset('bundles/admin/img/profile/portfolio/logo_azteca.jpg') }}" alt=""/> <div class="portfolio-text-info"> <h4>{{ audio.author }}</h4> <p>{{ audio.name }}</p> </div> </div> <div class="span5"> <div class="portfolio-info"> {% trans %}Archivo de audio{% endtrans %} <span>{{ audio.path }}</span> </div> </div> <div class="span2 portfolio-btn"> <a href="{{ app.request.basePath ~ '/' ~ audio.getWebPath() }}" class="btn bigicn-only"><span>{% trans %}Escuchar{% endtrans %}</span></a> </div> </div> </td> <td> <div class="span5 portfolio-btn"> <a id="download" href="{{ app.request.basePath ~ '/' ~ audio.getWebPath() }}" class="btn bigicn-only"><span>{% trans %}Descargar{% endtrans %}</span></a> </div> </td> </tr> {% endfor %} </tbody> </table> </div> <!--tab_1_2--> <div class="tab-pane row-fluid" id="tab_1_2"> {% if is_granted('ROLE_ADMIN') %} <div class="row-fluid"> <div class="span4"> <div class="booking-app"> <a href="{{ path('management_ebook_new') }}"> <i class="icon-book pull-right"></i> <span class="pull-right">{% trans %}Registrar Ebook{% endtrans %}</span> </a> </div> </div> </div> <div class="space40"></div> {% endif %} <table class="table table-striped table-hover" id="ebook"> <thead> <tr> <th align="center"></th> </tr> </thead> <tbody> {% for ebook in ebooks %} <tr class="odd gradeX"> <td> <div class="row-fluid portfolio-block"> <div class="span5 portfolio-text"> <img src="{{ asset('bundles/admin/img/profile/portfolio/logo_conquer.jpg') }}" alt=""/> <div class="portfolio-text-info"> <h4>{% trans %}Ebook{% endtrans %}</h4> <p>{{ ebook.name }}</p> </div> </div> <div class="span5"> <div class="portfolio-info"> {% trans %}Fichero de Texto{% endtrans %} <span>{{ ebook.path }}</span> </div> </div> <div class="span2 portfolio-btn"> <a href="{{ app.request.basePath ~ '/' ~ ebook.getWebPath() }}" class="btn bigicn-only"><span>{% trans %}Descargar{% endtrans %}</span></a> </div> </div> </td> </tr> {% endfor %} </tbody> </table> </div> <!--end tab-pane--> </div> </div> <!--END TABS--> </div> </div> {% endblock %} {% block javascripts %} <script src="{{ asset('bundles/admin/scripts/download.js') }}" type="text/javascript"></script> <script type="text/javascript" src="{{ asset('bundles/admin/plugins/data-tables/jquery.dataTables.js') }}"></script> <script type="text/javascript" src="{{ asset('bundles/admin/plugins/data-tables/DT_bootstrap.js') }}"></script> <script> $('#audio, #ebook').dataTable({ "aLengthMenu": [ [5, 15, 20, -1], [5, 15, 20, "Todos"] // change per page values here ], // set the initial value "iDisplayLength": 5, "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ por página", "oPaginate": { "sPrevious": "Anterior", "sNext": "Siguiente" } }, "aoColumnDefs": [{ 'bSortable': false, 'aTargets': [0] } ] }); </script> {% endblock %}
10,343
https://github.com/Mehdi-Hamida/site-vitrine-3.0/blob/master/js/languages-animation-dynamic-text-typing.js
Github Open Source
Open Source
MIT
null
site-vitrine-3.0
Mehdi-Hamida
JavaScript
Code
250
664
//SCRIPT ANIMATION DYNAMIC TEXT TYPING - LANGUES PARLEES ... // List of sentences var _LANGUAGE_CONTENT2 = [ "Je parle Français", "I speak English", "Hablo Español" ]; // Current sentence being processed var _PART2 = 0; // Character number of the current sentence being processed var _PART_INDEX2 = 0; // Holds the handle returned from setInterval var _INTERVAL_VAL2; // Element that holds the text var _ELEMENT2 = document.querySelector("#languages-typing-text"); // Cursor element // var _CURSOR = document.querySelector("#cursor"); // Implements typing effect function Type2() { // Get substring with 1 characater added var languageText = _LANGUAGE_CONTENT2[_PART2].substring(0, _PART_INDEX2 + 1); _ELEMENT2.innerHTML = `💬` + languageText; _PART_INDEX2++; // If full sentence has been displayed then start to delete the sentence after some time if(languageText === _LANGUAGE_CONTENT2[_PART2]) { // Hide the cursor // _CURSOR.style.display = 'none'; clearInterval(_INTERVAL_VAL2); setTimeout(function() { _INTERVAL_VAL2 = setInterval(Delete2, 50); }, 1000); } } // Implements deleting effect function Delete2() { // Get substring with 1 character deleted var languageText = _LANGUAGE_CONTENT2[_PART2].substring(0, _PART_INDEX2 - 1); _ELEMENT2.innerHTML = `💬` + languageText; _PART_INDEX2--; // If sentence has been deleted then start to display the next sentence if(languageText === '') { clearInterval(_INTERVAL_VAL2); // If current sentence was last then display the first one, else move to the next if(_PART2 == (_LANGUAGE_CONTENT2.length - 1)) _PART2 = 0; else _PART2++; _PART_INDEX2 = 0; // Start to display the next sentence after some time setTimeout(function() { // _CURSOR.style.display = 'inline-block'; _INTERVAL_VAL2 = setInterval(Type2, 100); }, 200); } } // Start the typing effect on load _INTERVAL_VAL2 = setInterval(Type2, 0);
19,937
https://github.com/skylarkui/skylark-totaljs-components/blob/master/.original/j-Loading/component.js
Github Open Source
Open Source
MIT
null
skylark-totaljs-components
skylarkui
JavaScript
Code
44
182
COMPONENT('loading', function(self) { var pointer; self.readonly(); self.singleton(); self.nocompile && self.nocompile(); self.make = function() { self.aclass('ui-loading'); self.append('<div></div>'); }; self.show = function() { clearTimeout(pointer); self.rclass('hidden'); return self; }; self.hide = function(timeout) { clearTimeout(pointer); pointer = setTimeout(function() { self.aclass('hidden'); }, timeout || 1); return self; }; });
29,909
https://github.com/ojmakhura/andromda/blob/master/andromda-documentation/samples/timetracker-ejb3/core/src/main/java/org/andromda/timetracker/service/UserServiceBean.java
Github Open Source
Open Source
BSD-3-Clause, Apache-1.1, Apache-2.0, LicenseRef-scancode-public-domain
2,022
andromda
ojmakhura
Java
Code
244
786
// license-header java merge-point // // Generated by SessionBeanImpl.vsl in andromda-ejb3-cartridge on 08/05/2014 14:24:56. // Modify as necessary. If deleted it will be regenerated. // package org.andromda.timetracker.service; import java.util.Collection; import org.andromda.timetracker.domain.User; import org.andromda.timetracker.domain.UserDao; import org.andromda.timetracker.domain.UserDaoException; import org.andromda.timetracker.vo.UserDetailsVO; import org.andromda.timetracker.vo.UserVO; /** * @see UserServiceBase * * Remember to manually configure the local business interface this bean implements if originally you only * defined the remote business interface. However, this change is automatically reflected in the ejb-jar.xml. * * Do not specify the javax.ejb.Stateless annotation * Instead, the session bean is defined in the ejb-jar.xml descriptor. */ // Uncomment to enable webservices for UserServiceBean // @javax.jws.WebService(endpointInterface = "org.andromda.timetracker.service.UserServiceWSInterface", serviceName = "UserService") public class UserServiceBean extends UserServiceBase implements UserServiceRemote { // --------------- Constructors --------------- /** * Default constructor extending base class default constructor */ public UserServiceBean() { super(); } // -------- Business Methods Impl -------------- /** * @see UserServiceBase#getAllUsers() */ @Override protected UserVO[] handleGetAllUsers() throws Exception { Collection userVOs = this.getUserDao().loadAll(UserDao.TRANSFORM_USERVO); return (UserVO[])userVOs.toArray(new UserVO[0]); } /** * @see UserServiceBase#registerUser(UserDetailsVO) */ @Override protected UserDetailsVO handleRegisterUser(UserDetailsVO userDetailVO) throws Exception { User user = this.getUserDao().userDetailsVOToEntity(userDetailVO); user = this.getUserDao().create(user); return this.getUserDao().toUserDetailsVO(user); } /** * @see UserServiceBase#getAllUsers() */ @Override protected UserVO handleGetUser(String username) throws Exception { try { User user = this.getUserDao().findByUsername(username); return getUserDao().toUserVO(user); } catch (UserDaoException ex) { throw new UserDoesNotExistException("User does not exist " + username); } } /** * @see UserServiceBase#removeUser(UserVO) */ @Override protected void handleRemoveUser(UserVO userVO) throws Exception { getUserDao().remove(userVO.getId()); } // -------- Lifecycle Callback Implementation -------------- }
1,880
https://github.com/nesto-software/moment-holiday/blob/master/packages/database-mongoose/src/schemas/recurring-date.schema.ts
Github Open Source
Open Source
MIT
2,023
moment-holiday
nesto-software
TypeScript
Code
61
178
import { RecurringDate } from "@nesto-software/moment-holiday-core"; import { Schema } from "mongoose"; import { dateDiscriminatorKey } from "./abstract-date.schema"; const recurringDateSchema = new Schema( { day: { type: Number, required: true, }, month: { type: Number, required: true, }, }, { discriminatorKey: dateDiscriminatorKey, _id: false, }, ); recurringDateSchema.methods.deserialize = function (): RecurringDate { return new RecurringDate(this.day, this.month); }; export { recurringDateSchema };
19,234
https://github.com/joaomvg/joaomvg.github.io/blob/master/.gitignore
Github Open Source
Open Source
2,022
joaomvg.github.io
joaomvg
Ignore List
Code
4
29
.vscode/ .jekyll-cache/ _site/cloud-computing/* _site/images/
11,627
https://github.com/adrtod/adrtod.github.io/blob/master/_bibtex.r
Github Open Source
Open Source
CC0-1.0
null
adrtod.github.io
adrtod
R
Code
77
288
library(bibtex) library(purrr) library(tools) library(yaml) bib <- read.bib("files/todeschini.bib") %>% unclass() compact_person <- function(x) { x %>% unclass() %>% map(compact) # remove empty fields } str_latex <- function(x) { x %>% parseLatex() %>% latexToUtf8() %>% deparseLatex(dropBraces=TRUE) } bib <- bib %>% modify(~c(list(bibtype = attr(., "bibtype")), .)) %>% modify(~modify_if(., ~inherits(., "person"), compact_person, .else = str_latex)) comment <- "# File automatically generated from _data/todeschini.bib # Do NOT edit. # To regenerate, run: # Rscript _bibtex.r " comment %>% c(as.yaml(bib)) %>% writeLines("_data/bib.yml")
7,531
https://github.com/pgalias/zephyrus/blob/master/src/components/templates/team/minimalisticCards.tsx
Github Open Source
Open Source
MIT
null
zephyrus
pgalias
TypeScript
Code
134
456
import React, { FC, useState } from 'react'; import { getRandomEmployee, RandomSmallAvatar } from './utils'; const TeamMember: FC = () => { const [employee] = useState(getRandomEmployee()); return ( <article className="flex flex-wrap p-2 border-2 border-gray-200 dark:border-blue-200 rounded-lg"> <div className="w-1/4"> <RandomSmallAvatar className="rounded-full w-full" /> </div> <div className="flex-grow flex flex-col justify-center pl-3"> <h3 className="font-bold text-blueGray-900 dark:text-blue-100 m-0"> {employee.name} </h3> <p className="text-sm text-gray-400">{employee.title}</p> </div> </article> ); }; export const MinimalisticCards: FC = () => ( <section className="text-gray-800 dark:text-gray-50"> <h2 className="text-3xl text-center mb-4">Our team</h2> <p className="text-center mb-8"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur consequatur culpa delectus dolor expedita explicabo facilis fuga fugiat incidunt ipsa numquam obcaecati quas saepe sequi similique sint velit, vero voluptas. </p> <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3"> <TeamMember /> <TeamMember /> <TeamMember /> <TeamMember /> <TeamMember /> <TeamMember /> </div> </section> );
23,506
https://github.com/amuramoto/realm-objc/blob/master/examples/swift/RealmSwiftSimpleExample/RealmSwiftSimpleExample/Objects.h
Github Open Source
Open Source
Apache-2.0
2,014
realm-objc
amuramoto
Objective-C
Code
136
261
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #import <Realm/Realm.h> @interface Dog : RLMObject @property NSString *name; @property NSInteger age; @end // This protocol enables typed collections. i.e.: // RLMArray<Dog> @protocol Dog <NSObject> @end @interface Person : RLMObject @property NSString *name; @property RLMArray<Dog> *dogs; @end
40,309
https://github.com/silvanperego/LogTracker/blob/master/logtracker/src/main/java/org/sper/logtracker/data/AbstractDataListener.java
Github Open Source
Open Source
Apache-2.0
2,020
LogTracker
silvanperego
Java
Code
76
264
package org.sper.logtracker.data; import java.util.ArrayList; import java.util.List; public abstract class AbstractDataListener<RECEIVE,SEND> implements DataListener<RECEIVE> { private List<DataListener<SEND>> listenerList = new ArrayList<DataListener<SEND>>(); public void addListener(DataListener<SEND> listener) { listenerList.add(listener); } protected void sendToListeners(SEND send) { for (DataListener<SEND> listener : listenerList) { listener.receiveData(send); } } @Override public void publishData() { for (DataListener<? extends SEND> listener : listenerList) { listener.publishData(); } } /** * Entfernt alle Listener, mit einer spezifischen Klasse. * @param cls */ public void removeListeners() { listenerList.clear(); } }
47,800
https://github.com/duanzengxin/shujuku-----123/blob/master/酒店餐饮服务管理系统/Service/IFrontDeskCallBack.cs
Github Open Source
Open Source
Apache-2.0
2,019
shujuku-----123
duanzengxin
C#
Code
48
199
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HCSMS.Model; using HCSMS.Model.Application; using System.ServiceModel; namespace HCSMS.Service { [ServiceContract] public interface IFrontDeskCallBack { [OperationContract] void ServeItem(List<RequestHandleInfo> itemList); [OperationContract] void RequestDeny(List<RequestHandleInfo> itemList); [OperationContract] void StopSupplyItem(string itemId); [OperationContract] void RunOutOfItem(string itemId); [OperationContract] void ErrorMessage(ErrorEventArgs error); [OperationContract] void InformationMessage(NotifyEventArgs msg); } }
25,778
https://github.com/golevi/chia-blockchain/blob/master/chia/types/coin_record.go
Github Open Source
Open Source
MIT
2,021
chia-blockchain
golevi
Go
Code
86
293
// https://github.com/Chia-Network/chia-blockchain/blob/main/chia/types/coin_record.py package types import "github.com/golevi/chia-blockchain/chia/types/blockchain" // CoinRecord are values that correspond to a CoinName that are used // in keeping track of the unspent database. // // coin: Coin // confirmed_block_index: uint32 // spent_block_index: uint32 // spent: bool // coinbase: bool // timestamp: uint64 # Timestamp of the block at height confirmed_block_index // type CoinRecord struct { Coin blockchain.Coin `json:"coin"` ConfirmedBlockIndex uint32 `json:"confirmed_block_index"` SpentBlockIndex uint32 `json:"spent_block_index"` Spent bool `json:"spent"` Coinbase bool `json:"coinbase"` Timestamp uint64 `json:"timestamp"` } func (cr CoinRecord) Name() string { return cr.Coin.StringID() }
47,789
https://github.com/nnneznaika/psd2/blob/master/src/Psd2/Gateway/AbstractBankGateway.php
Github Open Source
Open Source
MIT
2,017
psd2
nnneznaika
PHP
Code
251
869
<?php namespace OakLabs\Psd2\Gateway; use GuzzleHttp\Client as GuzzleHttp; use GuzzleHttp\ClientInterface as GuzzleInterface; use League\OAuth2\Client\Token\AccessToken; use OakLabs\Psd2\Authorization\AuthorizationInterface; abstract class AbstractBankGateway { protected const API_ACCESS_TOKEN = ''; protected const API_ACCESS_TOKEN_SANDBOX = ''; protected const API_ACCOUNT_DETAILS = ''; protected const API_ACCOUNT_DETAILS_SANDBOX = ''; protected const API_SEPA_TRANSACTIONS = ''; protected const API_SEPA_TRANSACTIONS_SANDBOX = ''; /** * @var AccessToken */ protected $accessToken; /** * @var AuthorizationInterface */ protected $authorization; /** * @var \GuzzleHttp\Client */ protected $client; /** * @var bool */ protected $useSandbox = true; public function __construct() { $this->setClient(new GuzzleHttp()); } /** * @param \GuzzleHttp\ClientInterface $client */ public function setClient(GuzzleInterface $client) { $this->client = $client; } /** * @return bool */ public function isUsingSandbox(): bool { return $this->useSandbox; } /** * Use the Sandbox environment. */ public function setSandboxEnvironment() { $this->useSandbox = true; } /** * Use the Production environment. */ public function unsetSandboxEnvironment() { $this->useSandbox = false; } /** * @param AuthorizationInterface $authorization */ public function setAuthorization(AuthorizationInterface $authorization) { $this->authorization = $authorization; } /** * @param AccessToken|string $accessToken * @return $this */ public function setAccessToken($accessToken) { if ($accessToken instanceof AccessToken) { $this->accessToken = $accessToken; } else { $this->accessToken = new AccessToken(['access_token' => $accessToken]); } return $this; } /** * @return AccessToken */ public function getTokens(): AccessToken { return $this->accessToken; } protected function getAccessToken(): string { return $this->getTokens()->getToken(); } protected function getAccessTokenUrl(): string { return $this->isUsingSandbox() ? static::API_ACCESS_TOKEN_SANDBOX : static::API_ACCESS_TOKEN; } protected function getAccountDetailsUrl(): string { return $this->isUsingSandbox() ? static::API_ACCOUNT_DETAILS_SANDBOX : static::API_ACCOUNT_DETAILS; } protected function getSepaTransactionsUrl(): string { return $this->isUsingSandbox() ? static::API_SEPA_TRANSACTIONS_SANDBOX : static::API_SEPA_TRANSACTIONS; } }
24,240
https://github.com/lexmartinez/eatery/blob/master/src/components/Modal/BaseModal/style.ts
Github Open Source
Open Source
MIT
2,019
eatery
lexmartinez
TypeScript
Code
138
425
import { StyleSheet } from 'react-native'; import { Colors, Fonts } from '../../../config/Constant'; import { getResponsiveStyle, Platform } from '../../../config/Utilities'; const titleSize = Platform.select({ ios: 45, android: 50 }) const textSize = Platform.select({ ios: 14, android: 18 }) export default StyleSheet.create(getResponsiveStyle({ main: { flex: 1, backgroundColor: Colors.primary_white, alignItems: 'center', justifyContent: 'center', paddingHorizontal: 30, }, container: { alignItems: 'center', paddingBottom: Platform.select({ android: 60, ios: 80 }) }, title: { color: Colors.primary_grey, fontFamily: Fonts.BOLD, fontSize: titleSize, lineHeight: titleSize, marginBottom: 15, textAlign: 'center' }, text: { color: Colors.primary_grey, fontFamily: Fonts.MEDIUM, fontSize: textSize, lineHeight: textSize, textAlign: 'center' }, image: { height: 190, width: 280, marginBottom: 10 }, imageContainer: { flex: 0, alignItems: 'center', justifyContent: 'center', marginTop: Platform.select({ ios: 70, android: 45 }), marginBottom: 15, paddingHorizontal: 30 }, close: { position: 'absolute', right: 30, top: Platform.select({ ios: 70, android: 50 }) } }));
17,224
https://github.com/krgamestudios/Dungeon/blob/master/scr/underdirk.lua
Github Open Source
Open Source
Zlib
2,017
Dungeon
krgamestudios
Lua
Code
1,654
4,921
--[[ /* Copyright: (c) Kayne Ruse 2016 * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. */ --]] local regionAPI = require("region") local regionPagerAPI = require("region_pager") local modtable = {} -- --utility functions function modtable.Sqr(x) return x*x end function modtable.Dist(x, y, i, j) return math.sqrt(modtable.Sqr(x - i) + modtable.Sqr(y - j)) end function modtable.GThenSwitch(a, b) --BUGFIX: This resolves a problem with the for loop and iterating through paths, ensuring that they iterate upwards if a > b then return b, a else return a, b end end --tile macros, mapped to the tilesheet "dungeon_sheet.png" modtable.wall = 1 modtable.open = 2 modtable.doorv = 3 modtable.doorh = 4 modtable.sdoorv = 5 modtable.sdoorh = 6 modtable.stairsnd = 7 modtable.stairswd = 8 modtable.stairssd = 9 modtable.stairsed = 10 --list of filters for finding door locations modtable.hfilters = { --normal filter orientation {modtable.open, modtable.open, modtable.open, modtable.wall, modtable.open, modtable.wall, -1, -1, -1}, {modtable.wall, modtable.open, modtable.open, modtable.wall, modtable.open, modtable.wall, -1, -1, -1}, {modtable.open, modtable.open, modtable.wall, modtable.wall, modtable.open, modtable.wall, -1, -1, -1}, --rotated 180 degrees {-1, -1, -1, modtable.wall, modtable.open, modtable.wall, modtable.open, modtable.open, modtable.open}, {-1, -1, -1, modtable.wall, modtable.open, modtable.wall, modtable.open, modtable.open, modtable.wall}, {-1, -1, -1, modtable.wall, modtable.open, modtable.wall, modtable.wall, modtable.open, modtable.open} } modtable.vfilters = { --90 degrees {modtable.open, modtable.wall, -1, modtable.open, modtable.open, -1, modtable.open, modtable.wall, -1}, {modtable.open, modtable.wall, -1, modtable.open, modtable.open, -1, modtable.wall, modtable.wall, -1}, {modtable.wall, modtable.wall, -1, modtable.open, modtable.open, -1, modtable.open, modtable.wall, -1}, --270 degrees {-1, modtable.wall, modtable.open, -1, modtable.open, modtable.open, -1, modtable.wall, modtable.open}, {-1, modtable.wall, modtable.wall, -1, modtable.open, modtable.open, -1, modtable.wall, modtable.open}, {-1, modtable.wall, modtable.open, -1, modtable.open, modtable.open, -1, modtable.wall, modtable.wall} } modtable.cornerfilters = { {modtable.wall, modtable.wall, modtable.wall, -1, modtable.open, modtable.wall, modtable.wall, -1, modtable.wall}, {modtable.wall, modtable.wall, modtable.wall, modtable.wall, modtable.open, -1, modtable.wall, -1, modtable.wall}, {modtable.wall, -1, modtable.wall, modtable.wall, modtable.open, -1, modtable.wall, modtable.wall, modtable.wall}, {modtable.wall, -1, modtable.wall, -1, modtable.open, modtable.wall, modtable.wall, modtable.wall, modtable.wall} } --blank backgrounds function modtable.Blank(r) for i = 1, regionAPI.GetWidth(r) do for j = 1, regionAPI.GetHeight(r) do regionAPI.SetTile(r, i, j, 1, modtable.wall) end end end function modtable.GenerateDungeon(x, y, w, h, n) --setup regionPagerAPI.SetOnCreate(modtable.Blank) --make the rooms rooms = {} --basic rooms for i = 1, n do rooms[i] = modtable.GenerateRoomObject(math.random(x, x+w), math.random(y, y+h), 2, 2, 6, 6) end --TODO: prefab rooms --shift the rooms apart local restart = true while restart == true do restart = false --compare each room to each other room, and shift them apart if a collision is detected for i = 1, n do for j = 1, n do local retFlag = modtable.ShiftCollisions(rooms[i], rooms[j]) if retFlag == 1 then restart = true end if retFlag == 2 then print("Warning: Objects can't be shifted") rooms[j].x = rooms[j].x + 1 end end end end --connect the rooms with pathway representations for i = 1, n do --determine the centers AFTER shifting rooms[i].centerX = rooms[i].x + math.floor(rooms[i].w / 2) rooms[i].centerY = rooms[i].y + math.floor(rooms[i].h / 2) end for i = 1, n do local closest = -1 local dist = 9999999999 --find the closest room to room[i] for k = 1, n do local d = modtable.Dist(rooms[i].x, rooms[i].y, rooms[k].x, rooms[k].y) if d < dist and i ~= k and rooms[k].target == -1 then closest = k dist = d end end rooms[i].target = closest end --save the resulting rooms for k = 1, n do for i = rooms[k].x, rooms[k].x + rooms[k].w do for j = rooms[k].y, rooms[k].y + rooms[k].h do regionPagerAPI.SetTile(i, j, 0, modtable.open) end end --generate the paths if rooms[k].target ~= -1 then modtable.GenPath(rooms[k].centerX, rooms[k].centerY, rooms[rooms[k].target].centerX, rooms[rooms[k].target].centerY) else print("ERROR: -1 target found") end end --prep the arguments for the filter algorithm local lowerX = 0 local upperX = 0 local lowerY = 0 local upperY = 0 regionPagerAPI.ForEach(function(r) --mimicing the "publish" code if (regionAPI.GetX(r) < lowerX) then lowerX = regionAPI.GetX(r) end if (regionAPI.GetX(r) > upperX) then upperX = regionAPI.GetX(r) end if (regionAPI.GetY(r) < lowerY) then lowerY = regionAPI.GetY(r) end if (regionAPI.GetY(r) > upperY) then upperY = regionAPI.GetY(r) end end) --pass to the filter algorithm modtable.MatchFilters( lowerX+1, upperX+regionAPI.GetWidth()-2, lowerY+1, upperY+regionAPI.GetHeight()-2, modtable.hfilters, function (i, j) local t = math.random(10) if (t <= 7) then regionPagerAPI.SetTile(i, j, 0, modtable.doorh) end if (t >= 8 and t <= 9) then regionPagerAPI.SetTile(i, j, 0, modtable.sdoorh) end end ) modtable.MatchFilters( lowerX+1, upperX+regionAPI.GetWidth()-2, lowerY+1, upperY+regionAPI.GetHeight()-2, modtable.vfilters, function (i, j) local t = math.random(10) if (t <= 7) then regionPagerAPI.SetTile(i, j, 0, modtable.doorv) end if (t >= 8 and t <= 9) then regionPagerAPI.SetTile(i, j, 0, modtable.sdoorv) end end ) --correcting the "kink" doors modtable.MatchFilters( lowerX+1, upperX+regionAPI.GetWidth()-2, lowerY+1, upperY+regionAPI.GetHeight()-2, modtable.cornerfilters, function (i, j) if (regionPagerAPI.GetTile(i-1, j, 0) ~= modtable.wall) then regionPagerAPI.SetTile(i-1, j, 0, modtable.open) end if (regionPagerAPI.GetTile(i+1, j, 0) ~= modtable.wall) then regionPagerAPI.SetTile(i+1, j, 0, modtable.open) end if (regionPagerAPI.GetTile(i, j-1, 0) ~= modtable.wall) then regionPagerAPI.SetTile(i, j-1, 0, modtable.open) end if (regionPagerAPI.GetTile(i, j+1, 0) ~= modtable.wall) then regionPagerAPI.SetTile(i, j+1, 0, modtable.open) end end ) -- for i = lowerX+1, upperX+regionAPI.GetWidth()-2 do -- for j = lowerY+1, upperY+regionAPI.GetHeight()-2 do -- regionPagerAPI.GetTile(i, j, 0) -- end -- end end function modtable.GenerateRoomObject(x, y, minW, minH, maxW, maxH) local obj = {} obj.x = x obj.y = y obj.w = math.random(minW, maxW) obj.h = math.random(minH, maxH) --for passages -- obj.centerX = obj.x + math.floor(obj.w / 2) -- obj.centerY = obj.y + math.floor(obj.h / 2) obj.target = -1 return obj end ------------------------- --Collision checking ------------------------- function modtable.CheckCollision(lhs, rhs) --check if two room objects overlap if lhs.x > rhs.x + rhs.w then return false end if lhs.y > rhs.y + rhs.h then return false end if lhs.x + lhs.w < rhs.x then return false end if lhs.y + lhs.h < rhs.y then return false end return true end function modtable.ShiftCollisions(lhs, rhs) --return values: -1 = same object, 0 = move on, 1 = shifting occurred, 2 = object can't be shifted local retFlag = 0 if lhs == rhs then return -1 end --add a margin to avoid kissing lhs.x = lhs.x - 1 lhs.y = lhs.y - 1 lhs.w = lhs.w + 2 lhs.h = lhs.h + 2 --very crude separation algorithm while modtable.CheckCollision(lhs, rhs) do --error checking retFlag = 2 if math.abs(lhs.x - rhs.x) > math.abs(lhs.y - rhs.y) then --X direction if lhs.x < rhs.x then lhs.x = lhs.x - 1 rhs.x = rhs.x + 1 retFlag = 1 end if lhs.x > rhs.x then lhs.x = lhs.x + 1 rhs.x = rhs.x - 1 retFlag = 1 end else --Y direction if lhs.y < rhs.y then lhs.y = lhs.y - 1 rhs.y = rhs.y + 1 retFlag = 1 end if lhs.y > rhs.y then lhs.y = lhs.y + 1 rhs.y = rhs.y - 1 retFlag = 1 end end --error checking if retFlag == 2 then --correct the margin lhs.x = lhs.x + 1 lhs.y = lhs.y + 1 lhs.w = lhs.w - 2 lhs.h = lhs.h - 2 --return the error return retFlag end end --correct the margin lhs.x = lhs.x + 1 lhs.y = lhs.y + 1 lhs.w = lhs.w - 2 lhs.h = lhs.h - 2 return retFlag end ------------------------- --GenPath generates the longest path first, wich is why it's split into three parts ------------------------- function modtable.GenPath(x1, y1, x2, y2) -- print("path with", x1, y1, x2, y2) if math.abs(x2-x1) > math.abs(y2-y1) then return modtable.GenPathX(x1, y1, x2, y2) else return modtable.GenPathY(x1, y1, x2, y2) end end function modtable.GenPathX(x1, y1, x2, y2) local x1s local x2s local y1s local y2s --BUGFIX x1s, x2s = modtable.GThenSwitch(x1, x2) y1s, y2s = modtable.GThenSwitch(y1, y2) --generate a simple path between two coordinates, starting with cardinal X for i = x1s, x2s do regionPagerAPI.SetTile(i, y1, 0, modtable.open) -- io.write("x") end for j = y1s, y2s do regionPagerAPI.SetTile(x2, j, 0, modtable.open) -- io.write("y") end -- io.write("+\n") end function modtable.GenPathY(x1, y1, x2, y2) local x1s local x2s local y1s local y2s --BUGFIX x1s, x2s = modtable.GThenSwitch(x1, x2) y1s, y2s = modtable.GThenSwitch(y1, y2) --generate a simple path between two coordinates, starting with cardinal Y for j = y1s, y2s do regionPagerAPI.SetTile(x1, j, 0, modtable.open) -- io.write("y") end -- io.write("(", y1, ",", y2, ")") for i = x1s, x2s do regionPagerAPI.SetTile(i, y2, 0, modtable.open) -- io.write("x") end -- io.write("-\n") end ------------------------- --MatchFilters, for generating doors in correct places ------------------------- function modtable.MatchFilters(lowerX, upperX, lowerY, upperY, filters, callback) --for each potential location for i = lowerX, upperX do for j = lowerY, upperY do --compare it to the filters for _, f in pairs(filters) do if (f[1] ~= -1 and f[1] ~= regionPagerAPI.GetTile(i-1, j-1, 0)) then goto continue end if (f[2] ~= -1 and f[2] ~= regionPagerAPI.GetTile(i , j-1, 0)) then goto continue end if (f[3] ~= -1 and f[3] ~= regionPagerAPI.GetTile(i+1, j-1, 0)) then goto continue end if (f[4] ~= -1 and f[4] ~= regionPagerAPI.GetTile(i-1, j , 0)) then goto continue end if (f[5] ~= -1 and f[5] ~= regionPagerAPI.GetTile(i , j , 0)) then goto continue end if (f[6] ~= -1 and f[6] ~= regionPagerAPI.GetTile(i+1, j , 0)) then goto continue end if (f[7] ~= -1 and f[7] ~= regionPagerAPI.GetTile(i-1, j+1, 0)) then goto continue end if (f[8] ~= -1 and f[8] ~= regionPagerAPI.GetTile(i , j+1, 0)) then goto continue end if (f[9] ~= -1 and f[9] ~= regionPagerAPI.GetTile(i+1, j+1, 0)) then goto continue end callback(i, j) ::continue:: end end end end ------------------------- --return the resulting table ------------------------- return modtable
30,854
https://github.com/zrrrzzt/echo-micro/blob/master/index.js
Github Open Source
Open Source
MIT
null
echo-micro
zrrrzzt
JavaScript
Code
68
207
'use strict' const readFileSync = require('fs').readFileSync const md = require('markdown-it')() const { parse } = require('url') const { json, send } = require('micro') module.exports = async (request, response) => { response.setHeader('Access-Control-Allow-Origin', '*') response.setHeader('Access-Control-Allow-Methods', 'GET, POST') const data = request.method === 'POST' ? await json(request) : parse(request.url, true).query if (Object.keys(data).length > 0) { send(response, 200, data) } else { const readme = readFileSync(`${__dirname}/README.md`, 'utf-8') send(response, 200, md.render(readme)) } }
44,994
https://github.com/sandysuarezjimenez/HolandaCatalinaFw/blob/master/src/main/java/org/hcjf/io/net/http/layered/LayeredResponse.java
Github Open Source
Open Source
Apache-2.0
2,022
HolandaCatalinaFw
sandysuarezjimenez
Java
Code
58
151
package org.hcjf.io.net.http.layered; import org.hcjf.io.net.http.HttpResponse; /** * Response package for the layered contexts. * @author javaito */ public class LayeredResponse extends HttpResponse { private final Object layerResponse; public LayeredResponse(Object layerResponse) { this.layerResponse = layerResponse; } /** * Get the response object of the layer's invocation * @return Response object. */ public final Object getLayerResponse() { return layerResponse; } }
11,055
https://github.com/yznima/Slapdash-Android/blob/master/SlapDash/app/src/main/java/com/virginiatech/slapdash/slapdash/SQLDatabaseService/SlapDashSQLHelper.java
Github Open Source
Open Source
MIT
2,017
Slapdash-Android
yznima
Java
Code
84
253
package com.virginiatech.slapdash.slapdash.SQLDatabaseService; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by nima on 10/19/16. * TODO: actually use this and complete implementation */ public class SlapDashSQLHelper extends SQLiteOpenHelper { // If you change the database schema, you must increment the database version. public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "SlapDash.db"; public SlapDashSQLHelper(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
452
https://github.com/arata-nvm/lutrix/blob/master/src/smt/bit_blaster.rs
Github Open Source
Open Source
MIT
null
lutrix
arata-nvm
Rust
Code
937
3,530
use crate::{sat::types::*, smt::ast::*, smt::tseytin}; use super::{bit_vector::BitVector, solver::Solver}; impl Solver { pub(crate) fn transform(&mut self, expr: Expression) -> BitVector { match expr { Expression::Constant(var, length) => self.constant(var, length), Expression::Variable(name) => self.variable(name), Expression::Not(expr) => { let expr = self.transform(*expr); self.not(expr) } Expression::And(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.and(val1, val2) } Expression::Eq(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.eq(val1, val2) } Expression::Or(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.or(val1, val2) } Expression::Xor(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.xor(val1, val2) } Expression::BvNot(val1) => { let val1 = self.transform(*val1); self.bvnot(val1) } Expression::BvAnd(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvand(val1, val2) } Expression::BvOr(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvor(val1, val2) } Expression::BvXor(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvxor(val1, val2) } Expression::BvAdd(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvadd(val1, val2) } Expression::BvSub(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvsub(val1, val2) } Expression::BvMul(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvmul(val1, val2) } Expression::BvShl(val, n) => { let val = self.transform(*val); self.bvshl(val, n) } Expression::BvShr(val, n) => { let val = self.transform(*val); self.bvshr(val, n) } Expression::BvUlt(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvult(val1, val2) } Expression::BvUle(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvule(val1, val2) } Expression::BvUgt(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvugt(val1, val2) } Expression::BvUge(val1, val2) => { let val1 = self.transform(*val1); let val2 = self.transform(*val2); self.bvuge(val1, val2) } } } fn constant(&mut self, var: usize, length: usize) -> BitVector { let tmp = self.next_literals(length); for i in 0..length { let l = tmp.at(length - i - 1); match (var >> i) & 1 { 0 => self.add_clause(&[-l]), 1 => self.add_clause(&[l]), _ => unreachable!(), } } tmp } fn variable(&mut self, name: String) -> BitVector { match self.variables.get(&name) { Some(var) => var.clone(), None => panic!("variable `{}` not found", name), } } fn not(&mut self, val: BitVector) -> BitVector { let dst = self.next_literal(); tseytin::not(self, dst.as_bool(), val.as_bool()); dst } fn and(&mut self, val1: BitVector, val2: BitVector) -> BitVector { let dst = self.next_literal(); tseytin::and(self, dst.as_bool(), val1.as_bool(), val2.as_bool()); dst } fn eq(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); match val1.len() { 1 => { let tmp = self.xor(val1, val2); self.not(tmp) } _ => { let tmp1 = self.bvxor(val1, val2); let tmp2 = self.next_literal(); tseytin::or_many(self, tmp2.as_bool(), &tmp1.literals); self.not(tmp2) } } } fn or(&mut self, val1: BitVector, val2: BitVector) -> BitVector { let dst = self.next_literal(); tseytin::or(self, dst.as_bool(), val1.as_bool(), val2.as_bool()); dst } fn xor(&mut self, val1: BitVector, val2: BitVector) -> BitVector { let dst = self.next_literal(); tseytin::xor(self, dst.as_bool(), val1.as_bool(), val2.as_bool()); dst } fn bvnot(&mut self, val: BitVector) -> BitVector { let dst = self.next_literals(val.len()); for i in 0..dst.len() { tseytin::not(self, dst.at(i), val.at(i)); } dst } fn bvand(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); let dst = self.next_literals(val1.len()); for i in 0..dst.len() { tseytin::and(self, dst.at(i), val1.at(i), val2.at(i)); } dst } fn bvor(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); let dst = self.next_literals(val1.len()); for i in 0..dst.len() { tseytin::or(self, dst.at(i), val1.at(i), val2.at(i)); } dst } fn bvxor(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); let dst = self.next_literals(val1.len()); for i in 0..dst.len() { tseytin::xor(self, dst.at(i), val1.at(i), val2.at(i)); } dst } fn bvadd(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); let dst = self.next_literals(val1.len()); let mut carry = self.next_literal().as_bool(); self.add_clause(&[carry.inverted()]); for i in (0..dst.len()).rev() { let new_carry = self.next_literal().as_bool(); self.full_adder(dst.at(i), new_carry, val1.at(i), val2.at(i), carry); carry = new_carry; } dst } fn bvsub(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); let val2_not = self.bvnot(val2); let one = self.constant(1, val1.len()); let val2_comp = self.bvadd(val2_not, one); self.bvadd(val1, val2_comp) } fn bvmul(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); let mut dst = self.constant(0, val1.len()); for i in 0..val1.len() { let tmp = self.bvshl(val1.clone(), i); let tmp2 = self.next_literals(val1.len()); for j in 0..val1.len() { tseytin::and(self, tmp2.at(j), tmp.at(j), val2.at(val1.len() - i - 1)); } dst = self.bvadd(dst, tmp2); } dst } fn bvshl(&mut self, val: BitVector, n: usize) -> BitVector { let dst = self.next_literals(val.len()); if val.len() >= n { for i in 0..(val.len() - n) { let eq = self.eq( BitVector::new_bool(dst.at(i)), BitVector::new_bool(val.at(i + n)), ); self.add_clause(&[eq.as_bool()]); } } for i in 1..=n.min(val.len()) { self.add_clause(&[dst.at(val.len() - i).inverted()]); } dst } fn bvshr(&mut self, val: BitVector, n: usize) -> BitVector { let dst = self.next_literals(val.len()); for i in n..val.len() { let eq = self.eq( BitVector::new_bool(dst.at(i)), BitVector::new_bool(val.at(i - n)), ); self.add_clause(&[eq.as_bool()]); } for i in 0..n.min(val.len()) { self.add_clause(&[dst.at(i).inverted()]); } dst } fn bvult(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); // TODO let tmp = self.bvsub(val1, val2); BitVector::new_bool(tmp.at(0)) } fn bvule(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); let tmp1 = self.bvult(val1.clone(), val2.clone()); let tmp2 = self.eq(val1, val2); self.or(tmp1, tmp2) } fn bvugt(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); self.bvult(val2, val1) } fn bvuge(&mut self, val1: BitVector, val2: BitVector) -> BitVector { assert_eq!(val1.len(), val2.len()); // TODO self.bvule(val2, val1) } fn full_adder( &mut self, sum: Literal, carry: Literal, src1: Literal, src2: Literal, prev_carry: Literal, ) { let s1 = self.next_literal().as_bool(); let c1 = self.next_literal().as_bool(); let c2 = self.next_literal().as_bool(); tseytin::half_adder(self, s1, c1, src1, src2); tseytin::half_adder(self, sum, c2, s1, prev_carry); tseytin::or(self, carry, c1, c2); } fn next_literal(&mut self) -> BitVector { BitVector::new_bool(self.sat_solver.new_literal()) } fn next_literals(&mut self, length: usize) -> BitVector { let literals = (0..length).map(|_| self.next_literal().as_bool()).collect(); BitVector::new(literals) } }
12,115
https://github.com/apache/syncope/blob/master/core/provisioning-java/src/main/java/org/apache/syncope/core/provisioning/java/propagation/AbstractPropagationTaskExecutor.java
Github Open Source
Open Source
Apache-2.0
2,023
syncope
apache
Java
Code
2,315
9,028
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.syncope.core.provisioning.java.propagation; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; import org.apache.syncope.common.lib.to.ExecTO; import org.apache.syncope.common.lib.to.Item; import org.apache.syncope.common.lib.to.OrgUnit; import org.apache.syncope.common.lib.to.Provision; import org.apache.syncope.common.lib.types.AuditElements; import org.apache.syncope.common.lib.types.AuditElements.Result; import org.apache.syncope.common.lib.types.ExecStatus; import org.apache.syncope.common.lib.types.ResourceOperation; import org.apache.syncope.common.lib.types.TaskType; import org.apache.syncope.common.lib.types.TraceLevel; import org.apache.syncope.core.persistence.api.attrvalue.validation.PlainAttrValidationManager; import org.apache.syncope.core.persistence.api.dao.ExternalResourceDAO; import org.apache.syncope.core.persistence.api.dao.PlainSchemaDAO; import org.apache.syncope.core.persistence.api.dao.TaskDAO; import org.apache.syncope.core.persistence.api.entity.AnyUtils; import org.apache.syncope.core.persistence.api.entity.AnyUtilsFactory; import org.apache.syncope.core.persistence.api.entity.ExternalResource; import org.apache.syncope.core.persistence.api.entity.policy.PropagationPolicy; import org.apache.syncope.core.persistence.api.entity.task.PropagationData; import org.apache.syncope.core.persistence.api.entity.task.PropagationTask; import org.apache.syncope.core.persistence.api.entity.task.TaskExec; import org.apache.syncope.core.persistence.api.entity.task.TaskUtilsFactory; import org.apache.syncope.core.provisioning.api.AuditManager; import org.apache.syncope.core.provisioning.api.Connector; import org.apache.syncope.core.provisioning.api.ConnectorManager; import org.apache.syncope.core.provisioning.api.TimeoutException; import org.apache.syncope.core.provisioning.api.data.TaskDataBinder; import org.apache.syncope.core.provisioning.api.event.AnyLifecycleEvent; import org.apache.syncope.core.provisioning.api.notification.NotificationManager; import org.apache.syncope.core.provisioning.api.propagation.PropagationActions; import org.apache.syncope.core.provisioning.api.propagation.PropagationManager; import org.apache.syncope.core.provisioning.api.propagation.PropagationReporter; import org.apache.syncope.core.provisioning.api.propagation.PropagationTaskExecutor; import org.apache.syncope.core.provisioning.api.propagation.PropagationTaskInfo; import org.apache.syncope.core.provisioning.api.utils.ExceptionUtils2; import org.apache.syncope.core.provisioning.java.pushpull.OutboundMatcher; import org.apache.syncope.core.provisioning.java.utils.ConnObjectUtils; import org.apache.syncope.core.provisioning.java.utils.MappingUtils; import org.apache.syncope.core.spring.implementation.ImplementationManager; import org.apache.syncope.core.spring.security.AuthContextUtils; import org.identityconnectors.framework.common.exceptions.ConnectorException; import org.identityconnectors.framework.common.objects.Attribute; import org.identityconnectors.framework.common.objects.AttributeBuilder; import org.identityconnectors.framework.common.objects.AttributeDelta; import org.identityconnectors.framework.common.objects.AttributeUtil; import org.identityconnectors.framework.common.objects.ConnectorObject; import org.identityconnectors.framework.common.objects.ConnectorObjectBuilder; import org.identityconnectors.framework.common.objects.Name; import org.identityconnectors.framework.common.objects.ObjectClass; import org.identityconnectors.framework.common.objects.OperationalAttributes; import org.identityconnectors.framework.common.objects.SyncDeltaType; import org.identityconnectors.framework.common.objects.Uid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.retry.RetryException; import org.springframework.retry.backoff.ExponentialBackOffPolicy; import org.springframework.retry.backoff.ExponentialRandomBackOffPolicy; import org.springframework.retry.backoff.FixedBackOffPolicy; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.RetryTemplate; import org.springframework.transaction.annotation.Transactional; @Transactional(rollbackFor = { Throwable.class }) public abstract class AbstractPropagationTaskExecutor implements PropagationTaskExecutor { protected static final Logger LOG = LoggerFactory.getLogger(PropagationTaskExecutor.class); protected final Map<String, RetryTemplate> retryTemplates = Collections.synchronizedMap(new HashMap<>()); protected final ConnectorManager connectorManager; protected final ConnObjectUtils connObjectUtils; protected final TaskDAO taskDAO; protected final ExternalResourceDAO resourceDAO; protected final PlainSchemaDAO plainSchemaDAO; protected final NotificationManager notificationManager; protected final AuditManager auditManager; protected final TaskDataBinder taskDataBinder; protected final AnyUtilsFactory anyUtilsFactory; protected final TaskUtilsFactory taskUtilsFactory; protected final OutboundMatcher outboundMatcher; protected final PlainAttrValidationManager validator; protected final ApplicationEventPublisher publisher; protected final Map<String, PropagationActions> perContextActions = new ConcurrentHashMap<>(); public AbstractPropagationTaskExecutor( final ConnectorManager connectorManager, final ConnObjectUtils connObjectUtils, final TaskDAO taskDAO, final ExternalResourceDAO resourceDAO, final PlainSchemaDAO plainSchemaDAO, final NotificationManager notificationManager, final AuditManager auditManager, final TaskDataBinder taskDataBinder, final AnyUtilsFactory anyUtilsFactory, final TaskUtilsFactory taskUtilsFactory, final OutboundMatcher outboundMatcher, final PlainAttrValidationManager validator, final ApplicationEventPublisher publisher) { this.connectorManager = connectorManager; this.connObjectUtils = connObjectUtils; this.taskDAO = taskDAO; this.resourceDAO = resourceDAO; this.plainSchemaDAO = plainSchemaDAO; this.notificationManager = notificationManager; this.auditManager = auditManager; this.taskDataBinder = taskDataBinder; this.anyUtilsFactory = anyUtilsFactory; this.taskUtilsFactory = taskUtilsFactory; this.outboundMatcher = outboundMatcher; this.validator = validator; this.publisher = publisher; } @Override public void expireRetryTemplate(final String resource) { retryTemplates.remove(resource); } protected List<PropagationActions> getPropagationActions(final ExternalResource resource) { List<PropagationActions> result = new ArrayList<>(); resource.getPropagationActions().forEach(impl -> { try { result.add(ImplementationManager.build( impl, () -> perContextActions.get(impl.getKey()), instance -> perContextActions.put(impl.getKey(), instance))); } catch (Exception e) { LOG.error("While building {}", impl, e); } }); return result; } protected void checkMandatoryMissing( final PropagationTaskInfo taskInfo, final Set<Attribute> attrs, final boolean enablePasswordCheck) { // check if there is any missing or null / empty mandatory attribute Set<Object> mandatoryAttrNames = new HashSet<>(); Optional.ofNullable(AttributeUtil.find(PropagationManager.MANDATORY_MISSING_ATTR_NAME, attrs)). ifPresent(missing -> { attrs.remove(missing); if (taskInfo.getOperation() == ResourceOperation.CREATE) { // SYNCOPE-1751 remove __PASSWORD__ if enablePasswordCheck is false, this is needed to support // LinkedAccount update propagation without password mandatoryAttrNames.addAll(enablePasswordCheck ? missing.getValue() : missing.getValue().stream(). filter(v -> !OperationalAttributes.PASSWORD_NAME.equals(v)). collect(Collectors.toList())); } }); Optional.ofNullable(AttributeUtil.find(PropagationManager.MANDATORY_NULL_OR_EMPTY_ATTR_NAME, attrs)). ifPresent(nullOrEmpty -> { attrs.remove(nullOrEmpty); mandatoryAttrNames.addAll(nullOrEmpty.getValue()); }); if (!mandatoryAttrNames.isEmpty()) { throw new IllegalArgumentException( "Not attempted because there are mandatory attributes without value(s): " + mandatoryAttrNames); } } protected Uid doCreate( final PropagationTaskInfo taskInfo, final Connector connector, final AtomicReference<Boolean> propagationAttempted) { Set<Attribute> attrs = taskInfo.getPropagationData().getAttributes(); checkMandatoryMissing(taskInfo, attrs, true); LOG.debug("Create {} on {}", attrs, taskInfo.getResource().getKey()); Uid result = connector.create(taskInfo.getObjectClass(), attrs, null, propagationAttempted); taskInfo.getResource().getProvisionByAnyType(taskInfo.getAnyType()). filter(provision -> provision.getUidOnCreate() != null). ifPresent(provision -> { AnyUtils anyUtils = anyUtilsFactory.getInstance(taskInfo.getAnyTypeKind()); anyUtils.addAttr( validator, taskInfo.getEntityKey(), plainSchemaDAO.find(provision.getUidOnCreate()), result.getUidValue()); publisher.publishEvent(new AnyLifecycleEvent<>( this, SyncDeltaType.UPDATE, anyUtils.dao().find(taskInfo.getEntityKey()), AuthContextUtils.getDomain())); }); return result; } protected Uid doUpdate( final PropagationTaskInfo taskInfo, final Connector connector, final ConnectorObject beforeObj, final AtomicReference<Boolean> propagationAttempted) { Set<Attribute> attrs = taskInfo.getPropagationData().getAttributes(); checkMandatoryMissing(taskInfo, attrs, false); LOG.debug("Update {} on {}", attrs, taskInfo.getResource().getKey()); // 1. check if rename is really required Name newName = AttributeUtil.getNameFromAttributes(attrs); LOG.debug("Rename required with value {}", newName); if (beforeObj != null && newName != null && newName.equals(beforeObj.getName()) && !newName.getNameValue().equals(beforeObj.getUid().getUidValue())) { LOG.debug("Remote object name unchanged"); attrs.remove(newName); } // 2. check whether anything is actually needing to be propagated, i.e. if there is attribute // difference between beforeObj - just read above from the connector - and the values to be propagated Map<String, Attribute> originalAttrMap = Map.of(); if (beforeObj != null) { originalAttrMap = beforeObj.getAttributes().stream(). collect(Collectors.toMap(attr -> attr.getName().toUpperCase(), Function.identity())); Map<String, Attribute> updateAttrMap = attrs.stream(). collect(Collectors.toMap(attr -> attr.getName().toUpperCase(), Function.identity())); // Only compare attribute from beforeObj that are also being updated originalAttrMap.keySet().removeAll(updateAttrMap.keySet()); } Uid result; if (!originalAttrMap.isEmpty() && originalAttrMap.values().equals(attrs)) { LOG.debug("Don't need to propagate anything: {} is equal to {}", originalAttrMap.values(), attrs); result = AttributeUtil.getUidAttribute(attrs); } else { LOG.debug("Attributes to update: {}", attrs); // 3. provision entry LOG.debug("Update {} on {}", attrs, taskInfo.getResource().getKey()); result = connector.update( Optional.ofNullable(beforeObj). map(ConnectorObject::getObjectClass). orElseGet(() -> taskInfo.getObjectClass()), Optional.ofNullable(beforeObj). map(ConnectorObject::getUid). orElseGet(() -> new Uid(taskInfo.getOldConnObjectKey() == null ? taskInfo.getConnObjectKey() : taskInfo.getOldConnObjectKey())), attrs, null, propagationAttempted); } return result; } protected Uid doUpdateDelta( final PropagationTaskInfo taskInfo, final Set<AttributeDelta> modifications, final Connector connector, final AtomicReference<Boolean> propagationAttempted) { Uid uid = new Uid(taskInfo.getConnObjectKey()); if (modifications.isEmpty()) { LOG.debug("Nothing to modify for {} on {}", uid, taskInfo.getResource().getKey()); } else { LOG.debug("Update Delta {} for {} on {}", modifications, uid, taskInfo.getResource().getKey()); connector.updateDelta( taskInfo.getObjectClass(), uid, modifications, null, propagationAttempted); } return uid; } protected Uid createOrUpdate( final PropagationTaskInfo taskInfo, final boolean fetchRemoteObj, final ConnectorObject beforeObj, final Connector connector, final AtomicReference<Boolean> propagationAttempted) { PropagationData propagationData = taskInfo.getPropagationData(); if (propagationData.getAttributeDeltas() == null) { if (beforeObj != null) { return doUpdate(taskInfo, connector, beforeObj, propagationAttempted); } if (fetchRemoteObj || taskInfo.getOperation() == ResourceOperation.CREATE) { return doCreate(taskInfo, connector, propagationAttempted); } return doUpdate(taskInfo, connector, beforeObj, propagationAttempted); } return doUpdateDelta(taskInfo, propagationData.getAttributeDeltas(), connector, propagationAttempted); } protected Uid delete( final PropagationTaskInfo taskInfo, final boolean fetchRemoteObj, final ConnectorObject beforeObj, final Connector connector, final AtomicReference<Boolean> propagationAttempted) { Uid result; if (fetchRemoteObj && beforeObj == null) { LOG.debug("{} not found on {}: ignoring delete", taskInfo.getConnObjectKey(), taskInfo.getResource().getKey()); result = null; } else { ObjectClass objectClass = Optional.ofNullable(beforeObj). map(ConnectorObject::getObjectClass). orElseGet(() -> taskInfo.getObjectClass()); Uid uid = Optional.ofNullable(beforeObj). map(ConnectorObject::getUid). orElseGet(() -> new Uid(taskInfo.getConnObjectKey())); LOG.debug("Delete {} on {}", uid, taskInfo.getResource().getKey()); connector.delete(objectClass, uid, null, propagationAttempted); result = uid; } return result; } protected Optional<RetryTemplate> retryTemplate(final ExternalResource resource) { RetryTemplate retryTemplate = null; if (resource.getPropagationPolicy() != null) { retryTemplate = retryTemplates.get(resource.getKey()); if (retryTemplate == null) { retryTemplate = new RetryTemplate(); SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); retryPolicy.setMaxAttempts(resource.getPropagationPolicy().getMaxAttempts()); retryTemplate.setRetryPolicy(retryPolicy); String[] params = resource.getPropagationPolicy().getBackOffParams().split(";"); switch (resource.getPropagationPolicy().getBackOffStrategy()) { case EXPONENTIAL: ExponentialBackOffPolicy eBackOffPolicy = new ExponentialBackOffPolicy(); if (params.length > 0) { try { eBackOffPolicy.setInitialInterval(Long.parseLong(params[0])); } catch (NumberFormatException e) { LOG.error("Could not convert to long: {}", params[0], e); } } if (params.length > 1) { try { eBackOffPolicy.setMaxInterval(Long.parseLong(params[1])); } catch (NumberFormatException e) { LOG.error("Could not convert to long: {}", params[1], e); } } if (params.length > 2) { try { eBackOffPolicy.setMultiplier(Double.parseDouble(params[2])); } catch (NumberFormatException e) { LOG.error("Could not convert to double: {}", params[2], e); } } retryTemplate.setBackOffPolicy(eBackOffPolicy); break; case RANDOM: ExponentialRandomBackOffPolicy erBackOffPolicy = new ExponentialRandomBackOffPolicy(); if (params.length > 0) { try { erBackOffPolicy.setInitialInterval(Long.parseLong(params[0])); } catch (NumberFormatException e) { LOG.error("Could not convert to long: {}", params[0], e); } } if (params.length > 1) { try { erBackOffPolicy.setMaxInterval(Long.parseLong(params[1])); } catch (NumberFormatException e) { LOG.error("Could not convert to long: {}", params[1], e); } } if (params.length > 2) { try { erBackOffPolicy.setMultiplier(Double.parseDouble(params[2])); } catch (NumberFormatException e) { LOG.error("Could not convert to double: {}", params[2], e); } } retryTemplate.setBackOffPolicy(erBackOffPolicy); break; case FIXED: default: FixedBackOffPolicy fBackOffPolicy = new FixedBackOffPolicy(); if (params.length > 0) { try { fBackOffPolicy.setBackOffPeriod(Long.parseLong(params[0])); } catch (NumberFormatException e) { LOG.error("Could not convert to long: {}", params[0], e); } } retryTemplate.setBackOffPolicy(fBackOffPolicy); } retryTemplates.put(resource.getKey(), retryTemplate); } } return Optional.ofNullable(retryTemplate); } @Override public TaskExec<PropagationTask> execute( final PropagationTaskInfo taskInfo, final PropagationReporter reporter, final String executor) { return retryTemplate(taskInfo.getResource()).map(rt -> rt.execute(context -> { LOG.debug("#{} Propagation attempt", context.getRetryCount()); TaskExec<PropagationTask> exec = doExecute(taskInfo, reporter, executor); if (context.getRetryCount() < taskInfo.getResource().getPropagationPolicy().getMaxAttempts() - 1 && !ExecStatus.SUCCESS.name().equals(exec.getStatus())) { throw new RetryException("Attempt #" + context.getRetryCount() + " failed"); } return exec; })).orElseGet(() -> doExecute(taskInfo, reporter, executor)); } protected boolean isFetchRemoteObj(final PropagationTaskInfo taskInfo) { return Optional.ofNullable(taskInfo.getResource().getPropagationPolicy()). map(PropagationPolicy::isFetchAroundProvisioning). orElse(true); } protected TaskExec<PropagationTask> doExecute( final PropagationTaskInfo taskInfo, final PropagationReporter reporter, final String executor) { Connector connector = taskInfo.getConnector() == null ? connectorManager.getConnector(taskInfo.getResource()) : taskInfo.getConnector(); List<PropagationActions> actions = getPropagationActions(taskInfo.getResource()); OffsetDateTime start = OffsetDateTime.now(); TaskExec<PropagationTask> exec = taskUtilsFactory.getInstance(TaskType.PROPAGATION).newTaskExec(); exec.setStatus(ExecStatus.CREATED.name()); exec.setExecutor(executor); String taskExecutionMessage = null; String failureReason = null; // Flag to state whether any propagation has been attempted AtomicReference<Boolean> propagationAttempted = new AtomicReference<>(false); boolean fetchRemoteObj = isFetchRemoteObj(taskInfo); ConnectorObject beforeObj = null; ConnectorObject afterObj = null; Provision provision = null; OrgUnit orgUnit = null; Uid uid = null; Result result; try { provision = taskInfo.getResource(). getProvisionByObjectClass(taskInfo.getObjectClass().getObjectClassValue()).orElse(null); orgUnit = taskInfo.getResource().getOrgUnit(); if (taskInfo.getBeforeObj().isEmpty()) { if (fetchRemoteObj) { // Try to read remote object BEFORE any actual operation beforeObj = provision == null && orgUnit == null ? null : orgUnit == null ? getRemoteObject(taskInfo, connector, provision, actions, false) : getRemoteObject(taskInfo, connector, orgUnit, actions, false); taskInfo.setBeforeObj(Optional.ofNullable(beforeObj)); } } else { beforeObj = taskInfo.getBeforeObj().get(); } actions.forEach(action -> action.before(taskInfo)); switch (taskInfo.getOperation()) { case CREATE: case UPDATE: uid = createOrUpdate(taskInfo, fetchRemoteObj, beforeObj, connector, propagationAttempted); break; case DELETE: uid = delete(taskInfo, fetchRemoteObj, beforeObj, connector, propagationAttempted); break; default: } exec.setStatus(propagationAttempted.get() ? ExecStatus.SUCCESS.name() : ExecStatus.NOT_ATTEMPTED.name()); result = Result.SUCCESS; LOG.debug("Successfully propagated to {}", taskInfo.getResource()); } catch (Exception e) { result = Result.FAILURE; exec.setStatus(ExecStatus.FAILURE.name()); propagationAttempted.set(true); LOG.error("Exception during provision on resource " + taskInfo.getResource().getKey(), e); if (e instanceof ConnectorException && e.getCause() != null) { taskExecutionMessage = e.getCause().getMessage(); if (e.getCause().getMessage() == null) { failureReason = e.getMessage(); } else { failureReason = e.getMessage() + "\n\n Cause: " + e.getCause().getMessage().split("\n")[0]; } } else { taskExecutionMessage = ExceptionUtils2.getFullStackTrace(e); if (e.getCause() == null) { failureReason = e.getMessage(); } else { failureReason = e.getMessage() + "\n\n Cause: " + e.getCause().getMessage().split("\n")[0]; } } actions.forEach(action -> action.onError(taskInfo, exec, e)); } finally { // Try to read remote object AFTER any actual operation if (uid != null) { taskInfo.setConnObjectKey(uid.getUidValue()); } if (fetchRemoteObj) { try { afterObj = provision == null && orgUnit == null ? null : orgUnit == null ? getRemoteObject(taskInfo, connector, provision, actions, true) : getRemoteObject(taskInfo, connector, orgUnit, actions, true); } catch (Exception ignore) { // ignore exception LOG.error("Error retrieving after object", ignore); } } if (!ExecStatus.FAILURE.name().equals(exec.getStatus()) && afterObj == null && uid != null && taskInfo.getOperation() != ResourceOperation.DELETE) { afterObj = new ConnectorObjectBuilder(). setObjectClass(taskInfo.getObjectClass()). setUid(uid). setName(Optional.ofNullable( AttributeUtil.getNameFromAttributes(taskInfo.getPropagationData().getAttributes())). orElseGet(() -> new Name(taskInfo.getConnObjectKey()))). build(); } exec.setStart(start); exec.setMessage(taskExecutionMessage); exec.setEnd(OffsetDateTime.now()); LOG.debug("Execution finished: {}", exec); hasToBeregistered(taskInfo, exec).ifPresent(task -> { LOG.debug("Execution to be stored: {}", exec); exec.setTask(task); task.add(exec); taskInfo.setKey(taskDAO.save(task).getKey()); }); String fiql = provision == null ? null : afterObj != null ? outboundMatcher.getFIQL(afterObj, taskInfo.getResource(), provision) : beforeObj != null ? outboundMatcher.getFIQL(beforeObj, taskInfo.getResource(), provision) : null; reporter.onSuccessOrNonPriorityResourceFailures( taskInfo, ExecStatus.valueOf(exec.getStatus()), failureReason, fiql, beforeObj, afterObj); } for (PropagationActions action : actions) { action.after(taskInfo, exec, afterObj); } // SYNCOPE-1136 String anyTypeKind = Optional.ofNullable(taskInfo.getAnyTypeKind()).map(Enum::name).orElse("realm"); String operation = taskInfo.getOperation().name().toLowerCase(); boolean notificationsAvailable = notificationManager.notificationsAvailable( AuditElements.EventCategoryType.PROPAGATION, anyTypeKind, taskInfo.getResource().getKey(), operation); boolean auditRequested = auditManager.auditRequested( AuthContextUtils.getUsername(), AuditElements.EventCategoryType.PROPAGATION, anyTypeKind, taskInfo.getResource().getKey(), operation); if (notificationsAvailable || auditRequested) { ExecTO execTO = taskDataBinder.getExecTO(exec); notificationManager.createTasks( AuthContextUtils.getWho(), AuditElements.EventCategoryType.PROPAGATION, anyTypeKind, taskInfo.getResource().getKey(), operation, result, beforeObj, new Object[] { execTO, afterObj }, taskInfo); auditManager.audit( AuthContextUtils.getWho(), AuditElements.EventCategoryType.PROPAGATION, anyTypeKind, taskInfo.getResource().getKey(), operation, result, beforeObj, new Object[] { execTO, afterObj }, taskInfo); } return exec; } protected TaskExec<PropagationTask> rejected( final PropagationTaskInfo taskInfo, final String rejectReason, final PropagationReporter reporter, final String executor) { TaskExec<PropagationTask> execution = taskUtilsFactory.getInstance(TaskType.PROPAGATION).newTaskExec(); execution.setStatus(ExecStatus.NOT_ATTEMPTED.name()); execution.setExecutor(executor); execution.setStart(OffsetDateTime.now()); execution.setMessage(rejectReason); execution.setEnd(execution.getStart()); hasToBeregistered(taskInfo, execution).ifPresent(task -> { LOG.debug("Execution to be stored: {}", execution); execution.setTask(task); task.add(execution); taskDAO.save(task); }); reporter.onSuccessOrNonPriorityResourceFailures( taskInfo, ExecStatus.valueOf(execution.getStatus()), rejectReason, null, null, null); return execution; } /** * Check whether an execution has to be stored, for a given task. * * @param taskInfo propagation task * @param execution to be decide whether to store or not * @return true if execution has to be store, false otherwise */ protected Optional<PropagationTask> hasToBeregistered( final PropagationTaskInfo taskInfo, final TaskExec<PropagationTask> execution) { boolean failed = ExecStatus.valueOf(execution.getStatus()) != ExecStatus.SUCCESS; ExternalResource resource = taskInfo.getResource(); boolean result; switch (taskInfo.getOperation()) { case CREATE: result = (failed && resource.getCreateTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) || resource.getCreateTraceLevel() == TraceLevel.ALL; break; case UPDATE: result = (failed && resource.getUpdateTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) || resource.getUpdateTraceLevel() == TraceLevel.ALL; break; case DELETE: result = (failed && resource.getDeleteTraceLevel().ordinal() >= TraceLevel.FAILURES.ordinal()) || resource.getDeleteTraceLevel() == TraceLevel.ALL; break; default: result = false; } if (!result) { return Optional.empty(); } PropagationTask task = Optional.ofNullable(taskInfo.getKey()). map(key -> taskDAO.<PropagationTask>find(TaskType.PROPAGATION, key)). orElseGet(() -> { PropagationTask t = taskUtilsFactory.getInstance(TaskType.PROPAGATION).newTask(); t.setResource(resourceDAO.find(resource.getKey())); t.setObjectClassName(taskInfo.getObjectClass().getObjectClassValue()); t.setAnyTypeKind(taskInfo.getAnyTypeKind()); t.setAnyType(taskInfo.getAnyType()); t.setEntityKey(taskInfo.getEntityKey()); t.setOperation(taskInfo.getOperation()); t.setConnObjectKey(taskInfo.getConnObjectKey()); t.setOldConnObjectKey(taskInfo.getOldConnObjectKey()); return t; }); task.setPropagationData(taskInfo.getPropagationData()); return Optional.of(task); } /** * Get remote object for given task. * * @param connector connector facade proxy * @param taskInfo current propagation task * @param provision provision * @param actions propagation actions * @param latest 'FALSE' to retrieve object using old connObjectKey if not null. * @return remote connector object. */ protected ConnectorObject getRemoteObject( final PropagationTaskInfo taskInfo, final Connector connector, final Provision provision, final List<PropagationActions> actions, final boolean latest) { String connObjectKeyValue = latest || taskInfo.getOldConnObjectKey() == null ? taskInfo.getConnObjectKey() : taskInfo.getOldConnObjectKey(); List<ConnectorObject> matches = outboundMatcher.match(taskInfo, connector, provision, actions, connObjectKeyValue); LOG.debug("Found for propagation task {}: {}", taskInfo, matches); return matches.isEmpty() ? null : matches.get(0); } /** * Get remote object for given task. * * @param connector connector facade proxy * @param taskInfo current propagation task * @param orgUnit orgUnit * @param actions propagation actions * @param latest 'FALSE' to retrieve object using old connObjectKey if not null. * @return remote connector object. */ protected ConnectorObject getRemoteObject( final PropagationTaskInfo taskInfo, final Connector connector, final OrgUnit orgUnit, final List<PropagationActions> actions, final boolean latest) { String connObjectKey = latest || taskInfo.getOldConnObjectKey() == null ? taskInfo.getConnObjectKey() : taskInfo.getOldConnObjectKey(); Set<String> moreAttrsToGet = new HashSet<>(); actions.forEach(action -> moreAttrsToGet.addAll(action.moreAttrsToGet(Optional.of(taskInfo), orgUnit))); ConnectorObject obj = null; Optional<Item> connObjectKeyItem = orgUnit.getConnObjectKeyItem(); if (connObjectKeyItem.isPresent()) { try { obj = connector.getObject( taskInfo.getObjectClass(), AttributeBuilder.build(connObjectKeyItem.get().getExtAttrName(), connObjectKey), orgUnit.isIgnoreCaseMatch(), MappingUtils.buildOperationOptions( MappingUtils.getPropagationItems(orgUnit.getItems().stream()), moreAttrsToGet.toArray(String[]::new))); } catch (TimeoutException toe) { LOG.debug("Request timeout", toe); throw toe; } catch (RuntimeException ignore) { LOG.debug("While resolving {}", connObjectKey, ignore); } } return obj; } }
15,806
https://github.com/heliosRX/heliosRX/blob/master/build/release.sh
Github Open Source
Open Source
MIT
2,022
heliosRX
heliosRX
Shell
Code
135
311
#!/usr/bin/env bash set -e echo "Enter heliosRX release version: " read VERSION read -p "Releasing $VERSION - are you sure? (y/n)" -n 1 -r echo if [[ $REPLY =~ ^[Yy]$ ]] then echo "Releasing $VERSION ..." # run tests npm test 2>/dev/null # build VERSION=$VERSION npm run build # check if there is uncommitted changes if [[ $( git diff-index HEAD | grep -v "dist/" | wc -c ) -ne 0 ]] then echo echo echo "Uncommited changes!" exit fi # commit git add -A ./dist git commit -m "[build] $VERSION" # set version npm version $VERSION --message "[release] $VERSION" # tag (is created by npm version) # git tag -a "v$VERSION" -m "[release] $VERSION" # publish # git push origin refs/tags/v$VERSION # git push git push github --tags git push github npm publish fi
25,377
https://github.com/Jaypatel33/Introduction-to-Programming-with-MATLAB/blob/master/Homework_08/maxsubsum.m
Github Open Source
Open Source
MIT
2,015
Introduction-to-Programming-with-MATLAB
Jaypatel33
MATLAB
Code
66
207
function [row,col,numrows,numcols,summa] = maxsubsum(A) [n,m] = size (A); summa = A(1,1); row = 1; col = 1; numrows = 1; numcols = 1; for i = 1:1:n for j = 1:1:m for k = 1:1:n for l = 1:1:m submatrix = A(i:1:k, j:1:l); if sum(submatrix(:)) > summa summa = sum(submatrix(:)); row = i; col = j; [numrows, numcols] = size(submatrix); end end end end end end
30,307
https://github.com/dickster/DD/blob/master/src/client/app/config/row.config.ts
Github Open Source
Open Source
MIT
null
DD
dickster
TypeScript
Code
10
33
import {WidgetConfig} from "./widget.config"; export class RowConfig { widgets:WidgetConfig<any>[]; }
33,580
https://github.com/grusso14/eprot/blob/master/src/it/finsiel/siged/mvc/presentation/action/report/ReportAssegnatiAction.java
Github Open Source
Open Source
Apache-2.0
null
eprot
grusso14
Java
Code
615
3,212
package it.finsiel.siged.mvc.presentation.action.report; import it.finsiel.siged.constant.Constants; import it.finsiel.siged.constant.FileConstants; import it.finsiel.siged.constant.Parametri; import it.finsiel.siged.model.organizzazione.Utente; import it.finsiel.siged.mvc.bo.AlberoUfficiBO; import it.finsiel.siged.mvc.business.ReportProtocolloDelegate; import it.finsiel.siged.mvc.presentation.actionform.report.ReportAssegnatiForm; import it.finsiel.siged.mvc.presentation.helper.ReportType; import it.finsiel.siged.mvc.vo.organizzazione.UfficioVO; import it.finsiel.siged.report.protocollo.CommonReportDS; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.export.JRCsvExporter; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.engine.export.JRHtmlExporterParameter; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterParameter; import net.sf.jasperreports.engine.export.JRXmlExporter; import net.sf.jasperreports.engine.util.JRLoader; import org.apache.log4j.Logger; import org.apache.struts.Globals; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.util.MessageResources; public final class ReportAssegnatiAction extends Action { static Logger logger = Logger.getLogger(ReportAssegnatiAction.class .getName()); public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { MessageResources messages = getResources(request); MessageResources bundle = (MessageResources) request .getAttribute(Globals.MESSAGES_KEY); ActionMessages errors = new ActionMessages(); HttpSession session = request.getSession(); ReportAssegnatiForm reportForm = (ReportAssegnatiForm) form; Utente utente = (Utente) session.getAttribute(Constants.UTENTE_KEY); boolean ufficioCompleto = (utente.getUfficioVOInUso().getTipo() .equals(UfficioVO.UFFICIO_CENTRALE)); session.setAttribute("reportForm", reportForm); if (form == null) { logger.info(" Creating new ReportScaricatiForm Form"); form = new ReportAssegnatiForm(); request.setAttribute(mapping.getAttribute(), form); } if (reportForm.getUfficioCorrenteId() == 0) { AlberoUfficiBO.impostaUfficio(utente, reportForm, ufficioCompleto); } if (request.getParameter("selezionaUfficio") != null) { reportForm.setUfficioCorrenteId(Integer.parseInt(request .getParameter("selezionaUfficio"))); } else if (reportForm.getImpostaUfficioAction() != null) { reportForm.setImpostaUfficioAction(null); reportForm.setUfficioCorrenteId(reportForm .getUfficioSelezionatoId()); } else if (request.getParameter("ufficioPrecedenteAction") != null) { AlberoUfficiBO.impostaUfficio(utente, reportForm, ufficioCompleto); reportForm.setUfficioCorrenteId(reportForm.getUfficioCorrente() .getParentId()); } else if (reportForm.getBtnStampa() != null) { reportForm.setBtnStampa(null); reportForm.setReportFormats(new HashMap(1)); AlberoUfficiBO.impostaUfficio(utente, reportForm, ufficioCompleto); errors = reportForm.validate(mapping, request); if (!errors.isEmpty()) { saveErrors(request, errors); return (mapping.findForward("edit")); } int maxRighe = Integer.parseInt(bundle .getMessage("report.max.righe.lista")); int totalRecords = ReportProtocolloDelegate.getInstance() .countProtocolliAssegnati(utente, reportForm.getUfficioCorrenteId()); if (totalRecords < 1) { ActionMessages msg = new ActionMessages(); msg.add("recordNotFound", new ActionMessage("nessun_dato")); saveMessages(request, msg); return (mapping.findForward("input")); } if (totalRecords > maxRighe) { errors.add("controllo.maxrighe", new ActionMessage( "controllo.maxrighe", "" + totalRecords, "registro protocolli assegnati", "" + maxRighe)); } else { // carica report parameter HashMap common = new HashMap(); common.put("ReportTitle", messages.getMessage("report.title.stampa_protocolli_assegnati")); common.put("ReportSubTitle",reportForm.getUfficioCorrentePath().substring( 0,reportForm.getUfficioCorrentePath().length() - 1)); common.put("Assegnatario", String.valueOf(reportForm.getUfficioCorrenteId())); common.put("print", "true"); reportForm.addReportType(ReportType.getIstanceByType(Parametri.FORMATO_HTML, common, messages)); reportForm.addReportType(ReportType.getIstanceByType(Parametri.FORMATO_PDF, common, messages)); reportForm.addReportType(ReportType.getIstanceByType(Parametri.FORMATO_XLS, common, messages)); } // remove form from memory // session.removeAttribute(mapping.getAttribute()); // forward to page for print choices if (!errors.isEmpty()) { saveErrors(request, errors); } return (mapping.findForward("input")); } else if ("true".equals(request.getParameter("print"))) { stampaReport(request, response); return null; } AlberoUfficiBO.impostaUfficio(utente, reportForm, ufficioCompleto); session.setAttribute(mapping.getAttribute(), reportForm); if (!errors.isEmpty()) { saveErrors(request, errors); } return (mapping.findForward("input")); } public void stampaReport(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ServletContext context = getServlet().getServletContext(); HttpSession session = request.getSession(); OutputStream os = response.getOutputStream(); try { File reportFile = new File(context.getRealPath("/") + FileConstants.STAMPA_PROTOCOLLI_ASSEGNATI_REPORT_COMPILED); JasperReport jasperReport = (JasperReport) JRLoader .loadObject(reportFile.getPath()); Utente utente = (Utente) session.getAttribute(Constants.UTENTE_KEY); String assegnatario = request.getParameter("Assegnatario"); int assegnatarioId = Integer.parseInt(assegnatario); Map parameters = new HashMap(); parameters.put("ReportTitle", request.getParameter("ReportTitle")); parameters.put("BaseDir", reportFile.getParentFile()); parameters.put("ReportSubTitle", request .getParameter("ReportSubTitle")); Collection c = ReportProtocolloDelegate.getInstance() .stampaProtocolliAssegnati(utente, assegnatarioId); // TODO:assegnatario CommonReportDS ds = new CommonReportDS(c); // TODO: Attenzione il report viene immagazinato in memoria, // grossi report potrebbero causare // problemi, in tali casi predisporre una struttura a Stream che // scrive su FS su file // temporanei JasperPrint jasperPrint = JasperFillManager.fillReport( jasperReport, parameters, ds); String exportFormat = request.getParameter("ReportFormat"); response.setHeader("Content-Disposition", "attachment;filename=protocolliAssegnati." + exportFormat); response.setHeader("Cache-control", ""); if ("PDF".equals(exportFormat)) { response.setContentType("application/pdf"); JRPdfExporter exporter = new JRPdfExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os); exporter.exportReport(); } else if ("XLS".equals(exportFormat)) { response.setContentType("application/vnd.ms-excel"); JRCsvExporter exporter = new JRCsvExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os); exporter.setParameter( JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); exporter.exportReport(); } else if ("TXT".equals(exportFormat)) { } else if ("XML".equals(exportFormat)) { response.setContentType("text/html"); JRXmlExporter exporter = new JRXmlExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os); exporter.exportReport(); } else if ("CSV".equals(exportFormat)) { JRCsvExporter exporter = new JRCsvExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os); exporter.exportReport(); // default format is HTML } else if ("".equals(exportFormat) || "HTML".equals(exportFormat)) { Map imagesMap = new HashMap(); // session.setAttribute("IMAGES_MAP", imagesMap); JRHtmlExporter exporter = new JRHtmlExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os); exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap); exporter.setParameter( JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, new Boolean(false)); /* * exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, * "image.jsp?image="); */ exporter.exportReport(); } } catch (Exception e) { logger.debug("Errore di compilazione", e); response.setContentType("text/plain"); e.printStackTrace(new PrintStream(os)); } finally { os.close(); } } }
20,761
https://github.com/dahlia-os/fuchsia-pine64-pinephone/blob/master/src/connectivity/weave/adaptation/configuration_manager_delegate_impl.cpp
Github Open Source
Open Source
BSD-3-Clause
2,022
fuchsia-pine64-pinephone
dahlia-os
C++
Code
1,174
4,503
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // clang-format off #include <Weave/DeviceLayer/internal/WeaveDeviceLayerInternal.h> #include <Weave/DeviceLayer/internal/GenericConfigurationManagerImpl.ipp> #include "src/connectivity/weave/adaptation/configuration_manager_delegate_impl.h" #include "src/connectivity/weave/adaptation/group_key_store_impl.h" // clang-format on #include <lib/fdio/fd.h> #include <lib/fdio/fdio.h> #include <lib/fit/defer.h> #include <lib/syslog/cpp/macros.h> #include <net/ethernet.h> #include <sys/stat.h> #include <unistd.h> #include <zircon/status.h> #include "src/lib/fsl/vmo/file.h" #include "src/lib/fsl/vmo/strings.h" namespace nl { namespace Weave { namespace DeviceLayer { namespace { using ::nl::Weave::DeviceLayer::Internal::EnvironmentConfig; using ::nl::Weave::DeviceLayer::Internal::GenericConfigurationManagerImpl; using ::nl::Weave::DeviceLayer::Internal::WeaveConfigManager; using ::nl::Weave::Profiles::Security::AppKeys::GroupKeyStoreBase; // Store path and keys for static device information. constexpr char kDeviceInfoStorePath[] = "/config/data/device_info.json"; constexpr char kDeviceInfoConfigKey_BleDeviceNamePrefix[] = "ble-device-name-prefix"; constexpr char kDeviceInfoConfigKey_DeviceId[] = "device-id"; constexpr char kDeviceInfoConfigKey_DeviceIdPath[] = "device-id-path"; constexpr char kDeviceInfoConfigKey_EnableWoBLE[] = "enable-woble"; constexpr char kDeviceInfoConfigKey_EnableWoBLEAdvertisement[] = "enable-woble-advertisement"; constexpr char kDeviceInfoConfigKey_FirmwareRevision[] = "firmware-revision"; constexpr char kDeviceInfoConfigKey_MfrDeviceCertPath[] = "mfr-device-cert-path"; constexpr char kDeviceInfoConfigKey_ProductId[] = "product-id"; constexpr char kDeviceInfoConfigKey_VendorId[] = "vendor-id"; // Maximum number of chars in hex for a uint64_t. constexpr int kWeaveDeviceIdMaxLength = 16; // Maximum size of Weave certificate. constexpr int kWeaveCertificateMaxLength = UINT16_MAX; } // unnamed namespace ConfigurationManagerDelegateImpl::ConfigurationManagerDelegateImpl() : device_info_(WeaveConfigManager::CreateReadOnlyInstance(kDeviceInfoStorePath)) {} WEAVE_ERROR ConfigurationManagerDelegateImpl::Init() { WEAVE_ERROR err = WEAVE_NO_ERROR; auto context = PlatformMgrImpl().GetComponentContextForProcess(); FX_CHECK(context->svc()->Connect(hwinfo_device_.NewRequest()) == ZX_OK) << "Failed to connect to hwinfo device service."; FX_CHECK(context->svc()->Connect(weave_factory_data_manager_.NewRequest()) == ZX_OK) << "Failed to connect to weave factory data manager service."; FX_CHECK(context->svc()->Connect(factory_store_provider_.NewRequest()) == ZX_OK) << "Failed to connect to factory store"; err = EnvironmentConfig::Init(); if (err != WEAVE_NO_ERROR) { return err; } err = static_cast<GenericConfigurationManagerImpl<ConfigurationManagerImpl>*>(impl_)->_Init(); if (err != WEAVE_NO_ERROR) { return err; } err = GetAndStoreHWInfo(); if (err != WEAVE_NO_ERROR && err != WEAVE_DEVICE_ERROR_CONFIG_NOT_FOUND) { return err; } err = GetAndStorePairingCode(); if (err != WEAVE_NO_ERROR && err != WEAVE_DEVICE_ERROR_CONFIG_NOT_FOUND) { return err; } return WEAVE_NO_ERROR; } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetDeviceId(uint64_t& device_id) { WEAVE_ERROR err = EnvironmentConfig::ReadConfigValue(EnvironmentConfig::kConfigKey_MfrDeviceId, device_id); if (err == WEAVE_NO_ERROR) { return WEAVE_NO_ERROR; } err = device_info_->ReadConfigValue(kDeviceInfoConfigKey_DeviceId, &device_id); if (err != WEAVE_DEVICE_ERROR_CONFIG_NOT_FOUND) { return err; } char path[PATH_MAX] = {'\0'}; size_t out_size; err = device_info_->ReadConfigValueStr(kDeviceInfoConfigKey_DeviceIdPath, path, sizeof(path), &out_size); if (err == WEAVE_NO_ERROR) { err = GetDeviceIdFromFactory(path, &device_id); FX_CHECK(err == WEAVE_NO_ERROR) << "Failed getting device id from factory at path: " << path; impl_->StoreManufacturerDeviceId(device_id); return err; } err = GetDeviceIdFromFactory(path, &device_id); if (err != WEAVE_NO_ERROR) { return err; } return impl_->StoreManufacturerDeviceId(device_id); } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetManufacturerDeviceCertificate(uint8_t* buf, size_t buf_size, size_t& out_len) { WEAVE_ERROR err = EnvironmentConfig::ReadConfigValueBin( EnvironmentConfig::kConfigKey_MfrDeviceCert, buf, buf_size, out_len); if (err == WEAVE_NO_ERROR) { return err; } err = GetAndStoreMfrDeviceCert(); if (err != WEAVE_NO_ERROR) { return err; } return EnvironmentConfig::ReadConfigValueBin(EnvironmentConfig::kConfigKey_MfrDeviceCert, buf, buf_size, out_len); } bool ConfigurationManagerDelegateImpl::IsFullyProvisioned() { return ConnectivityMgr().IsWiFiStationProvisioned() && // TODO(fxbug.dev/58252) Due to incomplete implementation of ThreadStackManager, this // predicate does not yet include the line `ConnectivityMgr().IsThreadProvisioned() &&`, // but should once complete. ConfigurationMgr().IsPairedToAccount() && ConfigurationMgr().IsMemberOfFabric(); } bool ConfigurationManagerDelegateImpl::IsPairedToAccount() { // By default, just use the generic implementation in Weave Device Layer. return static_cast<GenericConfigurationManagerImpl<ConfigurationManagerImpl>*>(impl_) ->_IsPairedToAccount(); } bool ConfigurationManagerDelegateImpl::IsMemberOfFabric() { // By default, just use the generic implementation in Weave Device Layer. return static_cast<GenericConfigurationManagerImpl<ConfigurationManagerImpl>*>(impl_) ->_IsMemberOfFabric(); } GroupKeyStoreBase* ConfigurationManagerDelegateImpl::GetGroupKeyStore() { return &group_key_store_; } bool ConfigurationManagerDelegateImpl::CanFactoryReset() { return true; } void ConfigurationManagerDelegateImpl::InitiateFactoryReset() { EnvironmentConfig::FactoryResetConfig(); } WEAVE_ERROR ConfigurationManagerDelegateImpl::ReadPersistedStorageValue(Key key, uint32_t& value) { WEAVE_ERROR err = EnvironmentConfig::ReadConfigValue(key, value); return (err == WEAVE_DEVICE_ERROR_CONFIG_NOT_FOUND) ? WEAVE_ERROR_PERSISTED_STORAGE_VALUE_NOT_FOUND : err; } WEAVE_ERROR ConfigurationManagerDelegateImpl::WritePersistedStorageValue(Key key, uint32_t value) { WEAVE_ERROR err = EnvironmentConfig::WriteConfigValue(key, value); return (err != WEAVE_NO_ERROR) ? WEAVE_ERROR_PERSISTED_STORAGE_FAIL : err; } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetVendorId(uint16_t& vendor_id) { return device_info_->ReadConfigValue(kDeviceInfoConfigKey_VendorId, &vendor_id); } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetProductId(uint16_t& product_id) { return device_info_->ReadConfigValue(kDeviceInfoConfigKey_ProductId, &product_id); } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetFirmwareRevision(char* buf, size_t buf_size, size_t& out_len) { return device_info_->ReadConfigValueStr(kDeviceInfoConfigKey_FirmwareRevision, buf, buf_size, &out_len); } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetBleDeviceNamePrefix(char* device_name_prefix, size_t device_name_prefix_size, size_t* out_len) { return device_info_->ReadConfigValueStr(kDeviceInfoConfigKey_BleDeviceNamePrefix, device_name_prefix, device_name_prefix_size, out_len); } bool ConfigurationManagerDelegateImpl::IsWoBLEEnabled() { bool is_enabled = false; device_info_->ReadConfigValue(kDeviceInfoConfigKey_EnableWoBLE, &is_enabled); return is_enabled; } bool ConfigurationManagerDelegateImpl::IsWoBLEAdvertisementEnabled() { bool is_enabled = IsWoBLEEnabled(); if (is_enabled) { device_info_->ReadConfigValue(kDeviceInfoConfigKey_EnableWoBLEAdvertisement, &is_enabled); } return is_enabled; } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetDeviceDescriptorTLV(uint8_t* buf, size_t buf_size, size_t& encoded_len) { return static_cast<GenericConfigurationManagerImpl<ConfigurationManagerImpl>*>(impl_) ->_GetDeviceDescriptorTLV(buf, buf_size, encoded_len); } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetAndStoreHWInfo() { fuchsia::hwinfo::DeviceInfo device_info; if (ZX_OK == hwinfo_device_->GetInfo(&device_info) && device_info.has_serial_number()) { return impl_->StoreSerialNumber(device_info.serial_number().c_str(), device_info.serial_number().length()); } return WEAVE_DEVICE_ERROR_CONFIG_NOT_FOUND; } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetAndStorePairingCode() { fuchsia::weave::FactoryDataManager_GetPairingCode_Result pairing_code_result; fuchsia::weave::FactoryDataManager_GetPairingCode_Response pairing_code_response; std::string pairing_code; char read_value[ConfigurationManager::kMaxPairingCodeLength + 1]; size_t read_value_size = 0; WEAVE_ERROR err; // If a pairing code is provided in config-data, it takes precedent over the // value provided by the factory data manager. err = device_info_->ReadConfigValueStr(EnvironmentConfig::kConfigKey_PairingCode, read_value, ConfigurationManager::kMaxPairingCodeLength + 1, &read_value_size); if (err == WEAVE_NO_ERROR) { return impl_->StorePairingCode(read_value, read_value_size); } // Otherwise, use the factory data manager as the source of truth. zx_status_t status = weave_factory_data_manager_->GetPairingCode(&pairing_code_result); if (ZX_OK != status || !pairing_code_result.is_response()) { return WEAVE_DEVICE_ERROR_CONFIG_NOT_FOUND; } pairing_code_response = pairing_code_result.response(); if (pairing_code_response.pairing_code.size() > ConfigurationManager::kMaxPairingCodeLength) { return WEAVE_DEVICE_ERROR_CONFIG_NOT_FOUND; } return impl_->StorePairingCode((const char*)pairing_code_response.pairing_code.data(), pairing_code_response.pairing_code.size()); } WEAVE_ERROR ConfigurationManagerDelegateImpl::GetAndStoreMfrDeviceCert() { char path[PATH_MAX] = {'\0'}; char mfr_cert[kWeaveCertificateMaxLength]; size_t out_size; zx_status_t status; WEAVE_ERROR err; err = device_info_->ReadConfigValueStr(kDeviceInfoConfigKey_MfrDeviceCertPath, path, sizeof(path), &out_size); if (err != WEAVE_NO_ERROR) { FX_LOGS(ERROR) << "No manufacturer device certificate was found"; return err; } status = ReadFactoryFile(path, mfr_cert, sizeof(mfr_cert), &out_size); if (status != ZX_OK) { FX_LOGS(ERROR) << "Failed getting manufacturer certificate from factory with status " << zx_status_get_string(status) << " for path: " << path; return WEAVE_DEVICE_ERROR_CONFIG_NOT_FOUND; } return impl_->StoreManufacturerDeviceCertificate(reinterpret_cast<uint8_t*>(mfr_cert), out_size); } zx_status_t ConfigurationManagerDelegateImpl::ReadFactoryFile(const char* path, char* buf, size_t buf_size, size_t* out_len) { fuchsia::io::DirectorySyncPtr factory_directory; zx_status_t status; struct stat statbuf; int dir_fd; // Open the factory store directory as a file descriptor. status = factory_store_provider_->GetFactoryStore(factory_directory.NewRequest()); if (status != ZX_OK) { FX_LOGS(ERROR) << "Failed to get factory store: " << zx_status_get_string(status); return status; } status = fdio_fd_create(factory_directory.Unbind().TakeChannel().release(), &dir_fd); if (status != ZX_OK || dir_fd < 0) { FX_LOGS(ERROR) << "Failed to open factory store: " << zx_status_get_string(status); return status; } auto close_dir_defer = fit::defer([&] { close(dir_fd); }); // Grab the fd of the corresponding file path and validate. int fd = openat(dir_fd, path, O_RDONLY); if (fd < 0) { FX_LOGS(ERROR) << "Failed to open " << path << ": " << strerror(errno); return ZX_ERR_IO; } auto close_fd_defer = fit::defer([&] { close(fd); }); // Check the size of the file. if (fstat(fd, &statbuf) < 0) { FX_LOGS(ERROR) << "Could not stat file: " << path << ": " << strerror(errno); return ZX_ERR_IO; } size_t file_size = static_cast<size_t>(statbuf.st_size); if (file_size > buf_size) { FX_LOGS(ERROR) << "File too large for buffer: File size = " << file_size << ", buffer size = " << buf_size; return ZX_ERR_BUFFER_TOO_SMALL; } // Read up to buf_size bytes into buf. size_t total_read = 0; ssize_t current_read = 0; while ((current_read = read(fd, buf + total_read, buf_size - total_read)) > 0) { total_read += current_read; } // Store the total size read. if (out_len) { *out_len = total_read; } // Confirm that the last read was successful. if (current_read < 0) { FX_LOGS(ERROR) << "Failed to read from file: " << strerror(errno); status = ZX_ERR_IO; } return status; } zx_status_t ConfigurationManagerDelegateImpl::GetDeviceIdFromFactory(const char* path, uint64_t* factory_device_id) { zx_status_t status; char output[kWeaveDeviceIdMaxLength + 1] = {'\0'}; status = ReadFactoryFile(path, output, kWeaveDeviceIdMaxLength, nullptr); if (status != ZX_OK) { FX_LOGS(ERROR) << "Failed to read " << path << ": " << zx_status_get_string(status); return status; } if (output[0] == '\0') { FX_LOGS(ERROR) << "File containing device ID was empty."; return ZX_ERR_IO; } *factory_device_id = strtoull(output, NULL, 16); if (errno == ERANGE) { FX_LOGS(ERROR) << "Failed to strtoull device ID: " << strerror(errno); return ZX_ERR_IO; } return ZX_OK; } } // namespace DeviceLayer } // namespace Weave } // namespace nl
49,692
https://github.com/andreaskuster/dace/blob/master/dace/codegen/targets/rtl.py
Github Open Source
Open Source
BSD-3-Clause, LicenseRef-scancode-unknown-license-reference
2,021
dace
andreaskuster
Python
Code
1,733
6,473
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. import itertools from typing import List, Tuple, Dict from dace import dtypes, config, registry, symbolic, nodes, sdfg from dace.sdfg import graph, state, find_input_arraynode, find_output_arraynode from dace.codegen import codeobject, dispatcher, prettycode from dace.codegen.targets import target, framecode from dace.codegen.targets.common import sym2cpp @registry.autoregister_params(name='rtl') class RTLCodeGen(target.TargetCodeGenerator): """ RTL Code Generator (SystemVerilog) """ title = 'RTL' target_name = 'rtl' languages = [dtypes.Language.SystemVerilog] def __init__(self, frame_codegen: framecode.DaCeCodeGenerator, sdfg: sdfg.SDFG): # store reference to sdfg self.sdfg: sdfg.SDFG = sdfg # store reference to frame code generator self.frame: framecode.DaCeCodeGenerator = frame_codegen # get dispatcher to register callbacks for allocation/nodes/.. code generators self.dispatcher: dispatcher.TargetDispatcher = frame_codegen.dispatcher # register node dispatcher -> generate_node(), predicate: process tasklets only self.dispatcher.register_node_dispatcher( self, lambda sdfg, node: isinstance(node, nodes.Tasklet) and node. language == dtypes.Language.SystemVerilog) # register all storage types that connect from/to an RTL tasklet for src_storage, dst_storage in itertools.product( dtypes.StorageType, dtypes.StorageType): self.dispatcher.register_copy_dispatcher( src_storage, dst_storage, None, self, lambda sdfg, dfg, src_node, dest_node: (isinstance(src_node, nodes.Tasklet) and src_node.language == dtypes.Language.SystemVerilog) or (isinstance(dest_node, nodes.Tasklet) and dest_node.language == dtypes.Language.SystemVerilog)) # local variables self.verilator_debug: bool = config.Config.get_bool( "compiler", "rtl", "verilator_enable_debug") self.code_objects: List[codeobject.CodeObject] = list() self.cpp_general_header_added: bool = False def generate_node(self, sdfg: sdfg.SDFG, dfg: state.StateSubgraphView, state_id: int, node: nodes.Node, function_stream: prettycode.CodeIOStream, callsite_stream: prettycode.CodeIOStream): # check instance type if isinstance(node, nodes.Tasklet): """ handle Tasklet: (1) generate in->tasklet (2) generate tasklet->out (3) generate tasklet """ # generate code to handle data input to the tasklet for edge in dfg.in_edges(node): # find input array src_node = find_input_arraynode(dfg, edge) # dispatch code gen (copy_memory) self.dispatcher.dispatch_copy(src_node, node, edge, sdfg, dfg, state_id, function_stream, callsite_stream) # generate code to handle data output from the tasklet for edge in dfg.out_edges(node): # find output array dst_node = find_output_arraynode(dfg, edge) # dispatch code gen (define_out_memlet) self.dispatcher.dispatch_output_definition( node, dst_node, edge, sdfg, dfg, state_id, function_stream, callsite_stream) # generate tasklet code self.unparse_tasklet(sdfg, dfg, state_id, node, function_stream, callsite_stream) else: raise RuntimeError( "Only tasklets are handled here, not {}. This should have been filtered by the predicate" .format(type(node))) def copy_memory(self, sdfg: sdfg.SDFG, dfg: state.StateSubgraphView, state_id: int, src_node: nodes.Node, dst_node: nodes.Node, edge: graph.MultiConnectorEdge, function_stream: prettycode.CodeIOStream, callsite_stream: prettycode.CodeIOStream): """ Generate input/output memory copies from the array references to local variables (i.e. for the tasklet code). """ if isinstance(edge.src, nodes.AccessNode) and isinstance( edge.dst, nodes.Tasklet): # handle AccessNode->Tasklet if isinstance(dst_node.in_connectors[edge.dst_conn], dtypes.pointer): # pointer accessor line: str = "{} {} = &{}[0];".format( dst_node.in_connectors[edge.dst_conn].ctype, edge.dst_conn, edge.src.data) elif isinstance(dst_node.in_connectors[edge.dst_conn], dtypes.vector): # vector accessor line: str = "{} {} = *({} *)(&{}[0]);".format( dst_node.in_connectors[edge.dst_conn].ctype, edge.dst_conn, dst_node.in_connectors[edge.dst_conn].ctype, edge.src.data) else: # scalar accessor line: str = "{}* {} = &{}[0];".format( dst_node.in_connectors[edge.dst_conn].ctype, edge.dst_conn, edge.src.data) else: raise RuntimeError( "Not handling copy_memory case of type {} -> {}.".format( type(edge.src), type(edge.dst))) # write accessor to file callsite_stream.write(line) def define_out_memlet(self, sdfg: sdfg.SDFG, dfg: state.StateSubgraphView, state_id: int, src_node: nodes.Node, dst_node: nodes.Node, edge: graph.MultiConnectorEdge, function_stream: prettycode.CodeIOStream, callsite_stream: prettycode.CodeIOStream): """ Generate output copy code (handled within the rtl tasklet code). """ if isinstance(edge.src, nodes.Tasklet) and isinstance( edge.dst, nodes.AccessNode): if isinstance(src_node.out_connectors[edge.src_conn], dtypes.pointer): # pointer accessor line: str = "{} {} = &{}[0];".format( src_node.out_connectors[edge.src_conn].ctype, edge.src_conn, edge.dst.data) elif isinstance(src_node.out_connectors[edge.src_conn], dtypes.vector): # vector accessor line: str = "{} {} = *({} *)(&{}[0]);".format( src_node.out_connectors[edge.src_conn].ctype, edge.src_conn, src_node.out_connectors[edge.src_conn].ctype, edge.dst.data) else: # scalar accessor line: str = "{}* {} = &{}[0];".format( src_node.out_connectors[edge.src_conn].ctype, edge.src_conn, edge.dst.data) else: raise RuntimeError( "Not handling define_out_memlet case of type {} -> {}.".format( type(edge.src), type(edge.dst))) # write accessor to file callsite_stream.write(line) def get_generated_codeobjects(self): """ Return list of code objects (that are later generating code files). """ return self.code_objects @property def has_initializer(self): """ Disable initializer method generation. """ return False @property def has_finalizer(self): """ Disable exit/finalizer method generation. """ return False @staticmethod def cmake_options(): """ Process variables to be exposed to the CMakeList.txt script. """ # get flags from config verbose = config.Config.get_bool("compiler", "rtl", "verbose") verilator_flags = config.Config.get("compiler", "rtl", "verilator_flags") verilator_lint_warnings = config.Config.get_bool( "compiler", "rtl", "verilator_lint_warnings") # create options list options = [ "-DDACE_RTL_VERBOSE=\"{}\"".format(verbose), "-DDACE_RTL_VERILATOR_FLAGS=\"{}\"".format(verilator_flags), "-DDACE_RTL_VERILATOR_LINT_WARNINGS=\"{}\"".format( verilator_lint_warnings) ] return options def generate_rtl_parameters(self, constants): # construct parameters module header if len(constants) == 0: return str() else: return "#(\n{}\n)".format(" " + "\n".join([ "{} parameter {} = {}".format("," if i > 0 else "", key, sym2cpp(constants[key])) for i, key in enumerate(constants) ])) def generate_rtl_inputs_outputs(self, sdfg, tasklet): # construct input / output module header inputs = list() for inp in tasklet.in_connectors: # add vector index idx_str = "" # catch symbolic (compile time variables) check_issymbolic([ tasklet.in_connectors[inp].veclen, tasklet.in_connectors[inp].bytes ], sdfg) # extract parameters vec_len = int( symbolic.evaluate(tasklet.in_connectors[inp].veclen, sdfg.constants)) total_size = int( symbolic.evaluate(tasklet.in_connectors[inp].bytes, sdfg.constants)) # generate vector representation if vec_len > 1: idx_str = "[{}:0]".format(vec_len - 1) # add element index idx_str += "[{}:0]".format(int(total_size / vec_len) * 8 - 1) # generate padded string and add to list inputs.append(", input{padding}{idx_str} {name}".format( padding=" " * (17 - len(idx_str)), idx_str=idx_str, name=inp)) outputs = list() for inp in tasklet.out_connectors: # add vector index idx_str = "" # catch symbolic (compile time variables) check_issymbolic([ tasklet.out_connectors[inp].veclen, tasklet.out_connectors[inp].bytes ], sdfg) # extract parameters vec_len = int( symbolic.evaluate(tasklet.out_connectors[inp].veclen, sdfg.constants)) total_size = int( symbolic.evaluate(tasklet.out_connectors[inp].bytes, sdfg.constants)) # generate vector representation if vec_len > 1: idx_str = "[{}:0]".format(vec_len - 1) # add element index idx_str += "[{}:0]".format(int(total_size / vec_len) * 8 - 1) # generate padded string and add to list outputs.append(", output reg{padding}{idx_str} {name}".format( padding=" " * (12 - len(idx_str)), idx_str=idx_str, name=inp)) return inputs, outputs def generate_cpp_inputs_outputs(self, tasklet): # generate cpp input reading/output writing code """ input: for vectors: for (int i = 0; i < WIDTH; i++){{ model->a[i] = a[i]; }} for scalars: model->a = a[0]; output: for vectors: for(int i = 0; i < WIDTH; i++){{ b[i] = (int)model->b[i]; }} for scalars: b[0] = (int)model->b; """ input_read_string = "\n".join([ "model->{name} = {name}[in_ptr++];".format( name=var_name) if isinstance(tasklet.in_connectors[var_name], dtypes.pointer) else """\ for(int i = 0; i < {veclen}; i++){{ model->{name}[i] = {name}[i]; }}\ """.format(veclen=tasklet.in_connectors[var_name].veclen, name=var_name) if isinstance(tasklet.in_connectors[var_name], dtypes.vector) else "model->{name} = {name}[in_ptr++];".format(name=var_name) for var_name in tasklet.in_connectors ]) output_read_string = "\n".join([ "{name}[out_ptr++] = (int)model->{name};".format( name=var_name) if isinstance(tasklet.out_connectors[var_name], dtypes.pointer) else """\ for(int i = 0; i < {veclen}; i++){{ {name}[i] = (int)model->{name}[i]; }}\ """.format(veclen=tasklet.out_connectors[var_name].veclen, name=var_name) if isinstance(tasklet.out_connectors[var_name], dtypes.vector) else "{name}[out_ptr++] = (int)model->{name};".format(name=var_name) for var_name in tasklet.out_connectors ]) # return generated strings return input_read_string, output_read_string def generate_cpp_vector_init(self, tasklet): init_vector_string = "\n".join([ """\ for(int i = 0; i < {veclen}; i++){{ model->{name}[i] = 0; }}\ """.format(veclen=tasklet.in_connectors[var_name].veclen, name=var_name) if isinstance(tasklet.in_connectors[var_name], dtypes.vector) else "" for var_name in tasklet.in_connectors ]) return "// initialize vector\n" if len( init_vector_string) > 0 else "" + init_vector_string def generate_cpp_num_elements(self): # TODO: compute num_elements=#elements that enter/leave the pipeline, for now we assume in_elem=out_elem (i.e. no reduction) return "int num_elements = {};".format(1) def generate_cpp_internal_state(self, tasklet): internal_state_str = " ".join([ "{}=0x%x".format(var_name) for var_name in { **tasklet.in_connectors, **tasklet.out_connectors } ]) internal_state_var = ", ".join([ "model->{}".format(var_name) for var_name in { **tasklet.in_connectors, **tasklet.out_connectors } ]) return internal_state_str, internal_state_var def unparse_tasklet(self, sdfg: sdfg.SDFG, dfg: state.StateSubgraphView, state_id: int, node: nodes.Node, function_stream: prettycode.CodeIOStream, callsite_stream: prettycode.CodeIOStream): # extract data state = sdfg.nodes()[state_id] tasklet = node # construct variables paths unique_name: str = "top_{}_{}_{}".format(sdfg.sdfg_id, sdfg.node_id(state), state.node_id(tasklet)) # generate system verilog module components parameter_string: str = self.generate_rtl_parameters(sdfg.constants) inputs, outputs = self.generate_rtl_inputs_outputs(sdfg, tasklet) # create rtl code object (that is later written to file) self.code_objects.append( codeobject.CodeObject( name="{}".format(unique_name), code=RTLCodeGen.RTL_HEADER.format(name=unique_name, parameters=parameter_string, inputs="\n".join(inputs), outputs="\n".join(outputs)) + tasklet.code.code + RTLCodeGen.RTL_FOOTER, language="sv", target=RTLCodeGen, title="rtl", target_type="", additional_compiler_kwargs="", linkable=True, environments=None)) # generate verilator simulation cpp code components inputs, outputs = self.generate_cpp_inputs_outputs(tasklet) vector_init = self.generate_cpp_vector_init(tasklet) num_elements = self.generate_cpp_num_elements() internal_state_str, internal_state_var = self.generate_cpp_internal_state( tasklet) # add header code to stream if not self.cpp_general_header_added: sdfg.append_global_code( cpp_code=RTLCodeGen.CPP_GENERAL_HEADER_TEMPLATE.format( debug_include="// generic includes\n#include <iostream>" if self.verilator_debug else "")) self.cpp_general_header_added = True sdfg.append_global_code( cpp_code=RTLCodeGen.CPP_MODEL_HEADER_TEMPLATE.format( name=unique_name)) # add main cpp code to stream callsite_stream.write(contents=RTLCodeGen.CPP_MAIN_TEMPLATE.format( name=unique_name, inputs=inputs, outputs=outputs, num_elements=num_elements, vector_init=vector_init, internal_state_str=internal_state_str, internal_state_var=internal_state_var, debug_sim_start="std::cout << \"SIM {name} START\" << std::endl;" if self.verilator_debug else "", debug_feed_element="std::cout << \"feed new element\" << std::endl;" if self.verilator_debug else "", debug_export_element="std::cout << \"export element\" << std::endl;" if self.verilator_debug else "", debug_internal_state=""" // report internal state VL_PRINTF("[t=%lu] clk_i=%u rst_i=%u valid_i=%u ready_i=%u valid_o=%u ready_o=%u \\n", main_time, model->clk_i, model->rst_i, model->valid_i, model->ready_i, model->valid_o, model->ready_o); VL_PRINTF("{internal_state_str}\\n", {internal_state_var}); std::cout << std::flush; """.format(internal_state_str=internal_state_str, internal_state_var=internal_state_var) if self.verilator_debug else "", debug_read_input_hs= "std::cout << \"remove read_input_hs flag\" << std::endl;" if self.verilator_debug else "", debug_output_hs= "std::cout << \"remove write_output_hs flag\" << std::endl;" if self.verilator_debug else "", debug_sim_end="std::cout << \"SIM {name} END\" << std::endl;" if self.verilator_debug else ""), sdfg=sdfg, state_id=state_id, node_id=node) CPP_GENERAL_HEADER_TEMPLATE = """\ {debug_include} // verilator includes #include <verilated.h> """ CPP_MODEL_HEADER_TEMPLATE = """\ // include model header, generated from verilating the sv design #include "V{name}.h" """ CPP_MAIN_TEMPLATE = """\ {debug_sim_start} vluint64_t main_time = 0; // instantiate model V{name}* model = new V{name}; // apply initial input values model->rst_i = 0; // no reset model->clk_i = 0; // neg clock model->valid_i = 0; // not valid model->ready_i = 0; // not ready model->eval(); {vector_init} // reset design model->rst_i = 1; model->clk_i = 1; // rising model->eval(); model->clk_i = 0; // falling model->eval(); model->rst_i = 0; model->clk_i = 1; // rising model->eval(); model->clk_i = 0; // falling model->eval(); // simulate until in_handshakes = out_handshakes = num_elements bool read_input_hs = false, write_output_hs = false; int in_ptr = 0, out_ptr = 0; {num_elements} while (out_ptr < num_elements) {{ // increment time main_time++; // check if valid_i and ready_o have been asserted at the rising clock edge -> input read handshake if (model->ready_o == 1 && model->valid_i == 1){{ read_input_hs = true; }} // feed new element if(model->valid_i == 0 && in_ptr < num_elements){{ {debug_feed_element} {inputs} model->valid_i = 1; }} // export element if(model->valid_o == 1){{ {debug_export_element} {outputs} model->ready_i = 1; }} // check if valid_o and ready_i have been asserted at the rising clock edge -> output write handshake if (model->ready_i == 1 && model->valid_o == 1){{ write_output_hs = true; }} // positive clock edge model->clk_i = !model->clk_i; model->eval(); {debug_internal_state} // check if valid_i and ready_o have been asserted at the rising clock edge if (read_input_hs){{ // remove valid_i flag model->valid_i = 0; {debug_read_input_hs} read_input_hs = false; }} // check if valid_o and ready_i have been asserted at the rising clock edge if (write_output_hs){{ // remove ready_i flag model->ready_i = 0; {debug_output_hs} write_output_hs = false; }} // negative clock edge model->clk_i = !model->clk_i; model->eval(); }} {debug_internal_state} // final model cleanup model->final(); // clean up resources delete model; model = NULL; {debug_sim_end} """ RTL_HEADER = """\ module {name} {parameters} ( input clk_i // convention: clk_i clocks the design , input rst_i // convention: rst_i resets the design , input valid_i , input ready_i {inputs} , output reg ready_o , output reg valid_o {outputs} ); """ RTL_FOOTER = """\ endmodule """ def check_issymbolic(iterator: iter, sdfg): for item in iterator: # catch symbolic (compile time variables) if symbolic.issymbolic(item, sdfg.constants): raise ValueError( "Please use sdfg.specialize to make the following symbol(s) constant: {}" .format(", ".join([ str(x) for x in item.free_symbols if str(x) not in sdfg.constants ])))
15,010
https://github.com/flyfire/Programming-Notes-Code/blob/master/Python/Python3-Base/13_Network/Server/CoroutinesServer.py
Github Open Source
Open Source
Apache-2.0
2,019
Programming-Notes-Code
flyfire
Python
Code
50
209
######################### # 协程非阻塞服务器 ######################### import gevent from gevent import socket, monkey # 如果有IO操作,需要调用此函数 monkey.patch_all() def handle_request(conn): while True: data = conn.recv(1024) if not data: conn.close() break print("receive:", data) conn.send(data) def server(port): s = socket.socket() s.bind(('', port)) s.listen(5) while True: cli, addr = s.accept() gevent.spawn(handle_request, cli) if __name__ == '__main__': server(7788)
7,940
https://github.com/dlang/dub/blob/master/test/test_registry.d
Github Open Source
Open Source
MIT
2,023
dub
dlang
D
Code
208
642
#!/usr/bin/env dub /+dub.sdl: dependency "vibe-d:http" version="~>0.9" versions "VibeNoSSL" +/ import std.array; import vibe.core.args; import vibe.core.core; import vibe.core.path; import vibe.http.fileserver; import vibe.http.router; import vibe.http.server; /* Provide a special API File Handler as Vibe.d's builtin serveStaticFiles doesn't deal well with query params. This will blindly check if the requestURI payload exists on the filesystem and if so, return the file. It replaces `?` with `__` for Windows compatibility. Params: skip = initial part of the requestURI to skip over folder = the base directory from which to serve API requests from */ auto apiFileHandler(string skip, string folder) { import std.functional : toDelegate; void handler(HTTPServerRequest req, HTTPServerResponse res) { import std.algorithm : skipOver; import std.path : buildPath; import std.file : exists; // ? can't be part of path names on Windows auto requestURI = req.requestURI.replace("?", "__"); requestURI.skipOver(skip); const reqFile = buildPath(folder, requestURI); if (reqFile.exists) { return req.sendFile(res, PosixPath(reqFile)); } } return toDelegate(&handler); } void main(string[] args) { import std.conv; immutable folder = readRequiredOption!string("folder", "Folder to service files from."); immutable port = readRequiredOption!ushort("port", "Port to use"); auto router = new URLRouter; router.get("stop", (HTTPServerRequest req, HTTPServerResponse res){ res.writeVoidBody; exitEventLoop(); }); router.get("/packages/gitcompatibledubpackage/1.0.2.zip", (req, res) { res.writeBody("", HTTPStatus.badGateway); }); router.get("*", folder.serveStaticFiles); router.get("/fallback/*", folder.serveStaticFiles(new HTTPFileServerSettings("/fallback"))); router.get("/api/*", apiFileHandler("/", folder)); router.get("/fallback/api/*", apiFileHandler("/fallback/", folder)); listenHTTP(text(":", port), router); runApplication(); }
19,477
https://github.com/pleuvoir/spring-framework-1.2.9/blob/master/src/org/springframework/context/event/SimpleApplicationEventMulticaster.java
Github Open Source
Open Source
Apache-2.0
null
spring-framework-1.2.9
pleuvoir
Java
Code
232
434
/* * Copyright 2002-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.event; import java.util.Iterator; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; /** * Simple implementation of the ApplicationEventMulticaster interface. * * <p>Multicasts all events to all registered listeners, leaving it up to * the listeners to ignore events that they are not interested in. * Listeners will usually perform corresponding <code>instanceof</code> * checks on the passed-in event object. * * <p>All listeners are invoked in the calling thread. This allows the danger of * a rogue listener blocking the entire application, but adds minimal overhead. * * <p>An alternative implementation could be more sophisticated in both these respects. * * @author Rod Johnson * @author Juergen Hoeller */ public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster { public void multicastEvent(ApplicationEvent event) { for (Iterator it = getApplicationListeners().iterator(); it.hasNext();) { ApplicationListener listener = (ApplicationListener) it.next(); listener.onApplicationEvent(event); } } }
16,235
https://github.com/alicesilva/Projeto-Si1/blob/master/disque-saude-frontend-master/app/core/controller/gerenciaQueixasController.js
Github Open Source
Open Source
MIT
2,017
Projeto-Si1
alicesilva
JavaScript
Code
74
316
app.controller("gerenciaQueixasController", function ($scope, queixaService, $location, toastr) { $scope.queixas = ""; var getQueixas = function () { queixaService.getQueixas() .then(function success(response) { $scope.queixas = response.data; console.log(response.data); }) }; getQueixas(); $scope.addComentario = function(id, comentario){ queixaService.addComentario(id, comentario) .then(function success(response){ console.log(response.data) }, function error(error){ toastr.error("Erro ao adicionar comentário!") }); } $scope.modificaStatusDaQueixa = function(id, status){ queixaService.modificaStatus(id, status) .then(function success(response){ console.log(response.data) }, function error(error){ toastr.error("Erro ao modificar o status da queixa!") }); } $scope.voltar = function () { $location.path("/menu_adm") } });
13,575
https://github.com/CSCfi/pouta-ansible-cuda-demo/blob/master/.gitignore
Github Open Source
Open Source
MIT
2,017
pouta-ansible-cuda-demo
CSCfi
Ignore List
Code
4
15
hosts inventory roles/ ssh.config
12,703
https://github.com/just-drive/Tama/blob/master/Tama/Plugins/tama_drawer/tamaframe.py
Github Open Source
Open Source
BSD-3-Clause
2,021
Tama
just-drive
Python
Code
1,966
6,620
from win32ctypes.pywin32 import win32api import win32.lib.win32con as win32con import win32.win32gui as win32gui from wx.lib.delayedresult import startWorker import PIL import wx import wx.aui as aui import wx.adv as adv import wx.lib.newevent import os import threading import datetime import random import mouse from screeninfo import get_monitors import Plugins.tama_drawer.tama_drawer_events from Plugins.tama_drawer.tama_drawer_events import TamaMoodEvent from Plugins.tama_drawer.tama_drawer_events import EVT_TAMA_MOOD # # The two tools below were acquired from the below wxPythonWiki tutorial: # https://wiki.wxpython.org/WorkingWithImages # import Plugins.tama_drawer.ImgConv # wxImage <==> PilImage import Plugins.tama_drawer.BitmapManip # mask wxBmap <==> PilImage <== file from PIL import Image, ImageDraw, ImageChops, ImageSequence def GetRamdomWxColorAndInverse() : r, g, b = (random.randint(0, 127), random.randint(0, 127), random.randint(0, 127)) if random.randint(0, 1) : # Gaurantee a large contrast r, g, b = (255-r, 255-g, 255-b) #end if R, G, B, = (255-r, 255-g, 255-b) # The inverse return (wx.Colour(r, g, b), wx.Colour(R, G, B)) def CreateInnerMaskBmapFromOuterMask( srcBmap ) : """ Derive the inner mask wxBitmap from the Outer mask wxBitmap. The srcBmap must be "well behaved" in that a continuous border must present so that a floodfill to the perimeter area will not reach into the inner area. The border color must be >=128. So, the srcBmap consists of a transparent/BLACK perimeter, an white/opaque frame border and a transparent/BLACK inner area. When completed, the outer_area+border will be transparent/BLACK, the parent's frame border will be transparent/BLACK and the inner area will be opaque/WHITE. 1. outer perimeter (black) --> Floodfill to white/255 Now both perimeter and border are white). 2. Invert the image and return as a wxBitmap.. """ # Start with an 'L' Pil copy of the RGB input wxBitmap. dstPilImage = ImgConv.PilImageFromWxBitmap( srcBmap ).convert( 'L' ) # Make sure the image is quantized to binary. dstPilImage = dstPilImage.point(lambda i: (i / 128) * 255) size = dstPilImage.size ImageDraw.floodfill( dstPilImage, (0, 0), (255) ) return ImgConv.WxBitmapFromPilImage( ImageChops.invert( dstPilImage ) ) #end def #------------------------------------------------------------------------------ class TamaFrame(wx.Frame): """ Shaped window from disk image files and optional disk transparency mask files. The user cannot resize the window because there are no resizing decorations ! The entire popup is just a control-less bitmap image. However, all that is visible (opaque) can be repositioned by dragging. """ def __init__( self, parent, image_filename=None, mask_filename=None, outer_or_inner_window=1, # default to a shaped frame window posn=(0, 0), bgTransparency=100 ) : style = ( wx.STAY_ON_TOP ) """ The TamaFrame inherits from wx.Frame, and thus receives the ability to be used in a wxpython (wx) app This is the window that is created for the application, Tama's actual form will be inside of this frame, and the frame itself is only slightly visible (This can be tweaked). """ wx.Frame.__init__(self, parent, wx.ID_ANY, style=style, title = 'Tama', name = 'Tama') self.bgTransparency = bgTransparency self.SetBackgroundStyle(wx.BG_STYLE_ERASE) self.image_filename = image_filename self.image_wxBitmaps = [] self.parent = parent self.current_bitmap = None self.timer = wx.Timer(self, wx.ID_ANY) self.timer.Start(60) #Will be used to get locations of screens, so that the correct #screen is drawn to when drawing with a ScreenDC self.screens = [] self.screen_positions = [] for screen in get_monitors(): self.screens.append(screen) #Bounding_boxes is a list of rect objects where bounding_boxes[0] #Represents the client size of screen[0] #This will be used to draw with a ScreenDC, which considers all #monitors to be one screen. self.bounding_boxes = [] for screen_idx in range(len(self.screens)): self.bounding_boxes.append(wx.Display(screen_idx).GetClientArea()) self.SetTitle('Tama') self.SetSize( (250, 250) ) self.current_screen = wx.Display().GetFromPoint((self.bounding_boxes[0].GetX(), self.bounding_boxes[0].GetY())) self.SetPosition((self.bounding_boxes[0].GetX(), self.bounding_boxes[0].GetY())) self.current_mood = None self.last_mouse_pos = wx.Point(0,0) self.tama_widget = TamaWidget(self) self.previous_update = datetime.datetime.now() self.screenContext = None self.is_border_window = outer_or_inner_window self.is_inner_window = not outer_or_inner_window if wx.Platform == '__WXGTK__' : # GTK-only, use as an event handler. self.Bind( wx.EVT_WINDOW_CREATE, self.DrawWindow ) #end if #------------------------------ # This handler is always required. self.Bind(wx.EVT_PAINT, self.OnPaint) self.Bind(wx.EVT_TIMER, self.OnTimer) #self.Bind(wx.EVT_ERASE_BACKGROUND, self.DoNothing) # Enable the user to quit the app by pressing <ESC>. self.Bind( wx.EVT_KEY_UP, self.OnKeyDown ) # Comment this to disable. # Enable window dragging. self.Bind( wx.EVT_MOTION, self.OnMotion ) # Comment this to disable. self.Bind(wx.EVT_LEFT_UP, self.OnRelease) self.Bind(wx.EVT_CLOSE, parent.OnClose) #mouse.on_right_click(self.ShowRightMenu) self.Bind(wx.EVT_CONTEXT_MENU, self.ShowRightMenu) #Linux and Windows will have different ways to create this kind of transparent frame. if wx.Platform == '__WXMSW__': hwnd = self.GetHandle() extendedStyleSettings = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE) win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, extendedStyleSettings | win32con.WS_EX_LAYERED | win32con.WS_CHILD) win32gui.SetLayeredWindowAttributes(hwnd, 0, 255, win32con.LWA_COLORKEY) self.SetTransparent(190) elif wx.Platform == '__WXGTK__': pass else: pass self.SetDoubleBuffered(True) self.Layout() self.Show() #-------------------------------------------- def SetOtherWindow( self, otherWindow ) : """ Allow the other ShapedWindow to be referenced in this instantiation. """ self.otherWindow = otherWindow #end def def SetMyPosition( self, posn ) : """ This is for "OtherWindow" to call, never "self".""" self.SetPosition( posn ) #end def def OnPaint( self, event ) : self.DrawWindow() event.Skip() return # Very important to let all higher level handlers be called. #end def def DoNothing(self, event): pass def SetImage(self, pil_image): if pil_image: width, height = pil_image.size self.image_wxBitmaps.append(wx.BitmapFromBuffer(width, height, pil_image.convert('RGB').tobytes(), pil_image.convert('RGBA').getchannel('A').tobytes())) return def DrawWindow(self) : """Implement window drawing at any time.""" # screenContext will be drawn to after memoryContext is given the right combined bitmap context = wx.PaintDC(self) # Blit will copy the pixels from self.combined_image, which is a # MemoryDC that contains the current Tama Image to be displayed. # This image is newly generated within the Tama task system, in order to # reduce image display time. if len(self.image_wxBitmaps) and context.CanDrawBitmap(): context.DrawBitmap(self.image_wxBitmaps.pop(), 0, 0, False) del context #end def DrawWindow #-------------------------------------------- def OnTimer(self, event): if not self.tama_widget.is_grabbed() and self.tama_widget.is_moving(): self.move_direction() self.SetImage(self.tama_widget.next()) self.Refresh() return def show_window_pinning(self, event): self.parent.frames[2].Show() return def show_copyx(self, event): self.parent.frames[3].Show() return def show_macro_recorder(self, event): self.parent.frames[4].Show() return def show_settings(self, event): self.parent.frames[5].Show() return def ShowRightMenu(self, *args) : """ Create and show a Context Menu """ # only do this part the first time so the events are only bound once if not hasattr(self, "itemOneId"): self.itemOneId = wx.NewId() self.itemTwoId = wx.NewId() self.itemThreeId = wx.NewId() self.itemFourId = wx.NewId() self.itemFiveId = wx.NewId() self.Bind(wx.EVT_MENU, self.show_window_pinning, id=self.itemOneId) self.Bind(wx.EVT_MENU, self.show_copyx, id=self.itemTwoId) self.Bind(wx.EVT_MENU, self.show_macro_recorder, id=self.itemThreeId) self.Bind(wx.EVT_MENU, self.show_settings, id=self.itemFourId) self.Bind(wx.EVT_MENU, self.parent.OnClose, id=self.itemFiveId) # build the menu menu = wx.Menu() itemOne = menu.Append(self.itemOneId, "Pin a Window...") itemTwo = menu.Append(self.itemTwoId, "Copy X...") itemThree = menu.Append(self.itemThreeId, "Record Mouse Events...") itemFour = menu.Append(self.itemFourId, "Settings") itemFive = menu.Append(self.itemFiveId, "Exit") # show the popup menu self.PopupMenu(menu) menu.Destroy() def OnKeyDown( self, event ) : """Quit the app if the user presses Q, q or Esc""" keyCode = event.GetKeyCode() quitCodes = [27, ord('Q'), ord('q')] event.Skip() # Allow any following event processing. if (keyCode in quitCodes) : self.Close( force=True ) #end if #end def #-------------------------------------------- def OnMotion( self, event ) : """Implement window client area dragging since this window has no frame to grab.""" if not event.Dragging() : # Mouse is moving but no button is down. self.dragPosn = None return #end if #self.CaptureMouse() if self.dragPosn == None : # Previous non-dragging mouse position # Capture the first mouse coord after pressing any button self.dragPosn = event.GetPosition() else: if not self.tama_widget.is_grabbed(): self.tama_widget.is_grabbed(True) currPosn = event.GetPosition() self.current_screen = wx.Display().GetFromWindow(self) displacement = self.dragPosn - currPosn newPosn = self.GetPosition() - displacement self.SetPosition( newPosn ) self.Update() def move_direction(self): window_pos = self.GetScreenPosition() if self.tama_widget.is_moving() and 'Move' in self.tama_widget.get_anim_name(): #box represents the client area of the current screen that Tama is located on. #and the upper left corner does not have to be 0,0 box = self.bounding_boxes[self.current_screen] if self.tama_widget.get_movement_direction() == 'Move Left': if self.bounding_boxes[self.current_screen].Contains( wx.Point(window_pos[0]-2, window_pos[1])): self.Move(window_pos[0]-2, window_pos[1]) else: self.tama_widget.is_moving(False) elif self.tama_widget.get_movement_direction() == 'Move Right': if self.bounding_boxes[self.current_screen].Contains( wx.Point(window_pos[0] + self.GetSize().GetWidth(), window_pos[1])): self.Move(window_pos[0]+2, window_pos[1]) else: self.tama_widget.is_moving(False) else: pass self.Update() def OnRelease(self, event): if self.tama_widget.is_grabbed(): self.tama_widget.is_grabbed(False) def needs_update(self): return self.tama_widget.needs_update() def needs_mood(self): if self.current_mood is None: return True return False def generate(self, event): if self.tama_widget.is_moving(): self.tama_widget.is_moving(False, None) if 'Sleeping' in event.get_modifiers(): self.tama_widget.set_animation('Sleeping') elif 'Eating' in event.get_modifiers(): self.tama_widget.set_animation('Eating') elif 'Thinking_of_Food' in event.get_modifiers(): self.tama_widget.set_animation('Thinking_of_Food') else: self.tama_widget.set_animation('Idle') self.Refresh() return def set_current_mood(self, current_mood): self.tama_widget.set_current_mood(current_mood) self.Show() return def get_bounding_boxes(self): return self.bounding_boxes def OnClose(self, e): e.Skip() class TamaWidget(): """ Holds the processes that handle generating Tama from a stack of layers that are provided via (tama_stream) It will yield images from tama_generate() as the animation is changed by a current_mood update. """ def __init__(self, parent): self.assets_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Assets") self.parent = parent self.available_folders = [] self.current_mood = None self.animation_duration = 0 self.frame_idx = 0 #self.tama_generator = wx.Process() self.current_animation_name = 'Idle' self.idle_animation_path = os.path.join(os.path.join(self.assets_folder, 'Idle'), 'Idle_0.gif') self.current_folder_animations = [self.idle_animation_path] #GenericAnimationCtrl is used here in order to detect when an animation is done playing. self.current_gif = Image.open(self.idle_animation_path) self.current_animation = [] self.prev_animation = None self.grabbed = False self.moving = False self.direction = None def set_current_mood(self, current_mood): self.current_mood = current_mood return def get_movement_direction(self): return self.direction def needs_update(self): if (self.is_grabbed() and self.current_animation_name != 'Grabbed') \ or (not self.is_grabbed() and self.current_animation_name == 'Grabbed'): return True elif self.frame_idx - self.animation_duration >= -1: return True return False def get_current_animation(self): if self.current_animation: return self.current_animation[self.frame_idx] return None def get_anim_name(self): return self.current_animation_name # Returns the current frame and increments the frame_idx by one. def next(self): if self.frame_idx >= self.animation_duration-1: self.set_animation(self.current_animation_name) im = self.get_current_animation() if im: self.frame_idx += 1 return im else: return None def is_grabbed(self, ishe = None): ''' This allows other classes to "grab" Tama as well. Returns whether or not 'grabbed' animations will play if used without the bool Sets grabbed animations to play and returns the screen position if used with the bool ''' if ishe is None: return self.grabbed self.grabbed = ishe if self.is_moving(): if ishe == True: if 'Move' not in self.current_animation_name \ and 'Grabbed' not in self.current_animation_name: self.prev_animation = self.current_animation_name self.set_animation('Grabbed') self.is_moving(False) if ishe == False: return else: if ishe == True: if 'Move' not in self.current_animation_name \ and 'Grabbed' not in self.current_animation_name: self.prev_animation = self.current_animation_name self.set_animation('Grabbed') if ishe == False: self.set_animation(self.prev_animation) def is_moving(self, ishe = None, dir = -1): ''' This allows other classes to trigger Tama left-right movements Returns whether or not moving animations are playing Sets moving animations to play ''' if ishe is None: return self.moving self.moving = ishe if dir == 0: self.direction = 'Move Left' elif dir == 1: self.direction = 'Move Right' else: self.direction = "Idle" self.moving = False if not self.is_grabbed(): self.moving = ishe if ishe == True: if 'Move' not in self.current_animation_name \ and 'Grabbed' not in self.current_animation_name: self.prev_animation = self.current_animation_name self.set_animation(self.direction) elif ishe == False: self.set_animation(self.prev_animation) else: self.moving = False def pngs_exist(self, gif_idx, anim_name): if os.path.exists(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen')): pngs = [file.name for file in os.scandir(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen')) if file.is_dir() != True and '.png' in file.name.lower()] for png in pngs: if str(gif_idx) + "_" in png: return True return False def set_animation(self, anim_name): #This has to happen every time set_animation is called, or indices will go out of range when calling self.next() self.frame_idx = 0 if self.is_grabbed(): #in the future, we can set a grabbed + anim_name animation here, and rotate the animation on user drag. anim_name = 'Grabbed' elif random.randrange(0, 2) == 0: if not self.is_moving(): dir = random.randrange(0, 2) self.is_moving(True, dir) else: self.is_moving(False) return gifs = [file.path for file in os.scandir(os.path.join(self.assets_folder, anim_name)) if file.is_dir() != True and '.gif' in file.name.lower()] if os.path.exists(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen')): pngs = [file.path for file in os.scandir(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen')) if file.is_dir() != True and '.png' in file.name.lower()] else: pngs = [] if len(gifs) < 1: self.current_animation_name = 'Idle' current_gif = Image.open(self.idle_animation_path) if not os.path.exists(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen')): os.mkdir(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen'), 0) for frame in ImageSequence.Iterator(current_gif): combined_anim_name = "" + str(0) + "_" + anim_name + "_frame" + str(self.animation_duration) + ".png" path_to_frame = os.path.join(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen'), combined_anim_name) gif_info = frame.info frame.save(path_to_frame, **gif_info) self.current_animation.append(Image.open(path_to_frame)) self.animation_duration += 1 else: self.animation_duration = 0 self.current_animation_name = anim_name self.current_animation = [] gif_idx = random.randrange(0, len(gifs), 1) #if there aren't any pngs yet for this animation, create them if self.pngs_exist(gif_idx, anim_name): pngs = [file.path for file in os.scandir(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen')) if file.is_dir() != True and '.png' in file.name.lower() and str(gif_idx) + "_" + anim_name + "_frame" in file.name] for png in pngs: combined_anim_name = "" + str(gif_idx) + "_" + anim_name + "_frame" + str(self.animation_duration) + ".png" path_to_frame = os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen') self.current_animation.append(Image.open(pngs[pngs.index(os.path.join(path_to_frame, combined_anim_name))])) self.animation_duration += 1 else: current_gif = Image.open(gifs[gif_idx]) if not os.path.exists(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen')): os.mkdir(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen'), 0) for frame in ImageSequence.Iterator(current_gif): combined_anim_name = "" + str(gif_idx) + "_" + anim_name + "_frame" + str(self.animation_duration) + ".png" path_to_frame = os.path.join(os.path.join(os.path.join(self.assets_folder, anim_name), 'Gen'), combined_anim_name) gif_info = frame.info frame.save(path_to_frame, **gif_info) self.current_animation.append(Image.open(path_to_frame)) self.animation_duration += 1 return
18,333
https://github.com/fahad0001/talkfood/blob/master/app/Item.php
Github Open Source
Open Source
MIT
null
talkfood
fahad0001
PHP
Code
32
129
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Item extends Model { protected $fillable = [ 'itemid', 'order_id','item_name','item_price','item_qty','subitem_id' ]; // protected $table = 'item_table'; public $timestamps=false; public function subItem(){ return $this->hasOne('App\SubMenu', 'id','subitem_id'); } }
34,884
https://github.com/IliyanIlievPH/MAVN.Service.AdminAPI/blob/master/src/MAVN.Service.AdminAPI.DomainServices/ImageService.cs
Github Open Source
Open Source
MIT
2,020
MAVN.Service.AdminAPI
IliyanIlievPH
C#
Code
266
931
using System; using System.Linq; using Common.Log; using Lykke.Common.Log; using MAVN.Service.AdminAPI.Domain.Services; using Microsoft.AspNetCore.Http; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.Processing; using SixLabors.Primitives; namespace MAVN.Service.AdminAPI.DomainServices { public class ImageService : IImageService { private const string PngContentType = "image/png"; private const string JpegContentType = "image/jpeg"; private static readonly string[] ImageContentTypes = { PngContentType, JpegContentType }; private readonly bool _mobileAppImageDoOptimization; private readonly int _mobileAppImageMinWidth; private readonly int _mobileAppImageWarningFileSizeInKB; private readonly ILog _log; public ImageService( bool mobileAppImageDoOptimization, int mobileAppImageMinWidth, int mobileAppImageWarningFileSizeInKB, ILogFactory logFactory ) { _mobileAppImageDoOptimization = mobileAppImageDoOptimization; _mobileAppImageMinWidth = mobileAppImageMinWidth; _mobileAppImageWarningFileSizeInKB = mobileAppImageWarningFileSizeInKB; _log = logFactory.CreateLog(this); } public byte[] HandleFile(IFormFile file, Guid RuleContentId) { using (var ms = new System.IO.MemoryStream()) { file.CopyTo(ms); if (ImageContentTypes.Contains(file.ContentType) && _mobileAppImageDoOptimization) { using (var image = Image.Load(ms.ToArray())) { var originalWidth = image.Width; var originalHeight = image.Height; var heightToWidthCoefficient = image.Height * 1.0 / image.Width; if (originalWidth > _mobileAppImageMinWidth) { var newHeight = Math.Round(_mobileAppImageMinWidth * heightToWidthCoefficient, MidpointRounding.AwayFromZero); image.Mutate(x => x.Resize( new ResizeOptions { Mode = heightToWidthCoefficient < 1 ? ResizeMode.Max : ResizeMode.Min, Size = new Size( _mobileAppImageMinWidth, newHeight <= int.MaxValue ? (int) newHeight : int.MaxValue ) } )); } using (var outStream = new System.IO.MemoryStream()) { image.Save(outStream, new JpegEncoder() { Quality = 80 }); var byteArray = outStream.ToArray(); var logData = new { RuleContentId, file.ContentType, originalFileLength = file.Length, resizedFileLength = byteArray.Length, originalWidth, originalHeight, heightToWidthCoefficient, resizedWidth = image.Width, resizedHeight = image.Height }; _log.Info($"Image handled. Data = '{logData}'", context: new { RuleContentId }); if (byteArray.Length / 1024 > _mobileAppImageWarningFileSizeInKB) { _log.Warning($"Handled image file size ({byteArray.Length}) exceeds MobileAppImageWarningFileSizeInKB: {_mobileAppImageWarningFileSizeInKB} KB.", context: new { RuleContentId }); } return byteArray; } } } else { return ms.ToArray(); } } } } }
16,495
https://github.com/svaz/gonftyourself/blob/master/src/utils/Wallet.js
Github Open Source
Open Source
MIT
2,021
gonftyourself
svaz
JavaScript
Code
162
585
import * as Web3 from 'web3' import { web3Provider } from './constants' export async function getERC20TokenBalance(tokenAddress) { const web3 = new Web3(web3Provider); let account = await web3.eth.getAccounts(); // The minimum ABI to get ERC20 Token balance let walletAddress = account[0]; let minABI = [ // balanceOf { "constant":true, "inputs":[{"name":"_owner","type":"address"}], "name":"balanceOf", "outputs":[{"name":"balance","type":"uint256"}], "type":"function" }, // decimals { "constant":true, "inputs":[], "name":"decimals", "outputs":[{"name":"","type":"uint8"}], "type":"function" } ]; let contract = new web3.eth.Contract(minABI,tokenAddress); const tokenBalanceWei = await contract.methods.balanceOf(walletAddress).call(); const tokenBalance = web3.utils.fromWei(tokenBalanceWei,"ether"); return tokenBalance; } export async function getWethBalance() { let tokenAddress = "0xc778417E063141139Fce010982780140Aa0cD5Ab"; // weth Address return await getERC20TokenBalance(tokenAddress); } export async function getEthBalance() { const web3 = new Web3(web3Provider); let account = await web3.eth.getAccounts(); let weiBalance = await web3.eth.getBalance(account[0]); const ethBalance = web3.utils.fromWei(weiBalance,"ether"); return ethBalance; } export async function connectWallet() { console.log('connecting wallet') if(window.ethereum) { console.log('enabling ethereum') await window.ethereum.enable(); console.log('finished enabling eth') try{ let account = await window.ethereum.selectedAddress; return account; }catch(e) { alert('Error occurred') return; } }else{ alert('Please install a crypto wallet'); return; } }
35,164
https://github.com/bis83/pomdog/blob/master/include/Pomdog/Pomdog.hpp
Github Open Source
Open Source
MIT
null
pomdog
bis83
C++
Code
267
1,572
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_89D6FE57_7B46_4032_92AE_EA4D52643E23_HPP #define POMDOG_89D6FE57_7B46_4032_92AE_EA4D52643E23_HPP #include "Application/Duration.hpp" #include "Application/Game.hpp" #include "Application/GameClock.hpp" #include "Application/GameHost.hpp" #include "Application/GameWindow.hpp" #include "Application/MouseCursor.hpp" #include "Application/TimePoint.hpp" #include "Application/Timer.hpp" #include "Audio/AudioChannels.hpp" #include "Audio/AudioClip.hpp" #include "Audio/AudioEmitter.hpp" #include "Audio/AudioEngine.hpp" #include "Audio/AudioListener.hpp" #include "Audio/SoundEffect.hpp" #include "Audio/SoundState.hpp" #include "Content/AssetManager.hpp" #include "Content/AssetBuilders/PipelineStateBuilder.hpp" #include "Content/AssetBuilders/ShaderBuilder.hpp" #include "Math/BoundingBox.hpp" #include "Math/BoundingBox2D.hpp" #include "Math/BoundingCircle.hpp" #include "Math/BoundingSphere.hpp" #include "Math/Color.hpp" #include "Math/ContainmentType.hpp" #include "Math/Degree.hpp" #include "Math/MathHelper.hpp" #include "Math/Matrix2x2.hpp" #include "Math/Matrix3x2.hpp" #include "Math/Matrix3x3.hpp" #include "Math/Matrix4x4.hpp" #include "Math/Point2D.hpp" #include "Math/Point3D.hpp" #include "Math/Quaternion.hpp" #include "Math/Radian.hpp" #include "Math/Ray.hpp" #include "Math/Rectangle.hpp" #include "Math/Vector2.hpp" #include "Math/Vector3.hpp" #include "Math/Vector4.hpp" #include "Logging/Log.hpp" #include "Logging/LogChannel.hpp" #include "Logging/LogEntry.hpp" #include "Logging/LogLevel.hpp" #include "Logging/LogStream.hpp" #include "Graphics/Blend.hpp" #include "Graphics/BlendDescription.hpp" #include "Graphics/BlendFunction.hpp" #include "Graphics/BufferUsage.hpp" #include "Graphics/ClearOptions.hpp" #include "Graphics/ComparisonFunction.hpp" #include "Graphics/ConstantBuffer.hpp" #include "Graphics/CullMode.hpp" #include "Graphics/DepthStencilDescription.hpp" #include "Graphics/DepthStencilOperation.hpp" #include "Graphics/EffectAnnotation.hpp" #include "Graphics/EffectConstantDescription.hpp" #include "Graphics/EffectReflection.hpp" #include "Graphics/EffectVariableClass.hpp" #include "Graphics/EffectVariableType.hpp" #include "Graphics/EffectVariable.hpp" #include "Graphics/FillMode.hpp" #include "Graphics/GraphicsCommandList.hpp" #include "Graphics/GraphicsCommandQueue.hpp" #include "Graphics/GraphicsDevice.hpp" #include "Graphics/IndexBuffer.hpp" #include "Graphics/IndexElementSize.hpp" #include "Graphics/InputClassification.hpp" #include "Graphics/InputElement.hpp" #include "Graphics/InputElementFormat.hpp" #include "Graphics/InputLayoutDescription.hpp" #include "Graphics/InputLayoutHelper.hpp" #include "Graphics/PipelineState.hpp" #include "Graphics/PipelineStateDescription.hpp" #include "Graphics/PresentationParameters.hpp" #include "Graphics/PrimitiveTopology.hpp" #include "Graphics/RasterizerDescription.hpp" #include "Graphics/RenderTarget2D.hpp" #include "Graphics/SamplerDescription.hpp" #include "Graphics/SamplerState.hpp" #include "Graphics/Shader.hpp" #include "Graphics/ShaderLanguage.hpp" #include "Graphics/ShaderPipelineStage.hpp" #include "Graphics/StencilOperation.hpp" #include "Graphics/SurfaceFormat.hpp" #include "Graphics/Texture.hpp" #include "Graphics/Texture2D.hpp" #include "Graphics/TextureAddressMode.hpp" #include "Graphics/TextureFilter.hpp" #include "Graphics/VertexBuffer.hpp" #include "Graphics/VertexBufferBinding.hpp" #include "Graphics/Viewport.hpp" #include "Input/ButtonState.hpp" #include "Input/Gamepad.hpp" #include "Input/GamepadButtons.hpp" #include "Input/GamepadCapabilities.hpp" #include "Input/GamepadDPad.hpp" #include "Input/GamepadState.hpp" #include "Input/GamepadThumbSticks.hpp" #include "Input/GamepadType.hpp" #include "Input/Keyboard.hpp" #include "Input/KeyboardState.hpp" #include "Input/Keys.hpp" #include "Input/KeyState.hpp" #include "Input/Mouse.hpp" #include "Input/MouseState.hpp" #include "Input/PlayerIndex.hpp" #include "Input/TouchLocation.hpp" #include "Input/TouchLocationState.hpp" #include "Signals/Connection.hpp" #include "Signals/ConnectionList.hpp" #include "Signals/Event.hpp" #include "Signals/EventQueue.hpp" #include "Signals/Helpers.hpp" #include "Signals/ScopedConnection.hpp" #include "Signals/Signal.hpp" #include "Utility/Any.hpp" #include "Utility/Assert.hpp" #include "Utility/Exception.hpp" #include "Utility/StringHelper.hpp" #include "Basic/Export.hpp" #include "Basic/Platform.hpp" #include "Basic/Version.hpp" #endif // POMDOG_89D6FE57_7B46_4032_92AE_EA4D52643E23_HPP
38,889
https://github.com/ken1ma/jna-tlb-access-2010/blob/master/office/src/main/java/jp/kenichi/jna/tlb/office/IMsoSeries.java
Github Open Source
Open Source
MIT
2,018
jna-tlb-access-2010
ken1ma
Java
Code
2,157
10,178
package jp.kenichi.jna.tlb.office; import com.sun.jna.platform.win32.COM.util.annotation.ComInterface; import com.sun.jna.platform.win32.COM.util.annotation.ComMethod; import com.sun.jna.platform.win32.COM.util.annotation.ComProperty; import com.sun.jna.platform.win32.COM.util.IDispatch; import com.sun.jna.platform.win32.COM.util.IUnknown; import com.sun.jna.platform.win32.COM.util.IRawDispatchHandle; import com.sun.jna.platform.win32.Variant.VARIANT; /** * <p>uuid({000C170B-0000-0000-C000-000000000046})</p> */ @ComInterface(iid="{000C170B-0000-0000-C000-000000000046}") public interface IMsoSeries extends IUnknown, IRawDispatchHandle, IDispatch { /** * <p>id(0x96)</p> * <p>vtableId(7)</p> * @param RHS [out] {@code com.sun.jna.platform.win32.COM.util.IDispatch} */ @ComProperty(name = "Parent", dispId = 0x96) com.sun.jna.platform.win32.WinNT.HRESULT getParent(VARIANT RHS); /** * <p>id(0x97)</p> * <p>vtableId(8)</p> * @param Type [in, optional] {@code XlDataLabelsType} * @param IMsoLegendKey [in, optional] {@code Object} * @param AutoText [in, optional] {@code Object} * @param HasLeaderLines [in, optional] {@code Object} * @param RHS [out] {@code Object} */ @ComMethod(name = "_ApplyDataLabels", dispId = 0x97) com.sun.jna.platform.win32.WinNT.HRESULT _ApplyDataLabels(XlDataLabelsType Type, Object IMsoLegendKey, Object AutoText, Object HasLeaderLines, VARIANT RHS); /** * <p>id(0x2f)</p> * <p>vtableId(9)</p> * @param RHS [out] {@code XlAxisGroup} */ @ComProperty(name = "AxisGroup", dispId = 0x2f) com.sun.jna.platform.win32.WinNT.HRESULT getAxisGroup(VARIANT RHS); /** * <p>id(0x2f)</p> * <p>vtableId(10)</p> * @param RHS [in] {@code XlAxisGroup} */ @ComProperty(name = "AxisGroup", dispId = 0x2f) com.sun.jna.platform.win32.WinNT.HRESULT setAxisGroup(XlAxisGroup RHS); /** * <p>id(0x80)</p> * <p>vtableId(11)</p> * @param RHS [out] {@code IMsoBorder} */ @ComProperty(name = "Border", dispId = 0x80) com.sun.jna.platform.win32.WinNT.HRESULT getBorder(VARIANT RHS); /** * <p>id(0x70)</p> * <p>vtableId(12)</p> * @param RHS [out] {@code Object} */ @ComMethod(name = "ClearFormats", dispId = 0x70) com.sun.jna.platform.win32.WinNT.HRESULT ClearFormats(VARIANT RHS); /** * <p>id(0x227)</p> * <p>vtableId(13)</p> * @param RHS [out] {@code Object} */ @ComMethod(name = "Copy", dispId = 0x227) com.sun.jna.platform.win32.WinNT.HRESULT Copy(VARIANT RHS); /** * <p>id(0x9d)</p> * <p>vtableId(14)</p> * @param Index [in, optional] {@code Object} * @param RHS [out] {@code com.sun.jna.platform.win32.COM.util.IDispatch} */ @ComMethod(name = "DataLabels", dispId = 0x9d) com.sun.jna.platform.win32.WinNT.HRESULT DataLabels(Object Index, VARIANT RHS); /** * <p>id(0x75)</p> * <p>vtableId(15)</p> * @param RHS [out] {@code Object} */ @ComMethod(name = "Delete", dispId = 0x75) com.sun.jna.platform.win32.WinNT.HRESULT Delete(VARIANT RHS); /** * <p>id(0x98)</p> * <p>vtableId(16)</p> * @param Direction [in] {@code XlErrorBarDirection} * @param Include [in] {@code XlErrorBarInclude} * @param Type [in] {@code XlErrorBarType} * @param Amount [in, optional] {@code Object} * @param MinusValues [in, optional] {@code Object} * @param RHS [out] {@code Object} */ @ComMethod(name = "ErrorBar", dispId = 0x98) com.sun.jna.platform.win32.WinNT.HRESULT ErrorBar(XlErrorBarDirection Direction, XlErrorBarInclude Include, XlErrorBarType Type, Object Amount, Object MinusValues, VARIANT RHS); /** * <p>id(0x9f)</p> * <p>vtableId(17)</p> * @param RHS [out] {@code IMsoErrorBars} */ @ComProperty(name = "ErrorBars", dispId = 0x9f) com.sun.jna.platform.win32.WinNT.HRESULT getErrorBars(VARIANT RHS); /** * <p>id(0xb6)</p> * <p>vtableId(18)</p> * @param RHS [out] {@code Integer} */ @ComProperty(name = "Explosion", dispId = 0xb6) com.sun.jna.platform.win32.WinNT.HRESULT getExplosion(VARIANT RHS); /** * <p>id(0xb6)</p> * <p>vtableId(19)</p> * @param RHS [in] {@code Integer} */ @ComProperty(name = "Explosion", dispId = 0xb6) com.sun.jna.platform.win32.WinNT.HRESULT setExplosion(Integer RHS); /** * <p>id(0x105)</p> * <p>vtableId(20)</p> * @param RHS [out] {@code String} */ @ComProperty(name = "Formula", dispId = 0x105) com.sun.jna.platform.win32.WinNT.HRESULT getFormula(VARIANT RHS); /** * <p>id(0x105)</p> * <p>vtableId(21)</p> * @param RHS [in] {@code String} */ @ComProperty(name = "Formula", dispId = 0x105) com.sun.jna.platform.win32.WinNT.HRESULT setFormula(String RHS); /** * <p>id(0x107)</p> * <p>vtableId(22)</p> * @param RHS [out] {@code String} */ @ComProperty(name = "FormulaLocal", dispId = 0x107) com.sun.jna.platform.win32.WinNT.HRESULT getFormulaLocal(VARIANT RHS); /** * <p>id(0x107)</p> * <p>vtableId(23)</p> * @param RHS [in] {@code String} */ @ComProperty(name = "FormulaLocal", dispId = 0x107) com.sun.jna.platform.win32.WinNT.HRESULT setFormulaLocal(String RHS); /** * <p>id(0x108)</p> * <p>vtableId(24)</p> * @param RHS [out] {@code String} */ @ComProperty(name = "FormulaR1C1", dispId = 0x108) com.sun.jna.platform.win32.WinNT.HRESULT getFormulaR1C1(VARIANT RHS); /** * <p>id(0x108)</p> * <p>vtableId(25)</p> * @param RHS [in] {@code String} */ @ComProperty(name = "FormulaR1C1", dispId = 0x108) com.sun.jna.platform.win32.WinNT.HRESULT setFormulaR1C1(String RHS); /** * <p>id(0x109)</p> * <p>vtableId(26)</p> * @param RHS [out] {@code String} */ @ComProperty(name = "FormulaR1C1Local", dispId = 0x109) com.sun.jna.platform.win32.WinNT.HRESULT getFormulaR1C1Local(VARIANT RHS); /** * <p>id(0x109)</p> * <p>vtableId(27)</p> * @param RHS [in] {@code String} */ @ComProperty(name = "FormulaR1C1Local", dispId = 0x109) com.sun.jna.platform.win32.WinNT.HRESULT setFormulaR1C1Local(String RHS); /** * <p>id(0x4e)</p> * <p>vtableId(28)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "HasDataLabels", dispId = 0x4e) com.sun.jna.platform.win32.WinNT.HRESULT getHasDataLabels(VARIANT RHS); /** * <p>id(0x4e)</p> * <p>vtableId(29)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "HasDataLabels", dispId = 0x4e) com.sun.jna.platform.win32.WinNT.HRESULT setHasDataLabels(Boolean RHS); /** * <p>id(0xa0)</p> * <p>vtableId(30)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "HasErrorBars", dispId = 0xa0) com.sun.jna.platform.win32.WinNT.HRESULT getHasErrorBars(VARIANT RHS); /** * <p>id(0xa0)</p> * <p>vtableId(31)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "HasErrorBars", dispId = 0xa0) com.sun.jna.platform.win32.WinNT.HRESULT setHasErrorBars(Boolean RHS); /** * <p>id(0x81)</p> * <p>vtableId(32)</p> * @param RHS [out] {@code IMsoInterior} */ @ComProperty(name = "Interior", dispId = 0x81) com.sun.jna.platform.win32.WinNT.HRESULT getInterior(VARIANT RHS); /** * <p>id(0x67f)</p> * <p>vtableId(33)</p> * @param RHS [out] {@code ChartFillFormat} */ @ComProperty(name = "Fill", dispId = 0x67f) com.sun.jna.platform.win32.WinNT.HRESULT getFill(VARIANT RHS); /** * <p>id(0x84)</p> * <p>vtableId(34)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "InvertIfNegative", dispId = 0x84) com.sun.jna.platform.win32.WinNT.HRESULT getInvertIfNegative(VARIANT RHS); /** * <p>id(0x84)</p> * <p>vtableId(35)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "InvertIfNegative", dispId = 0x84) com.sun.jna.platform.win32.WinNT.HRESULT setInvertIfNegative(Boolean RHS); /** * <p>id(0x49)</p> * <p>vtableId(36)</p> * @param RHS [out] {@code Integer} */ @ComProperty(name = "MarkerBackgroundColor", dispId = 0x49) com.sun.jna.platform.win32.WinNT.HRESULT getMarkerBackgroundColor(VARIANT RHS); /** * <p>id(0x49)</p> * <p>vtableId(37)</p> * @param RHS [in] {@code Integer} */ @ComProperty(name = "MarkerBackgroundColor", dispId = 0x49) com.sun.jna.platform.win32.WinNT.HRESULT setMarkerBackgroundColor(Integer RHS); /** * <p>id(0x4a)</p> * <p>vtableId(38)</p> * @param RHS [out] {@code XlColorIndex} */ @ComProperty(name = "MarkerBackgroundColorIndex", dispId = 0x4a) com.sun.jna.platform.win32.WinNT.HRESULT getMarkerBackgroundColorIndex(VARIANT RHS); /** * <p>id(0x4a)</p> * <p>vtableId(39)</p> * @param RHS [in] {@code XlColorIndex} */ @ComProperty(name = "MarkerBackgroundColorIndex", dispId = 0x4a) com.sun.jna.platform.win32.WinNT.HRESULT setMarkerBackgroundColorIndex(XlColorIndex RHS); /** * <p>id(0x4b)</p> * <p>vtableId(40)</p> * @param RHS [out] {@code Integer} */ @ComProperty(name = "MarkerForegroundColor", dispId = 0x4b) com.sun.jna.platform.win32.WinNT.HRESULT getMarkerForegroundColor(VARIANT RHS); /** * <p>id(0x4b)</p> * <p>vtableId(41)</p> * @param RHS [in] {@code Integer} */ @ComProperty(name = "MarkerForegroundColor", dispId = 0x4b) com.sun.jna.platform.win32.WinNT.HRESULT setMarkerForegroundColor(Integer RHS); /** * <p>id(0x4c)</p> * <p>vtableId(42)</p> * @param RHS [out] {@code XlColorIndex} */ @ComProperty(name = "MarkerForegroundColorIndex", dispId = 0x4c) com.sun.jna.platform.win32.WinNT.HRESULT getMarkerForegroundColorIndex(VARIANT RHS); /** * <p>id(0x4c)</p> * <p>vtableId(43)</p> * @param RHS [in] {@code XlColorIndex} */ @ComProperty(name = "MarkerForegroundColorIndex", dispId = 0x4c) com.sun.jna.platform.win32.WinNT.HRESULT setMarkerForegroundColorIndex(XlColorIndex RHS); /** * <p>id(0xe7)</p> * <p>vtableId(44)</p> * @param RHS [out] {@code Integer} */ @ComProperty(name = "MarkerSize", dispId = 0xe7) com.sun.jna.platform.win32.WinNT.HRESULT getMarkerSize(VARIANT RHS); /** * <p>id(0xe7)</p> * <p>vtableId(45)</p> * @param RHS [in] {@code Integer} */ @ComProperty(name = "MarkerSize", dispId = 0xe7) com.sun.jna.platform.win32.WinNT.HRESULT setMarkerSize(Integer RHS); /** * <p>id(0x48)</p> * <p>vtableId(46)</p> * @param RHS [out] {@code XlMarkerStyle} */ @ComProperty(name = "MarkerStyle", dispId = 0x48) com.sun.jna.platform.win32.WinNT.HRESULT getMarkerStyle(VARIANT RHS); /** * <p>id(0x48)</p> * <p>vtableId(47)</p> * @param RHS [in] {@code XlMarkerStyle} */ @ComProperty(name = "MarkerStyle", dispId = 0x48) com.sun.jna.platform.win32.WinNT.HRESULT setMarkerStyle(XlMarkerStyle RHS); /** * <p>id(0x6e)</p> * <p>vtableId(48)</p> * @param RHS [out] {@code String} */ @ComProperty(name = "Name", dispId = 0x6e) com.sun.jna.platform.win32.WinNT.HRESULT getName(VARIANT RHS); /** * <p>id(0x6e)</p> * <p>vtableId(49)</p> * @param RHS [in] {@code String} */ @ComProperty(name = "Name", dispId = 0x6e) com.sun.jna.platform.win32.WinNT.HRESULT setName(String RHS); /** * <p>id(0xd3)</p> * <p>vtableId(50)</p> * @param RHS [out] {@code Object} */ @ComMethod(name = "Paste", dispId = 0xd3) com.sun.jna.platform.win32.WinNT.HRESULT Paste(VARIANT RHS); /** * <p>id(0xa1)</p> * <p>vtableId(51)</p> * @param RHS [out] {@code XlChartPictureType} */ @ComProperty(name = "PictureType", dispId = 0xa1) com.sun.jna.platform.win32.WinNT.HRESULT getPictureType(VARIANT RHS); /** * <p>id(0xa1)</p> * <p>vtableId(52)</p> * @param RHS [in] {@code XlChartPictureType} */ @ComProperty(name = "PictureType", dispId = 0xa1) com.sun.jna.platform.win32.WinNT.HRESULT setPictureType(XlChartPictureType RHS); /** * <p>id(0xa2)</p> * <p>vtableId(53)</p> * @param RHS [out] {@code Double} */ @ComProperty(name = "PictureUnit", dispId = 0xa2) com.sun.jna.platform.win32.WinNT.HRESULT getPictureUnit(VARIANT RHS); /** * <p>id(0xa2)</p> * <p>vtableId(54)</p> * @param RHS [in] {@code Double} */ @ComProperty(name = "PictureUnit", dispId = 0xa2) com.sun.jna.platform.win32.WinNT.HRESULT setPictureUnit(Double RHS); /** * <p>id(0xe4)</p> * <p>vtableId(55)</p> * @param RHS [out] {@code Integer} */ @ComProperty(name = "PlotOrder", dispId = 0xe4) com.sun.jna.platform.win32.WinNT.HRESULT getPlotOrder(VARIANT RHS); /** * <p>id(0xe4)</p> * <p>vtableId(56)</p> * @param RHS [in] {@code Integer} */ @ComProperty(name = "PlotOrder", dispId = 0xe4) com.sun.jna.platform.win32.WinNT.HRESULT setPlotOrder(Integer RHS); /** * <p>id(0x46)</p> * <p>vtableId(57)</p> * @param Index [in, optional] {@code Object} * @param RHS [out] {@code com.sun.jna.platform.win32.COM.util.IDispatch} */ @ComMethod(name = "Points", dispId = 0x46) com.sun.jna.platform.win32.WinNT.HRESULT Points(Object Index, VARIANT RHS); /** * <p>id(0xeb)</p> * <p>vtableId(58)</p> * @param RHS [out] {@code Object} */ @ComMethod(name = "Select", dispId = 0xeb) com.sun.jna.platform.win32.WinNT.HRESULT Select(VARIANT RHS); /** * <p>id(0xa3)</p> * <p>vtableId(59)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "Smooth", dispId = 0xa3) com.sun.jna.platform.win32.WinNT.HRESULT getSmooth(VARIANT RHS); /** * <p>id(0xa3)</p> * <p>vtableId(60)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "Smooth", dispId = 0xa3) com.sun.jna.platform.win32.WinNT.HRESULT setSmooth(Boolean RHS); /** * <p>id(0x9a)</p> * <p>vtableId(61)</p> * @param Index [in, optional] {@code Object} * @param RHS [out] {@code com.sun.jna.platform.win32.COM.util.IDispatch} */ @ComMethod(name = "Trendlines", dispId = 0x9a) com.sun.jna.platform.win32.WinNT.HRESULT Trendlines(Object Index, VARIANT RHS); /** * <p>id(0x6c)</p> * <p>vtableId(62)</p> * @param RHS [out] {@code Integer} */ @ComProperty(name = "Type", dispId = 0x6c) com.sun.jna.platform.win32.WinNT.HRESULT getType(VARIANT RHS); /** * <p>id(0x6c)</p> * <p>vtableId(63)</p> * @param RHS [in] {@code Integer} */ @ComProperty(name = "Type", dispId = 0x6c) com.sun.jna.platform.win32.WinNT.HRESULT setType(Integer RHS); /** * <p>id(0x578)</p> * <p>vtableId(64)</p> * @param RHS [out] {@code XlChartType} */ @ComProperty(name = "ChartType", dispId = 0x578) com.sun.jna.platform.win32.WinNT.HRESULT getChartType(VARIANT RHS); /** * <p>id(0x578)</p> * <p>vtableId(65)</p> * @param RHS [in] {@code XlChartType} */ @ComProperty(name = "ChartType", dispId = 0x578) com.sun.jna.platform.win32.WinNT.HRESULT setChartType(XlChartType RHS); /** * <p>id(0x579)</p> * <p>vtableId(66)</p> * @param ChartType [in] {@code XlChartType} */ @ComMethod(name = "ApplyCustomType", dispId = 0x579) com.sun.jna.platform.win32.WinNT.HRESULT ApplyCustomType(XlChartType ChartType); /** * <p>id(0xa4)</p> * <p>vtableId(67)</p> * @param RHS [out] {@code Object} */ @ComProperty(name = "Values", dispId = 0xa4) com.sun.jna.platform.win32.WinNT.HRESULT getValues(VARIANT RHS); /** * <p>id(0xa4)</p> * <p>vtableId(68)</p> * @param RHS [in] {@code Object} */ @ComProperty(name = "Values", dispId = 0xa4) com.sun.jna.platform.win32.WinNT.HRESULT setValues(Object RHS); /** * <p>id(0x457)</p> * <p>vtableId(69)</p> * @param RHS [out] {@code Object} */ @ComProperty(name = "XValues", dispId = 0x457) com.sun.jna.platform.win32.WinNT.HRESULT getXValues(VARIANT RHS); /** * <p>id(0x457)</p> * <p>vtableId(70)</p> * @param RHS [in] {@code Object} */ @ComProperty(name = "XValues", dispId = 0x457) com.sun.jna.platform.win32.WinNT.HRESULT setXValues(Object RHS); /** * <p>id(0x680)</p> * <p>vtableId(71)</p> * @param RHS [out] {@code Object} */ @ComProperty(name = "BubbleSizes", dispId = 0x680) com.sun.jna.platform.win32.WinNT.HRESULT getBubbleSizes(VARIANT RHS); /** * <p>id(0x680)</p> * <p>vtableId(72)</p> * @param RHS [in] {@code Object} */ @ComProperty(name = "BubbleSizes", dispId = 0x680) com.sun.jna.platform.win32.WinNT.HRESULT setBubbleSizes(Object RHS); /** * <p>id(0x57b)</p> * <p>vtableId(73)</p> * @param RHS [out] {@code XlBarShape} */ @ComProperty(name = "BarShape", dispId = 0x57b) com.sun.jna.platform.win32.WinNT.HRESULT getBarShape(VARIANT RHS); /** * <p>id(0x57b)</p> * <p>vtableId(74)</p> * @param RHS [in] {@code XlBarShape} */ @ComProperty(name = "BarShape", dispId = 0x57b) com.sun.jna.platform.win32.WinNT.HRESULT setBarShape(XlBarShape RHS); /** * <p>id(0x67b)</p> * <p>vtableId(75)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "ApplyPictToSides", dispId = 0x67b) com.sun.jna.platform.win32.WinNT.HRESULT getApplyPictToSides(VARIANT RHS); /** * <p>id(0x67b)</p> * <p>vtableId(76)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "ApplyPictToSides", dispId = 0x67b) com.sun.jna.platform.win32.WinNT.HRESULT setApplyPictToSides(Boolean RHS); /** * <p>id(0x67c)</p> * <p>vtableId(77)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "ApplyPictToFront", dispId = 0x67c) com.sun.jna.platform.win32.WinNT.HRESULT getApplyPictToFront(VARIANT RHS); /** * <p>id(0x67c)</p> * <p>vtableId(78)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "ApplyPictToFront", dispId = 0x67c) com.sun.jna.platform.win32.WinNT.HRESULT setApplyPictToFront(Boolean RHS); /** * <p>id(0x67d)</p> * <p>vtableId(79)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "ApplyPictToEnd", dispId = 0x67d) com.sun.jna.platform.win32.WinNT.HRESULT getApplyPictToEnd(VARIANT RHS); /** * <p>id(0x67d)</p> * <p>vtableId(80)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "ApplyPictToEnd", dispId = 0x67d) com.sun.jna.platform.win32.WinNT.HRESULT setApplyPictToEnd(Boolean RHS); /** * <p>id(0x681)</p> * <p>vtableId(81)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "Has3DEffect", dispId = 0x681) com.sun.jna.platform.win32.WinNT.HRESULT getHas3DEffect(VARIANT RHS); /** * <p>id(0x681)</p> * <p>vtableId(82)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "Has3DEffect", dispId = 0x681) com.sun.jna.platform.win32.WinNT.HRESULT setHas3DEffect(Boolean RHS); /** * <p>id(0x67)</p> * <p>vtableId(83)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "Shadow", dispId = 0x67) com.sun.jna.platform.win32.WinNT.HRESULT getShadow(VARIANT RHS); /** * <p>id(0x67)</p> * <p>vtableId(84)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "Shadow", dispId = 0x67) com.sun.jna.platform.win32.WinNT.HRESULT setShadow(Boolean RHS); /** * <p>id(0x572)</p> * <p>vtableId(85)</p> * @param RHS [out] {@code Boolean} */ @ComProperty(name = "HasLeaderLines", dispId = 0x572) com.sun.jna.platform.win32.WinNT.HRESULT getHasLeaderLines(VARIANT RHS); /** * <p>id(0x572)</p> * <p>vtableId(86)</p> * @param RHS [in] {@code Boolean} */ @ComProperty(name = "HasLeaderLines", dispId = 0x572) com.sun.jna.platform.win32.WinNT.HRESULT setHasLeaderLines(Boolean RHS); /** * <p>id(0x682)</p> * <p>vtableId(87)</p> * @param RHS [out] {@code IMsoLeaderLines} */ @ComProperty(name = "LeaderLines", dispId = 0x682) com.sun.jna.platform.win32.WinNT.HRESULT getLeaderLines(VARIANT RHS); /** * <p>id(0x782)</p> * <p>vtableId(88)</p> * @param Type [in, optional] {@code XlDataLabelsType} * @param IMsoLegendKey [in, optional] {@code Object} * @param AutoText [in, optional] {@code Object} * @param HasLeaderLines [in, optional] {@code Object} * @param ShowSeriesName [in, optional] {@code Object} * @param ShowCategoryName [in, optional] {@code Object} * @param ShowValue [in, optional] {@code Object} * @param ShowPercentage [in, optional] {@code Object} * @param ShowBubbleSize [in, optional] {@code Object} * @param Separator [in, optional] {@code Object} * @param RHS [out] {@code Object} */ @ComMethod(name = "ApplyDataLabels", dispId = 0x782) com.sun.jna.platform.win32.WinNT.HRESULT ApplyDataLabels(XlDataLabelsType Type, Object IMsoLegendKey, Object AutoText, Object HasLeaderLines, Object ShowSeriesName, Object ShowCategoryName, Object ShowValue, Object ShowPercentage, Object ShowBubbleSize, Object Separator, VARIANT RHS); /** * <p>id(0x60020052)</p> * <p>vtableId(89)</p> * @param ppChartFormat [out] {@code IMsoChartFormat} */ @ComProperty(name = "Format", dispId = 0x60020052) com.sun.jna.platform.win32.WinNT.HRESULT getFormat(VARIANT ppChartFormat); /** * <p>id(0x94)</p> * <p>vtableId(90)</p> * @param ppval [out] {@code com.sun.jna.platform.win32.COM.util.IDispatch} */ @ComProperty(name = "Application", dispId = 0x94) com.sun.jna.platform.win32.WinNT.HRESULT getApplication(VARIANT ppval); /** * <p>id(0x95)</p> * <p>vtableId(91)</p> * @param pval [out] {@code Integer} */ @ComProperty(name = "Creator", dispId = 0x95) com.sun.jna.platform.win32.WinNT.HRESULT getCreator(VARIANT pval); /** * <p>id(0xa59)</p> * <p>vtableId(92)</p> * @param RHS [out] {@code Double} */ @ComProperty(name = "PictureUnit2", dispId = 0xa59) com.sun.jna.platform.win32.WinNT.HRESULT getPictureUnit2(VARIANT RHS); /** * <p>id(0xa59)</p> * <p>vtableId(93)</p> * @param RHS [in] {@code Double} */ @ComProperty(name = "PictureUnit2", dispId = 0xa59) com.sun.jna.platform.win32.WinNT.HRESULT setPictureUnit2(Double RHS); /** * <p>id(0x784)</p> * <p>vtableId(94)</p> * @param RHS [out] {@code Integer} */ @ComProperty(name = "PlotColorIndex", dispId = 0x784) com.sun.jna.platform.win32.WinNT.HRESULT getPlotColorIndex(VARIANT RHS); /** * <p>id(0xb44)</p> * <p>vtableId(95)</p> * @param RHS [out] {@code Integer} */ @ComProperty(name = "InvertColor", dispId = 0xb44) com.sun.jna.platform.win32.WinNT.HRESULT getInvertColor(VARIANT RHS); /** * <p>id(0xb44)</p> * <p>vtableId(96)</p> * @param RHS [in] {@code Integer} */ @ComProperty(name = "InvertColor", dispId = 0xb44) com.sun.jna.platform.win32.WinNT.HRESULT setInvertColor(Integer RHS); /** * <p>id(0xb45)</p> * <p>vtableId(97)</p> * @param RHS [out] {@code XlColorIndex} */ @ComProperty(name = "InvertColorIndex", dispId = 0xb45) com.sun.jna.platform.win32.WinNT.HRESULT getInvertColorIndex(VARIANT RHS); /** * <p>id(0xb45)</p> * <p>vtableId(98)</p> * @param RHS [in] {@code XlColorIndex} */ @ComProperty(name = "InvertColorIndex", dispId = 0xb45) com.sun.jna.platform.win32.WinNT.HRESULT setInvertColorIndex(XlColorIndex RHS); }
10,961
https://github.com/ronaldtorres/kirby-navigation/blob/master/src/components/modal/default.vue
Github Open Source
Open Source
MIT
2,021
kirby-navigation
ronaldtorres
Vue
Code
97
512
<template> <k-dialog size="medium" class="k-pages-dialog" v-bind:visible="modal" v-on:cancel="modal_close" v-on:submit="modal_submit"> <slot name="modal_header"> </slot> <slot name="modal_body"> </slot> </k-dialog> </template> <script> export default { props: { modal: Object, }, methods: { modal_close() { this.$emit('modal_close') }, modal_submit() { this.$emit('modal_submit') } } } </script> <style lang="scss" scoped> .k-pages-dialog-navbar { display: flex; align-items: center; justify-content: center; margin-bottom: 0.5rem; padding-right: 38px; } .k-pages-dialog-navbar .k-button { width: 38px; } .k-pages-dialog-navbar .k-button[disabled] { opacity: 0; } .k-pages-dialog-navbar .k-headline { flex-grow: 1; text-align: center; } .k-pages-dialog .k-list-item { cursor: pointer; } .k-pages-dialog .k-list-item .k-button[data-theme="disabled"], .k-pages-dialog .k-list-item .k-button[disabled] { opacity: 0.25; } .k-pages-dialog .k-list-item .k-button[data-theme="disabled"]:hover { opacity: 1; } </style>
18,011
https://github.com/appressoas/ievv_opensource/blob/master/ievv_opensource/utils/lazy_string.py
Github Open Source
Open Source
BSD-3-Clause
null
ievv_opensource
appressoas
Python
Code
30
132
class LazyString(object): def __init__(self, formatstring, *args, **kwargs): self.formatstring = formatstring self.args = args self.kwargs = kwargs def __str__(self): return self.formatstring.format(*self.args, **self.kwargs) def __repr__(self): return 'LazyString({!r}, args={!r}, kwargs={!r})'.format( self.formatstring, self.args, self.kwargs)
17,838
https://github.com/midoks/hammer/blob/master/vendor/golang.org/x/tools/go/analysis/passes/cgocall/testdata/src/c/c.go
Github Open Source
Open Source
MIT
2,022
hammer
midoks
Go
Code
68
119
// Copyright 2016 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. // Test the cgo checker on a file that doesn't use cgo. package c import "unsafe" // Passing a pointer (via the slice), but C isn't cgo. var _ = C.f(unsafe.Pointer(new([]int))) var C struct{ f func(interface{}) int }
51,022
https://github.com/bragi/ioke/blob/master/src/main/ioke/lang/Mixins.java
Github Open Source
Open Source
MIT
2,016
ioke
bragi
Java
Code
114
517
/* * See LICENSE file in distribution for copyright and licensing information. */ package ioke.lang; import ioke.lang.mixins.Comparing; import ioke.lang.mixins.Enumerable; import ioke.lang.exceptions.ControlFlow; /** * * @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a> */ public class Mixins { public static void init(IokeObject mixins) throws ControlFlow { mixins.setKind("Mixins"); mixins.setCell("=", mixins.runtime.base.getCells().get("=")); mixins.setCell("==", mixins.runtime.base.getCells().get("==")); mixins.setCell("cell", mixins.runtime.base.getCells().get("cell")); mixins.setCell("cell=", mixins.runtime.base.getCells().get("cell=")); mixins.setCell("cell?", mixins.runtime.base.getCells().get("cell?")); mixins.setCell("cells", mixins.runtime.base.getCells().get("cells")); mixins.setCell("cellNames", mixins.runtime.base.getCells().get("cellNames")); mixins.setCell("mimic", mixins.runtime.base.getCells().get("mimic")); IokeObject comparing = new IokeObject(mixins.runtime, "allows different objects to be compared, based on the spaceship operator being available"); comparing.mimicsWithoutCheck(mixins); Comparing.init(comparing); mixins.registerCell("Comparing", comparing); IokeObject enumerable = new IokeObject(mixins.runtime, "adds lots of helpful methods that can be done on enumerable methods. based on the 'each' method being available on the self."); enumerable.mimicsWithoutCheck(mixins); Enumerable.init(enumerable); mixins.registerCell("Enumerable", enumerable); } }// Mixins
8,324
https://github.com/Gamingpc/platform/blob/master/src/Core/System/Currency/CurrencyCollection.php
Github Open Source
Open Source
MIT, LicenseRef-scancode-generic-cla
2,019
platform
Gamingpc
PHP
Code
55
168
<?php declare(strict_types=1); namespace Shopware\Core\System\Currency; use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection; /** * @method void add(CurrencyEntity $entity) * @method void set(string $key, CurrencyEntity $entity) * @method CurrencyEntity[] getIterator() * @method CurrencyEntity[] getElements() * @method CurrencyEntity|null get(string $key) * @method CurrencyEntity|null first() * @method CurrencyEntity|null last() */ class CurrencyCollection extends EntityCollection { protected function getExpectedClass(): string { return CurrencyEntity::class; } }
4,813
https://github.com/mehr-licht/OrgaFarma/blob/master/WebAvi/WebAvi/obj/Release/AspnetCompileMerge/TempBuildDir/Views/Home/About.vbhtml
Github Open Source
Open Source
MIT
null
OrgaFarma
mehr-licht
Visual Basic
Code
95
266
@Code ViewData("Title") = "Acerca" End Code <br /> <br /> <h2>WebAvi</h2> <br /> <br /> <h3>aplicação online de apoio à conferência de receituário</h3> <br /> <p> O WebAvi permite que confira o receituário facilmente</p> <br /> <br /> É uma adaptação do software PrescAvi que foi criado em 2009 pela e para a OrgaFarma Lda usar na conferência de receituário das farmácias suas clientes. <br /> <br /> <style> BODY { background-color: cadetblue; } body input[class='form-control'] { background-color: lightblue; color: black; font-family: Verdana; font-language-override: "PT"; border: 2px solid #456879; border-radius: 10px; text-align: center; } </style>
50,132
https://github.com/cantek41/DynamicDashBoard/blob/master/Dynamic/Service/DataService.cs
Github Open Source
Open Source
MIT
2,019
DynamicDashBoard
cantek41
C#
Code
131
395
using Dynamic.Models; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Web; namespace Dynamic.Service { public class DataService { private static ApplicationDbContext context; private static DataService _service; public static DataService getService(ApplicationDbContext _context) { if (_service == null) _service = new DataService(); context = new ApplicationDbContext(); return _service; } private DataService() { } public JArray ExecuteSqlQueryJson(string sql) { using (IDbConnection oaConnection = context.Database.Connection) { using (IDbCommand oaCommand = oaConnection.CreateCommand()) { oaCommand.CommandText = sql; if (oaConnection.State == ConnectionState.Closed) oaConnection.Open(); using (IDataReader reader = oaCommand.ExecuteReader()) { var result = new JArray(); while (reader.Read()) { var row = new JObject(); for (int i = 0; i < reader.FieldCount; i++) { // var b = reader.GetValue(i); row.Add(reader.GetName(i).ToString(), new JValue(reader.GetValue(i) ?? JValue.CreateNull())); } result.Add(row); } return result; } } } } } }
22,438
https://github.com/yasir-sherwani99/customboxes/blob/master/resources/views/admin/pages/admins/index.blade.php
Github Open Source
Open Source
MIT
null
customboxes
yasir-sherwani99
PHP
Code
292
1,394
@extends('admin') @section('style') <script src="{{ asset('admin/app-assets/js/core/libraries/jquery.min.js') }}" ></script> @endsection @section('breadcrums') <div class="content-header-left col-md-9 col-12 mb-2 breadcrumb-new"> <h3 class="content-header-title mb-0 d-inline-block">Administrators</h3> <div class="row breadcrumbs-top d-inline-block"> <div class="breadcrumb-wrapper col-12"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">Home</a> </li> <li class="breadcrumb-item"><a href="javascript:;">Admin Management</a> </li> <li class="breadcrumb-item active">Administrators </li> </ol> </div> </div> </div> <div class="content-header-right col-md-3 col-12"> <a href="{{ route('admin.administrators.create') }}"> <button class="btn btn-sm btn-danger box-shadow-2 round btn-min-width pull-right" type="button">New Administrator</button> </a> </div> @endsection @section('content') @if (Session::has('success')) <div class="alert alert-icon-left alert-arrow-left alert-success alert-dismissible mb-2" role="alert"> <span class="alert-icon"><i class="la la-thumbs-o-up text-bold-600"></i></span> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <strong>Well done!</strong> <span class="text-bold-600">{{ Session::get('success') }}</span> </div> <script> $(document).ready(function(){ setTimeout(function(){ toastr.success("{{ Session::get('success') }}", 'PX System Says', {"hideDuration": 500, positionClass: 'toast-top-right'}); }, 2000); }); </script> @endif @if (count($errors) > 0) <div class="row"> <div class="col-md-12"> <div class="alert alert-danger alert-dismissible"> <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button> <b><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> Alert!</b> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </div> </div> </div> <script> $(document).ready(function(){ setTimeout(function(){ toastr.error('You must fill in all of the required fields!', 'PX System Says', {"hideDuration": 500, positionClass: 'toast-top-right'}); }, 2000); }); </script> @endif <div class="content-body"> <section id="user-profile-cards" class="row mt-2"> <div class="col-12"> <h4 class="text-uppercase">Admin Profiles</h4> <p>Manage system administrators.</p> </div> @foreach($admins as $admin) <div class="col-xl-4 col-md-6 col-12"> <div class="card card border-teal border-lighten-2"> <div class="text-center"> <div class="card-body"> @if($admin->image == NULL) <img src="{{ URL::asset('admin/app-assets/images/admin_images/default-avatar.png') }}" alt="admin avatar"><i></i> @else <img src="{{ URL::asset('admin/app-assets/images/admin_images/'.$admin->image) }}" alt="admin avatar"><i></i> @endif </div> <div class="card-body"> <h4 class="card-title">{{ $admin->first_name }}&nbsp;{{ $admin->last_name }}</h4> <ul class="list-inline list-inline-pipe"> <li> @if($admin->status == 1) <span class="success darken-4">Active</span> @else <span class="danger darken-4">Inactive</span> @endif </li> </ul> <h6 class="card-subtitle text-muted">{{ $admin->designation }}</h6> </div> <div class="card-body"> <a href="{{ route('admin.administrators.edit', $admin->id) }}"> <button type="button" class="btn btn-outline-info btn-md mr-1"><i class="la la-edit"></i> Edit Profile</button> </a> <!-- <button type="button" class="btn btn-primary mr-1"><i class="la la-eye"></i> Profile</button> --> </div> </div> </div> </div> @endforeach </section> </div> @endsection @section('script-admin') @endsection
19,370
https://github.com/gmprestes/BeerKeller/blob/master/Sistema/htmlsite/js/site/downloadFile.js
Github Open Source
Open Source
MIT
2,016
BeerKeller
gmprestes
JavaScript
Code
24
73
function downloadFile(requestID, fileUrl) { jQuery('<iframe id="' + requestID + '" src="' + fileUrl + '"></iframe>').appendTo('body').hide(); setTimeout(function () { $('#' + requestID).remove(); }, 30000); }
25,195
https://github.com/hosunrise/URCF-engine/blob/master/rpc/shared/register_param.go
Github Open Source
Open Source
MIT
null
URCF-engine
hosunrise
Go
Code
22
47
package shared type RegisterParam struct { Username string Password string Role []string } type VerifyParam struct { Username string Password string }
14,697
https://github.com/adil2604/alfa/blob/master/components/hero/Hero.vue
Github Open Source
Open Source
MIT
null
alfa
adil2604
Vue
Code
71
325
<template> <div class="container"> <div class="hero-body"> <b-carousel id="carousel-1" :interval="4000" controls indicators background="#ababab" img-width="1024" img-height="480" style="text-shadow: 1px 1px 2px #333;" > <!-- Text slides with image --> <b-carousel-slide img-src="../../static/slider1.jpg" > <p> Apple Watch Series 6 уже в продаже!<br> <b-button variant="primary">Заказать</b-button> </p> </b-carousel-slide> <!-- Slides with custom text --> <b-carousel-slide img-src="../../static/slider2.jpg"> </b-carousel-slide> </b-carousel> </div> </div> </template> <style lang="scss" scoped> .hero { background: url("../../static/slider1.png") no-repeat; background-position: center; } h1, h2 { color: #fff; } </style>
11,215
https://github.com/RomanIsko/lviv_bus_bot/blob/master/utils/vehicleTypeConverter.js
Github Open Source
Open Source
MIT
null
lviv_bus_bot
RomanIsko
JavaScript
Code
31
115
const convertVehicleTypeToEmoji = (vehicleType) => { switch (vehicleType) { case 'bus': case 'marshrutka': return '\u{1F68C}' case 'tram': return '\u{1F68B}' case 'trol': return '\u{1F68E}' default: return '' } } module.exports = convertVehicleTypeToEmoji
19,528
https://github.com/Karolyna84/meson/blob/master/mesonbuild/modules/qt.py
Github Open Source
Open Source
Apache-2.0
2,020
meson
Karolyna84
Python
Code
1,034
3,760
# Copyright 2015 The Meson development team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from .. import mlog from .. import build from ..mesonlib import MesonException, Popen_safe, extract_as_list, File, unholder from ..dependencies import Dependency, Qt4Dependency, Qt5Dependency import xml.etree.ElementTree as ET from . import ModuleReturnValue, get_include_args, ExtensionModule from ..interpreterbase import noPosargs, permittedKwargs, FeatureNew, FeatureNewKwargs from ..interpreter import extract_required_kwarg _QT_DEPS_LUT = { 4: Qt4Dependency, 5: Qt5Dependency } class QtBaseModule(ExtensionModule): tools_detected = False def __init__(self, interpreter, qt_version=5): ExtensionModule.__init__(self, interpreter) self.snippets.add('has_tools') self.qt_version = qt_version def _detect_tools(self, env, method): if self.tools_detected: return mlog.log('Detecting Qt{version} tools'.format(version=self.qt_version)) # FIXME: We currently require QtX to exist while importing the module. # We should make it gracefully degrade and not create any targets if # the import is marked as 'optional' (not implemented yet) kwargs = {'required': 'true', 'modules': 'Core', 'silent': 'true', 'method': method} qt = _QT_DEPS_LUT[self.qt_version](env, kwargs) # Get all tools and then make sure that they are the right version self.moc, self.uic, self.rcc, self.lrelease = qt.compilers_detect(self.interpreter) # Moc, uic and rcc write their version strings to stderr. # Moc and rcc return a non-zero result when doing so. # What kind of an idiot thought that was a good idea? for compiler, compiler_name in ((self.moc, "Moc"), (self.uic, "Uic"), (self.rcc, "Rcc"), (self.lrelease, "lrelease")): if compiler.found(): # Workaround since there is no easy way to know which tool/version support which flag for flag in ['-v', '-version']: p, stdout, stderr = Popen_safe(compiler.get_command() + [flag])[0:3] if p.returncode == 0: break stdout = stdout.strip() stderr = stderr.strip() if 'Qt {}'.format(self.qt_version) in stderr: compiler_ver = stderr elif 'version {}.'.format(self.qt_version) in stderr: compiler_ver = stderr elif ' {}.'.format(self.qt_version) in stdout: compiler_ver = stdout else: raise MesonException('{name} preprocessor is not for Qt {version}. Output:\n{stdo}\n{stderr}'.format( name=compiler_name, version=self.qt_version, stdo=stdout, stderr=stderr)) mlog.log(' {}:'.format(compiler_name.lower()), mlog.green('YES'), '({path}, {version})'.format( path=compiler.get_path(), version=compiler_ver.split()[-1])) else: mlog.log(' {}:'.format(compiler_name.lower()), mlog.red('NO')) self.tools_detected = True def parse_qrc(self, state, rcc_file): if type(rcc_file) is str: abspath = os.path.join(state.environment.source_dir, state.subdir, rcc_file) rcc_dirname = os.path.dirname(abspath) elif type(rcc_file) is File: abspath = rcc_file.absolute_path(state.environment.source_dir, state.environment.build_dir) rcc_dirname = os.path.dirname(abspath) try: tree = ET.parse(abspath) root = tree.getroot() result = [] for child in root[0]: if child.tag != 'file': mlog.warning("malformed rcc file: ", os.path.join(state.subdir, rcc_file)) break else: resource_path = child.text # We need to guess if the pointed resource is: # a) in build directory -> implies a generated file # b) in source directory # c) somewhere else external dependency file to bundle # # Also from qrc documentation: relative path are always from qrc file # So relative path must always be computed from qrc file ! if os.path.isabs(resource_path): # a) if resource_path.startswith(os.path.abspath(state.environment.build_dir)): resource_relpath = os.path.relpath(resource_path, state.environment.build_dir) result.append(File(is_built=True, subdir='', fname=resource_relpath)) # either b) or c) else: result.append(File(is_built=False, subdir=state.subdir, fname=resource_path)) else: path_from_rcc = os.path.normpath(os.path.join(rcc_dirname, resource_path)) # a) if path_from_rcc.startswith(state.environment.build_dir): result.append(File(is_built=True, subdir=state.subdir, fname=resource_path)) # b) else: result.append(File(is_built=False, subdir=state.subdir, fname=path_from_rcc)) return result except Exception: return [] @noPosargs @permittedKwargs({'method', 'required'}) @FeatureNew('qt.has_tools', '0.54.0') def has_tools(self, interpreter, state, args, kwargs): method = kwargs.get('method', 'auto') disabled, required, feature = extract_required_kwarg(kwargs, state.subproject, default=False) if disabled: mlog.log('qt.has_tools skipped: feature', mlog.bold(feature), 'disabled') return False self._detect_tools(state.environment, method) for tool in (self.moc, self.uic, self.rcc, self.lrelease): if not tool.found(): if required: raise MesonException('Qt tools not found') return False return True @FeatureNewKwargs('qt.preprocess', '0.49.0', ['uic_extra_arguments']) @FeatureNewKwargs('qt.preprocess', '0.44.0', ['moc_extra_arguments']) @FeatureNewKwargs('qt.preprocess', '0.49.0', ['rcc_extra_arguments']) @permittedKwargs({'moc_headers', 'moc_sources', 'uic_extra_arguments', 'moc_extra_arguments', 'rcc_extra_arguments', 'include_directories', 'dependencies', 'ui_files', 'qresources', 'method'}) def preprocess(self, state, args, kwargs): rcc_files, ui_files, moc_headers, moc_sources, uic_extra_arguments, moc_extra_arguments, rcc_extra_arguments, sources, include_directories, dependencies \ = [extract_as_list(kwargs, c, pop=True) for c in ['qresources', 'ui_files', 'moc_headers', 'moc_sources', 'uic_extra_arguments', 'moc_extra_arguments', 'rcc_extra_arguments', 'sources', 'include_directories', 'dependencies']] sources += args[1:] method = kwargs.get('method', 'auto') self._detect_tools(state.environment, method) err_msg = "{0} sources specified and couldn't find {1}, " \ "please check your qt{2} installation" if (moc_headers or moc_sources) and not self.moc.found(): raise MesonException(err_msg.format('MOC', 'moc-qt{}'.format(self.qt_version), self.qt_version)) if rcc_files: if not self.rcc.found(): raise MesonException(err_msg.format('RCC', 'rcc-qt{}'.format(self.qt_version), self.qt_version)) # custom output name set? -> one output file, multiple otherwise if args: qrc_deps = [] for i in rcc_files: qrc_deps += self.parse_qrc(state, i) name = args[0] rcc_kwargs = {'input': rcc_files, 'output': name + '.cpp', 'command': [self.rcc, '-name', name, '-o', '@OUTPUT@', rcc_extra_arguments, '@INPUT@'], 'depend_files': qrc_deps} res_target = build.CustomTarget(name, state.subdir, state.subproject, rcc_kwargs) sources.append(res_target) else: for rcc_file in rcc_files: qrc_deps = self.parse_qrc(state, rcc_file) if type(rcc_file) is str: basename = os.path.basename(rcc_file) elif type(rcc_file) is File: basename = os.path.basename(rcc_file.fname) name = 'qt' + str(self.qt_version) + '-' + basename.replace('.', '_') rcc_kwargs = {'input': rcc_file, 'output': name + '.cpp', 'command': [self.rcc, '-name', '@BASENAME@', '-o', '@OUTPUT@', rcc_extra_arguments, '@INPUT@'], 'depend_files': qrc_deps} res_target = build.CustomTarget(name, state.subdir, state.subproject, rcc_kwargs) sources.append(res_target) if ui_files: if not self.uic.found(): raise MesonException(err_msg.format('UIC', 'uic-qt{}'.format(self.qt_version), self.qt_version)) arguments = uic_extra_arguments + ['-o', '@OUTPUT@', '@INPUT@'] ui_kwargs = {'output': 'ui_@BASENAME@.h', 'arguments': arguments} ui_gen = build.Generator([self.uic], ui_kwargs) ui_output = ui_gen.process_files('Qt{} ui'.format(self.qt_version), ui_files, state) sources.append(ui_output) inc = get_include_args(include_dirs=include_directories) compile_args = [] for dep in unholder(dependencies): if isinstance(dep, Dependency): for arg in dep.get_compile_args(): if arg.startswith('-I') or arg.startswith('-D'): compile_args.append(arg) else: raise MesonException('Argument is of an unacceptable type {!r}.\nMust be ' 'either an external dependency (returned by find_library() or ' 'dependency()) or an internal dependency (returned by ' 'declare_dependency()).'.format(type(dep).__name__)) if moc_headers: arguments = moc_extra_arguments + inc + compile_args + ['@INPUT@', '-o', '@OUTPUT@'] moc_kwargs = {'output': 'moc_@BASENAME@.cpp', 'arguments': arguments} moc_gen = build.Generator([self.moc], moc_kwargs) moc_output = moc_gen.process_files('Qt{} moc header'.format(self.qt_version), moc_headers, state) sources.append(moc_output) if moc_sources: arguments = moc_extra_arguments + inc + compile_args + ['@INPUT@', '-o', '@OUTPUT@'] moc_kwargs = {'output': '@BASENAME@.moc', 'arguments': arguments} moc_gen = build.Generator([self.moc], moc_kwargs) moc_output = moc_gen.process_files('Qt{} moc source'.format(self.qt_version), moc_sources, state) sources.append(moc_output) return ModuleReturnValue(sources, sources) @FeatureNew('qt.compile_translations', '0.44.0') @permittedKwargs({'ts_files', 'install', 'install_dir', 'build_by_default', 'method'}) def compile_translations(self, state, args, kwargs): ts_files, install_dir = [extract_as_list(kwargs, c, pop=True) for c in ['ts_files', 'install_dir']] self._detect_tools(state.environment, kwargs.get('method', 'auto')) translations = [] for ts in ts_files: if not self.lrelease.found(): raise MesonException('qt.compile_translations: ' + self.lrelease.name + ' not found') cmd = [self.lrelease, '@INPUT@', '-qm', '@OUTPUT@'] lrelease_kwargs = {'output': '@BASENAME@.qm', 'input': ts, 'install': kwargs.get('install', False), 'build_by_default': kwargs.get('build_by_default', False), 'command': cmd} if install_dir is not None: lrelease_kwargs['install_dir'] = install_dir lrelease_target = build.CustomTarget('qt{}-compile-{}'.format(self.qt_version, ts), state.subdir, state.subproject, lrelease_kwargs) translations.append(lrelease_target) return ModuleReturnValue(translations, translations)
45,947
https://github.com/leventeliu/goproc/blob/master/timeout_chan.go
Github Open Source
Open Source
MIT
2,021
goproc
leventeliu
Go
Code
765
2,399
package goproc import ( "container/heap" "context" "fmt" "sync" "time" ) // Deadliner is the interface implemented by an object that can return a deadline time. type Deadliner interface { Deadline() time.Time } // TimeoutChanStats contains timeout chan statistics returned from TimeoutChan.Stats(). type TimeoutChanStats struct { Pushed int Popped int Cleared int } // String implements fmt.Stringer. func (s TimeoutChanStats) String() string { return fmt.Sprintf("TimeoutChanStats: Pushed=%d Popped=%d Cleared=%d", s.Pushed, s.Popped, s.Cleared) } // TimeoutChan is a type representing a channel for Deadliner objects. // TimeoutChan accepts Deadliner from TimeoutChan.In and sends Deadliner to Timeout.Out when its // deadline is reached. type TimeoutChan struct { In chan<- Deadliner Out <-chan Deadliner ctx context.Context pushCtrl *Controller popCtrl *Controller resolution time.Duration limit int in chan Deadliner out chan Deadliner resumePush chan interface{} resumePop chan interface{} reschedule chan interface{} closePush chan interface{} mu *sync.RWMutex pq *PriorityQueue pushed int popped int cleared int } // NewTimeoutChan creates a new TimeoutChan. With 0 limit an unlimited timeout chan will be // returned. func NewTimeoutChan(ctx context.Context, resolution time.Duration, limit int) *TimeoutChan { size := limit if limit == 0 { size = 1024 } in := make(chan Deadliner) out := make(chan Deadliner) tc := &TimeoutChan{ In: in, Out: out, ctx: ctx, pushCtrl: NewController(ctx, "TimeoutChan Push"), popCtrl: NewController(ctx, "TimeoutChan Pop"), resolution: resolution, limit: limit, in: in, out: out, resumePush: make(chan interface{}), resumePop: make(chan interface{}), reschedule: make(chan interface{}), closePush: make(chan interface{}), mu: &sync.RWMutex{}, pq: NewPriorityQueue(false, size), pushed: 0, popped: 0, cleared: 0, } tc.popCtrl.Go(tc.popProcess) tc.pushCtrl.Go(tc.pushProcess) return tc } // Push is an alias of TimeoutChan.In <- (in Deadliner), but bypasses background push process for // unlimited TimeoutChan. func (c *TimeoutChan) Push(in Deadliner) { if c.limit == 0 { c.push(in) } else { c.In <- in } } // Clear clears buffered Deadliners in TimeoutChan. func (c *TimeoutChan) Clear() int { c.mu.Lock() defer c.mu.Unlock() c.pushCtrl.Shutdown() c.popCtrl.Shutdown() l := c.pq.Clear() if c.limit > 0 && l == c.limit { defer func() { c.resumePush <- nil }() // queue is not full, resume } c.cleared += l c.pushCtrl = NewController(c.ctx, "TimeoutChan Push") c.popCtrl = NewController(c.ctx, "TimeoutChan Pop") c.popCtrl.Go(c.popProcess) c.pushCtrl.Go(c.pushProcess) return l } // Close closes TimeoutChan and waits until all buffered Deadliners in TimeoutChan to be sent and // read in TimeoutChan.Out before it returns. func (c *TimeoutChan) Close() { close(c.in) c.pushCtrl.Wait() close(c.closePush) c.popCtrl.Wait() close(c.out) close(c.resumePush) close(c.resumePop) close(c.reschedule) } // Shutdown closes TimeoutChan and returns immediately, any buffered Deadliners in TimeoutChan will // be ignored. func (c *TimeoutChan) Shutdown() { close(c.in) c.pushCtrl.Shutdown() close(c.closePush) c.popCtrl.Shutdown() close(c.out) close(c.resumePush) close(c.resumePop) close(c.reschedule) } // Stats returns TimeoutChan statistics. func (c *TimeoutChan) Stats() TimeoutChanStats { c.mu.RLock() defer c.mu.RUnlock() return TimeoutChanStats{ Pushed: c.pushed, Popped: c.popped, Cleared: c.cleared, } } func (c *TimeoutChan) len() int { c.mu.RLock() defer c.mu.RUnlock() return c.pq.Len() } func (c *TimeoutChan) peek() (<-chan interface{}, time.Duration) { c.mu.RLock() defer c.mu.RUnlock() return c.reschedule, c.pq.Peek().(Deadliner).Deadline().Sub(time.Now()) } type prioritierWrapper struct { Deadliner } func (w prioritierWrapper) Priority() int64 { return w.Deadline().UnixNano() } func (c *TimeoutChan) push(in Deadliner) { c.mu.Lock() defer c.mu.Unlock() if c.pq.Len() == 0 { defer func() { c.resumePop <- nil }() } else { if in.Deadline().Before(c.pq.Peek().(Deadliner).Deadline()) { // Most recent deadline changed, send reschedule notice defer func() { close(c.reschedule) c.reschedule = make(chan interface{}) }() } } heap.Push(c.pq, prioritierWrapper{in}) c.pushed++ } func (c *TimeoutChan) pop() Deadliner { c.mu.Lock() defer c.mu.Unlock() if c.limit > 0 && c.pq.Len() == c.limit { defer func() { c.resumePush <- nil }() // queue is not full, resume } c.popped++ return heap.Pop(c.pq).(prioritierWrapper).Deadliner // unwrap } func (c *TimeoutChan) pushProcess(ctx context.Context) { for { // Working phase select { case in, ok := <-c.in: if !ok { // End push process because `in` channel is closed and drained return } c.push(in) if c.limit == 0 || c.len() < c.limit { continue } // else queue is full, suspense case <-ctx.Done(): return } // Suspending phase select { case <-c.resumePush: case <-ctx.Done(): return } } } func (c *TimeoutChan) popProcess(ctx context.Context) { for { // Suspending phase select { case <-c.resumePop: case <-c.closePush: if c.len() == 0 { return } case <-ctx.Done(): return } // Working phase outerLoop: for { // Peeking sub-phase reschedule, delta := c.peek() if delta <= 0 { select { case c.out <- c.pop(): if c.len() == 0 { break outerLoop // queue is empty, suspend } case <-ctx.Done(): return } } // Spinning sub-phase if d := delta / 2; d > c.resolution { delta = d } else if delta > c.resolution { delta = c.resolution } timer := time.NewTimer(delta) select { case <-reschedule: // should receive any reschedule after last peek if !timer.Stop() { <-timer.C } case <-timer.C: case <-ctx.Done(): return } } } }
13,927
https://github.com/tmcclure911/AuraApp/blob/master/src/main/webapp/WEB-INF/components/phoneTest/phoneSender/phoneSenderController.js
Github Open Source
Open Source
MIT
null
AuraApp
tmcclure911
JavaScript
Code
30
152
({ sendPhone : function(component, event, helper) { console.log("Sending phone"); var phoneEvent = $A.get("e.phoneTest:phoneMessage"); phoneEvent.setParams({ "name": "Matt", "date": new Date(), "message": "A tweet!", "imageUrl": "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" }); phoneEvent.fire(); component.set("v.inputText", ""); } })
22,937
https://github.com/PlatiaTeam/authy-client/blob/master/src/bin/commands/application.js
Github Open Source
Open Source
MIT
2,022
authy-client
PlatiaTeam
JavaScript
Code
21
54
/** * Export command definition. */ export default { builder: yargs => yargs.commandDir('application'), command: 'application <command>', describe: 'Manage application information' };
23,192
https://github.com/tjaranowski/Data-Structures/blob/master/src/main/java/pl/nosystems/java/datastructures/state/Full.java
Github Open Source
Open Source
MIT
null
Data-Structures
tjaranowski
Java
Code
19
66
package pl.nosystems.java.datastructures.state; @SuppressWarnings("WeakerAccess") public class Full extends Exception { public Full() {} public Full(Throwable throwable) { super(throwable); } }
23,370
https://github.com/BrecanYT/discord-bot/blob/master/node_modules/free-translate/dist/index.d.ts
Github Open Source
Open Source
MIT
null
discord-bot
BrecanYT
TypeScript
Code
23
51
import { Language } from './types/Language'; export interface Translate { from: Language; to: Language; } export declare function translate(text: string, languages: Translate): Promise<string>;
10,655
https://github.com/caiquetorres/graphql-example-nestjs/blob/master/src/main.ts
Github Open Source
Open Source
MIT
2,021
graphql-example-nestjs
caiquetorres
TypeScript
Code
151
431
import { INestApplication, ValidationPipe } from '@nestjs/common' import { NestFactory } from '@nestjs/core' import { EnvService } from './modules/env/services/env.service' import { AppModule } from './app.module' import { I18nFilter } from './filters/i18n/i18n.filter' import { SentryFilter } from './filters/sentry/sentry.filter' import { I18nService } from 'nestjs-i18n' async function bootstrap() { const app = await NestFactory.create(AppModule) const envService = app.get(EnvService) const i18nService = app.get(I18nService) setupPipes(app) setupFilters(app, envService, i18nService) app.enableCors() await app.listen(envService.get('PORT') || 3000) } bootstrap() //#region Setup /** * Function that set the global pipes to the application * * @param app stores the application instance */ function setupPipes(app: INestApplication): void { app.useGlobalPipes( new ValidationPipe({ whitelist: true, }), ) } /** * Function that set the filters to the application * * @param app stores the application instance * @param envService stores the application settings */ function setupFilters( app: INestApplication, envService: EnvService, i18nService: I18nService, ): void { app.useGlobalFilters( new SentryFilter(envService), new I18nFilter(i18nService), ) } //#endregion
46,606
https://github.com/CiscoTestAutomation/genielibs/blob/master/pkgs/sdk-pkg/src/genie/libs/sdk/apis/iosxe/install/execute.py
Github Open Source
Open Source
Apache-2.0
2,023
genielibs
CiscoTestAutomation
Python
Code
3,021
8,516
# Python import logging import re import time # Unicon from unicon.eal.dialogs import Statement, Dialog log = logging.getLogger(__name__) def execute_install_remove_version(device, version=None, timeout=60, connect_timeout = 10): """ Performs install remove for the version provided on the device Args: device ('obj'): Device object version ('str, optional'): Base Version to remove timeout ('int, optional'): Timeout value connect_timeout ('int, optional'): Time to wait before sending the promt (when pattern "SUCCESS: install_remove" matches) Returns: True if install remove is successful False if install remove is not successful Raises: SubCommandFailure """ log.info(f"Performing install remove for version {version} on {device.name}") def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog([ Statement(pattern=r".*\[y/n\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement(pattern=r".*Nothing to clean\.", action=None, args=None, loop_continue=True, continue_timer=False), Statement(pattern=r"%s#" % device.name, action=None, args=None, loop_continue=False, continue_timer=False), Statement(pattern=r".*SUCCESS\: install_remove.*", action=slow_sendline, args=None, loop_continue=False, continue_timer=False), ]) if version: cmd = f"install remove version {version}" try: output = device.execute(cmd, reply=dialog, timeout=timeout) except Exception as e: log.error(f"Error while executing {cmd} on {device.name}: {e}") return False match = re.search(r"FAILED: install_remove.*", output) result = 'failed' if match else 'successful' log.info(f"install remove version {result} on {device.name}") return True if not match else match def execute_install_activate(device, abort_timer=None, prompt=True, issu=False, smu=False, file_name=None, timeout=900, connect_timeout=10): """ Performs install activate with auto abort timer on the device Args: device ('obj'): Device object abort_timer ('str, optional'): abort timer value prompt ('bool, optional'): True sets the command to ask for prompt and False sets the prompt level to none issu ('bool, optional'): Force the operation to use issu technique smu ('bool, optional'): Force the operation to use smu technique file_name ('str, optional'): Path of the image file for smu operation timeout ('int, optional'): Timeout value connect_timeout ('int, optional'): Time to wait before sending the prompt (when pattern "Press RETURN to get started" matches) Returns: True if install activate is successful False if install activate is not successful Raises: SubCommandFailure """ def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog([ Statement(pattern=r".*\[y/n\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement(pattern=r".*Please confirm you have changed boot config to .*\/packages\.conf \[y/n\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement(pattern=r".*you may save configuration and re-enter the command\. \[y/n/q\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement(pattern=r"%s.*# " % device.name, action=None, args=None, loop_continue=True, continue_timer=False), Statement(pattern=r".*Press RETURN to get started.*", action=slow_sendline, args=None, loop_continue=False, continue_timer=False), Statement(pattern = r".*SUCCESS: install_activate.*", action = None, args = None, loop_continue = False, continue_timer = False), ]) cmd = "install activate " # no smu, no issu, abort_timer and prompt none if not smu and not issu and abort_timer and not prompt: cmd +=f" auto-abort-timer {abort_timer} prompt-level none" # smu, no issu, abort_timer, prompt none elif smu and not issu and abort_timer and not prompt: cmd += f" file {file_name} auto-abort-timer {abort_timer} prompt-level none" # smu, no issu, no abort_timer, prompt none elif smu and not issu and not abort_timer and not prompt: cmd += f" file {file_name} prompt-level none" # smu, no issu, abort_timer, with prompt elif smu and not issu and abort_timer: cmd += f" file {file_name} auto-abort-timer {abort_timer}" # smu, no issu, abort_timer, with prompt elif smu and not issu and not abort_timer: cmd += f" file {file_name}" # smu, issu, abort_timer, with prompt elif smu and issu and abort_timer: cmd += f" file {file_name} issu auto-abort-timer {abort_timer}" # smu, issu, no abort_timer, with prompt elif smu and issu and not abort_timer: cmd += f" file {file_name} issu" # no smu, no issu, and prompt none elif not smu and not issu and abort_timer: cmd += f" auto-abort-timer {abort_timer}" # no smu, issu, abort_timer elif issu and not smu and abort_timer: cmd += f" issu auto-abort-timer {abort_timer}" # no smu, issu, not abort_timer elif issu and not smu and not abort_timer: cmd += " issu" log.info(f"Performing {cmd} on device {device.name}") try: device.api.execute_write_memory() output = device.execute(cmd, reply=dialog, timeout=timeout) log.info(f"{cmd} is successful on device {device.name}") except Exception as e: log.error(f"Error while executing {cmd} on {device.name}: {e}") return False match = re.search(r".*SUCCESS: install_activate.*", output) result = 'successful' if match else 'failed' log.info(f"install activate operation is {result} on {device.name}") return output if match else match def execute_install_remove(device, file_path=None, timeout=60, connect_timeout=10): """ Performs install remove on the device Args: device ('obj'): Device object file_path ('str, optional'): Path of the file on device to remove timeout ('int, optional'): Timeout value connect_timeout ('int, optional'): Time to wait before sending the promt (when pattern "SUCCESS: install_remove" matches) Returns: True if install remove is successful False if install remove is not successful Raises: SubCommandFailure """ log.info("Performing install remove on {hostname} to remove the " "unused files ".format(hostname=device.name)) def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog([ Statement(pattern=r".*\[y/n\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement(pattern=r".*Nothing to clean\.", action=None, args=None, loop_continue=True, continue_timer=False), Statement(pattern=r"%s#" % device.name, action=None, args=None, loop_continue=False, continue_timer=False), Statement(pattern=r".*SUCCESS\: install_remove.*", action=slow_sendline, args=None, loop_continue=False, continue_timer=False), ]) cmd = 'install remove' if file_path: cmd += f' file {file_path}' else: cmd += ' inactive' try: device.api.execute_write_memory() output = device.execute(cmd, reply=dialog, timeout=timeout) except Exception as e: log.error(f"Error while executing {cmd} on {device.name}: {e}") return False match = re.search(r"FAILED:*", output) result = 'failed' if match else 'successful' log.info(f"install remove inactive is {result} on {device.name}") return True if not match else match def execute_install_one_shot(device, file_path=None, prompt=True, issu=False, negative_test=False, timeout=900, connect_timeout=10, xfsu=False): """ Performs install one shot on the device Args: device ('obj'): Device object file_path ('str, optional'): Path of the image prompt ('bool, optional'): True sets the command to ask for prompt and False sets the prompt level to none issu ('bool, optional'): Force the operation to use issu technique negative_test ('bool, optional'): Flag for install add pass/Fail cases timeout ('int, optional'): Timeout value connect_timeout ('int, optional'): Time to wait before sending the prompt (when pattern "Press RETURN to get started" matches) Returns: True if install one shot is successful False if install one shot is not successful Raises: Exception """ def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog ([ Statement(pattern = r".*\[y/n\]\s*$", action = "sendline(y)", args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*you may save configuration and re-enter the command\. \[y/n/q\]", action = "sendline(y)", args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*Press RETURN to get started.*", action = slow_sendline, args = None, loop_continue = False, continue_timer = False), Statement(pattern = r".*SUCCESS\: install_add_activate_commit.*", action = None, args = None, loop_continue = False, continue_timer = False), ]) log.info(f"Perform install one shot {device.name}") cmd = f"install add file {file_path} activate" if issu: cmd += f" issu" if xfsu: cmd += f" xfsu" cmd += " commit" if not prompt: cmd += " prompt-level none" try: device.api.execute_write_memory() output = device.execute(cmd, reply=dialog, timeout=timeout) except Exception as e: log.error(f"Error while executing {cmd} on {device.name}: {e}") pattern = 'SUCCESS' if negative_test else 'FAILED' result = 'fail' if pattern in output else 'successful' log.info(f"install one shot operation {result} on {device.name}") return (output if result == 'successful' else False) def execute_install_add(device, file_path=None, prompt=True, negative_test=False, timeout=900, connect_timeout=10): """ Performs install add on the device Args: device ('obj'): Device object file_path ('str, optional'): Path of the image prompt ('bool, optional'): True sets the command to ask for prompt and False sets the prompt level to none negative_test ('str, optional'): Flag for install add pass/Fail cases timeout ('int, optional'): Timeout value connect_timeout ('int, optional'): Time to wait before sending the prompt (when pattern "Press RETURN to get started" matches) Returns: True if install one shot is successful False if install one shot is not successful Raises: SubCommandFailure """ def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') if negative_test == False: dialog = Dialog ([ Statement(pattern = r".*Finished initial file syncing", action = None, args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*SUCCESS\: install_add", action = None, args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*FAILED\: install_add", action = None, args = None, loop_continue = False, continue_timer = False), Statement(pattern = r"%s.*#"%device.name, action = None, args = None, loop_continue = False, continue_timer = False), Statement(pattern = r"Press RETURN to get started!", action = slow_sendline, args = None, loop_continue = True, continue_timer = False), ]) else: dialog = Dialog ([ Statement(pattern = r".*Finished initial file syncing", action = None, args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*SUCCESS\: install_add", action = None, args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*Copying.*", action = slow_sendline, args = None, loop_continue = False, continue_timer = False), Statement(pattern = r".*FAILED\: install_add", action = None, args = None, loop_continue = True, continue_timer = False), Statement(pattern = r"Press RETURN to get started!", action = slow_sendline, args = None, loop_continue = True, continue_timer = False), ]) log.info(f"Perform install add on device {device.name}") cmd = f"install add file {file_path}" if not prompt: cmd += " prompt-level none" try: device.api.execute_write_memory() output = device.execute(cmd, reply=dialog, timeout=timeout) except Exception as e: log.error(f"Error while executing {cmd} on {device.name}: {e}") return False pattern = 'SUCCESS' if negative_test else 'FAILED' result = 'fail' if pattern in output else 'successful' log.info(f"Install add {result} on {device.name}") return( output if result == 'successful' else False) def execute_install_commit(device, timeout=900, connect_timeout=10): """ Performs install commit on the device Args: device ('obj'): Device object timeout ('int, optional'): Timeout value connect_timeout ('int, optional'): Time to wait before sending the prompt (when pattern SUCCESS: install_commit" matches) Returns: True if install commit is successful False if install commit is not successful Raises: SubCommandFailure """ log.info("Executing Install Commit on {0}" .format(device.name)) def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog ([ Statement(pattern = r".*SUCCESS\: install_commit", action = slow_sendline, args = None, loop_continue = True, continue_timer = False), Statement(pattern=r"%s#" % device.name, action = None, args = None, loop_continue = False, continue_timer = False), ]) try: device.api.execute_write_memory() output = device.execute("install commit", reply=dialog, timeout=timeout) except Exception as e: log.error(f"Error while executing install commit on {device.name}: {e}") return False match = re.search(r"SUCCESS\: install_commit", output) result = 'successful' if match else 'failed' log.info(f"install commit operation {result} on {device.name}") return output if match else match def execute_create_rollback_label(device, rollback_id, rollback_label): """ Creates rollback label for rollback id Args: device ('obj'): Device object rollback_id ('str'): rollback id for which label has to be created . rollback_label ('str'): rollback label Returns: True if rollback label is successfully created False if failed to creted rollback label Raises: SubCommandFailure """ log.info(f"Creating rollback label for rollback id {rollback_id}") try: device.execute(f"install label {rollback_id} label-name {rollback_label}") except Exception as e: log.error(f"Failed to create label for rollback id {rollback_id}: {e}") return False log.info(f"Created label for rollback id {rollback_id}") return True def execute_create_rollback_description(device, rollback_id, rollback_description): """ Creates rollback description for rollback id Args: device ('obj'): Device object rollback_id ('str'): rollback id for which label has to be created . rollback_description ('str'): rollback description Returns: True if rollback description is successfully created False if failed to creted rollback label Raises: SubCommandFailure """ log.info(f"Creating rollback description for rollback id {rollback_id}") try: device.execute(f"install label {rollback_id} description \"{rollback_description}\"") except Exception as e: log.error(f"Failed to create description for rollback id {rollback_id}: {e}") return False log.info(f"Created description for rollback id {rollback_id}") return True def execute_clear_install_state(device, timeout=900, connect_timeout=10): """ Performs clear install state on device Args: device ('obj'): Device object timeout ('int, optional'): Timeout value connect_timeout ('int, optional'): Time to wait before sending the prompt (when pattern "Press RETURN to get started" matches) Returns: True if clear install state is successfull False if clear install state is not successfull Raises: SubCommandFailure """ def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog ([ Statement(pattern = r".*\[y/n\]", action = "sendline(y)", args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*Press RETURN to get started.*", action = slow_sendline, args = None, loop_continue = False, continue_timer = False), Statement(pattern=r"%s#" % device.name, action = None, args = None, loop_continue = False, continue_timer = False), ]) log.info(f"Performing clear install state on {device.name}") cmd = "clear install state " try: device.api.execute_write_memory() device.execute(cmd, reply=dialog, prompt_recovery=True, error_pattern=[], timeout=timeout) except Exception as e: log.error(f"Error while executing clear install state on device {device.name}: {e}") return False return True def execute_install_auto_abort_timer_stop(device, timeout=120): """ Performs install auto-abort-timer stop on device Args: device ('obj'): Device object timeout ('int, optional'): Timeout value Returns: True if install auto-abort-timer stop is successful False if install auto-abort-timer stop is not successful Raises: SubCommandFailure """ try: output = device.execute("install auto-abort-timer stop", timeout=timeout) except Exception as e: log.error("Error thrown while executing is {0}".format(e)) match = re.search('.*SUCCESS.*', output) result = 'successful' if match else 'failed' log.info(f"ISSU auto-abort timer stop command execution is {result} on {device.name}") return(True if result == 'successful' else False ) def execute_clear_install_label(device, timeout=900, connect_timeout=10, id = None ,label_name = None): """ Performs clear install state on device Args: device ('obj'): Device object timeout ('int, optional'): Timeout value id = ('str optional'): rollback_label id label_name = ('str optional'): rollback_label name connect_timeout ('int, optional'): Time to wait before sending the prompt (when pattern "Press RETURN to get started" matches) Returns: True if clear install state is successfull False if clear install state is not successfull Raises: SubCommandFailure """ def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog ([ Statement(pattern = r".*SUCCESS\: clear_install_label", action = slow_sendline, args = None, loop_continue = True, continue_timer = False), Statement(pattern=r"%s#" % device.name, action = None, args = None, loop_continue = False, continue_timer = False), ]) log.info(f"Performing clear install label on {device.name}") cmd = cmd = f"clear install label " if id: cmd += f" id {id}" elif label_name: cmd += f" label-name {label_name}" else: log.info("No proper values provided") return False try: device.execute("wr mem") device.execute(cmd, reply=dialog, timeout=timeout) except Exception as e: log.error(f"Error while executing clear install label on device {device.name}: {e}") return False return True def execute_install_abort(device, issu=False, timeout=900, connect_timeout=10): """ Performs install abort on the device Args: device ('obj'): Device object issu ('bool, optional'): True Forces the operation to use issu technique timeout ('int, optional'): Timeout value connect_timeout ('int, optional'): Time to wait before sending the promt (when pattern "Press RETURN to get started" matches) Returns: True if install abort is successful False if install abort is not successful Raises: SubCommandFailure """ log.info("Executing Install abort on {0}".format(device.name)) def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog([ Statement(pattern=r".*\[y/n\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement( pattern=r".*you may save configuration and re-enter the command\. \[y/n/q\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement(pattern=r"%s.*# " % device.name, action=None, args=None, loop_continue=True, continue_timer=False), Statement(pattern=r".*Press RETURN to get started.*", action=slow_sendline, args=None, loop_continue=False, continue_timer=False), ]) cmd = "install abort" if issu: cmd += " issu" try: device.api.execute_write_memory() output = device.execute(cmd, reply=dialog, timeout=timeout) log.info("Successfully completed install abort on {}".format(device.name)) except Exception as e: log.error(f"Failed to execute install abort on device {device.name}: {e}") return False match = re.search(r"^FAILED\:\s+install_abort.*", output) result = 'failed' if match else 'successful' log.info(f"install abort operation {result} on {device.name}") return output if not match else match def execute_install_deactivate(device, abort_timer=None, prompt=True, issu=False, file_name=None, timeout=900, connect_timeout=10): """ Performs install deactivate with auto abort timer on the device Args: device ('obj'): Device object abort_timer ('str, optional'): abort timer value prompt ('bool, optional'): True sets the command to ask for prompt and False sets the prompt level to none issu ('bool, optional'): Force the operation to use issu technique file_name ('str, optional'): Path of the image file for smu operation timeout ('int, optional'): Timeout value connect_timeout ('int, optional'): Time to wait before sending the prompt (when pattern "Press RETURN to get started" matches) Returns: True if install activate is successful False if install activate is not successful Raises: SubCommandFailure """ def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog ([ Statement(pattern = r".*\[y/n\]", action = "sendline(y)", args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*Please confirm you have changed boot config to .*\/packages\.conf \[y/n\]", action = "sendline(y)", args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*you may save configuration and re-enter the command\. \[y/n/q\]", action = "sendline(y)", args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*This operation may require a reload of the system. Do you want to proceed\?\. \[y/n\]", action = "sendline(y)", args = None, loop_continue = True, continue_timer = False), Statement(pattern = r".*Press RETURN to get started.*", action = slow_sendline, args = None, loop_continue = False, continue_timer = False), Statement(pattern = r".*SUCCESS:*install_deactivate.*", action = slow_sendline, args = None, loop_continue = False, continue_timer = False), ]) cmd = f"install deactivate file {file_name} " if not issu and abort_timer and not prompt: cmd += f" auto-abort-timer {abort_timer} prompt-level none" elif not issu and abort_timer: cmd += f" auto-abort-timer {abort_timer}" elif issu and abort_timer: cmd += f" issu auto-abort-timer {abort_timer}" elif issu and not abort_timer: cmd += f" issu" elif not issu and abort_timer: cmd += f" auto-abort-timer {abort_timer}" elif not issu and not abort_timer and not prompt: cmd += f" prompt-level none" log.info(f"Performing {cmd} on device {device.name}") try: device.api.execute_write_memory() output = device.execute(cmd, reply=dialog, timeout=timeout, error_pattern=[]) log.info(f"{cmd} is successful on device {device.name}") except Exception as e: log.error(f"Error while executing {cmd} on {device.name}: {e}") return False match = re.search(r"^FAILED:*install_deactivate.*", output) result = 'failed' if match else 'successful' log.info(f"install deactivate operation {result} on {device.name}") return output if not match else match def execute_install_rollback(device, rollback_point=None, rollback_id=None, issu=False, rollback_label=None, timeout=900, connect_timeout=10, prompt=True): """ Performs rollback on the device Args: device ('obj'): Device object rollback_point ('str, optional'): Last committed/base installation point rollback_id ('str, optional'): specific install point id rollback_label ('str, optional'): specific install point label issu ('bool, optional'): Force the operation to use issu technique timeout ('int, optional'): Timeout value prompt ('bool, optional'): True sets the command to ask for prompt and False sets the prompt level to none connect_timeout ('int, optional'): Time to wait before sending the promt (when pattern "Press RETURN to get started" matches) Returns: True if rollback is successfull False if rollback is not successfull or rollback point not provided Raises: SubCommandFailure """ def slow_sendline(spawn): time.sleep(connect_timeout) spawn.sendline('') dialog = Dialog([ Statement(pattern=r".*\[y/n\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement(pattern=r".*Please confirm you have changed boot config to .*\/packages\.conf \[y/n\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement(pattern=r".*you may save configuration and re-enter " r"the command\. \[y/n/q\]", action="sendline(y)", args=None, loop_continue=True, continue_timer=False), Statement(pattern=r"%s.*# " % device.name, action=None, args=None, loop_continue=True, continue_timer=False), Statement(pattern=r".*Press RETURN to get started.*", action=slow_sendline, args=None, loop_continue=False, continue_timer=False), ]) log.info("Executing Install rollback on {0}" .format(device.name)) log.info("rollback label is : {rollback_label}" .format( rollback_label=rollback_label)) cmd = "install rollback to " if rollback_point == "committed": cmd += f"{rollback_point}" elif rollback_point == "base": cmd += f"{rollback_point}" elif rollback_id: cmd += f"id {rollback_id}" elif rollback_label: cmd += f"label {rollback_label}" else: log.info("rollback point not provided") return False if issu: cmd += " issu" if not prompt: cmd += " prompt-level none" try: device.execute("wr mem") output = device.execute(cmd, reply=dialog, timeout=timeout) log.info(f"Successfully completed install rollback on {device.name}") except Exception as e: log.error(f"Error while executing {cmd} on {device.name}: {e}") return False match = re.search(r"^FAILED\:\s+install_rollback.*", output) result = 'failed' if match else 'successful' log.info(f"install rollback operation got {result} on {device.name}") return output if not match else match
15,499
https://github.com/d0scoo1/naga_contracts/blob/master/mainnet/contracts/0x7944B4407796014D7D3191960A44478056beed07_WMTDrop/contracts/WMTDrop.sol
Github Open Source
Open Source
MIT
2,023
naga_contracts
d0scoo1
Gerber Image
Code
55
225
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.12; import "@openzeppelin/contracts@3.4.0/token/ERC20/IERC20.sol"; contract WMTDrop { mapping(address => bool) public mapped; IERC20 wmtToken; event Mapped(address sender, string cardanoAddress, uint256 amount0); constructor(address _tokenAddress) public { wmtToken = IERC20(_tokenAddress); } function mapAddress(string memory cardanoAddress) external { uint256 tokenBal = wmtToken.balanceOf(msg.sender); require(tokenBal>0,"No WMT Balance"); require(!mapped[msg.sender],"Already mapped"); mapped[msg.sender] = true; emit Mapped(msg.sender,cardanoAddress,tokenBal); } }
26,658
https://github.com/intfrr/jail/blob/master/sbin/jctl
Github Open Source
Open Source
BSD-2-Clause, BSD-3-Clause
2,016
jail
intfrr
Python
Code
46
197
#!/usr/bin/python # main program if __name__ == '__main__': from jail import setup from jail import chroot import argparse parser = argparse.ArgumentParser(description='Jail utilities') parser.add_argument('--chroot-update', action='store_true', help='Setup chroot environment') parser.add_argument('--groups-setup', action='store_true', help='Create jail groups') args = parser.parse_args() if args.chroot_update: print 'ChrootUpdate()' chroot.MakeBase() chroot.CopyJailFiles(chroot.ChrootJailCopy) elif args.groups_setup: print 'GroupsSetup()' setup.GroupsSetup()
23,905
https://github.com/xavor92/Ardis2Holzma/blob/master/editmatdb.h
Github Open Source
Open Source
MIT
2,021
Ardis2Holzma
xavor92
C
Code
50
173
#ifndef EDITMATDB_H #define EDITMATDB_H #include <QAbstractButton> #include <QDialog> #include <QList> #include "matdb.h" namespace Ui { class EditMatDB; } class EditMatDB : public QDialog { Q_OBJECT public: explicit EditMatDB(QWidget *parent = 0, MatDB *mat_db = 0); ~EditMatDB(); private slots: void on_buttonBox_clicked(QAbstractButton *button); private: Ui::EditMatDB *ui; MatDB *mat_db_new; }; #endif // EDITMATDB_H
43,626
https://github.com/NinoMaj/carousel-virtualized/blob/master/tests/components/CarouselVirtualized/CarouselVirtualized.tsx
Github Open Source
Open Source
MIT
2,022
carousel-virtualized
NinoMaj
TypeScript
Code
272
1,076
import * as React from 'react'; import { fireEvent, render } from 'react-testing-library'; import 'react-testing-library/cleanup-after-each'; import { CarouselVirtualized } from '../../../src'; describe('CarouselVirtualized', () => { let slideRenderer; let defaultProps; let onEvent; let onItemsRendered; class Slide extends React.PureComponent { public render() { return slideRenderer(this.props); } } beforeEach(() => { jest.useFakeTimers(); onEvent = jest.fn(); onItemsRendered = jest.fn(); slideRenderer = jest.fn(({ style, index, ...rest }) => ( <div style={style} data-testid={`slide-${index}`}>{`slide-${index}`}</div> )); defaultProps = { children: Slide, itemCount: 100, onEvent, onItemsRendered, }; }); it('should render an empty list', () => { render( <CarouselVirtualized {...defaultProps} itemCount={0} height={400} width={800} itemSize={400} />, ); expect(slideRenderer).not.toHaveBeenCalled(); expect(onItemsRendered).not.toHaveBeenCalled(); }); it('should render slides', () => { render( <CarouselVirtualized {...defaultProps} height={400} width={800} itemSize={400} />, ); expect(slideRenderer).toHaveBeenCalledTimes(4); expect(onItemsRendered.mock.calls).toMatchSnapshot(); }); it('if height is not provided should have height of it\'s container', () => { const { getByTestId } = render( <div style={{ width: '800px', height: '400px' }}> <CarouselVirtualized {...defaultProps} width={800} itemSize={25} /> </div>, ); const container = getByTestId('carouselVirtualizedContainer'); expect(container.style.height).toBe('100%'); }); it('if width is not provided should have width of it\'s container', () => { const { getByTestId } = render( <div style={{ width: '800px', height: '400px' }}> <CarouselVirtualized {...defaultProps} height={400} itemSize={25} /> </div>, ); const container = getByTestId('carouselVirtualizedContainer'); expect(container.style.width).toBe('100%'); }); it('should render current index', () => { const { getByTestId } = render( <CarouselVirtualized {...defaultProps} currentIndex={5} height={400} width={800} itemSize={800} />, ); const container = getByTestId('carouselVirtualizedContainer'); const secondSlideInDom = container.children[0].children[0].children[1]; expect(secondSlideInDom.innerHTML).toBe('slide-5'); expect(onItemsRendered.mock.calls).toMatchSnapshot(); }); it('should fire onEvent with new index when arrow is clicked', () => { const rightArrow = ({ onClick }) => <button onClick={onClick}>RightArrow</button>; const { getByText } = render( <CarouselVirtualized {...defaultProps} currentIndex={5} height={400} width={800} itemSize={800} rightArrow={rightArrow} />, ); expect(onEvent).not.toHaveBeenCalled(); fireEvent.click(getByText('RightArrow')); expect(onEvent).toHaveBeenCalled(); expect(onEvent.mock.calls[0][0].newIndex).toBe(6); expect(onEvent.mock.calls).toMatchSnapshot(); }); });
36,963
https://github.com/harshanu11/Love-Babbar-450-In-CSharp/blob/master/Love-Babbar-450-In-CPPTest/07_binary_search_trees/02_deletion_of_node_in_BST.cpp
Github Open Source
Open Source
MIT
null
Love-Babbar-450-In-CSharp
harshanu11
C++
Code
222
605
/* link: https://leetcode.com/problems/delete-node-in-a-bst/ video: https://youtu.be/5_AZcOOc-kM */ #include "../06_binary_trees/01_level_order_traversal.cpp" #include "CppUnitTest.h" #include <iostream> #include <algorithm> #include <vector> #include <map> #include <unordered_set> #include <set> #include <unordered_map> #include <queue> #include <stack> using namespace std; using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace LoveBabbar450InCPPTest { //TEST_CLASS(BTSort) //{ //public: // TEST_METHOD(Test) // { // std::string charM = "harhs"; // int age = 14; // age = 55; // std::string lastName = "<<charM <<singh"; // } //}; } // ----------------------------------------------------------------------------------------------------------------------- // nodeBT* deleteNode(nodeBT* root, int key) { // base case if (!root) return NULL; // if value of root matches with the key if (root->data == key) { // if there is no right child then simply attach root's parent with root's child if (!root->right) { nodeBT* left = root->left; delete root; return left; } // if there is no left child then simply attach root's parent with root's child else if (!root->left) { nodeBT* right = root->right; delete root; return right; } // then swap with the right-subtrees' smallest child with curr-value, also BST won't change (trace it!) // alternative way we can also swap left-subtrees' greatest child with curr-value, still BST won't change else { nodeBT* right = root->right; while (right->left) { right = right->left; } swap(root->data, right->data); } } // get deleted and arranged root from the recursion root->left = deleteNode(root->left, key); root->right = deleteNode(root->right, key); return root; }
17,214
https://github.com/panicDev/KotlinDemo/blob/master/app/src/main/kotlin/id.paniclabs.kotlinmvp/model/PhotoUrls.kt
Github Open Source
Open Source
Apache-2.0
2,017
KotlinDemo
panicDev
Kotlin
Code
49
160
package id.paniclabs.kotlinmvp.model import com.google.gson.annotations.SerializedName /** * @author ali@pergikuliner * @created 5/23/17. * @project BelajarKotlinMVP. */ data class PhotoUrls( @SerializedName("raw") val raw: String? = null, @SerializedName("full") val full: String? = null, @SerializedName("regular") val regular: String? = null, @SerializedName("small") val small: String? = null, @SerializedName("thumb") val thumb: String? = null )
39,543
https://github.com/vgerich/Pods/blob/master/AviasalesSDK/Library/AviasalesSDK.framework/Headers/JRSDKPrice.h
Github Open Source
Open Source
MIT
2,019
Pods
vgerich
Objective-C
Code
48
95
// Copyright 2016 Go Travel Un Limited // This code is distributed under the terms and conditions of the MIT license. // @interface JRSDKPrice : JRSDKModelObject /** * Price currency */ @property (nonatomic, strong, nonnull) JRSDKCurrency currency; /** * Price value */ @property (nonatomic, assign) float value; @end
27,376
https://github.com/mcognetta/federated/blob/master/tensorflow_federated/python/research/utils/checkpoint_utils_test.py
Github Open Source
Open Source
Apache-2.0
null
federated
mcognetta
Python
Code
308
1,133
# Lint as: python3 # Copyright 2019, The TensorFlow Federated Authors. # # 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. """Tests for ServerState save.""" import functools import os import attr import tensorflow as tf import tensorflow_federated as tff from tensorflow_federated.python.examples.mnist import models from tensorflow_federated.python.research.utils import checkpoint_utils @attr.s(cmp=False, frozen=False) class Obj(object): """Container for all state that need to be stored in the checkpoint. Attributes: model: A ModelWeights structure, containing Tensors or Variables. optimizer_state: A list of Tensors or Variables, in the order returned by optimizer.variables(). round_num: Training round_num. """ model = attr.ib() optimizer_state = attr.ib() round_num = attr.ib() @classmethod def from_anon_tuple(cls, anon_tuple, round_num): # TODO(b/130724878): These conversions should not be needed. return cls( model=anon_tuple.model._asdict(recursive=True), optimizer_state=list(anon_tuple.optimizer_state), round_num=round_num) class SavedStateTest(tf.test.TestCase): def test_save_and_load(self): server_optimizer_fn = functools.partial( tf.keras.optimizers.SGD, learning_rate=0.1, momentum=0.9) iterative_process = tff.learning.build_federated_averaging_process( models.model_fn, server_optimizer_fn=server_optimizer_fn) server_state = iterative_process.initialize() # TODO(b/130724878): These conversions should not be needed. obj = Obj.from_anon_tuple(server_state, 1) export_dir = os.path.join(self.get_temp_dir(), 'ckpt_1') checkpoint_utils.save(obj, export_dir) loaded_obj = checkpoint_utils.load(export_dir, obj) self.assertAllClose(tf.nest.flatten(obj), tf.nest.flatten(loaded_obj)) def test_load_latest_state(self): server_optimizer_fn = functools.partial( tf.keras.optimizers.SGD, learning_rate=0.1, momentum=0.9) iterative_process = tff.learning.build_federated_averaging_process( models.model_fn, server_optimizer_fn=server_optimizer_fn) server_state = iterative_process.initialize() # TODO(b/130724878): These conversions should not be needed. obj_1 = Obj.from_anon_tuple(server_state, 1) export_dir = os.path.join(self.get_temp_dir(), 'ckpt_1') checkpoint_utils.save(obj_1, export_dir) # TODO(b/130724878): These conversions should not be needed. obj_2 = Obj.from_anon_tuple(server_state, 2) export_dir = os.path.join(self.get_temp_dir(), 'ckpt_2') checkpoint_utils.save(obj_2, export_dir) export_dir = checkpoint_utils.latest_checkpoint(self.get_temp_dir()) loaded_obj = checkpoint_utils.load(export_dir, obj_1) self.assertEqual(os.path.join(self.get_temp_dir(), 'ckpt_2'), export_dir) self.assertAllClose(tf.nest.flatten(obj_2), tf.nest.flatten(loaded_obj)) if __name__ == '__main__': tf.compat.v1.enable_v2_behavior() tf.test.main()
21,174
https://github.com/kaliop/kaliop-ez-remoteid-bundle/blob/master/Resources/views/tabs/modal_edit_remote_id.html.twig
Github Open Source
Open Source
MIT
2,020
kaliop-ez-remoteid-bundle
kaliop
Twig
Code
200
1,107
{% form_theme location_form '@ezdesign/content/form_fields.html.twig' %} {% form_theme content_form '@ezdesign/content/form_fields.html.twig' %} <div class="modal fade ez-modal" id="kaliop-remote-id-modal--edit-location" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> {{ form_start(location_form, { action: path('kaliop.remote_id.change_location', { locationId: location.id }), attr: { 'data-validate-url': path('kaliop.remote_id.validate_location', { locationId: location.id }) } }) }} <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title">{{ 'kaliop_ez_remote_id.tab_action.location_remote_id'|trans({}, 'kaliop_ez_remote_id') }}</h3> <button type="button" class="close" data-dismiss="modal" aria-label="{{ 'kaliop_ez_remote_id.action.close'|trans({}, 'kaliop_ez_remote_id') }}"> <svg class="ez-icon ez-icon--medium" aria-hidden="true"> <use xlink:href="{{ asset('bundles/ezplatformadminui/img/ez-icons.svg') }}#discard"></use> </svg> </button> </div> <div class="modal-body"> <div class="kaliop-remote-id-modal__errors" style="display: none;"></div> {{ form_widget(location_form.remoteId) }} </div> <div class="modal-footer justify-content-center"> <button type="button" class="btn btn-dark" data-dismiss="modal"> {{ 'kaliop_ez_remote_id.action.cancel'|trans({}, 'kaliop_ez_remote_id') }} </button> {{ form_widget(location_form.save, {'attr': {'class': 'btn btn-primary'}}) }} </div> </div> {{ form_end(location_form) }} </div> </div> <div class="modal fade ez-modal" id="kaliop-remote-id-modal--edit-content" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> {{ form_start(content_form, { action: path('kaliop.remote_id.change_content', { locationId: location.id }), attr: { 'data-validate-url': path('kaliop.remote_id.validate_content', { locationId: location.id }) } }) }} <div class="modal-content"> <div class="modal-header"> <h3 class="modal-title">{{ 'kaliop_ez_remote_id.tab_action.content_remote_id'|trans({}, 'kaliop_ez_remote_id') }}</h3> <button type="button" class="close" data-dismiss="modal" aria-label="{{ 'kaliop_ez_remote_id.action.close'|trans({}, 'kaliop_ez_remote_id') }}"> <svg class="ez-icon ez-icon--medium" aria-hidden="true"> <use xlink:href="{{ asset('bundles/ezplatformadminui/img/ez-icons.svg') }}#discard"></use> </svg> </button> </div> <div class="modal-body"> <div class="kaliop-remote-id-modal__errors" style="display: none;"></div> {{ form_widget(content_form.remoteId) }} </div> <div class="modal-footer justify-content-center"> <button type="button" class="btn btn-dark" data-dismiss="modal"> {{ 'kaliop_ez_remote_id.action.cancel'|trans({}, 'kaliop_ez_remote_id') }} </button> {{ form_widget(content_form.save, {'attr': {'class': 'btn btn-primary'}}) }} </div> </div> {{ form_end(content_form) }} </div> </div>
44,259
https://github.com/rshekar027/streamalert/blob/master/stream_alert_cli/manage_lambda/rollback.py
Github Open Source
Open Source
Apache-2.0
2,020
streamalert
rshekar027
Python
Code
285
873
""" Copyright 2017-present, Airbnb 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. """ from stream_alert_cli.logger import LOGGER_CLI import boto3 from botocore.exceptions import ClientError def _rollback_production(lambda_client, function_name): """Rollback the production alias for the given function name.""" version = lambda_client.get_alias( FunctionName=function_name, Name='production')['FunctionVersion'] if version == '$LATEST': # This won't happen with Terraform, but the alias could have been manually changed. LOGGER_CLI.error('%s:production is pointing to $LATEST instead of a published version', function_name) return current_version = int(version) if current_version == 1: LOGGER_CLI.warn('%s:production is already at version 1', function_name) return LOGGER_CLI.info('Rolling back %s:production from version %d => %d', function_name, current_version, current_version - 1) try: lambda_client.update_alias( FunctionName=function_name, Name='production', FunctionVersion=str(current_version - 1)) except ClientError: LOGGER_CLI.exception('version not updated') def rollback(options, config): """Rollback the current production Lambda version(s) by 1. Args: options: Argparse parsed options config (dict): Parsed configuration from conf/ """ rollback_all = 'all' in options.processor prefix = config['global']['account']['prefix'] clusters = sorted(options.clusters or config.clusters()) client = boto3.client('lambda') if rollback_all or 'alert' in options.processor: _rollback_production(client, '{}_streamalert_alert_processor'.format(prefix)) if rollback_all or 'alert_merger' in options.processor: _rollback_production(client, '{}_streamalert_alert_merger'.format(prefix)) if rollback_all or 'apps' in options.processor: for cluster in clusters: apps_config = config['clusters'][cluster]['modules'].get('stream_alert_apps', {}) for lambda_name in sorted(apps_config): _rollback_production(client, lambda_name) if rollback_all or 'athena' in options.processor: _rollback_production(client, '{}_streamalert_athena_partition_refresh'.format(prefix)) if rollback_all or 'rule' in options.processor: for cluster in clusters: _rollback_production(client, '{}_{}_streamalert_rule_processor'.format(prefix, cluster)) if rollback_all or 'threat_intel_downloader' in options.processor: _rollback_production(client, '{}_streamalert_threat_intel_downloader'.format(prefix))
27,839
https://github.com/Originate/OriginateUI/blob/master/Pod/Sources/Classes/OriginateValidatedTextField.m
Github Open Source
Open Source
MIT
2,017
OriginateUI
Originate
Objective-C
Code
296
1,196
// // OriginateValidatedTextField.m // OriginateUI // // Created by Allen Wu on 8/13/15. // Copyright (c) 2015 Originate. All rights reserved. // #import "OriginateValidatedTextField.h" @interface OriginateValidatedTextField () <UITextFieldDelegate> @property (nonatomic, assign, readwrite) BOOL valid; @property (nonatomic, assign) BOOL dirty; @property (nonatomic, weak) id<UITextFieldDelegate> externalDelegate; @end @implementation OriginateValidatedTextField - (instancetype)init { self = [super init]; if (self) { [self commonInit]; } return self; } - (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; if (self) { [self commonInit]; } return self; } - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self commonInit]; } return self; } - (void)commonInit { _validationMode = OriginateTextFieldValidationModeLive; self.delegate = self; [self addTarget:self action:@selector(textFieldChanged:) forControlEvents:UIControlEventEditingChanged]; } #pragma mark - Properties - (void)setDelegate:(id<UITextFieldDelegate>)delegate { if (self != delegate) { _externalDelegate = delegate; } [super setDelegate:self]; } - (void)setValid:(BOOL)valid { if (valid != _valid || !self.dirty) { self.dirty = YES; if (self.validationChangedBlock) { self.validationChangedBlock(valid, self); } } _valid = valid; } #pragma mark - - (void)textFieldChanged:(UITextField *)sender { if (self.validationMode == OriginateTextFieldValidationModeLive) { if (self.validationBlock) { self.valid = self.validationBlock(sender.text); } } } #pragma mark - <UITextFieldDelegate> - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { if ([self.externalDelegate respondsToSelector:@selector(textFieldShouldBeginEditing:)]) { return [self.externalDelegate textFieldShouldBeginEditing:textField]; } return YES; } - (void)textFieldDidBeginEditing:(UITextField *)textField { if ([self.externalDelegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) { [self.externalDelegate textFieldDidBeginEditing:textField]; } } - (BOOL)textFieldShouldEndEditing:(UITextField *)textField { if ([self.externalDelegate respondsToSelector:@selector(textFieldShouldEndEditing:)]) { return [self.externalDelegate textFieldShouldEndEditing:textField]; } return YES; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ([self.externalDelegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) { return [self.externalDelegate textField:textField shouldChangeCharactersInRange:range replacementString:string]; } return YES; } - (BOOL)textFieldShouldClear:(UITextField *)textField { if ([self.externalDelegate respondsToSelector:@selector(textFieldShouldClear:)]) { return [self.externalDelegate textFieldShouldClear:textField]; } return YES; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { if ([self.externalDelegate respondsToSelector:@selector(textFieldShouldReturn:)]) { return [self.externalDelegate textFieldShouldReturn:textField]; } return YES; } - (void)textFieldDidEndEditing:(UITextField *)textField { if (self.validationMode == OriginateTextFieldValidationModeOnBlur) { if (self.validationBlock) { self.valid = self.validationBlock(textField.text); } } if ([self.externalDelegate respondsToSelector:@selector(textFieldDidEndEditing:)]) { [self.externalDelegate textFieldDidEndEditing:textField]; } } @end
49,756
https://github.com/hao-wang/Montage/blob/master/js-test-suite/testsuite/056e2298deb94b64a7348cdb1be83413.js
Github Open Source
Open Source
MIT
2,021
Montage
hao-wang
JavaScript
Code
64
175
load("bf4b12814bc95f34eeb130127d8438ab.js"); load("93fae755edd261212639eed30afa2ca4.js"); // Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 10.4.3-1-58gs description: > checking 'this' from a global scope (Injected getter defined) ---*/ var o = {}; Object.defineProperty(o, "foo", { get : function() { return this; } }); if (o.foo!==o) { throw "'this' had incorrect value!"; }
18,799
https://github.com/wablair/pic-rtu/blob/master/main.h
Github Open Source
Open Source
0BSD
2,018
pic-rtu
wablair
C
Code
208
640
#ifndef _main_h_ #define _main_h_ #include "adcon.h" #define ASCIIHEX_TO_BIN(X) ((X < 65) ? (X - 48) : (X < 97) ? (X - 55) : \ (X - 87)) /* * must parenthesize (X) in order to preserve value if the result is * bit shifted */ #define BIN_TO_ASCIIHEX(X) (((X & 0x0F) < 10) ? ((X & 0x0F) + '0') : \ ((X & 0x0F) - 10 + 'A')) #define IOR44_LED_PORT PORTB #define IOR44_LED_DIRECTION_REGISTER TRISB #define IOR44_LED_PIN 0b01000000 /* set LED pin as an output */ #define led_init() IOR44_LED_DIRECTION_REGISTER = \ IOR44_LED_DIRECTION_REGISTER & (0xFF ^\ IOR44_LED_PIN); /* turn LED on */ #define led_on() IOR44_LED_PORT = IOR44_LED_PORT | IOR44_LED_PIN /* turn LED off */ #define led_off() IOR44_LED_PORT = IOR44_LED_PORT & (0xFF ^\ IOR44_LED_PIN) /* blink LED */ #define led_toggle() IOR44_LED_PORT = IOR44_LED_PORT ^ IOR44_LED_PIN #define led_blink led_toggle #define EEPROM_CONFIG_ADDRESS 0 #define EEPROM_COUNTER1_ADDRESS (2 + sizeof(config_t)) #define EEPROM_COUNTER2_ADDRESS (2 + EEPROM_COUNTER1_ADDRESS) #ifndef PIC_CLK /* #define PIC_CLK 3686400 */ #define PIC_CLK 4000000 /* #define PIC_CLK 8000000 */ /* #define PIC_CLK 16000000 */ /* #define PIC_CLK 18432000 */ /* #define PIC_CLK 20000000 */ #endif /* !PIC_CLK */ /* Some Hi-Tech PICC18 functions (i.e. __delay_ms) need this defined. */ #define _XTAL_FREQ PIC_CLK int rcif_poll(unsigned int, struct ad_data *); int get_aquaspy_sensor_data(void); #endif /* _main_h_ */
23,997
https://github.com/bpjohannessen/xamarin-forms-sqlite-sample/blob/master/Alus/Alus/Helpers/AProducers.cs
Github Open Source
Open Source
MIT
null
xamarin-forms-sqlite-sample
bpjohannessen
C#
Code
59
196
using System; using System.Collections.Generic; using System.Linq; using Alus.Models; using Alus.Services; using SQLite; namespace Alus.Helpers { public class AProducers { static SQLiteConnection db = AData.database; public AProducers() { } public static List<AProducer> GetAll() { return db.Query<AProducer>("SELECT * FROM [AProducers]").ToList(); } public static List<AProducer> GetProducerById(int ProducerId) { return db.Query<AProducer>("SELECT * FROM [AProducers] WHERE ProducerId = " + ProducerId); } } }
31,067
https://github.com/henrichg/PhoneProfilesPlus/blob/master/phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/LiveWallpapersDialogPreference.java
Github Open Source
Open Source
Apache-2.0
2,023
PhoneProfilesPlus
henrichg
Java
Code
371
1,462
package sk.henrichg.phoneprofilesplus; import android.app.WallpaperInfo; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.service.wallpaper.WallpaperService; import android.util.AttributeSet; import androidx.annotation.NonNull; import androidx.preference.DialogPreference; import java.util.ArrayList; import java.util.List; public class LiveWallpapersDialogPreference extends DialogPreference { LiveWallpapersDialogPreferenceFragment fragment; private final Context context; String value = ""; private String defaultValue; private boolean savedInstanceState; //final int disableSharedProfile; List<LiveWallpapersData> liveWallpapersList; public LiveWallpapersDialogPreference(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; liveWallpapersList = new ArrayList<>(); } @Override protected Object onGetDefaultValue(@NonNull TypedArray ta, int index) { super.onGetDefaultValue(ta, index); return ta.getString(index); } @Override protected void onSetInitialValue(Object defaultValue) { value = getPersistedString((String) defaultValue); this.defaultValue = (String)defaultValue; setSummaryLWDP(); } private void setSummaryLWDP() { String prefSummary = context.getString(R.string.live_wallpapers_pref_dlg_summary_text_not_selected); if (!value.isEmpty()) { // get label for ComponentName in value PackageManager packageManager = context.getPackageManager(); // get ResolveInfo of live wallpapers List<ResolveInfo> availableWallpapersList = packageManager.queryIntentServices( new Intent(WallpaperService.SERVICE_INTERFACE), PackageManager.GET_META_DATA); for (int i = 0; i < availableWallpapersList.size(); i++) { ResolveInfo wallpaperResInfo = availableWallpapersList.get(i); WallpaperInfo info; try { // WallaperInfo from ResolveInfo info = new WallpaperInfo(context, wallpaperResInfo); if (value.equals(info.getComponent().flattenToString())) { prefSummary = wallpaperResInfo.loadLabel(packageManager).toString(); break; } } catch (Exception ignored) { } } } setSummary(prefSummary); } void persistValue() { // to get ComponentName from value, use ComponentName.unflattenFromString(value) persistString(value); setSummaryLWDP(); } void resetSummary() { if (!savedInstanceState) { value = getPersistedString(defaultValue); setSummaryLWDP(); } savedInstanceState = false; } @Override protected Parcelable onSaveInstanceState() { savedInstanceState = true; final Parcelable superState = super.onSaveInstanceState(); /*if (isPersistent()) { return superState; }*/ final LiveWallpapersDialogPreference.SavedState myState = new LiveWallpapersDialogPreference.SavedState(superState); myState.value = value; myState.defaultValue = defaultValue; return myState; } @Override protected void onRestoreInstanceState(Parcelable state) { if ((state == null) || (!state.getClass().equals(LiveWallpapersDialogPreference.SavedState.class))) { // Didn't save state for us in onSaveInstanceState super.onRestoreInstanceState(state); setSummaryLWDP(); return; } // restore instance state LiveWallpapersDialogPreference.SavedState myState = (LiveWallpapersDialogPreference.SavedState)state; super.onRestoreInstanceState(myState.getSuperState()); value = myState.value; defaultValue = myState.defaultValue; setSummaryLWDP(); } /* void refreshListView() { if (fragment != null) fragment.refreshListView(); } */ // SavedState class private static class SavedState extends BaseSavedState { String value; String defaultValue; SavedState(Parcel source) { super(source); value = source.readString(); defaultValue = source.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(value); dest.writeString(defaultValue); } SavedState(Parcelable superState) { super(superState); } public static final Creator<LiveWallpapersDialogPreference.SavedState> CREATOR = new Creator<LiveWallpapersDialogPreference.SavedState>() { public LiveWallpapersDialogPreference.SavedState createFromParcel(Parcel in) { return new LiveWallpapersDialogPreference.SavedState(in); } public LiveWallpapersDialogPreference.SavedState[] newArray(int size) { return new LiveWallpapersDialogPreference.SavedState[size]; } }; } }
32,429
https://github.com/FenixEdu/fenixedu-scala-sdk/blob/master/src/main/scala/org/fenixedu/sdk/services/package.scala
Github Open Source
Open Source
MIT
null
fenixedu-scala-sdk
FenixEdu
Scala
Code
82
262
package org.fenixedu.sdk import cats.effect.Concurrent import io.circe.{Decoder, Encoder, Printer} import org.http4s.{EntityDecoder, EntityEncoder, circe} package object services { val jsonPrinter: Printer = Printer.noSpaces.copy(dropNullValues = true) implicit def jsonEncoder[F[_], A: Encoder]: EntityEncoder[F, A] = circe.jsonEncoderWithPrinterOf[F, A](jsonPrinter) implicit def jsonDecoder[F[_]: Concurrent, A: Decoder]: EntityDecoder[F, A] = circe.accumulatingJsonOf[F, A] // Without this decoding to Unit wont work. This makes the EntityDecoder[F, Unit] defined in EntityDecoder companion object // have a higher priority than the jsonDecoder defined above. https://github.com/http4s/http4s/issues/2806 implicit def void[F[_]: Concurrent]: EntityDecoder[F, Unit] = EntityDecoder.void }
35,021
https://github.com/maaeedee/NRI/blob/master/data/customizing.py
Github Open Source
Open Source
MIT
null
NRI
maaeedee
Python
Code
137
680
import numpy as np import networkx as nx def labeling (int_mat): all_groups = [] grp_type = np.unique(int_mat) grp_type = grp_type[grp_type>0] for j in grp_type : A = int_mat temp_mat = (A==j).astype(float) G = nx.from_numpy_matrix(temp_mat) groups = list(list(G.subgraph(c).nodes) for c in nx.connected_components(G)) # print(groups) sub_groups = [j for j in groups if len(j)>1] # print('sub_groups: ', sub_groups) if len(sub_groups)>=1: all_groups.append(sub_groups[0]) return all_groups def dataset(grp_labels, pos_vect): labeling = grp_labels database = [] for j in labeling: database.append(np.array(pos_vect[j, :, :], dtype=object)) return database def convert_gps(Box_yard,pos_vect): max_lon = Box_yard[1][0] min_lon = Box_yard[1][1] min_lat = Box_yard[0][0] max_lat = Box_yard[0][1] x_min = pos_vect[:,0,:].min() x_max = pos_vect[:,0,:].max() y_min = pos_vect[:,1,:].min() y_max = pos_vect[:,1,:].max() x = pos_vect[:,0,:] y = pos_vect[:,1,:] # A_new = (A_old-min(A))/(max(A)-min(A))*(max(new_range)-min(new_range))+min(new_range) new_x = ((x-x_min)/(x_max-x_min))*(max_lon-min_lon)+min_lon new_y = ((y-y_min)/(y_max-y_min))*(max_lat-min_lat)+min_lat new_pos_vect = np.zeros((pos_vect.shape[2], pos_vect.shape[0], pos_vect.shape[1])) new_pos_vect[:,:,0] = np.transpose(new_x, (1,0)) new_pos_vect[:,:,1] = np.transpose(new_y, (1,0)) return new_pos_vect
19,071
https://github.com/labs14-pawsitive/back-end/blob/master/data/migrations/20190712154806_first_layer_tables.js
Github Open Source
Open Source
MIT
null
back-end
labs14-pawsitive
JavaScript
Code
159
831
exports.up = function(knex, Promise) { return knex.schema .createTable('size', tbl => { tbl.increments() tbl.string('size', 256) .notNullable() .unique(); }) .createTable('coat_length', tbl => { tbl.increments() tbl.string('coat_length', 256) .notNullable() .unique(); }) .createTable('subscriptions', tbl => { tbl.increments(); tbl.string('subscription', 256) .notNullable() .unique(); tbl.integer('subscription_duration_mo') .notNullable(); tbl.decimal('price') .notNullable(); }) .createTable('ages', tbl => { tbl.increments(); tbl.string('age', 256) .notNullable() .unique(); }) .createTable('application_status', tbl => { tbl.increments(); tbl.string('application_status', 256) .notNullable() .unique(); }) .createTable('users', tbl => { tbl.increments(); tbl.string('email', 256) .notNullable() tbl.string('sub_id', 256) .notNullable() .unique() tbl.string('username', 256) .notNullable() tbl.timestamp('created_at', { precision: 6 }) .defaultTo(knex.fn.now(6)); }) .createTable('species', tbl => { tbl.increments(); tbl.string('species', 256) .notNullable() .unique(); }) .createTable('animal_status', tbl => { tbl.increments(); tbl.string('animal_status', 256) .notNullable() .unique(); }) .createTable('shelter_contacts', tbl => { tbl.increments() tbl.integer('shelter_id') tbl.string('name', 256) .notNullable(); tbl.string('email', 512) .notNullable(); tbl.string('phone', 256) .notNullable(); }) .createTable('roles', tbl => { tbl.increments(); tbl.string('role', 256) .notNullable() .unique(); }) .createTable('states', tbl => { tbl.increments(); tbl.string('state', 128) .notNullable() .unique(); }) }; exports.down = function(knex, Promise) { return knex.schema .dropTableIfExists('size') .dropTableIfExists('coat_length') .dropTableIfExists('subscriptions') .dropTableIfExists('ages') .dropTableIfExists('application_status') .dropTableIfExists('users') .dropTableIfExists('species') .dropTableIfExists('shelter_status') .dropTableIfExists('shelter_contacts') .dropTableIfExists('roles') .dropTableIfExists('states') };
18,813
https://github.com/Yuloran/wanandroid_java/blob/master/lib_repository/src/main/java/com/yuloran/lib_repository/http/interceptor/CacheControlInterceptor.java
Github Open Source
Open Source
Apache-2.0
2,020
wanandroid_java
Yuloran
Java
Code
288
814
/* * Copyright (C) 2018 Yuloran(https://github.com/Yuloran) * * 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.yuloran.lib_repository.http.interceptor; import com.yuloran.lib_core.utils.Logger; import com.yuloran.lib_core.utils.StringUtil; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.Response; /** * [缓存控制拦截器]<br /> * <strong>注:</strong> * <ol> * <li>网上博客错误用法太多,全是复制粘贴坑人的! * <li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control">Http Cache-Control 详解</a> * <li><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Caching_FAQ">Http 缓存详解</a> * <li>本例为正确用法,详见 <a href="https://www.jianshu.com/p/d3e67d57f287">你真的了解 OkHttp 缓存控制吗?</a> * </ol> * <p> * <strong>public vs private</strong> * <ul> * <li>public: Indicates that the response may be cached by any cache, even if the response would normally be * non-cacheable (e.g. if the response does not contain a max-age directive or the Expires header). * <li>private: Indicates that the response is intended for a single user and must not be stored by a shared cache. A * private cache may store the response. * </ul> * <p> * Author: Yuloran * Date Added: 2018/12/16 21:05 * * @since 1.0.0 */ public class CacheControlInterceptor implements Interceptor { private static final String TAG = "CacheControlInterceptor"; @Override public Response intercept(Chain chain) throws IOException { Logger.debug(TAG, "CacheControlInterceptor."); Response response = chain.proceed(chain.request()); String cacheControl = response.header("Cache-Control"); if (StringUtil.isEmpty(cacheControl)) { Logger.debug(TAG, "'Cache-Control' not set by the backend, add it ourselves."); // assume response is fresh within 1min, this is optional return response.newBuilder().removeHeader("Pragma").header("Cache-Control", "public, max-age=60").build(); } return response; } }
23,562
https://github.com/bzrmed10/inventoryFront/blob/master/src/app/pages/category/category-add/category-add.component.ts
Github Open Source
Open Source
MIT
null
inventoryFront
bzrmed10
TypeScript
Code
197
730
import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { SharedService } from 'src/app/services/shared.service'; import { Category } from '../category.model'; import { CategoryService } from '../category.service'; @Component({ selector: 'app-category-add', templateUrl: './category-add.component.html', styleUrls: ['./category-add.component.scss'] }) export class CategoryAddComponent implements OnInit { id: number; editMode = false; addCategoryForm : FormGroup ; error = { category_name : null}; constructor(private categoryService:CategoryService , private sharedService : SharedService , private router : Router, private route : ActivatedRoute) { } ngOnInit(): void { this.route.params.subscribe( (params :Params) => { this.id = +params['id']; this.editMode = params['id'] != null; this.initForm(); } ); } submit(){ if(this.editMode){ this.categoryService.editCategory(this.id,this.addCategoryForm.value).subscribe({ next: (data) => { this.addCategoryForm.reset(); this.categoryService.newChanges.next(true); this.router.navigate(['category']); this.sharedService.successToast('Category updated succesfully'); }, error: (error) => { this.error = error.error['errors']; this.sharedService.errorToast(error.error['message']) } }) }else{ this.categoryService.addCategory(this.addCategoryForm.value).subscribe({ next: (data) => { this.addCategoryForm.reset(); this.categoryService.newChanges.next(true); this.sharedService.successToast('Category added succesfully'); }, error: (error) => { this.error = error.error['errors']; this.sharedService.errorToast(error.error['message']) } }) } } private initForm(){ let category_name =''; if(this.editMode){ this.categoryService.getCategoryByIdApi(this.id).subscribe( (data : Category) => { this.addCategoryForm = new FormGroup ({ 'category_name' : new FormControl(data.category_name , Validators.required), }); } ); } this.addCategoryForm = new FormGroup ({ 'category_name' : new FormControl(category_name , Validators.required), }); } }
5,608
https://github.com/cosyUI/hybrid-sdk/blob/master/android/sdk/src/main/java/com/wya/hybrid/methods/bean/installed/InstalledData.java
Github Open Source
Open Source
MIT
2,020
hybrid-sdk
cosyUI
Java
Code
70
219
package com.wya.hybrid.methods.bean.installed; /** * @date: 2019/2/19 15:56 * @author: Chunjiang Mao * @classname: InstalledData * @describe: */ public class InstalledData { /** * 执行结果的返回方式。为false时通过callback返回,为true时直接返回。 */ private boolean sync; /** * scheme 或 包名 */ private String scheme; public boolean isSync() { return sync; } public void setSync(boolean sync) { this.sync = sync; } public String getScheme() { return scheme; } public void setScheme(String scheme) { this.scheme = scheme; } }
49,960
https://github.com/mem-memov/mytarget-php-ads-sdk/blob/master/src/Token/DoctrineCacheTokenStorage.php
Github Open Source
Open Source
Apache-2.0
2,016
mytarget-php-ads-sdk
mem-memov
PHP
Code
233
643
<?php namespace MyTarget\Token; use Doctrine\Common\Cache\Cache; use Psr\Http\Message\RequestInterface; use MyTarget as f; class DoctrineCacheTokenStorage implements TokenStorage { /** * @var Cache */ private $cache; /** * @var callable(string $id, RequestInterface, $context): string */ private $hashFunction; /** * @param Cache $cache * @param callable $hashFunction callable(string $id, RequestInterface, $context): string Identity function used as a default */ public function __construct(Cache $cache, callable $hashFunction = null) { $this->cache = $cache; $this->hashFunction = $hashFunction ?: function ($v) { return $v; }; } /** * @inheritdoc */ public function getToken($id, RequestInterface $request, array $context = null) { return $this->fetch($id, $request, $context); } /** * @inheritdoc */ public function updateToken($id, Token $token, RequestInterface $request, array $context = null) { $this->save($id, $token, $request, $context); } /** * @param string $id * @param RequestInterface $request * @param array|null $context * * @return Token|null */ protected function fetch($id, RequestInterface $request, array $context = null) { $tokenArray = $this->cache->fetch($this->hash($id, $request, $context)); if ( ! $tokenArray) { return null; } return Token::fromArray($tokenArray); } /** * @param string $id * @param Token $token * @param RequestInterface $request * @param array|null $context */ protected function save($id, Token $token, RequestInterface $request, array $context = null) { $this->cache->save($this->hash($id, $request, $context), $token->toArray()); } /** * @param string $id * @param RequestInterface $request * @param array|null $context * @return string */ protected function hash($id, RequestInterface $request, array $context = null) { $f = $this->hashFunction; return $f($id, $request, $context); } }
18,912