repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
dingjianhui1013/operator
src/main/java/com/itrus/ca/modules/key/entity/KeyUsbKeyInvoice.java
package com.itrus.ca.modules.key.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.SequenceGenerator; import javax.persistence.Transient; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; import com.itrus.ca.common.persistence.DataEntity; /** * key出库信息 */ @Entity @Table(name = "key_usb_key_invoice") public class KeyUsbKeyInvoice extends DataEntity implements java.io.Serializable { // Fields private Long id; private KeyUsbKeyDepot keyUsbKeyDepot; private Integer deliveryNum; private String description; private int outReason; private KeyGeneralInfo keyGeneralInfo; private String outReasonName; private KeyUsbKeyDepot keyUsbKeyDepotReceive; private String keySn; private Date startDate; private String companyName; // Constructors @Override public void setCreateDate(Date createDate) { // TODO Auto-generated method stub super.setCreateDate(createDate); } /** default constructor */ public KeyUsbKeyInvoice() { } /** full constructor */ public KeyUsbKeyInvoice(Integer deliveryNum, KeyUsbKeyDepot keyUsbKeyDepot, int outReason, KeyGeneralInfo keyGeneralInfo, String description, String keySn, Date startDate) { this.deliveryNum = deliveryNum; this.description = description; this.keyUsbKeyDepot = keyUsbKeyDepot; this.keyGeneralInfo = keyGeneralInfo; this.outReason = outReason; this.keySn = keySn; this.startDate = startDate; } // Property accessors // @SequenceGenerator(name="COMMON_SEQUENCE",sequenceName="COMMON_SEQUENCE") @SequenceGenerator(name = "KEY_USB_KEY_INVOICE_SEQUENCE", allocationSize = 1, initialValue = 1, sequenceName = "KEY_USB_KEY_INVOICE_SEQUENCE") @Id @GeneratedValue(generator = "KEY_USB_KEY_INVOICE_SEQUENCE", strategy = GenerationType.SEQUENCE) public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } @Column(name = "description", columnDefinition = "NVARCHAR2(255)") public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "usb_key_depot_id") public KeyUsbKeyDepot getKeyUsbKeyDepot() { return keyUsbKeyDepot; } public void setKeyUsbKeyDepot(KeyUsbKeyDepot keyUsbKeyDepot) { this.keyUsbKeyDepot = keyUsbKeyDepot; } @Column(name = "out_reason") public int getOutReason() { return outReason; } public void setOutReason(int outReason) { this.outReason = outReason; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "key_general_info_id") public KeyGeneralInfo getKeyGeneralInfo() { return keyGeneralInfo; } public void setKeyGeneralInfo(KeyGeneralInfo keyGeneralInfo) { this.keyGeneralInfo = keyGeneralInfo; } @Column(name = "delivery_num") public Integer getDeliveryNum() { return deliveryNum; } public void setDeliveryNum(Integer deliveryNum) { this.deliveryNum = deliveryNum; } @Transient public String getOutReasonName() { return outReasonName; } public void setOutReasonName(String outReasonName) { this.outReasonName = outReasonName; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "usb_key_depot_receive") public KeyUsbKeyDepot getKeyUsbKeyDepotReceive() { return keyUsbKeyDepotReceive; } public void setKeyUsbKeyDepotReceive(KeyUsbKeyDepot keyUsbKeyDepotReceive) { this.keyUsbKeyDepotReceive = keyUsbKeyDepotReceive; } @Column(name = "key_sn", columnDefinition = "NVARCHAR2(255)") public String getKeySn() { return keySn; } public void setKeySn(String keySn) { this.keySn = keySn; } @Column(name = "start_date") public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } @Column(name = "company_name", columnDefinition = "NVARCHAR2(255)") public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } }
LaraiFox/LibraryDev
archive/Quadrilateral.java
package net.laraifox.libdev.geometry; import laraifox.foxtail.core.math.Vector2f; import net.laraifox.lib.geometry.Quadrilateral; import net.laraifox.lib.geometry.Shape2D; import net.laraifox.lib.graphics.Transform2D; import net.laraifox.lib.graphics.Vertex2D; public class Quadrilateral extends Shape2D { public static final int VERTEX_BOTTOM_LEFT = 0; public static final int VERTEX_BOTTOM_RIGHT = 1; public static final int VERTEX_TOP_RIGHT = 2; public static final int VERTEX_TOP_LEFT = 3; public static final int VERTEX_COUNT = 4; public Quadrilateral() { this(new Transform2D(), Vector2f.Zero(), Vector2f.Zero(), Vector2f.Zero(), Vector2f.Zero()); } public Quadrilateral(Transform2D transform) { this(transform, Vector2f.Zero(), Vector2f.Zero(), Vector2f.Zero(), Vector2f.Zero()); } public Quadrilateral(Vector2f bottomLeft, Vector2f bottomRight, Vector2f topRight, Vector2f topLeft) { this(new Transform2D(), bottomLeft, bottomRight, topRight, topLeft); } public Quadrilateral(Transform2D transform, Vector2f bottomLeft, Vector2f bottomRight, Vector2f topRight, Vector2f topLeft) { super(transform, new Vector2f[] { bottomLeft, bottomRight, topRight, topLeft }); } public Quadrilateral(Transform2D transform, Vector2f[] points) { super(transform); this.vertices = new Vertex2D[VERTEX_COUNT]; for (int i = 0; i < VERTEX_COUNT; i++) { if (i >= points.length) this.vertices[i] = new Vertex2D(); this.vertices[i] = new Vertex2D(points[i]); } calculateEdgeNormals(); } public Quadrilateral(Quadrilateral quadrilateral) { super(quadrilateral.transform, quadrilateral.vertices); } }
AzDarGee/milieucities
spec/factories/meetings.rb
<reponame>AzDarGee/milieucities<filename>spec/factories/meetings.rb # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :meeting do meeting_type { Meeting::PUBLIC_MEETING_TYPE } date { DateTime.current } time '3:00 PM' location 'City Hall' trait :council do meeting_type { Meeting::COUNCIL_MEETING_TYPE } end end end
jdmota/abcd-mungo
examples/removable-iterator-places/BaseIterator.java
<gh_stars>0 import java.util.List; import jatyc.lib.Typestate; import jatyc.lib.Nullable; @Typestate("BaseIterator") public class BaseIterator { protected List<Object> items; protected int index; public BaseIterator(List<Object> items) { this.items = items; this.index = 0; } public boolean hasNext() { return this.index < this.items.size(); } public @Nullable Object next() { return this.items.get(this.index++); } public int remainingItems() { return this.items.size() - this.index; } }
SlimKatLegacy/android_external_chromium_org
base/memory/discardable_memory_emulated.cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/discardable_memory_emulated.h" #include "base/lazy_instance.h" #include "base/memory/discardable_memory_provider.h" namespace base { namespace { base::LazyInstance<internal::DiscardableMemoryProvider>::Leaky g_provider = LAZY_INSTANCE_INITIALIZER; } // namespace namespace internal { DiscardableMemoryEmulated::DiscardableMemoryEmulated(size_t size) : is_locked_(false) { g_provider.Pointer()->Register(this, size); } DiscardableMemoryEmulated::~DiscardableMemoryEmulated() { if (is_locked_) Unlock(); g_provider.Pointer()->Unregister(this); } bool DiscardableMemoryEmulated::Initialize() { return Lock() == DISCARDABLE_MEMORY_PURGED; } LockDiscardableMemoryStatus DiscardableMemoryEmulated::Lock() { DCHECK(!is_locked_); bool purged = false; memory_ = g_provider.Pointer()->Acquire(this, &purged); if (!memory_) return DISCARDABLE_MEMORY_FAILED; is_locked_ = true; return purged ? DISCARDABLE_MEMORY_PURGED : DISCARDABLE_MEMORY_SUCCESS; } void DiscardableMemoryEmulated::Unlock() { DCHECK(is_locked_); g_provider.Pointer()->Release(this, memory_.Pass()); is_locked_ = false; } void* DiscardableMemoryEmulated::Memory() const { DCHECK(memory_); return memory_.get(); } // static void DiscardableMemoryEmulated::PurgeForTesting() { g_provider.Pointer()->PurgeAll(); } } // namespace internal } // namespace base
cppguru/bde_verify
checks/csamisc/array-initialization/csamisc_arrayinitialization.t.cpp
// csamisc_arrayinitialization.t.cpp -*-C++-*- #include "csamisc_arrayinitialization.t.hpp" #include <bdes_ident.h> namespace bde_verify { namespace csamisc { namespace { struct s { s(int = 0); // IMPLICIT }; s::s(int) {} struct t { t(); t(int); // IMPLICIT }; t::t() {} t::t(int) {} } namespace { struct p { int a; int b; }; } } } // ----------------------------------------------------------------------------- int main(int ac, char* av[]) { bde_verify::csamisc::p pair = { 0 }; bde_verify::csamisc::s array00[5]; int array01[] = { ' ' }; int array02[1] = { ' ' }; int array03[5] = { ' ' }; int array04[5] = { }; int array05[5] = { 0 }; int array06[5] = { ' ', 0 }; int array07[5] = { int() }; int array08[5] = { ' ', int() }; int array09[5] = { ' ', int(' ') }; int array10[5] = { ' ', int('\0') }; int array11[5] = { ' ', '\0' }; bde_verify::csamisc::s array12[5] = { }; bde_verify::csamisc::s array13[5] = { bde_verify::csamisc::s() }; bde_verify::csamisc::s array14[5] = { bde_verify::csamisc::s(1) }; bde_verify::csamisc::s array15[5] = { bde_verify::csamisc::s(1), bde_verify::csamisc::s() }; bde_verify::csamisc::t array16[5] = {}; bde_verify::csamisc::t array17[5] = { bde_verify::csamisc::t() }; bde_verify::csamisc::t array18[5] = { bde_verify::csamisc::t(1) }; bde_verify::csamisc::t array19[5] = { bde_verify::csamisc::t(1), bde_verify::csamisc::t() }; int const array20[] = { 0, 1 }; char const array21[] = "foobar"; char array22[] = "foobar"; char const array23[] = { "foobar" }; char array24[] = { "foobar" }; } // ---------------------------------------------------------------------------- // Copyright (C) 2014 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
aamshukov/miscellaneous
c++/Ail/MAPI.cpp
//////////////////////////////////////////////////////////////////////////////////////// //...................................................................................... // This is a part of AI Library [Arthur's Interfaces Library]. . // 1998-2001 <NAME> . //...................................................................................... // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND . // DO NOT REMOVE MY NAME AND THIS NOTICE FROM THE SOURCE . //...................................................................................... //////////////////////////////////////////////////////////////////////////////////////// #ifndef __AIL_H__ # include <ail.hpp> #endif #ifndef __MAPI_INC__ # include <MAPI.inc> #endif __BEGIN_NAMESPACE__ //////////////////////////////////////////////////////////////////////////////////////// const tchar ConstMAPIKey[] = _T("Software\\Microsoft\\Windows Messaging Subsystem"); const tchar ConstMAPIVal[] = _T("MAPI"); const tchar ConstMAPIXVal[] = _T("MAPIX"); const tchar ConstMAPIKeyProfileWin[] = _T("Software\\Microsoft\\Windows Messaging Subsystem\\Profiles"); const tchar ConstMAPIKeyProfileWinNT[] = _T("Software\\Microsoft\\Windows NT\\CurrentVersion\\Windows Messaging Subsystem\\Profiles"); const tchar ConstMAPIProfileVal[] = _T("DefaultProfile"); //////////////////////////////////////////////////////////////////////////////////////// // class MAPIModule // ----- ---------- MAPIModule::MAPIModule() : Module(_t("MAPI32.DLL")) { } bool MAPIModule::IsMAPIPresent() { try { TCharStr key_name = ConstMAPIKey; RegKey key(RegKey::GetLocalMachineKey(), key_name); AutoPtrArray<tchar> buffer = new tchar[TEXT_SIZE_SMALL]; uint count = TEXT_SIZE_SMALL; key.QueryValue(ConstMAPIVal, null, reinterpret_cast<byte*>(&buffer), &count); if(StrCompare(buffer, _t("1")) == 0) { return true; } return false; } catch(RegKey::XRegKey&) { return false; } catch(...) { return false; } } bool MAPIModule::IsMAPIXPresent() { try { TCharStr key_name = ConstMAPIKey; RegKey key(RegKey::GetLocalMachineKey(), key_name); AutoPtrArray<tchar> buffer = new tchar[TEXT_SIZE_SMALL]; uint count = TEXT_SIZE_SMALL; key.QueryValue(ConstMAPIXVal, null, (byte*)&buffer, &count); if(StrCompare(buffer, _t("1")) == 0) { return true; } return false; } catch(RegKey::XRegKey&) { return false; } catch(...) { return false; } } TCharStr MAPIModule::GetDefaultMAPIProfile() { try { TCharStr key_name = IsWinNT() ? ConstMAPIKeyProfileWinNT : ConstMAPIKeyProfileWin; RegKey key(RegKey::GetCurrentUserKey(), key_name); const short _buffer_size_ = 64; // for profiles ! ... AutoPtrArray<tchar> buffer = new tchar[_buffer_size_]; uint count = _buffer_size_; InitMemory(&buffer, _buffer_size_); key.QueryValue(ConstMAPIProfileVal, null, reinterpret_cast<byte*>(&buffer), &count); return TCharStr(buffer); } catch(RegKey::XRegKey&) { return TCharStr(); } catch(...) { return TCharStr(); } } Module& MAPIModule::GetMAPIModule() { static MAPIModule TheModule; return TheModule; } // Simple MAPI ulong MAPIModule::MAPILogon(ulong ui_param, const tchar* profile, const tchar* password, uint flags, ulong reserved, LHANDLE* session) { const char _name[] = "MAPILogon"; static ModuleProc6<ulong, ulong, const tchar*, const tchar*, uint, ulong, LHANDLE*> MAPILogon(GetMAPIModule(), _name); return MAPILogon(ui_param, profile, password, flags, reserved, session); } ulong MAPIModule::MAPILogoff(LHANDLE session, ulong ui_param, uint flags, ulong reserved) { const char _name[] = "MAPILogoff"; static ModuleProc4<ulong, LHANDLE, ulong, uint, ulong> MAPILogoff(GetMAPIModule(), _name); return MAPILogoff(session, ui_param, flags, reserved); } ulong MAPIModule::MAPISendMail(LHANDLE session, ulong ui_param, MapiMessage* message, uint flags, ulong reserved) { const char _name[] = "MAPISendMail"; static ModuleProc5<ulong, LHANDLE, ulong, MapiMessage*, uint, ulong> MAPISendMail(GetMAPIModule(), _name); return MAPISendMail(session, ui_param, message, flags, reserved); } ulong MAPIModule::MAPISendDocuments(ulong ui_param, const tchar* delimiter, const tchar* path, const tchar* name, ulong reserved) { const char _name[] = "MAPISendDocuments"; static ModuleProc5<ulong, ulong, const tchar*, const tchar*, const tchar*, ulong> MAPISendDocuments(GetMAPIModule(), _name); return MAPISendDocuments(ui_param, delimiter, path, name, reserved); } ulong MAPIModule::MAPIFindNext(LHANDLE session, ulong ui_param, const tchar* type, const tchar* seed_id, uint flags, ulong reserved, const tchar* id) { const char _name[] = "MAPIFindNext"; static ModuleProc7<ulong, LHANDLE, ulong, const tchar*, const tchar*, uint, ulong, const tchar*> MAPIFindNext(GetMAPIModule(), _name); return MAPIFindNext(session, ui_param, type, seed_id, flags, reserved, id); } ulong MAPIModule::MAPIReadMail(LHANDLE session, ulong ui_param, const tchar* id, uint flags, ulong reserved, MapiMessage* message) { const char _name[] = "MAPIReadMail"; static ModuleProc6<ulong, LHANDLE, ulong, const tchar*, uint, ulong, MapiMessage*> MAPIReadMail(GetMAPIModule(), _name); return MAPIReadMail(session, ui_param, id, flags, reserved, message); } ulong MAPIModule::MAPISaveMail(LHANDLE session, ulong ui_param, MapiMessage* message, uint flags, ulong reserved, const tchar* id) { const char _name[] = "MAPISaveMail"; static ModuleProc6<ulong, LHANDLE, ulong, MapiMessage*, uint, ulong, const tchar*> MAPISaveMail(GetMAPIModule(), _name); return MAPISaveMail(session, ui_param, message, flags, reserved, id); } ulong MAPIModule::MAPIDeleteMail(LHANDLE session, ulong ui_param, const tchar* id, uint flags, ulong reserved) { const char _name[] = "MAPIDeleteMail"; static ModuleProc5<ulong, LHANDLE, ulong, const tchar*, uint, ulong> MAPIDeleteMail(GetMAPIModule(), _name); return MAPIDeleteMail(session, ui_param, id, flags, reserved); } ulong MAPIModule::MAPIFreeBuffer(void* p) { const char _name[] = "MAPIFreeBuffer"; static ModuleProc1<ulong, void*> MAPIFreeBuffer(GetMAPIModule(), _name); return MAPIFreeBuffer(p); } ulong MAPIModule::MAPIAddress(LHANDLE session, ulong ui_param, const tchar* caption, ulong edit_fields, const tchar* labels, ulong recips_count, MapiRecipDesc* recips_list, uint flags, ulong reserved, ulong* new_recips_count, MapiRecipDesc* new_recips_list) { const char _name[] = "MAPIAddress"; static ModuleProc11<ulong, LHANDLE, ulong, const tchar*, ulong, const tchar*, ulong, MapiRecipDesc*, uint, ulong, ulong*, MapiRecipDesc*> MAPIAddress(GetMAPIModule(), _name); return MAPIAddress(session, ui_param, caption, edit_fields, labels, recips_count, recips_list, flags, reserved, new_recips_count, new_recips_list); } ulong MAPIModule::MAPIDetails(LHANDLE session, ulong ui_param, MapiRecipDesc* recip, uint flags, ulong reserved) { const char _name[] = "MAPIDetails"; static ModuleProc5<ulong, LHANDLE, ulong, MapiRecipDesc*, uint, ulong> MAPIDetails(GetMAPIModule(), _name); return MAPIDetails(session, ui_param, recip, flags, reserved); } ulong MAPIModule::MAPIResolveName(LHANDLE session, ulong ui_param, const tchar* name, uint flags, ulong reserved, MapiRecipDesc** recip) { const char _name[] = "MAPIResolveName"; static ModuleProc6<ulong, LHANDLE, ulong, const tchar*, uint, ulong, MapiRecipDesc**> MAPIResolveName(GetMAPIModule(), _name); return MAPIResolveName(session, ui_param, name, flags, reserved, recip); } // MAPIX HRESULT MAPIModule::MAPIInitialize(void* init) { const char _name[] = "MAPIInitialize"; static ModuleProc1<HRESULT, void*> MAPIInitialize(GetMAPIModule(), _name); return MAPIInitialize(init); } void MAPIModule::MAPIUninitialize() { const char _name[] = "MAPIUninitialize"; static ModuleProcV0<> MAPIUninitialize(GetMAPIModule(), _name); MAPIUninitialize(); } HRESULT MAPIModule::MAPILogonEx(ulong ui_parem, const tchar* profile, const tchar* password, uint flags, IMAPISession* session) { const char _name[] = "MAPILogonEx"; static ModuleProc5<HRESULT, ulong, const tchar*, const tchar*, uint, IMAPISession*> MAPILogonEx(GetMAPIModule(), _name); return MAPILogonEx(ui_parem, profile, password, flags, session); } SCODE MAPIModule::MAPIAllocateBuffer(uint count, void** buffer) { const char _name[] = "MAPIAllocateBuffer"; static ModuleProc2<SCODE, uint, void**> MAPIAllocateBuffer(GetMAPIModule(), _name); return MAPIAllocateBuffer(count, buffer); } SCODE MAPIModule::MAPIAllocateMore(uint count, void* object, void** buffer) { const char _name[] = "MAPIAllocateMore"; static ModuleProc3<SCODE, uint, void*, void**> MAPIAllocateMore(GetMAPIModule(), _name); return MAPIAllocateMore(count, object, buffer); } HRESULT MAPIModule::MAPIAdminProfiles(uint flags, IProfAdmin** admin) { const char _name[] = "MAPIAdminProfiles"; static ModuleProc2<HRESULT, uint, IProfAdmin**> MAPIAdminProfiles(GetMAPIModule(), _name); return MAPIAdminProfiles(flags, admin); } //////////////////////////////////////////////////////////////////////////////////////// __END_NAMESPACE__
avim2809/CameraSiteBlocker
venv/Lib/site-packages/uiutil/frame/__init__.py
<gh_stars>0 # coding=utf-8 from .radio import BaseRadioFrame from .dynamic import DynamicFrame, DynamicScrollFrame, DynamicWidgetFrame from .frame import BaseFrame from .label import BaseLabelFrame from .launcher import LauncherFrame, LauncherGroupFrame, LauncherMixIn from .loading import LoadingFrame from .log import LogFrame from .log_ticker import LogTickerFrame from .scroll import BaseScrollFrame from .splash import SplashFrame from .switch import BaseSwitchFrame
bluepuppetcompany/user-email-address-component
lib/user_email_address_component/controls/write/claim.rb
<reponame>bluepuppetcompany/user-email-address-component<filename>lib/user_email_address_component/controls/write/claim.rb<gh_stars>0 module UserEmailAddressComponent module Controls module Write module Claim def self.call( id: nil, email_address: nil, user_id: nil ) id ||= ID.example email_address ||= UserEmailAddress.email_address user_id ||= User.id encoded_email_address = Digest::SHA256.hexdigest(email_address.downcase) claim = Commands::Claim.example( id: id, encoded_email_address: encoded_email_address, email_address: email_address, user_id: user_id ) command_stream_name = Messaging::StreamName.command_stream_name(encoded_email_address, "userEmailAddress") Messaging::Postgres::Write.(claim, command_stream_name) end end end end end
svisser/reasoning-about-preferences
src/holiday/PurchaseTravelBagPlan.java
package holiday; import summary.PreferencePlan; public class PurchaseTravelBagPlan extends PreferencePlan { }
XpressAI/SparkCyclone
aveobench/src/main/scala/com/nec/cyclone/colvector/CompressedBytePointerColBatch.scala
package com.nec.cyclone.colvector import com.nec.colvector._ import com.nec.spark.agile.core.{VeScalarType, VeString} import com.nec.util.CallContext import com.nec.vectorengine.{VeAsyncResult, VeProcess} import com.nec.ve.VeProcessMetrics import org.bytedeco.javacpp.BytePointer final case class CompressedBytePointerColBatch private[colvector] (columns: Seq[UnitColVector], buffer: BytePointer) { private[colvector] def newCompressedStruct(location: Long): BytePointer = { // Get container sizes val csizes = columns.map(_.veType.containerSize) // Create a combined buffer of the sum of container sizes val combined = new BytePointer(csizes.foldLeft(0L)(_ + _)) // Create data offset var dataOffset = 0L (columns, csizes.scanLeft(0)(_ + _)).zipped.foreach { case (column, structOffset) => // Get the buffer sizes for the column val dlens = column.bufferSizes.map(_.toLong) column.veType match { case _: VeScalarType => // Each address is the start of the combined data buffer (location) + // offset for the data corresponding to the Nth column + // buffer offset within the column combined.putLong(structOffset + 0, location + dataOffset) combined.putLong(structOffset + 8, location + dataOffset + dlens(0)) combined.putInt(structOffset + 16, column.numItems.abs) case VeString => val Some(actualDataSize) = column.dataSize combined.putLong(structOffset + 0, location + dataOffset) combined.putLong(structOffset + 8, location + dataOffset + dlens(0)) combined.putLong(structOffset + 16, location + dataOffset + dlens(0) + dlens(1)) combined.putLong(structOffset + 24, location + dataOffset + dlens(0) + dlens(1) + dlens(2)) combined.putInt(structOffset + 32, actualDataSize.abs) combined.putInt(structOffset + 36, column.numItems.abs) } // Update the data offset dataOffset += dlens.foldLeft(0L)(_ + _) } combined } def asyncToCompressedVeColBatch(implicit source: VeColVectorSource, process: VeProcess, context: CallContext, metrics: VeProcessMetrics): () => VeAsyncResult[CompressedVeColBatch] = { // Allocate memory on the VE val veLocations = Seq( // Size of the compressed struct columns.map(_.veType.containerSize.toLong).foldLeft(0L)(_ + _), // Size of the combined data buffer.limit() ).map(process.allocate) // Build the compressed struct on VH with the correct pointers to VE memory locations val struct = newCompressedStruct(veLocations(1)) // Construct the CompressedVeColBatch from the VE locations val batch = CompressedVeColBatch(columns, veLocations(0), veLocations(1)) () => { val handles = (Seq(struct, buffer), veLocations).zipped.map { case (buf, to) => process.putAsync(buf, to) } VeAsyncResult(handles) { () => struct.close batch } } } def toCompressedVeColBatch(implicit source: VeColVectorSource, process: VeProcess, context: CallContext, metrics: VeProcessMetrics): CompressedVeColBatch = { asyncToCompressedVeColBatch.apply().get() } }
GregDevProjects/carbon-header-fix
node_modules/@carbon/icons-react/es/document--add/32.js
<reponame>GregDevProjects/carbon-header-fix<filename>node_modules/@carbon/icons-react/es/document--add/32.js import { DocumentAdd32 } from '..'; export default DocumentAdd32;
krashnakant/jhipster-lite
src/main/java/tech/jhipster/lite/generator/client/angular/security/oauth2/domain/AngularOauth2.java
package tech.jhipster.lite.generator.client.angular.security.oauth2.domain; import static tech.jhipster.lite.common.domain.FileUtils.*; import static tech.jhipster.lite.generator.project.domain.Constants.MAIN_WEBAPP; import java.util.List; import java.util.Map; public class AngularOauth2 { private AngularOauth2() { // Cannot be instantiated } protected static final String APP_MODULE_TS_FILE_PATH = getPath(MAIN_WEBAPP, "app/app.module.ts"); protected static final String ENVIRONMENT_TS_FILE_PATH = getPath(MAIN_WEBAPP, "environments/environment.ts"); protected static final String ENVIRONMENT_PROD_TS_FILE_PATH = getPath(MAIN_WEBAPP, "environments/environment.prod.ts"); protected static final String APP_COMPONENT_HTML_FILE_PATH = getPath(MAIN_WEBAPP, "app/app.component.html"); protected static final String APP_COMPONENT_SPEC_TS_FILE_PATH = getPath(MAIN_WEBAPP, "app/app.component.spec.ts"); protected static List<String> getDependencies() { return List.of("keycloak-js"); } protected static Map<String, String> getFilesToAdd() { String authFolderPath = "app/auth"; String loginFolderPath = "app/login"; return Map.ofEntries( Map.entry("oauth2-auth.service.ts", authFolderPath), Map.entry("oauth2-auth.service.spec.ts", authFolderPath), Map.entry("http-auth.interceptor.ts", authFolderPath), Map.entry("http-auth.interceptor.spec.ts", authFolderPath), Map.entry("login.component.html", loginFolderPath), Map.entry("login.component.ts", loginFolderPath), Map.entry("login.component.spec.ts", loginFolderPath) ); } }
SEPIA-Framework/assist-server
src/main/java/net/b07z/sepia/server/assist/parameters/Confirm.java
package net.b07z.sepia.server.assist.parameters; import java.util.HashMap; import java.util.regex.Pattern; import org.json.simple.JSONObject; import net.b07z.sepia.server.assist.assistant.LANGUAGES; import net.b07z.sepia.server.assist.interpreters.NluInput; import net.b07z.sepia.server.assist.interpreters.NluResult; import net.b07z.sepia.server.assist.interpreters.RegexParameterSearch; import net.b07z.sepia.server.assist.interviews.InterviewData; import net.b07z.sepia.server.assist.users.User; import net.b07z.sepia.server.core.tools.Debugger; import net.b07z.sepia.server.core.tools.JSON; /** * Basically this is the same as YesNo but sometimes it makes a) sense to have 2 and b) we can treat this specially maybe (like no auto-extraction as optional or so). * * @author <NAME> * */ public class Confirm implements ParameterHandler{ //-----data----- public static final String PREFIX = "confirm_"; //prefix for special confirmation procedure public static final String OK = "ok"; //check parameter value against this and ... public static final String CANCEL = "cancel"; //..this public static HashMap<String, String> confirm_de = new HashMap<>(); public static HashMap<String, String> confirm_en = new HashMap<>(); static { confirm_de.put("<ok>", "ok"); confirm_de.put("<cancel>", "abbrechen"); confirm_en.put("<ok>", "ok"); confirm_en.put("<cancel>", "cancel"); } /** * Translate generalized value (e.g. &lt;yes&gt;) to local speakable name (e.g. "Ja"). * If generalized value is unknown returns empty string. * @param input - generalized value * @param language - ISO language code */ public static String getLocal(String input, String language){ String value = input; if (language.equals(LANGUAGES.DE)){ value = confirm_de.get(value); }else if (language.equals(LANGUAGES.EN)){ value = confirm_en.get(value); } if (value == null){ Debugger.println("Confirm.java - getLocal() has no '" + language + "' version for '" + input + "'", 3); return ""; } return value; } //---------------- User user; String language; boolean buildSuccess = false; NluInput nlu_input; String found = ""; @Override public void setup(NluInput nluInput) { this.user = nluInput.user; this.language = nluInput.language; this.nlu_input = nluInput; } @Override public void setup(NluResult nluResult) { this.user = nluResult.input.user; this.language = nluResult.language; this.nlu_input = nluResult.input; } @Override public String extract(String input) { //TODO: implement found String value = RegexParameterSearch.yes_or_no(input, language); if (value.equals("yes")){ return ("<" + "ok" + ">"); }else if (value.equals("no")){ return ("<" + "cancel" + ">"); }else{ return ""; } } @Override public String guess(String input) { return ""; } @Override public String getFound() { //TODO: implement return ""; } @Override public String remove(String input, String found) { if (language.equals(LANGUAGES.DE)){ input = input.replaceFirst("\\b()(" + Pattern.quote(found) + ")", "").trim(); }else{ input = input.replaceFirst("\\b()(" + Pattern.quote(found) + ")", "").trim(); } return null; } @Override public String responseTweaker(String input){ return input; } @Override public String build(String input) { //expects a yes/no tag! String commonValue = input.replaceAll("^<|>$", "").trim(); String localValue = getLocal(input, language); //is accepted result? if (localValue.isEmpty()){ return ""; } //build default result JSONObject itemResultJSON = new JSONObject(); JSON.add(itemResultJSON, InterviewData.VALUE, commonValue); JSON.add(itemResultJSON, InterviewData.VALUE_LOCAL, localValue); buildSuccess = true; return itemResultJSON.toJSONString(); } @Override public boolean validate(String input) { if (input.matches("^\\{\".*\"(\\s|):.+\\}$") && input.contains("\"" + InterviewData.VALUE + "\"")){ //System.out.println("IS VALID: " + input); //debug return true; }else{ return false; } } @Override public boolean buildSuccess() { return buildSuccess; } }
sunyunxian/test_lib
Python/Fluent_Python/chapter3/section5/5-9.py
<filename>Python/Fluent_Python/chapter3/section5/5-9.py foo = "foo" bar = "bar" class C: pass c = C() def f(): pass # print(dir(C)) # print(dir(f)) print(sorted(set(dir(f)) - set(dir(c)))) # print(f.__globals__) print(f.__call__())
lismaya/proyek_akhir_simekia
android/app/src/main/java/com/example/sipanji/SplashActivity.java
package com.example.sipanji; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.example.sipanji.util.SharedPrefManager; import com.example.sipanji.util.api.BaseApiService; import com.example.sipanji.util.api.UtilsApi; public class SplashActivity extends AppCompatActivity { SharedPrefManager sharedPrefManager; BaseApiService mBaseApiService; Context mContext; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; mBaseApiService = UtilsApi.getAPIService(); sharedPrefManager = new SharedPrefManager(this); int SPLASH_TIME_OUT = 2; new Handler().postDelayed(() -> { Intent intent = new Intent(SplashActivity.this, LoginActivity.class); startActivity(intent); finish(); }, SPLASH_TIME_OUT); } }
wqk317/mi8_kernel_source
mi8/drivers/staging/qca-wifi-host-cmn/umac/dfs/core/src/filtering/dfs_misc.c
/* * Copyright (c) 2016-2017 The Linux Foundation. All rights reserved. * Copyright (c) 2002-2010, Atheros Communications Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /** * DOC: This file really does contain miscellaneous functions that didn't fit * in anywhere else. */ #include "../dfs.h" #include "wlan_dfs_lmac_api.h" #include "wlan_dfs_mlme_api.h" #include "../dfs_internal.h" /** * dfs_adjust_pri_per_chan_busy() - Calculates adjust_pri. * @ext_chan_busy: Extension channel PRI. * @pri_margin: Primary margin. * * Calculates the adjust_pri using ext_chan_busy, DFS_EXT_CHAN_LOADING_THRESH * and pri_margin. * * Return: adjust_pri. */ static int dfs_adjust_pri_per_chan_busy(int ext_chan_busy, int pri_margin) { int adjust_pri = 0; if (ext_chan_busy > DFS_EXT_CHAN_LOADING_THRESH) { adjust_pri = ((ext_chan_busy - DFS_EXT_CHAN_LOADING_THRESH) * (pri_margin)); adjust_pri /= 100; } return adjust_pri; } /** * dfs_adjust_thresh_per_chan_busy() - Calculates adjust_thresh. * @ext_chan_busy: Extension channel PRI. * @thresh: Threshold value. * * Calculates the adjust_thresh using ext_chan_busy, DFS_EXT_CHAN_LOADING_THRESH * and thresh. * * Return: adjust_thresh. */ static int dfs_adjust_thresh_per_chan_busy(int ext_chan_busy, int thresh) { int adjust_thresh = 0; if (ext_chan_busy > DFS_EXT_CHAN_LOADING_THRESH) { adjust_thresh = ((ext_chan_busy - DFS_EXT_CHAN_LOADING_THRESH) * thresh); adjust_thresh /= 100; } return adjust_thresh; } /** * dfs_get_cached_ext_chan_busy() - Get cached ext chan busy. * @dfs: Pointer to wlan_dfs structure. * @ext_chan_busy: Extension channel PRI. */ static inline void dfs_get_cached_ext_chan_busy( struct wlan_dfs *dfs, int *ext_chan_busy) { *ext_chan_busy = 0; /* Check to see if the cached value of ext_chan_busy can be used. */ if (dfs->dfs_rinfo.dfs_ext_chan_busy && (dfs->dfs_rinfo.rn_lastfull_ts < dfs->dfs_rinfo.ext_chan_busy_ts)) { *ext_chan_busy = dfs->dfs_rinfo.dfs_ext_chan_busy; dfs_debug(dfs, WLAN_DEBUG_DFS2, "Use cached copy of ext_chan_busy extchanbusy=%d rn_lastfull_ts=%llu ext_chan_busy_ts=%llu", *ext_chan_busy, (uint64_t)dfs->dfs_rinfo.rn_lastfull_ts, (uint64_t)dfs->dfs_rinfo.ext_chan_busy_ts); } } int dfs_get_pri_margin(struct wlan_dfs *dfs, int is_extchan_detect, int is_fixed_pattern) { int adjust_pri = 0, ext_chan_busy = 0; int pri_margin; if (is_fixed_pattern) pri_margin = DFS_DEFAULT_FIXEDPATTERN_PRI_MARGIN; else pri_margin = DFS_DEFAULT_PRI_MARGIN; if (WLAN_IS_CHAN_11N_HT40(dfs->dfs_curchan)) { ext_chan_busy = lmac_get_ext_busy(dfs->dfs_pdev_obj); if (ext_chan_busy >= 0) { dfs->dfs_rinfo.ext_chan_busy_ts = lmac_get_tsf64(dfs->dfs_pdev_obj); dfs->dfs_rinfo.dfs_ext_chan_busy = ext_chan_busy; } else { dfs_get_cached_ext_chan_busy(dfs, &ext_chan_busy); } adjust_pri = dfs_adjust_pri_per_chan_busy(ext_chan_busy, pri_margin); pri_margin -= adjust_pri; } return pri_margin; } int dfs_get_filter_threshold(struct wlan_dfs *dfs, struct dfs_filter *rf, int is_extchan_detect) { int ext_chan_busy = 0; int thresh, adjust_thresh = 0; thresh = rf->rf_threshold; if (WLAN_IS_CHAN_11N_HT40(dfs->dfs_curchan)) { ext_chan_busy = lmac_get_ext_busy(dfs->dfs_pdev_obj); if (ext_chan_busy >= 0) { dfs->dfs_rinfo.ext_chan_busy_ts = lmac_get_tsf64(dfs->dfs_pdev_obj); dfs->dfs_rinfo.dfs_ext_chan_busy = ext_chan_busy; } else { dfs_get_cached_ext_chan_busy(dfs, &ext_chan_busy); } adjust_thresh = dfs_adjust_thresh_per_chan_busy(ext_chan_busy, thresh); dfs_debug(dfs, WLAN_DEBUG_DFS2, " filterID=%d extchanbusy=%d adjust_thresh=%d", rf->rf_pulseid, ext_chan_busy, adjust_thresh); thresh += adjust_thresh; } return thresh; } uint32_t dfs_round(int32_t val) { uint32_t ival, rem; if (val < 0) return 0; ival = val/100; rem = val - (ival * 100); if (rem < 50) return ival; else return ival + 1; }
aliostad/deep-learning-lang-detection
data/train/ruby/ce0e0f1252b0acb7d84bef1f1947bcf83a96babaaq_repositories_controller.rb
<gh_stars>10-100 require 'grit' include Grit class AqRepositoriesController < ApplicationController before_filter :login_required, :except => [:show, :view_file, :show_commits, :show_commit] def index @repositories = current_user.aq_repositories end def show @repository = AqRepository.find(params[:id]) if @repository.is_git? @grit_repo = Repo.new(@repository.path) end end def new @repository = AqRepository.new end def create @repository = AqRepository.new(params[:aq_repository]) @repository.owner = current_user if @repository.save flash[:notice] = t(:repo_create_ok) redirect_to @repository else flash[:notice] = t(:repo_create_ko) redirect_to aq_repositories end end def edit @repository = AqRepository.find(params[:id]) if @repository.owner != current_user @repository = nil flash[:notice] = t(:insufficient_rights) redirect_to root_path end end def update @repository = AqRepository.find(params[:id]) if @repository.rights.size == 0 @repository.owner = current_user end if @repository.update_attributes(params[:aq_repository]) flash[:notice] = t(:repo_update_ok) redirect_to @repository else render :action => 'edit' end end def destroy repository = AqRepository.find(params[:id]) repository.destroy flash[:notice] = t(:repo_destroy_ok) redirect_to aq_repositories_path end def join repository = AqRepository.find(params[:id]) if !repository.users.include?(current_user) a_right = Right.new a_right.role = "c" a_right.right = "r" a_right.status = "p" a_right.user = current_user repository.rights << a_right repository.save end redirect_to repository end def fork parent_repo = AqRepository.find(params[:id]) repository = AqRepository.new repository.fork(parent_repo) repository.save if repository redirect_to repository end def view_file @repository = AqRepository.find(params[:id]) if @repository.is_git? @grit_repo = Repo.new(@repository.path) end end def show_commits @repository = AqRepository.find(params[:id]) if @repository.is_git? @grit_repo = Repo.new(@repository.path) end end def show_commit @repository = AqRepository.find(params[:id]) if @repository.is_git? @grit_repo = Repo.new(@repository.path) end end end
cocomikes/YcShareElement
app/src/main/java/us/pinguo/shareelementdemo/simple/SimpleFragmentActivity.java
<reponame>cocomikes/YcShareElement<gh_stars>100-1000 package us.pinguo.shareelementdemo.simple; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import us.pinguo.shareelementdemo.R; import com.hw.ycshareelement.TransitionHelper; /** * Created by huangwei on 2018/9/18 0018. */ public class SimpleFragmentActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { TransitionHelper.enableTransition(this); super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple); getSupportFragmentManager().beginTransaction().add(R.id.simple_container, new Simple1Fragment()).commit(); } }
cctvzd7/aliyun-openapi-java-sdk
aliyun-java-sdk-workorder/src/main/java/com/aliyuncs/workorder/transform/v20200326/ListTicketsResponseUnmarshaller.java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.workorder.transform.v20200326; import java.util.ArrayList; import java.util.List; import com.aliyuncs.workorder.model.v20200326.ListTicketsResponse; import com.aliyuncs.workorder.model.v20200326.ListTicketsResponse.Data; import com.aliyuncs.workorder.model.v20200326.ListTicketsResponse.Data.ListItem; import com.aliyuncs.transform.UnmarshallerContext; public class ListTicketsResponseUnmarshaller { public static ListTicketsResponse unmarshall(ListTicketsResponse listTicketsResponse, UnmarshallerContext _ctx) { listTicketsResponse.setRequestId(_ctx.stringValue("ListTicketsResponse.RequestId")); listTicketsResponse.setCode(_ctx.integerValue("ListTicketsResponse.Code")); listTicketsResponse.setSuccess(_ctx.booleanValue("ListTicketsResponse.Success")); listTicketsResponse.setMessage(_ctx.stringValue("ListTicketsResponse.Message")); Data data = new Data(); data.setTotal(_ctx.integerValue("ListTicketsResponse.Data.Total")); data.setPageSize(_ctx.integerValue("ListTicketsResponse.Data.PageSize")); data.setCurrentPage(_ctx.integerValue("ListTicketsResponse.Data.CurrentPage")); List<ListItem> list = new ArrayList<ListItem>(); for (int i = 0; i < _ctx.lengthValue("ListTicketsResponse.Data.List.Length"); i++) { ListItem listItem = new ListItem(); listItem.setAddTime(_ctx.integerValue("ListTicketsResponse.Data.List["+ i +"].AddTime")); listItem.setTicketStatus(_ctx.stringValue("ListTicketsResponse.Data.List["+ i +"].TicketStatus")); listItem.setCreatorId(_ctx.stringValue("ListTicketsResponse.Data.List["+ i +"].CreatorId")); listItem.setId(_ctx.stringValue("ListTicketsResponse.Data.List["+ i +"].Id")); listItem.setTitle(_ctx.stringValue("ListTicketsResponse.Data.List["+ i +"].Title")); list.add(listItem); } data.setList(list); listTicketsResponse.setData(data); return listTicketsResponse; } }
NBAston/FishClient
temp/quick-scripts/src/assets/modules/plaza/script/prefab/bindPhone/unbind.js
<filename>temp/quick-scripts/src/assets/modules/plaza/script/prefab/bindPhone/unbind.js "use strict"; cc._RF.push(module, '47695rj25FGXKtHeivZBhVO', 'unbind'); // modules/plaza/script/prefab/bindPhone/unbind.js "use strict"; glGame.baseclass.extend({ properties: {}, onLoad: function onLoad() { this.registerEvent(); }, start: function start() {}, registerEvent: function registerEvent() {}, unRegisterEvent: function unRegisterEvent() {}, OnDestroy: function OnDestroy() { this.unRegisterEvent(); }, onClick: function onClick(name, node) { switch (name) { case "close": this.close(); break; case "btn_unbindSure": this.unbindSure_cb(); break; default: break; } }, //无法更改手机 unbindSure_cb: function unbindSure_cb() { this.close(); glGame.panel.showService(); }, close: function close() { this.remove(); } }); cc._RF.pop();
Fabs/dcos-ui
plugins/services/src/js/containers/framework-configuration/FrameworkConfigurationContainer.js
<reponame>Fabs/dcos-ui import PropTypes from "prop-types"; import React from "react"; import UniversePackage from "#SRC/js/structs/UniversePackage"; import Framework from "#PLUGINS/services/src/js/structs/Framework"; import { routerShape } from "react-router"; import FrameworkConfigurationReviewScreen from "#SRC/js/components/FrameworkConfigurationReviewScreen"; import Loader from "#SRC/js/components/Loader"; import CosmosPackagesStore from "#SRC/js/stores/CosmosPackagesStore"; import { COSMOS_SERVICE_DESCRIBE_CHANGE } from "#SRC/js/constants/EventTypes"; import { getDefaultFormState } from "react-jsonschema-form/lib/utils"; const METHODS_TO_BIND = [ "handleEditClick", "onCosmosPackagesStoreServiceDescriptionSuccess" ]; class FrameworkConfigurationContainer extends React.Component { constructor(props) { super(props); const { service } = this.props; this.state = { frameworkData: null }; METHODS_TO_BIND.forEach(method => { this[method] = this[method].bind(this); }); CosmosPackagesStore.fetchServiceDescription(service.getId()); } componentDidMount() { CosmosPackagesStore.addChangeListener( COSMOS_SERVICE_DESCRIBE_CHANGE, this.onCosmosPackagesStoreServiceDescriptionSuccess ); } componentWillUnmount() { CosmosPackagesStore.removeChangeListener( COSMOS_SERVICE_DESCRIBE_CHANGE, this.onCosmosPackagesStoreServiceDescriptionSuccess ); } onCosmosPackagesStoreServiceDescriptionSuccess() { const fullPackage = CosmosPackagesStore.getServiceDetails(); const packageDetails = new UniversePackage(fullPackage.package); const schema = packageDetails.getConfig(); const frameworkData = getDefaultFormState( schema, fullPackage.resolvedOptions, schema.definitions ); this.setState({ frameworkData }); } handleEditClick() { const { router } = this.context; const { service } = this.props; router.push( `/services/detail/${encodeURIComponent(service.getId())}/edit/` ); } render() { const { frameworkData } = this.state; if (!frameworkData) { return <Loader />; } return ( <FrameworkConfigurationReviewScreen frameworkData={frameworkData} onEditClick={this.handleEditClick} /> ); } } FrameworkConfigurationContainer.propTypes = { service: PropTypes.instanceOf(Framework).isRequired }; FrameworkConfigurationContainer.contextTypes = { router: routerShape }; module.exports = FrameworkConfigurationContainer;
WoodoLee/TorchCraft
3rdparty/pytorch/caffe2/operators/experimental/c10/schemas/batch_gather.cc
<filename>3rdparty/pytorch/caffe2/operators/experimental/c10/schemas/batch_gather.cc #include "caffe2/operators/experimental/c10/schemas/batch_gather.h" #include <c10/core/dispatch/OpSchemaRegistration.h> #include "caffe2/core/operator_c10wrapper.h" using caffe2::CPUContext; C10_DEFINE_OP_SCHEMA(caffe2::ops::BatchGather); namespace caffe2 { REGISTER_C10_OPERATOR_FOR_CAFFE2_DISPATCH( ops::BatchGather, void, C10BatchGather_DontUseThisOpYet) }
edzya/Python_RTU_08_20
Diena_13_Visualization/random/miss_num.py
<filename>Diena_13_Visualization/random/miss_num.py import random nums = [str(n)+"\n" for n in range(1, 51)] random.shuffle(nums) print(nums) nums.pop() with open("missing_number.txt", "w") as f: f.writelines(nums)
maurizioabba/rose
tests/CompileTests/ElsaTestCases/t0522.cc
<gh_stars>100-1000 // t0522.cc // use an explicit specialization before it is declared template <class T> struct A; // does not require instantiation yet, so it is ok that the definition // of A<T> has not been provided, and it is also ok that the // declaration of A<int> has not been provided typedef A<int> A_int; template <class T> struct A {}; // makes the program ill-formed, because A<int> has not // been declared //ERROR(1): A<int> bad; template <> struct A<int> { int x; }; int foo() { A_int a; return a.x; //ERRORIFMISSING(1): error 1 is still bad even without this }
genghechuangwy/cas
core/cas-server-core-services/src/test/java/org/apereo/cas/services/AbstractResourceBasedServiceRegistryTests.java
<filename>core/cas-server-core-services/src/test/java/org/apereo/cas/services/AbstractResourceBasedServiceRegistryTests.java<gh_stars>1-10 package org.apereo.cas.services; import lombok.SneakyThrows; import lombok.val; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.RandomUtils; import org.junit.jupiter.api.Tag; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.springframework.core.io.ClassPathResource; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; /** * This is {@link AbstractResourceBasedServiceRegistryTests}. * * @author <NAME> * @since 5.0.0 */ @Tag("FileSystem") public abstract class AbstractResourceBasedServiceRegistryTests extends AbstractServiceRegistryTests { public static final ClassPathResource RESOURCE = new ClassPathResource("services"); protected ServiceRegistry dao; public static Stream<Class<? extends RegisteredService>> getParameters() { return AbstractServiceRegistryTests.getParameters(); } @Override @SneakyThrows public void tearDownServiceRegistry() { FileUtils.cleanDirectory(RESOURCE.getFile()); super.tearDownServiceRegistry(); } @ParameterizedTest @MethodSource("getParameters") public void verifyServiceWithInvalidFileName(final Class<? extends RegisteredService> registeredServiceClass) { val r = buildRegisteredServiceInstance(RandomUtils.nextInt(), registeredServiceClass); r.setName("hell/o@world:*"); assertThrows(IllegalArgumentException.class, () -> this.dao.save(r)); } @Override public ServiceRegistry getNewServiceRegistry() { return this.dao; } }
portlek/synergy
client/src/main/java/io/github/portlek/synergy/client/config/ClientConfig.java
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package io.github.portlek.synergy.client.config; import io.github.portlek.configs.ConfigHolder; import io.github.portlek.configs.ConfigLoader; import io.github.portlek.configs.configuration.FileConfiguration; import io.github.portlek.configs.json.JsonType; import io.github.portlek.synergy.api.KeyStore; import io.github.portlek.synergy.core.util.SystemUtils; import java.util.Locale; import java.util.ResourceBundle; import org.jetbrains.annotations.NotNull; /** * a class that represents client's config. */ public final class ClientConfig implements ConfigHolder { /** * the key store. */ public static KeyStore key = new KeyStore.Impl("default-client-id", "client", "default-client-password"); /** * the client's language. */ public static Locale lang = Locale.US; /** * the configuration. */ private static FileConfiguration configuration; /** * the loader. */ private static ConfigLoader loader; /** * ctor. */ private ClientConfig() { } /** * obtains the language bundle. * * @return language bundle. */ @NotNull public static ResourceBundle getLanguageBundle() { return ResourceBundle.getBundle("Synergy", ClientConfig.lang); } /** * loads the config. */ public static void load() { ConfigLoader.builder() .setConfigHolder(new ClientConfig()) .setConfigType(JsonType.get()) .setFileName("client") .setFolder(SystemUtils.getHomePath()) .addLoaders(KeyStore.Loader.INSTANCE) .build() .load(true); } /** * sets the client's language. * * @param lang the lang to set. */ public static void setLanguage(@NotNull final Locale lang) { ClientConfig.lang = lang; ClientConfig.configuration.set("lang", lang.getLanguage() + "_" + lang.getCountry().toUpperCase(Locale.ROOT)); ClientConfig.loader.save(); } }
hideack/evac
lib/plugin/out/mail.js
var nodemailer = require('nodemailer'); var mail = {}; mail.output = function(args, word, next) { if (word != "") { var transporter = nodemailer.createTransport(); var options = { from: args.from, to: args.to, subject: args.subject, text: word }; transporter.sendMail(options, function(error, info) { if(error) { next(true, "send mail error."); } else { next(false, info.response); } }); } } module.exports = mail;
aeoncl/wlmatrix
WLMatrix/include/libmatrix/dto/AccountDataDirectResponse.h
<reponame>aeoncl/wlmatrix #pragma once #include "AccountDataResponse.h" #include <optional> #include "DirectEvent.h" class AccountDataDirectResponse : public AccountDataResponse { public: std::optional<std::string> getUserIdForRoomId(std::string roomId); };
suztomo/java-pubsublite
google-cloud-pubsublite/src/main/java/com/google/cloud/pubsublite/internal/CursorClientSettings.java
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.pubsublite.internal; import static com.google.cloud.pubsublite.internal.ExtractStatus.toCanonical; import static com.google.cloud.pubsublite.internal.wire.ServiceClients.addDefaultSettings; import com.google.api.gax.rpc.ApiException; import com.google.auto.value.AutoValue; import com.google.cloud.pubsublite.CloudRegion; import com.google.cloud.pubsublite.v1.CursorServiceClient; import com.google.cloud.pubsublite.v1.CursorServiceSettings; import java.util.Optional; @AutoValue public abstract class CursorClientSettings { // Required parameters. abstract CloudRegion region(); // Optional parameters. abstract Optional<CursorServiceClient> serviceClient(); public static Builder newBuilder() { return new AutoValue_CursorClientSettings.Builder(); } @AutoValue.Builder public abstract static class Builder { // Required parameters. public abstract Builder setRegion(CloudRegion region); // Optional parameters. public abstract Builder setServiceClient(CursorServiceClient serviceClient); public abstract CursorClientSettings build(); } CursorClient instantiate() throws ApiException { CursorServiceClient serviceClient; if (serviceClient().isPresent()) { serviceClient = serviceClient().get(); } else { try { serviceClient = CursorServiceClient.create( addDefaultSettings(region(), CursorServiceSettings.newBuilder())); } catch (Throwable t) { throw toCanonical(t).underlying; } } return new CursorClientImpl(region(), serviceClient); } }
leapframework/framework
data/orm/src/main/java/leap/orm/event/EntityListenersBuilder.java
<reponame>leapframework/framework /* * Copyright 2017 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 leap.orm.event; import leap.core.annotation.Transactional; import leap.lang.Buildable; import java.util.*; public class EntityListenersBuilder implements Buildable<EntityListenersImpl> { protected final Map<PreCreateListener, Boolean> preCreateListeners = new LinkedHashMap<>(); protected final Map<PostCreateListener, Boolean> postCreateListeners = new LinkedHashMap<>(); protected final Map<PreUpdateListener, Boolean> preUpdateListeners = new LinkedHashMap<>(); protected final Map<PostUpdateListener, Boolean> postUpdateListeners = new LinkedHashMap<>(); protected final Map<PreDeleteListener, Boolean> preDeleteListeners = new LinkedHashMap<>(); protected final Map<PostDeleteListener, Boolean> postDeleteListeners = new LinkedHashMap<>(); protected final Set<PostLoadListener> postLoadListeners = new LinkedHashSet<>(); public EntityListenersBuilder addPreCreateListeners(PreCreateListener... listeners) { for(PreCreateListener listener : listeners) { addPreCreateListener(listener, listener.getClass().isAnnotationPresent(Transactional.class)); } return this; } public EntityListenersBuilder addPostCreateListeners(PostCreateListener... listeners) { for(PostCreateListener listener : listeners) { addPostCreateListener(listener, listener.getClass().isAnnotationPresent(Transactional.class)); } return this; } public EntityListenersBuilder addPreUpdateListeners(PreUpdateListener... listeners) { for(PreUpdateListener listener : listeners) { addPreUpdateListener(listener, listener.getClass().isAnnotationPresent(Transactional.class)); } return this; } public EntityListenersBuilder addPostUpdateListeners(PostUpdateListener... listeners) { for(PostUpdateListener listener : listeners) { addPostUpdateListener(listener, listener.getClass().isAnnotationPresent(Transactional.class)); } return this; } public EntityListenersBuilder addPreDeleteListeners(PreDeleteListener... listeners) { for(PreDeleteListener listener : listeners) { addPreDeleteListener(listener, listener.getClass().isAnnotationPresent(Transactional.class)); } return this; } public EntityListenersBuilder addPostDeleteListeners(PostDeleteListener... listeners) { for(PostDeleteListener listener : listeners) { addPostDeleteListener(listener, listener.getClass().isAnnotationPresent(Transactional.class)); } return this; } public EntityListenersBuilder addPostLoadListeners(PostLoadListener... listeners) { for(PostLoadListener listener : listeners) { addPostLoadListener(listener); } return this; } public EntityListenersBuilder addPreCreateListener(PreCreateListener listener, boolean transactional) { preCreateListeners.put(listener, transactional); return this; } public EntityListenersBuilder addPostCreateListener(PostCreateListener listener, boolean transactional) { postCreateListeners.put(listener, transactional); return this; } public EntityListenersBuilder addPreUpdateListener(PreUpdateListener listener, boolean transactional) { preUpdateListeners.put(listener, transactional); return this; } public EntityListenersBuilder addPostUpdateListener(PostUpdateListener listener, boolean transactional) { postUpdateListeners.put(listener, transactional); return this; } public EntityListenersBuilder addPreDeleteListener(PreDeleteListener listener, boolean transactional) { preDeleteListeners.put(listener, transactional); return this; } public EntityListenersBuilder addPostDeleteListener(PostDeleteListener listener, boolean transactional) { postDeleteListeners.put(listener, transactional); return this; } public EntityListenersBuilder addPostLoadListener(PostLoadListener listener) { postLoadListeners.add(listener); return this; } @Override public EntityListenersImpl build() { List<PreCreateListener> noTransPreCreateListeners = new ArrayList<>(); List<PreCreateListener> inTransPreCreateListeners = new ArrayList<>(); List<PostCreateListener> noTransPostCreateListeners = new ArrayList<>(); List<PostCreateListener> inTransPostCreateListeners = new ArrayList<>(); preCreateListeners.forEach((listener, trans) -> { if(trans) { inTransPreCreateListeners.add(listener); } else { noTransPreCreateListeners.add(listener); } }); postCreateListeners.forEach((listener, trans) -> { if(trans) { inTransPostCreateListeners.add(listener); } else { noTransPostCreateListeners.add(listener); } }); List<PreUpdateListener> noTransPreUpdateListeners = new ArrayList<>(); List<PreUpdateListener> inTransPreUpdateListeners = new ArrayList<>(); List<PostUpdateListener> noTransPostUpdateListeners = new ArrayList<>(); List<PostUpdateListener> inTransPostUpdateListeners = new ArrayList<>(); preUpdateListeners.forEach((listener, trans) -> { if(trans) { inTransPreUpdateListeners.add(listener); } else { noTransPreUpdateListeners.add(listener); } }); postUpdateListeners.forEach((listener, trans) -> { if(trans) { inTransPostUpdateListeners.add(listener); } else { noTransPostUpdateListeners.add(listener); } }); List<PreDeleteListener> noTransPreDeleteListeners = new ArrayList<>(); List<PreDeleteListener> inTransPreDeleteListeners = new ArrayList<>(); List<PostDeleteListener> noTransPostDeleteListeners = new ArrayList<>(); List<PostDeleteListener> inTransPostDeleteListeners = new ArrayList<>(); preDeleteListeners.forEach((listener, trans) -> { if(trans) { inTransPreDeleteListeners.add(listener); } else { noTransPreDeleteListeners.add(listener); } }); postDeleteListeners.forEach((listener, trans) -> { if(trans) { inTransPostDeleteListeners.add(listener); } else { noTransPostDeleteListeners.add(listener); } }); return new EntityListenersImpl(noTransPreCreateListeners.toArray(new PreCreateListener[0]), inTransPreCreateListeners.toArray(new PreCreateListener[0]), noTransPostCreateListeners.toArray(new PostCreateListener[0]), inTransPostCreateListeners.toArray(new PostCreateListener[0]), noTransPreUpdateListeners.toArray(new PreUpdateListener[0]), inTransPreUpdateListeners.toArray(new PreUpdateListener[0]), noTransPostUpdateListeners.toArray(new PostUpdateListener[0]), inTransPostUpdateListeners.toArray(new PostUpdateListener[0]), noTransPreDeleteListeners.toArray(new PreDeleteListener[0]), inTransPreDeleteListeners.toArray(new PreDeleteListener[0]), noTransPostDeleteListeners.toArray(new PostDeleteListener[0]), inTransPostDeleteListeners.toArray(new PostDeleteListener[0]), postLoadListeners.toArray(new PostLoadListener[0])); } }
GorgonMeducer/pikascript
bsp/cm32m101A/Firmware/cm32m101a_std_periph_driver/src/misc.c
/* ****************************************************************************** * * COPYRIGHT(c) 2020, China Mobile IOT * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of China Mobile IOT nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /** * @file misc.c * @author CMIOT * @version v1.0.0 * * @COPYRIGHT(c) 2020, China Mobile IOT. All rights reserved. */ #include "misc.h" /** @addtogroup cm32m101a_StdPeriph_Driver * @{ */ /** @addtogroup MISC * @brief MISC driver modules * @{ */ /** @addtogroup MISC_Private_TypesDefinitions * @{ */ /** * @} */ /** @addtogroup MISC_Private_Defines * @{ */ #define AIRCR_VECTKEY_MASK ((uint32_t)0x05FA0000) /** * @} */ /** @addtogroup MISC_Private_Macros * @{ */ /** * @} */ /** @addtogroup MISC_Private_Variables * @{ */ /** * @} */ /** @addtogroup MISC_Private_FunctionPrototypes * @{ */ /** * @} */ /** @addtogroup MISC_Private_Functions * @{ */ /** * @brief Configures the priority grouping: pre-emption priority and subpriority. * @param NVIC_PriorityGroup specifies the priority grouping bits length. * This parameter can be one of the following values: * @arg NVIC_PriorityGroup_0 0 bits for pre-emption priority * 4 bits for subpriority * @arg NVIC_PriorityGroup_1 1 bits for pre-emption priority * 3 bits for subpriority * @arg NVIC_PriorityGroup_2 2 bits for pre-emption priority * 2 bits for subpriority * @arg NVIC_PriorityGroup_3 3 bits for pre-emption priority * 1 bits for subpriority * @arg NVIC_PriorityGroup_4 4 bits for pre-emption priority * 0 bits for subpriority */ void NVIC_PriorityGroupConfig(uint32_t NVIC_PriorityGroup) { /* Check the parameters */ assert_param(IS_NVIC_PRIORITY_GROUP(NVIC_PriorityGroup)); /* Set the PRIGROUP[10:8] bits according to NVIC_PriorityGroup value */ SCB->AIRCR = AIRCR_VECTKEY_MASK | NVIC_PriorityGroup; } /** * @brief Initializes the NVIC peripheral according to the specified * parameters in the NVIC_InitStruct. * @param NVIC_InitStruct pointer to a NVIC_InitType structure that contains * the configuration information for the specified NVIC peripheral. */ void NVIC_Init(NVIC_InitType* NVIC_InitStruct) { uint32_t tmppriority = 0x00, tmppre = 0x00, tmpsub = 0x0F; /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(NVIC_InitStruct->NVIC_IRQChannelCmd)); assert_param(IS_NVIC_PREEMPTION_PRIORITY(NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority)); assert_param(IS_NVIC_SUB_PRIORITY(NVIC_InitStruct->NVIC_IRQChannelSubPriority)); if (NVIC_InitStruct->NVIC_IRQChannelCmd != DISABLE) { /* Compute the Corresponding IRQ Priority --------------------------------*/ tmppriority = (0x700 - ((SCB->AIRCR) & (uint32_t)0x700)) >> 0x08; tmppre = (0x4 - tmppriority); tmpsub = tmpsub >> tmppriority; tmppriority = (uint32_t)NVIC_InitStruct->NVIC_IRQChannelPreemptionPriority << tmppre; tmppriority |= NVIC_InitStruct->NVIC_IRQChannelSubPriority & tmpsub; tmppriority = tmppriority << 0x04; NVIC->IP[NVIC_InitStruct->NVIC_IRQChannel] = tmppriority; /* Enable the Selected IRQ Channels --------------------------------------*/ NVIC->ISER[NVIC_InitStruct->NVIC_IRQChannel >> 0x05] = (uint32_t)0x01 << (NVIC_InitStruct->NVIC_IRQChannel & (uint8_t)0x1F); } else { /* Disable the Selected IRQ Channels -------------------------------------*/ NVIC->ICER[NVIC_InitStruct->NVIC_IRQChannel >> 0x05] = (uint32_t)0x01 << (NVIC_InitStruct->NVIC_IRQChannel & (uint8_t)0x1F); } } /** * @brief Sets the vector table location and Offset. * @param NVIC_VectTab specifies if the vector table is in RAM or FLASH memory. * This parameter can be one of the following values: * @arg NVIC_VectTab_RAM * @arg NVIC_VectTab_FLASH * @param Offset Vector Table base offset field. This value must be a multiple * of 0x200. */ void NVIC_SetVectorTable(uint32_t NVIC_VectTab, uint32_t Offset) { /* Check the parameters */ assert_param(IS_NVIC_VECTTAB(NVIC_VectTab)); assert_param(IS_NVIC_OFFSET(Offset)); SCB->VTOR = NVIC_VectTab | (Offset & (uint32_t)0x1FFFFF80); } /** * @brief Selects the condition for the system to enter low power mode. * @param LowPowerMode Specifies the new mode for the system to enter low power mode. * This parameter can be one of the following values: * @arg NVIC_LP_SEVONPEND * @arg NVIC_LP_SLEEPDEEP * @arg NVIC_LP_SLEEPONEXIT * @param Cmd new state of LP condition. This parameter can be: ENABLE or DISABLE. */ void NVIC_SystemLPConfig(uint8_t LowPowerMode, FunctionalState Cmd) { /* Check the parameters */ assert_param(IS_NVIC_LP(LowPowerMode)); assert_param(IS_FUNCTIONAL_STATE(Cmd)); if (Cmd != DISABLE) { SCB->SCR |= LowPowerMode; } else { SCB->SCR &= (uint32_t)(~(uint32_t)LowPowerMode); } } /** * @brief Configures the SysTick clock source. * @param SysTick_CLKSource specifies the SysTick clock source. * This parameter can be one of the following values: * @arg SysTick_CLKSource_HCLK_Div8 AHB clock divided by 8 selected as SysTick clock source. * @arg SysTick_CLKSource_HCLK AHB clock selected as SysTick clock source. */ void SysTick_CLKSourceConfig(uint32_t SysTick_CLKSource) { /* Check the parameters */ assert_param(IS_SYSTICK_CLK_SOURCE(SysTick_CLKSource)); if (SysTick_CLKSource == SysTick_CLKSource_HCLK) { SysTick->CTRL |= SysTick_CLKSource_HCLK; } else { SysTick->CTRL &= SysTick_CLKSource_HCLK_Div8; } } #if (__MPU_PRESENT == 1) /** * @brief Enable the MPU. * @param MPU_Control: Specifies the control mode of the MPU during hard fault, * NMI, FAULTMASK and privileged accessto the default memory * This parameter can be one of the following values: * @arg MPU_HFNMI_PRIVDEF_NONE * @arg MPU_HARDFAULT_NMI * @arg MPU_PRIVILEGED_DEFAULT * @arg MPU_HFNMI_PRIVDEF * @retval None */ void MPU_Enable(uint32_t MPU_Control) { /* Ensure MPU setting take effects */ __DSB(); __ISB(); /* Enable the MPU */ MPU->CTRL = (MPU_Control | MPU_CTRL_ENABLE_Msk); #ifdef SCB_SHCSR_MEMFAULTENA_Msk SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk; #endif } /** * @brief Disable the MPU. * @retval None */ void MPU_Disable(void) { __DSB(); __ISB(); #ifdef SCB_SHCSR_MEMFAULTENA_Msk SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk; #endif MPU->CTRL &= ~MPU_CTRL_ENABLE_Msk; } /** * @brief Initialize and configure the Region and the memory to be protected. * @param MPU_Init: Pointer to a MPU_Region_InitTypeDef structure that contains * the initialization and configuration information. * @retval None */ void MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) { /* Check the parameters */ assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number)); assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable)); /* Set the Region number */ MPU->RNR = MPU_Init->Number; if ((MPU_Init->Enable) != RESET) { /* Check the parameters */ assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec)); assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission)); assert_param(IS_MPU_TEX_LEVEL(MPU_Init->TypeExtField)); assert_param(IS_MPU_ACCESS_SHAREABLE(MPU_Init->IsShareable)); assert_param(IS_MPU_ACCESS_CACHEABLE(MPU_Init->IsCacheable)); assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable)); assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable)); assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size)); MPU->RBAR = MPU_Init->BaseAddress; MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos); } else { MPU->RBAR = 0x00; MPU->RASR = 0x00; } } #endif /* __MPU_PRESENT */ /** * @} */ /** * @} */ /** * @} */
yhexie/mrpt
libs/obs/src/CObservationRobotPose.cpp
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "obs-precomp.h" // Precompiled headers #include <mrpt/utils/CStream.h> #include <mrpt/obs/CObservationRobotPose.h> #include <mrpt/system/os.h> #include <mrpt/math/matrix_serialization.h> using namespace mrpt::obs; using namespace mrpt::utils; using namespace mrpt::poses; // This must be added to any CSerializable class implementation file. IMPLEMENTS_SERIALIZABLE(CObservationRobotPose, CObservation,mrpt::obs) /** Default constructor */ CObservationRobotPose::CObservationRobotPose( ) { } /*--------------------------------------------------------------- Implements the writing to a CStream capability of CSerializable objects ---------------------------------------------------------------*/ void CObservationRobotPose::writeToStream(mrpt::utils::CStream &out, int *version) const { if (version) *version = 0; else { out << pose; out << sensorLabel << timestamp; } } /*--------------------------------------------------------------- Implements the reading from a CStream capability of CSerializable objects ---------------------------------------------------------------*/ void CObservationRobotPose::readFromStream(mrpt::utils::CStream &in, int version) { switch(version) { case 0: { in >> pose; in >> sensorLabel >> timestamp; } break; default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version) }; } void CObservationRobotPose::getSensorPose( CPose3D &out_sensorPose ) const { out_sensorPose = sensorPose; } void CObservationRobotPose::setSensorPose( const CPose3D &newSensorPose ) { sensorPose = newSensorPose; } void CObservationRobotPose::getDescriptionAsText(std::ostream &o) const { using namespace std; CObservation::getDescriptionAsText(o); o << "Sensor pose: " << sensorPose << endl; o << "Pose: " << pose.asString() << endl; }
Fenex/KTS
userjs/BigTextArea.user.js
// ==UserScript== // @name klavogonki: BigTextarea // @namespace klavogonki // @include http://klavogonki.ru/forum* // @author Fenex // @version 1.1 KTS // @icon http://www.gravatar.com/avatar.php?gravatar_id=d9c74d6be48e0163e9e45b54da0b561c&r=PG&s=48&default=identicon // ==/UserScript== //edit width and height of textBox if(!document.getElementById('KTS_BigTextArea')) { var brain = ''; var fnx_rows = '15'; var fnx_cols = '125'; var textareas = document.getElementsByTagName('textarea'); for (i=0;i<textareas.length;i++) { textareas[i].rows = fnx_rows; textareas[i].cols = fnx_cols; } //add function of clear textarea. if (document.getElementById('write-block')){ var fnx_s = document.createElement('script'); fnx_s.innerHTML = 'function fnx_btn_clear(){if (document.getElementById("fast-reply_textarea").value == ""){document.getElementById("fast-reply_textarea").value = brain;}else{brain = document.getElementById("fast-reply_textarea").value;document.getElementById("fast-reply_textarea").value = "";}};function fnx_btn_cancel(){document.getElementById("write-link").style.display="";document.getElementById("write-block").style.display="none";}'; document.body.appendChild(fnx_s); //add button "Cancel" and "Clear" var div_space = document.createElement('span'); div_space.innerHTML = ' <input type="button" value="Стереть" onClick="fnx_btn_clear()"> <input type="button" value="Отмена" onClick="fnx_btn_cancel()">'; var sfb = document.getElementById('write-block').getElementsByTagName('p')[0].getElementsByTagName('input')[0]; sfb.parentNode.insertBefore(div_space, sfb.nextSibling.nextSibling.nextSibling);} var tmp_elem = document.createElement('div'); tmp_elem.id = 'KTS_BigTextArea'; tmp_elem.style.display = 'none'; document.body.appendChild(tmp_elem); }
AndreiKononov/ui-orders
src/settings/OrderTemplates/OrderTemplatesEditor/PurchaseOrderNotesForm/PurchaseOrderNotesForm.js
import React from 'react'; import { Row, Col, } from '@folio/stripes/components'; import { FieldsNotes, } from '../../../../common/POFields'; const PurchaseOrderNotesForm = () => { return ( <Row start="xs"> <Col xs={12}> <FieldsNotes /> </Col> </Row> ); }; export default PurchaseOrderNotesForm;
yb4/parking_lot_management_software
src/structures/Student.java
package structures; import components.misc.DatabaseBridge; import components.misc.DatabaseVerifier; import java.sql.Date; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; /** * Created by Sudarshan on 3/22/2016. */ public class Student implements Comparable{ public static final String STUDENT_EXPORT_HEADER = "Last Name, First Name, Student ID, Grade, " + "Car Make, Car Model, Car Color, Car Year, License Plate Number, " + "Sticker Number, Insurance Expiry Date, Student Spot Number, Student Spot Zone, Paint Field (if applicable)"; private String firstName; private String lastName; private String studentID; private int grade; private String carMake; private String carModel; private String carColor; private String carYear; private String licensePlateNumber; private String stickerNumber; private PaintField paintField; private Date insuranceExpiryDate; // private boolean isInRoom=false; // private boolean isWaiting=false; // private boolean isApproved=false; public Student(String lastName, String firstName, String studentID, int grade, String carMake, String carModel, String carColor, String carYear, String licensePlateNumber, String stickerNumber, Date insuranceExpiryDate, PaintField paintField) { this.lastName = lastName; this.firstName = firstName; this.studentID = studentID; this.grade = grade; this.carMake = carMake; this.carModel = carModel; this.carColor = carColor; this.carYear = carYear; this.licensePlateNumber = licensePlateNumber; this.stickerNumber = stickerNumber; this.paintField = paintField; this.insuranceExpiryDate = insuranceExpiryDate; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getStudentID() { return studentID; } public int getGrade() { return grade; } public String getCarMake() { return carMake; } public String getCarModel() { return carModel; } public String getCarColor() { return carColor; } public String getCarYear() { return carYear; } public String getLicensePlateNumber() { return licensePlateNumber; } public String getStickerNumber() { return stickerNumber; } public PaintField getPaintField() { return paintField; } public Date getInsuranceExpiryDate() { return insuranceExpiryDate; } public String getInsuranceExpiryDay (){ if(insuranceExpiryDate == null) return ""; DateFormat dateFormat = new SimpleDateFormat("dd"); return dateFormat.format(insuranceExpiryDate); } public String getInsuranceExpiryMonth(){ if(insuranceExpiryDate == null) return ""; DateFormat dateFormat = new SimpleDateFormat("MM"); return dateFormat.format(insuranceExpiryDate); } public String getInsuranceExpiryYear(){ if(insuranceExpiryDate == null) return ""; DateFormat dateFormat = new SimpleDateFormat("YYYY"); return dateFormat.format(insuranceExpiryDate); } public String getStudentStatus(){ try { if (DatabaseVerifier.checkIfStudentApproved(DatabaseBridge.CONNECTION, studentID)) return "The Student is Approved"; if (DatabaseVerifier.checkIfStudentWaiting(DatabaseBridge.CONNECTION, studentID)) return "The Student is Waiting for Approval"; if (DatabaseVerifier.checkIfStudentInRoom(DatabaseBridge.CONNECTION, studentID)) return "The Student has Checked In"; } catch (SQLException e){ e.printStackTrace(); } return "The Student has not started the process"; } @Override public String toString(){ return lastName+", "+firstName+" ["+studentID+"]"; } @Override public int compareTo(Object o) { if(o instanceof Student) { Student compared = (Student) (o); return lastName.compareTo(compared.getLastName()); } else return 0; } public String getExportString() throws SQLException { String date = ""; if(insuranceExpiryDate != null) { DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); date = df.format(insuranceExpiryDate); } String toReturn = ""; toReturn += lastName + ","; toReturn += firstName + ","; toReturn += studentID + ","; toReturn += grade + ","; toReturn += carMake + ","; toReturn += carModel + ","; toReturn += carColor + ","; toReturn += carYear + ","; toReturn += licensePlateNumber + ","; toReturn += stickerNumber + ","; toReturn += date + ","; if(DatabaseVerifier.getStudentSpotNumber(DatabaseBridge.CONNECTION, studentID) > 0) { toReturn += DatabaseVerifier.getStudentSpotNumber(DatabaseBridge.CONNECTION, studentID) + ","; toReturn += DatabaseVerifier.convertSpotToZone(DatabaseVerifier.getStudentSpotNumber(DatabaseBridge.CONNECTION, studentID))+ ","; }else toReturn += ",,"; toReturn += paintField; return toReturn; } }
MingfeiPan/leetcode
tree/98.cc
<filename>tree/98.cc /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { if (!root) return true; std::stack<TreeNode*> s; bool init = false; int pre = 0; while (true) { while (root) { s.emplace(root); root = root->left; } if (s.empty()) break; root = s.top(); s.pop(); if (!init) { pre = root->val; init = true; } else { if (pre >= root->val) { return false; } pre = root->val; } root = root->right; } return true; } };
dimitri-dev/CodeWars
0047 - Sum The Tree/solution.cpp
<gh_stars>0 int sumTheTreeValues(node* root) { if (root == nullptr) return 0; int sum = root->value; if (root->left != nullptr) sum += sumTheTreeValues(root->left); if (root->right != nullptr) sum += sumTheTreeValues(root->right); return sum; }
nuagenetworks/nuage-tempest-plugin
nuage_tempest_plugin/tests/api/test_vpnaas.py
<filename>nuage_tempest_plugin/tests/api/test_vpnaas.py<gh_stars>1-10 import netaddr from tempest.lib.common.utils import data_utils from testtools.matchers import Contains from testtools.matchers import Not from nuage_tempest_plugin.lib.test import nuage_test from nuage_tempest_plugin.lib.topology import Topology from nuage_tempest_plugin.lib.utils.data_utils import nextitem from nuage_tempest_plugin.services.vpnaas.vpnaas_mixins import VPNMixin CONF = Topology.get_conf() LOG = Topology.get_logger(__name__) class VPNaaSBase(VPNMixin): def_net_partition = Topology.def_netpartition @classmethod def skip_checks(cls): raise cls.skipException('VPNaaS is no longer supported with Nuage.') class VPNaaSTest(VPNaaSBase): def _find_dummy_router(self, router_id): """_find_dummy_router Given the router ID for vpnservice find dummy router created by plugin. """ routers = self.routers_client.list_routers() routers = routers['routers'] dummy_router_name = 'r_d_' + router_id dummy_router = ( nextitem(router for router in routers if router['name'] == dummy_router_name) ) return dummy_router def _find_dummy_subnet(self, subnet_id): """_find_dummy_subnet Given the subnet ID for vpnservice find dummy subnet created by plugin. """ subnets = self.subnets_client.list_subnets() subnets = subnets['subnets'] dummy_subnet_name = 's_d_' + subnet_id dummy_subnet = ( nextitem(subnet for subnet in subnets if subnet['name'] == dummy_subnet_name) ) return dummy_subnet def test_ikepolicy_create_delete(self): """Create delete ikepolicy """ ikepolicies = self.ikepolicy_client.list_ikepolicy() pre_ids = [ikepolicy['id'] for ikepolicy in ikepolicies] with self.ikepolicy('ikepolicy') as created_ikepolicy: ikepolicies = self.ikepolicy_client.list_ikepolicy() post_ids = [ikepolicy['id'] for ikepolicy in ikepolicies] self.assertThat(pre_ids, Not(Contains(created_ikepolicy['id']))) self.assertThat(post_ids, Contains(created_ikepolicy['id'])) def test_ipsecpolicy_create_delete(self): """Create delete ipsecpolicy """ ipsecpolicies = self.ipsecpolicy_client.list_ipsecpolicy() pre_ids = [ipsecpolicy['id'] for ipsecpolicy in ipsecpolicies] with self.ipsecpolicy('ipsecpolicy') as created_ipsecpolicy: ipsecpolicies = self.ipsecpolicy_client.list_ipsecpolicy() post_ids = [ipsecpolicy['id'] for ipsecpolicy in ipsecpolicies] self.assertThat(pre_ids, Not(Contains(created_ipsecpolicy['id']))) self.assertThat(post_ids, Contains(created_ipsecpolicy['id'])) def test_vpnservice_create_delete(self): """test_vpnservice_create_delete Create delete vpnservice with environment. Also verifies the dummy router and subnet created by plugin. """ vpnservices = self.vpnservice_client.list_vpnservice() pre_ids = [vpnservice['id'] for vpnservice in vpnservices] routers = self.routers_client.list_routers() subnets = self.subnets_client.list_subnets() router_id = routers['routers'][0]['id'] subnet_id = subnets['subnets'][0]['id'] kwargs = {'name': 'vpnservice'} # Creating the vpn service with self.vpnservice(router_id, subnet_id, **kwargs) as created_vpnservice: vpnservices = self.vpnservice_client.list_vpnservice() # Finding the dummy router and subnet # dummy_router = self._find_dummy_router(router_id) # dummy_subnet = self._find_dummy_subnet(subnet_id) # passed to os_data ... post_ids = [vpnservice['id'] for vpnservice in vpnservices] self.assertThat(pre_ids, Not(Contains(created_vpnservice['id']))) self.assertThat(post_ids, Contains(created_vpnservice['id'])) # VSD verification # tag_name = 'verify_vpn_dummy_router' # nuage_ext.nuage_extension.nuage_components( # nuage_ext._generate_tag(tag_name, self.__class__.__name__), # self) def test_ipsecsiteconnection_create_delete(self): """test_ipsecsiteconnection_create_delete Create delete of ipsecsiteconnection using ikepolicy, ipsecpolicy and vpnservice. Also verifies the dummy router and subnet and the vm interface created by plugin. """ ipsecsiteconnections = ( self.ipsecsiteconnection_client.list_ipsecsiteconnection() ) pre_ids = ( [ipsecsiteconnection['id'] for ipsecsiteconnection in ipsecsiteconnections] ) routers = self.routers_client.list_routers() subnets = self.subnets_client.list_subnets() router_id = routers['routers'][0]['id'] subnet_id = subnets['subnets'][0]['id'] kwargs = {'name': 'vpn'} with self.vpnservice(router_id, subnet_id, **kwargs) \ as created_vpnservice, \ self.ikepolicy('ikepolicy') as created_ikepolicy, \ self.ipsecpolicy('ipsecpolicy') as created_ipsecpolicy: vpnservices = self.vpnservice_client.list_vpnservice() # Finding the dummy router and subnet # created by plugin and adding to the os_data_struct # dummy_router = self._find_dummy_router(router_id) # dummy_subnet = self._find_dummy_subnet(subnet_id) post_ids = [vpnservice['id'] for vpnservice in vpnservices] self.assertThat(pre_ids, Not(Contains(created_vpnservice['id']))) self.assertThat(post_ids, Contains(created_vpnservice['id'])) # VSD verification # tag_name = 'verify_vpn_dummy_router' # nuage_ext.nuage_extension.nuage_components( # nuage_ext._generate_tag(tag_name, self.__class__.__name__), # self) ipnkwargs = {'name': 'ipsecconn'} with self.ipsecsiteconnection( created_vpnservice['id'], created_ikepolicy['id'], created_ipsecpolicy['id'], '172.20.0.2', '172.20.0.2', '2.0.0.0/24', 'secret', **ipnkwargs) as created_ipsecsiteconnection: ipsecsiteconnections = ( self.ipsecsiteconnection_client.list_ipsecsiteconnection() ) post_ids = ( [ipsecsiteconnection['id'] for ipsecsiteconnection in ipsecsiteconnections] ) self.assertThat(pre_ids, Not( Contains(created_ipsecsiteconnection['id']))) self.assertThat(post_ids, Contains( created_ipsecsiteconnection['id'])) # VSD Verification # tag_name = 'verify_ipsec_vminterface' # nuage_ext.nuage_extension.nuage_components( # nuage_ext._generate_tag( # tag_name, self.__class__.__name__), self) class VPNaaSCliTests(VPNaaSBase): @staticmethod def _verify_resource_list(resource, resource_dict, present): """Verify the resources created from list of resources """ resource_list = [resources['id'] for resources in resource_dict] if present: if resource in resource_list: LOG.debug('Found %s', resource) return True else: LOG.debug('ERROR: Not Found %s', resource) return False else: if resource in resource_list: LOG.debug('ERROR: Found %s', resource) return False else: LOG.debug('Not Found %s', resource) return True def _create_verify_ikepolicy(self, name): """Creates and verifies ikepolicy in neutron DB """ name = data_utils.rand_name(name) # Creating a IKE Policy ikepolicy = self.vpnservice_client.create_ikepolicy(name) # Showing the created IKE Policy ikepolicy_info = self.vpnservice_client.show_ikepolicy(name) self.assertEqual(ikepolicy_info['name'], name) return ikepolicy['ikepolicy'] def _delete_verify_ikepolicy(self, id, name): """Deletes and verifies ikepolicy in neutron DB """ # Deleting the IKE Policy self.vpnservice_client.delete_ikepolicy(id) # Verifying delete in list IKE Policy ikepolicies = self.vpnservice_client.list_ikepolicy() result = self._verify_resource_list(id, ikepolicies, False) self.assertEqual(result, True) def _create_verify_ipsecpolicy(self, name): """Creates and verifies ipsecpolicy in neutron DB """ name = data_utils.rand_name(name) # Creating a IPSecPolicy ipsecpolicy = self.vpnservice_client.create_ipsecpolicy(name) # Showing the created IPSecPolicy ipsecpolicy_info = self.vpnservice_client.show_ipsecpolicy(name) self.assertEqual(ipsecpolicy_info['name'], name) return ipsecpolicy['ipsecpolicy'] def _delete_verify_ipsecpolicy(self, id, name): """Deletes and verifies ipsecpolicy in neutron DB """ # Deleting the IPSecPolicy self.vpnservice_client.delete_ipsecpolicy(id) # Verifying delete in list IPSecPolicy ipsecpolicies = self.vpnservice_client.list_ipsecpolicy() result = self._verify_resource_list(id, ipsecpolicies, False) self.assertEqual(result, True) def _create_verify_vpn_environment(self, name, cidr, public): """Creates router and subnet for vpn service """ # Creating Network netname = name + '-network-' netname = data_utils.rand_name(netname) network = self.create_network(network_name=netname) # Creating Subnet mask_bit = int(cidr.split("/")[1]) gateway_ip = cidr.split("/")[0][:cidr.rfind(".")] + ".1" cidr = netaddr.IPNetwork(cidr) subkwargs = {'name': netname} subnet = ( self.subnets_client.create_subnet( network, gateway=gateway_ip, cidr=cidr, mask_bits=mask_bit, **subkwargs ) ) # Creating router routername = name + '-router-' routername = data_utils.rand_name(routername) router = self.routers_client.create_router(router_name=routername) self.routers_client.add_router_interface( router['id'], subnet['id'] ) self.routers_client.set_router_gateway_with_args( router['id'], public['network']['id'] ) # publicsub = ( # self.subnets_client.show_subnet( # public['network']['subnets']) # ) return subnet, router def _delete_verify_vpn_environment(self, router, subnet): """Deleting and verifying the router and subnet""" # Deleting from neutron DB self.routers_client.delete_router( router['id']) self.networks_client.delete_network( subnet['network_id']) def _create_verify_vpnservice(self, name, router, subnet): """Creating and verifying the vpnservice""" name = name + '-vpnservice-' name = data_utils.rand_name(name) # Creating a VPNService vpnservice = ( self.vpnaas_client.create_vpnservice( router['id'], subnet['id'], name ) ) # Showing the created VPNService vpnservice_info = self.vpnservice_client.show_vpnservice( vpnservice['vpnservice']['id']) self.assertEqual(vpnservice_info['name'], name) # Verifying that the dummy router and subnet is created dummy_router, dummy_subnet = ( self._verify_vpnaas_dummy_router( router, subnet, vpnservice['vpnservice']) ) return vpnservice['vpnservice'], dummy_router, dummy_subnet def _verify_vpnaas_dummy_router(self, router, subnet, vpnservice): """Verifies the dummy router created by vpnservice """ # Creating Dummy Router and subnet name dummy_router_name = 'r_d_' + router['id'] dummy_subnet_name = 's_d_' + subnet['id'] # Searching for dummy router in neutron dummy_router_info = ( self.routers_client.show_router(dummy_router_name) ) dummy_router_info = dummy_router_info['router'] self.assertEqual(dummy_router_info['name'], dummy_router_name) # Searching for dummy subnet in neutron dummy_subnet_info = ( self.subnets_client.show_subnet(dummy_subnet_name) ) dummy_subnet_info = dummy_subnet_info['subnet'] self.assertEqual(dummy_subnet_info['name'], dummy_subnet_name) return dummy_router_info, dummy_subnet_info def _delete_verify_vpnservice(self, id, name): """Deletes and verifies the vpnservice """ # Deleting the VPNService self.vpnservice_client.delete_vpnservice(id) # Verifying delete in list VPNService vpnservices = self.vpnservice_client.list_vpnservice() result = self._verify_resource_list(id, vpnservices, False) self.assertEqual(result, True) def _create_verify_ipsecsiteconnection(self, vpnservice_id, ikepolicy_id, ipsecpolicy_id, peer_address, peer_id, peer_cidrs, psk, name, parent): """Creates and verifies the ipsecsiteconnection """ name = name + '-ipsecsiteconnection-' name = data_utils.rand_name(name) # Creating a IPSecSiteConnection ipsecsiteconnection = ( self.vpnservice_client.create_ipsecsiteconnection( vpnservice_id, ikepolicy_id, ipsecpolicy_id, peer_address, peer_id, peer_cidrs, psk, name ) ) # Showing the created IPSecSiteConnection ipsecsiteconnection_info = ( self.vpnservice_client.show_ipsecsiteconnection( ipsecsiteconnection['ipsecsiteconnection']['id'] ) ) self.assertEqual(ipsecsiteconnection_info['name'], name) return ipsecsiteconnection['ipsecsiteconnection'] def _delete_verify_ipsecsiteconnection(self, id, name): """Deletes and verifies the ipsecsiteconnection """ # Deleting the VPNService self.vpnservice_client.delete_ipsecsiteconnection(id) # Verifying delete in list VPNService ipsecsiteconnections = ( self.vpnservice_client.list_ipsecsiteconnection() ) result = self._verify_resource_list(id, ipsecsiteconnections, False) self.assertEqual(result, True) @nuage_test.header() def test_create_delete_ikepolicy(self): """TestCase to create/show/list/delete ikepolicy """ # Create Verify ikepolicy = self._create_verify_ikepolicy('ikepolicy') ikepolicy_id = ikepolicy['id'] ikepolicy_name = ikepolicy['name'] # Delete Verify self._delete_verify_ikepolicy( ikepolicy_id, ikepolicy_name ) def test_create_delete_ipsecpolicy(self): """TestCase to create/show/list/delete ipsecpolicy """ # Create Verify ipsecpolicy = self._create_verify_ipsecpolicy('ipsecpolicy') ipsecpolicy_id = ipsecpolicy['id'] ipsecpolicy_name = ipsecpolicy['name'] # Delete Verify self._delete_verify_ipsecpolicy( ipsecpolicy_id, ipsecpolicy_name ) def test_create_delete_vpnservice(self): """TestCase to create/show/list/delete vpnservice """ name = 'vpn' pubnetid = CONF.network.public_network_id pubnet = self.networks_client.show_network(pubnetid) # Creating Site for VPN Service subnet, router = ( self._create_verify_vpn_environment( name, '10.20.0.0/24', pubnet ) ) # Create Verify VPNService vpnservice, dummy_router, dummy_subnet = ( self._create_verify_vpnservice( name, router, subnet ) ) # VSD Verification # tag_name = 'verify_vpn_dummy_router' # nuage_ext.nuage_extension.nuage_components( # nuage_ext._generate_tag(tag_name, self.__class__.__name__), self) # Delete Verify VPNService self._delete_verify_vpnservice( vpnservice['id'], vpnservice['name'], ) # Delete environment self._delete_verify_vpn_environment( router, subnet ) def test_create_duplicate_vpnservice(self): """Tests creation of duplicate vpnservice """ name = 'vpn' pubnetid = CONF.network.public_network_id pubnet = self.networks_client.show_network(pubnetid) # Creating Site for VPN Service subnet, router = ( self._create_verify_vpn_environment( name, '10.20.0.0/24', pubnet ) ) # Create First Verify VPNService vpnservice, dummy_router, dummy_subnet = ( self._create_verify_vpnservice( name, router, subnet ) ) # Create Duplicate VPNService self.vpnservice_client.create_vpnservice( router['id'], subnet['id'], name, positive=False) # tag_name = 'verify_vpn_dummy_router' # nuage_ext.nuage_extension.nuage_components( # nuage_ext._generate_tag(tag_name, self.__class__.__name__), self) # Delete Verify VPNService self._delete_verify_vpnservice( vpnservice['id'], vpnservice['name'] ) # Delete environment self._delete_verify_vpn_environment( router, subnet ) def test_create_delete_ipsecsiteconnection(self): """Tests create/show/list/delete of ipsecsiteconnection In two different vpnservices """ pubnetid = CONF.network.public_network_id pubnet = self.networks_client.show_network(pubnetid) # Creating Site1 name1 = 'vpn1' cidr1 = '10.20.0.0/24' subnet1, router1 = ( self._create_verify_vpn_environment( name1, cidr1, pubnet ) ) # Creating VPN1 vpnservice1, dummy_router1, dummy_subnet1 = ( self._create_verify_vpnservice( name1, router1, subnet1 ) ) # Creating Site2 name2 = 'vpn2' cidr2 = '10.30.0.0/24' subnet2, router2 = ( self._create_verify_vpn_environment( name2, cidr2, pubnet ) ) # Creating VPN2 vpnservice2, dummy_router2, dummy_subnet2 = ( self._create_verify_vpnservice( name2, router2, subnet2 ) ) # tag_name = 'verify_vpn_dummy_router' # nuage_ext.nuage_extension.nuage_components( # nuage_ext._generate_tag(tag_name, self.__class__.__name__), self) # Creating IKE Policy ikepolicy = self._create_verify_ikepolicy('ikepolicy') ikepolicy_id = ikepolicy['id'] ikepolicy_name = ikepolicy['name'] # Creating IPSecPolicy ipsecpolicy = self._create_verify_ipsecpolicy('ipsecpolicy') ipsecpolicy_id = ipsecpolicy['id'] ipsecpolicy_name = ipsecpolicy['name'] # Creating IPSecSiteConnection1 vpn_ip1 = vpnservice1['external_v4_ip'] ipsecsiteconnection1 = ( self._create_verify_ipsecsiteconnection( vpnservice1['id'], ikepolicy_id, ipsecpolicy_id, vpn_ip1, vpn_ip1, cidr1, 'secret', name1, vpnservice1['name'] ) ) # Creating IPSecSiteConnection2 vpn_ip2 = vpnservice2['external_v4_ip'] ipsecsiteconnection2 = ( self._create_verify_ipsecsiteconnection( vpnservice2['id'], ikepolicy_id, ipsecpolicy_id, vpn_ip2, vpn_ip2, cidr2, 'secret', name2, vpnservice2['name'] ) ) # tag_name = 'verify_ipsec_vminterface' # nuage_ext.nuage_extension.nuage_components( # nuage_ext._generate_tag(tag_name, self.__class__.__name__), self) # Delete IPSecSiteconnections self._delete_verify_ipsecsiteconnection( ipsecsiteconnection1['id'], ipsecsiteconnection1['name'] ) self._delete_verify_ipsecsiteconnection( ipsecsiteconnection2['id'], ipsecsiteconnection2['name'] ) # Delete VPNService self._delete_verify_vpnservice( vpnservice1['id'], vpnservice1['name'] ) self._delete_verify_vpnservice( vpnservice2['id'], vpnservice2['name'] ) # Delete IKEpolicy and IPSecPolicy self._delete_verify_ipsecpolicy( ipsecpolicy_id, ipsecpolicy_name ) self._delete_verify_ikepolicy( ikepolicy_id, ikepolicy_name ) # Delete Routers and Subnets self._delete_verify_vpn_environment( router1, subnet1 ) self._delete_verify_vpn_environment( router2, subnet2 )
TheFriendlyCoder/pyjen
tests/test_views/test_all_view.py
<reponame>TheFriendlyCoder/pyjen from pyjen.plugins.allview import AllView def test_find_view(jenkins_api): expected_name = "all" v = jenkins_api.find_view(expected_name) assert isinstance(v, AllView)
gammaker/Intra
Intra/Concurrency/detail/AtomicGNU.h
#pragma once #ifndef INTRA_LIBRARY_ATOMIC #define INTRA_LIBRARY_ATOMIC INTRA_LIBRARY_ATOMIC_GNU #endif #include "Cpp/Features.h" #include "Concurrency/Atomic.h" namespace Intra { namespace Concurrency { #define INTRA_ATOMIC_METHOD_GET(mo, MO) \ template<typename T> forceinline T AtomicBase<T>::Get ## mo() const noexcept \ {return __atomic_load_n(&mValue, __ATOMIC_ ## MO);} #define INTRA_ATOMIC_METHOD_SET(mo, MO) \ template<typename T> forceinline void AtomicBase<T>::Set ## mo(T val) noexcept \ {__atomic_store_n(&mValue, val, __ATOMIC_ ## MO);} #define INTRA_ATOMIC_METHOD_GET_SET(mo, MO) \ template<typename T> forceinline T AtomicBase<T>::GetSet ## mo(T val) noexcept \ {return __atomic_exchange_n(&mValue, val, __ATOMIC_ ## MO);} #define INTRA_ATOMIC_METHOD_CAS(method, MO, weak) \ template<typename T> forceinline bool AtomicBase<T>::method(T expected, T desired) noexcept \ {return __atomic_compare_exchange_n(&mValue, &expected, desired, weak, __ATOMIC_ ## MO, __ATOMIC_ ## MO);} #define INTRA_ATOMIC_METHOD_CAS2(method, MO, weak) \ template<typename T> forceinline bool AtomicBase<T>::method(T& expected, T desired) noexcept \ {return __atomic_compare_exchange_n(&mValue, &expected, desired, weak, __ATOMIC_ ## MO, __ATOMIC_ ## MO);} INTRA_ATOMIC_METHOD_GET(, SEQ_CST) INTRA_ATOMIC_METHOD_GET(Relaxed, RELAXED) INTRA_ATOMIC_METHOD_GET(Consume, CONSUME) INTRA_ATOMIC_METHOD_GET(Acquire, ACQUIRE) INTRA_ATOMIC_METHOD_SET(, SEQ_CST) INTRA_ATOMIC_METHOD_SET(Relaxed, RELAXED) INTRA_ATOMIC_METHOD_SET(Release, RELEASE) INTRA_ATOMIC_METHOD_GET_SET(, SEQ_CST) INTRA_ATOMIC_METHOD_GET_SET(Relaxed, RELAXED) INTRA_ATOMIC_METHOD_GET_SET(Consume, CONSUME) INTRA_ATOMIC_METHOD_GET_SET(Acquire, ACQUIRE) INTRA_ATOMIC_METHOD_GET_SET(Release, RELEASE) INTRA_ATOMIC_METHOD_GET_SET(AcquireRelease, ACQ_REL) INTRA_ATOMIC_METHOD_CAS(WeakCompareSet, SEQ_CST, true) INTRA_ATOMIC_METHOD_CAS(WeakCompareSetRelaxed, RELAXED, true) INTRA_ATOMIC_METHOD_CAS(WeakCompareSetConsume, CONSUME, true) INTRA_ATOMIC_METHOD_CAS(WeakCompareSetAcquire, ACQUIRE, true) INTRA_ATOMIC_METHOD_CAS(WeakCompareSetRelease, RELEASE, true) INTRA_ATOMIC_METHOD_CAS(WeakCompareSetAcquireRelease, ACQ_REL, true) INTRA_ATOMIC_METHOD_CAS2(WeakCompareGetSet, SEQ_CST, true) INTRA_ATOMIC_METHOD_CAS2(WeakCompareGetSetRelaxed, RELAXED, true) INTRA_ATOMIC_METHOD_CAS2(WeakCompareGetSetConsume, CONSUME, true) INTRA_ATOMIC_METHOD_CAS2(WeakCompareGetSetAcquire, ACQUIRE, true) INTRA_ATOMIC_METHOD_CAS2(WeakCompareGetSetRelease, RELEASE, true) INTRA_ATOMIC_METHOD_CAS2(WeakCompareGetSetAcquireRelease, ACQ_REL, true) INTRA_ATOMIC_METHOD_CAS(CompareSet, SEQ_CST, false) INTRA_ATOMIC_METHOD_CAS(CompareSetRelaxed, RELAXED, false) INTRA_ATOMIC_METHOD_CAS(CompareSetConsume, CONSUME, false) INTRA_ATOMIC_METHOD_CAS(CompareSetAcquire, ACQUIRE, false) INTRA_ATOMIC_METHOD_CAS(CompareSetRelease, RELEASE, false) INTRA_ATOMIC_METHOD_CAS(CompareSetAcquireRelease, ACQ_REL, false) INTRA_ATOMIC_METHOD_CAS2(CompareGetSet, SEQ_CST, false) INTRA_ATOMIC_METHOD_CAS2(CompareGetSetRelaxed, RELAXED, false) INTRA_ATOMIC_METHOD_CAS2(CompareGetSetConsume, CONSUME, false) INTRA_ATOMIC_METHOD_CAS2(CompareGetSetAcquire, ACQUIRE, false) INTRA_ATOMIC_METHOD_CAS2(CompareGetSetRelease, RELEASE, false) INTRA_ATOMIC_METHOD_CAS2(CompareGetSetAcquireRelease, ACQ_REL, false) #define INTRA_ATOMIC_METHOD_BINARY_ONE(method, stdmethod, mo, MO) \ template<typename T> forceinline T AtomicInteger<T>::method ## mo(T rhs) noexcept \ {return __atomic_ ## stdmethod(&this->mValue, rhs, __ATOMIC_ ## MO);} #define INTRA_ATOMIC_METHOD_BINARY(method, stdmethod) \ INTRA_ATOMIC_METHOD_BINARY_ONE(method, stdmethod, , SEQ_CST) \ INTRA_ATOMIC_METHOD_BINARY_ONE(method, stdmethod, Relaxed, RELAXED) \ INTRA_ATOMIC_METHOD_BINARY_ONE(method, stdmethod, Consume, CONSUME) \ INTRA_ATOMIC_METHOD_BINARY_ONE(method, stdmethod, Acquire, ACQUIRE) \ INTRA_ATOMIC_METHOD_BINARY_ONE(method, stdmethod, Release, RELEASE) \ INTRA_ATOMIC_METHOD_BINARY_ONE(method, stdmethod, AcquireRelease, ACQ_REL) INTRA_ATOMIC_METHOD_BINARY(GetAdd, fetch_add) INTRA_ATOMIC_METHOD_BINARY(GetSub, fetch_sub) INTRA_ATOMIC_METHOD_BINARY(GetAnd, fetch_and) INTRA_ATOMIC_METHOD_BINARY(GetOr, fetch_or) INTRA_ATOMIC_METHOD_BINARY(GetXor, fetch_xor) INTRA_ATOMIC_METHOD_BINARY(Add, add_fetch) INTRA_ATOMIC_METHOD_BINARY(Sub, sub_fetch) INTRA_ATOMIC_METHOD_BINARY(And, and_fetch) INTRA_ATOMIC_METHOD_BINARY(Or, or_fetch) INTRA_ATOMIC_METHOD_BINARY(Xor, xor_fetch) #define INTRA_ATOMIC_INCREMENT_DECREMENT(mo, a) \ template<typename T> forceinline T AtomicInteger<T>::Increment ## mo() noexcept {return Add ## mo a(1);}\ template<typename T> forceinline T AtomicInteger<T>::Decrement ## mo() noexcept {return Sub ## mo a(1);}\ template<typename T> forceinline T AtomicInteger<T>::GetIncrement ## mo() noexcept {return GetAdd ## mo a(1);}\ template<typename T> forceinline T AtomicInteger<T>::GetDecrement ## mo() noexcept {return GetSub ## mo a(1);} INTRA_ATOMIC_INCREMENT_DECREMENT(,) INTRA_ATOMIC_INCREMENT_DECREMENT(Relaxed,) INTRA_ATOMIC_INCREMENT_DECREMENT(Consume,) INTRA_ATOMIC_INCREMENT_DECREMENT(Acquire,) INTRA_ATOMIC_INCREMENT_DECREMENT(Release,) INTRA_ATOMIC_INCREMENT_DECREMENT(AcquireRelease,) #undef INTRA_ATOMIC_METHOD_GET #undef INTRA_ATOMIC_METHOD_SET #undef INTRA_ATOMIC_METHOD_GET_SET #undef INTRA_ATOMIC_METHOD_CAS #undef INTRA_ATOMIC_METHOD_BINARY_ONE #undef INTRA_ATOMIC_METHOD_BINARY #undef INTRA_ATOMIC_INCREMENT_DECREMENT }}
tradecraftio/tradecraft
src/qt/trafficgraphwidget.h
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2011-2021 The Freicoin Developers // // This program is free software: you can redistribute it and/or modify it under // the terms of version 3 of the GNU Affero General Public License as published // by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS // FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more // details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #ifndef FREICOIN_QT_TRAFFICGRAPHWIDGET_H #define FREICOIN_QT_TRAFFICGRAPHWIDGET_H #include <QWidget> #include <QQueue> class ClientModel; QT_BEGIN_NAMESPACE class QPaintEvent; class QTimer; QT_END_NAMESPACE class TrafficGraphWidget : public QWidget { Q_OBJECT public: explicit TrafficGraphWidget(QWidget *parent = nullptr); void setClientModel(ClientModel *model); int getGraphRangeMins() const; protected: void paintEvent(QPaintEvent *); public Q_SLOTS: void updateRates(); void setGraphRangeMins(int mins); void clear(); private: void paintPath(QPainterPath &path, QQueue<float> &samples); QTimer *timer; float fMax; int nMins; QQueue<float> vSamplesIn; QQueue<float> vSamplesOut; quint64 nLastBytesIn; quint64 nLastBytesOut; ClientModel *clientModel; }; #endif // FREICOIN_QT_TRAFFICGRAPHWIDGET_H
hailongz/golang
ss/main.go
package main import ( "fmt" "log" "net/http" "os" "os/signal" "strings" "syscall" "time" _ "github.com/go-sql-driver/mysql" "github.com/hailongz/golang/dynamic" "github.com/hailongz/golang/mq" _ "github.com/hailongz/golang/mq/ali" _ "github.com/hailongz/golang/mq/nsq" less "github.com/hailongz/golang/ss/app" _ "github.com/hailongz/golang/ss/base" _ "github.com/hailongz/golang/ss/crypto" _ "github.com/hailongz/golang/ss/db" _ "github.com/hailongz/golang/ss/geoip" _ "github.com/hailongz/golang/ss/influx" _ "github.com/hailongz/golang/ss/mq" _ "github.com/hailongz/golang/ss/redis" _ "github.com/hailongz/golang/ss/view" "github.com/hailongz/golang/stat" "github.com/hailongz/golang/svc" "github.com/hailongz/golang/text" ) func main() { app, err := less.NewAppWithEnv() if err != nil { log.Panicln(err) } dynamic.Each(dynamic.Get(app.GetConfig(), "fonts"), func(_ interface{}, p interface{}) bool { text.Load(dynamic.StringValue(p, "")) return true }) log.Println("[Font]", strings.Join(text.GetFamilys(), ",")) block := false { init := dynamic.Get(app.GetConfig(), "init") if init != nil { input := less.Input{ Path: "__init__", Data: init, } input.Trace = fmt.Sprintf("%d", app.NewID()) log.Printf("[%s] [INIT]\n", input.Trace) _, err := app.Exec("/main.js", &input) if err != nil { log.Printf("[%s] [__init__] [ERROR] %s\n", input.Trace, err) } else { log.Printf("[%s] [__init__] [OK]\n", input.Trace) } } } { cfg := dynamic.GetWithKeys(app.GetConfig(), []string{"mq", "consumer"}) if cfg != nil { stype := dynamic.StringValue(dynamic.Get(cfg, "type"), "") if stype != "" { q, err := mq.OpenConsumer(stype, cfg) if err != nil { log.Panicln(err) } defer q.Close() log.Println("[MQ]", dynamic.Get(cfg, "addr")) err = q.Open(func(name string, data interface{}) error { input := less.Input{ Path: name, Data: data, } input.Trace = fmt.Sprintf("%d", app.NewID()) log.Printf("[%s] [MQ] %s %s\n", input.Trace, name, data) _, err := app.Exec("/main.js", &input) if err != nil { log.Printf("[%s] [MQ] [ERROR] %s %s\n", input.Trace, name, err) return err } log.Printf("[%s] [MQ] [OK] %s\n", input.Trace, name) return nil }, int(dynamic.IntValue(dynamic.Get(cfg, "concurrency"), 1))) if err != nil { log.Panicln(err) } block = true } } } { collector := dynamic.Get(app.GetConfig(), "collector") if collector != nil { dynamic.Each(collector, func(key interface{}, value interface{}) bool { input := less.Input{ Path: dynamic.StringValue(dynamic.Get(value, "name"), ""), Data: dynamic.Get(value, "data"), } tv := dynamic.IntValue(dynamic.Get(value, "interval"), 6000) go func(input *less.Input, tv time.Duration) { t := time.NewTicker(tv) for { input.Trace = fmt.Sprintf("%d", app.NewID()) log.Printf("[%s] [COLLECTOR] %s %s\n", input.Trace, input.Path, input.Data) _, err := app.Exec("/main.js", input) if err != nil { log.Printf("[%s] [COLLECTOR] [ERROR] %s %s\n", input.Trace, input.Path, err) } else { log.Printf("[%s] [COLLECTOR] [OK] %s\n", input.Trace, input.Path) } <-t.C } }(&input, time.Duration(tv)*time.Millisecond) return true }) block = true } } if dynamic.Get(app.GetConfig(), "httpd") != nil { s := svc.New() address := dynamic.StringValue(dynamic.GetWithKeys(app.GetConfig(), []string{"httpd", "addr"}), ":80") http.HandleFunc("/__stat", stat.HandleFunc()) http.HandleFunc("/", less.HandleFunc(app, s)) log.Println("[HTTPD]", address) srv := &http.Server{ Addr: address, IdleTimeout: 6 * time.Second, } { go func() { ch := make(chan os.Signal, 1) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) log.Println("[SIGNAL]", <-ch) signal.Stop(ch) s.Done() log.Println("[SERVER] [DONE]") srv.Close() log.Println("[SERVER] [CLOSE]") }() } log.Println(srv.ListenAndServe()) } else if block { select {} } else { input := less.Input{ Path: "main.js", Data: os.Args, } _, err := app.Exec("/main.js", &input) if err != nil { log.Println(err) } } }
ahmadhassan7/COVID-19-Diagnoser
webapp/src/components/withSplashScreen.js
<gh_stars>1-10 import React, {Component} from 'react'; function LoadingMessage() { return ( <div className="ai-login__splashscreen"> <img src='logo.png' width="200px" height="200px"/> </div> ); } function withSplashScreen(WrappedComponent) { return class extends Component { constructor(props) { super(props); this.state = { loading: true, }; } async componentDidMount() { try { //await auth0Client.loadSession(); // here we should await login setTimeout(() => { this.setState({ loading: false, }); }, 1500) } catch (err) { console.log(err); this.setState({ loading: false, }); } } render() { // while checking user session, show "loading" message if (this.state.loading) return LoadingMessage(); // otherwise, show the desired route return <WrappedComponent {...this.props} />; } }; } export default withSplashScreen;
Rarioty/Parallax-Engine
tests/PIL/Collections/perfs_collection_stack.cpp
<gh_stars>1-10 #include <Parallax/Collections/Stack.hpp> #include <iostream> #include <iomanip> #include <chrono> #include <stack> using namespace Parallax; int main(int argc, char *argv[]) { std::chrono::duration<double> elapsedStd; std::chrono::duration<double> elapsedParallax; Collections::Stack<int>* stack; std::stack<int>* stdstack; U32 i; // Header std::cout << "| Test name | Nb elements | Std time | Parallax time |" << std::endl; std::cout << "|-------------+-------------+---------------+---------------|" << std::endl; /********************************************************************************************* * Push ********************************************************************************************/ stack = new Collections::Stack<int>(); stdstack = new std::stack<int>(); auto start = std::chrono::high_resolution_clock::now(); for (i = 0; i < 1000000; ++i) { stdstack->push(i); } auto finish = std::chrono::high_resolution_clock::now(); elapsedStd = finish - start; std::cout << "| push | 1 000 000 | " << std::setw(11) << std::setfill(' ') << elapsedStd.count() << " s | "; start = std::chrono::high_resolution_clock::now(); for (i = 0; i < 1000000; ++i) { stack->push(i); } finish = std::chrono::high_resolution_clock::now(); elapsedParallax = finish - start; // Printing values std::cout << std::setw(11) << std::setfill(' ') << elapsedParallax.count() << " s |" << std::endl; delete stack; delete stdstack; /********************************************************************************************* * Pop ********************************************************************************************/ stack = new Collections::Stack<int>(); stdstack = new std::stack<int>(); for (i = 0; i < 1000000; ++i) { stdstack->push(i); } start = std::chrono::high_resolution_clock::now(); for (i = 0; i < 1000000; ++i) { stdstack->pop(); } finish = std::chrono::high_resolution_clock::now(); elapsedStd = finish - start; std::cout << "| pop | 1 000 000 | " << std::setw(11) << std::setfill(' ') << elapsedStd.count() << " s | "; for (i = 0; i < 1000000; ++i) { stack->push(i); } start = std::chrono::high_resolution_clock::now(); for (i = 0; i < 1000000; ++i) { stack->pop(); } finish = std::chrono::high_resolution_clock::now(); elapsedParallax = finish - start; // Printing values std::cout << std::setw(11) << std::setfill(' ') << elapsedParallax.count() << " s |" << std::endl; delete stack; delete stdstack; return 0; }
peterzernia/wanderlist
frontend/src/components/Success.js
import React from 'react' import { func, string } from 'prop-types' import IconButton from '@material-ui/core/IconButton' import Close from '@material-ui/icons/Close' const Success = ({ removeError, success }) => ( <div className="success-message"> <IconButton style={{ float: 'right', padding: '0 auto' }} onClick={removeError}> <Close /> </IconButton> <div style={{ width: 48, height: 48, float: 'left' }} /> {success && <p>{success}</p>} </div> ) export default Success Success.propTypes = { removeError: func.isRequired, success: string.isRequired, }
aberdev/orientdb
server/src/main/java/com/orientechnologies/orient/server/network/protocol/ONetworkProtocolData.java
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * 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. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.server.network.protocol; import com.orientechnologies.orient.core.command.OCommandRequestText; import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory; import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerBinary; import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerNetwork; /** * Saves all the important information about the network connection. Useful for monitoring and * statistics. * * @author <NAME> (l.garulli--(at)--orientdb.com) */ public class ONetworkProtocolData { public String commandInfo = null; public String commandDetail = null; public String lastDatabase = null; public String lastUser = null; public String serverInfo = null; public String caller = null; public String driverName = null; public String driverVersion = null; public short protocolVersion = -1; public int sessionId = -1; public String clientId = null; public String currentUserId = null; private String serializationImpl = null; public boolean serverUser = false; public String serverUsername = null; public OCommandRequestText command = null; public boolean supportsLegacyPushMessages = true; public boolean collectStats = true; private ORecordSerializer serializer; public String getSerializationImpl() { return serializationImpl; } public void setSerializationImpl(String serializationImpl) { if (serializationImpl.equals(ORecordSerializerBinary.NAME)) { serializationImpl = ORecordSerializerNetwork.NAME; } this.serializationImpl = serializationImpl; serializer = ORecordSerializerFactory.instance().getFormat(serializationImpl); } public void setSerializer(ORecordSerializer serializer) { this.serializer = serializer; this.serializationImpl = serializer.getName(); } public ORecordSerializer getSerializer() { return serializer; } }
RodrigoRomero2308/gantt-chart
packages/ibm-gantt-chart/src/timetable/index.js
<filename>packages/ibm-gantt-chart/src/timetable/index.js export default from './timetable';
BoxInABoxICT/BoxPlugin
mofa/mofa/test_settings.py
# This program has been developed by students from the bachelor Computer Science at Utrecht University within the # Software and Game project course # ©Copyright Utrecht University Department of Information and Computing Sciences. """These settings will be used when running tests.""" # noinspection PyUnresolvedReferences from .settings import * # Moodle MOODLE_BASE_URL = 'DUMMY_MOODLE_BASE_URL' MOODLE_BASE_IP = 'DUMMY_MOODLE_BASE_IP' MOODLE_WEBSERVICE_URL = 'DUMMY_MOODLE_URL' MOODLE_TOKEN = "DUMMY_MOODLE_TOKEN" # Learning Locker LL_URL = "DUMMY_LL_URL/" LL_AUTH_KEY = "DUMMY_LL_AUTH_KEY" ORGANISATION = "DUMMY_ORGANISATION" DJANGO_URL = "DUMMY_DJANGO_URL" DJANGO_PORT = "1234" SYNC_AGENT_URLS = {'course': f'{DJANGO_URL}:{DJANGO_PORT}/assistants/api/course_sync_agent/', 'user': f'{DJANGO_URL}:{DJANGO_PORT}/assistants/api/user_sync_agent/', 'question': f'{DJANGO_URL}:{DJANGO_PORT}/assistants/api/question_sync_agent/'} INSTALLED_APPS = [ 'analytics.apps.AnalyticsConfig', 'database_API.apps.DatabaseApiConfig', 'assistants.apps.AssistantsConfig', 'scheduler.apps.SchedulerConfig', 'courses.apps.CoursesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'smart_selects', 'django_nose', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3', } } NOSE_ARGS = [ '--with-coverage', '--cover-package=assistants,courses,scheduler,analytics,database_API', ] TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
Allenjonesing/tutorials
Direct3D/Toon Shading/d3d_texture.h
<gh_stars>100-1000 #ifndef D3D_TEXTURE_H #define D3D_TEXTURE_H #include <d3dx9tex.h> // This is our D3D texture class. It will handle all of the // texture needs for our app. class CD3DTexture { public: CD3DTexture(); // Constructor // Loads the texture specified by the file name and optionally lets you specify the // width and height of the texture. Returns true for success, false otherwise bool load(const char *fileName, int width = 0, int height = 0); void select(const char *name); // Selects the texture as the current texture into // the effect file ~CD3DTexture(); // Free up memory private: IDirect3DTexture9 *mTexture; // DX9 texture interface. This allows us to manage // a texture resource inside of a D3D app // We make the copy constructor and assignment operator private because // we do NOT want anyone accidentally making a copy of this class // It should always be passed by pointer or reference CD3DTexture(const CD3DTexture &obj) {} CD3DTexture& operator =(CD3DTexture &obj) { return *this; } }; #endif
KleeGroup/vertigo-extensions
vertigo-account/src/test/java/io/vertigo/account/data/TestIdentities.java
/** * vertigo - application development platform * * Copyright (C) 2013-2020, Vertigo.io, <EMAIL> * * 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 io.vertigo.account.data; import java.util.Arrays; 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 io.vertigo.account.account.Account; import io.vertigo.account.account.AccountGroup; import io.vertigo.account.plugins.account.store.loader.AccountLoader; import io.vertigo.account.plugins.account.store.loader.GroupLoader; import io.vertigo.datamodel.structure.model.UID; import io.vertigo.datastore.filestore.model.VFile; public final class TestIdentities implements AccountLoader, GroupLoader { private final Map<String, Account> accountsMap = new HashMap<>(); private final Map<String, Account> accountsMapByAuth = new HashMap<>(); private final Map<String, AccountGroup> groupsMap = new HashMap<>(); private final Map<UID<Account>, Set<UID<AccountGroup>>> groupsPerAccount = new HashMap<>(); private final Map<UID<AccountGroup>, Set<UID<Account>>> accountsPerGroup = new HashMap<>(); private TestIdentities() { //rien } public static UID<Account> createAccountURI(final String id) { return UID.of(Account.class, id); } public static UID<AccountGroup> createGroupURI(final String id) { return UID.of(AccountGroup.class, id); } public void initData() { final Account testAccount0 = Account.builder("0").withAuthToken("john.doe").withDisplayName("<NAME>").withEmail("<EMAIL>").build(); final Account testAccount1 = Account.builder("1").withAuthToken("<PASSWORD>").withDisplayName("<NAME>").withEmail("<EMAIL>").build(); final Account testAccount2 = Account.builder("2").withAuthToken("bill.<PASSWORD>").withDisplayName("<NAME>").withEmail("<EMAIL>").build(); final Account testAccount3 = Account.builder("3").withAuthToken("admin").withDisplayName("<NAME>").withEmail("<EMAIL>").build(); saveAccounts(Arrays.asList(testAccount0, testAccount1, testAccount2, testAccount3)); final UID<Account> accountURI0 = createAccountURI(testAccount0.getId()); final UID<Account> accountURI1 = createAccountURI(testAccount1.getId()); final UID<Account> accountURI2 = createAccountURI(testAccount2.getId()); final AccountGroup testAccountGroup1 = new AccountGroup("100", "TIME's cover"); final UID<AccountGroup> group1Uri = UID.of(AccountGroup.class, testAccountGroup1.getId()); saveGroup(testAccountGroup1); attach(accountURI1, group1Uri); attach(accountURI2, group1Uri); final AccountGroup groupAll = new AccountGroup("ALL", "Everyone"); final UID<AccountGroup> groupAllUri = UID.of(AccountGroup.class, groupAll.getId()); saveGroup(groupAll); attach(accountURI0, groupAllUri); attach(accountURI1, groupAllUri); attach(accountURI2, groupAllUri); //---create 10 noisy data final List<Account> accounts = createAccounts(); saveAccounts(accounts); for (final Account account : accounts) { final UID<Account> accountUri = createAccountURI(account.getId()); attach(accountUri, groupAllUri); } } private static int SEQ_ID = 10; private static List<Account> createAccounts() { return List.of( createAccount("<NAME>", "<EMAIL>"), createAccount("<NAME>", "<EMAIL>"), createAccount("<NAME>", "<EMAIL>"), createAccount("<NAME>", "<EMAIL>"), createAccount("<NAME>", "<EMAIL>"), createAccount("<NAME>", "<EMAIL>"), createAccount("<NAME>", "<EMAIL>"), createAccount("<NAME>", "<EMAIL>"), createAccount("<NAME>", "<EMAIL>"), createAccount("<NAME>", "<EMAIL>")); } private static Account createAccount(final String displayName, final String email) { return Account.builder(Integer.toString(SEQ_ID++)) .withAuthToken(email.substring(0, email.indexOf('@'))) .withDisplayName(displayName) .withEmail(email) .build(); } private void attach(final UID<Account> accountURI, final UID<AccountGroup> groupURI) { groupsPerAccount.computeIfAbsent(accountURI, key -> new HashSet<>()).add(groupURI); accountsPerGroup.computeIfAbsent(groupURI, key -> new HashSet<>()).add(accountURI); } private void saveGroup(final AccountGroup accountGroup) { groupsMap.put(accountGroup.getId(), accountGroup); } private void saveAccounts(final List<Account> accounts) { accounts.stream().forEach(account -> { accountsMap.put(account.getId(), account); accountsMapByAuth.put(account.getAuthToken(), account); }); } @Override public long getAccountsCount() { return accountsMap.size(); } @Override public Account getAccount(final UID<Account> accountURI) { return accountsMap.get(accountURI); } @Override public Optional<VFile> getPhoto(final UID<Account> accountURI) { return Optional.empty(); } @Override public Optional<Account> getAccountByAuthToken(final String userAuthToken) { return Optional.ofNullable(accountsMapByAuth.get(userAuthToken)); } @Override public long getGroupsCount() { return groupsMap.size(); } @Override public AccountGroup getGroup(final UID<AccountGroup> groupURI) { return groupsMap.get(groupURI); } @Override public Set<UID<AccountGroup>> getGroupURIs(final UID<Account> accountURI) { return groupsPerAccount.computeIfAbsent(accountURI, key -> Collections.emptySet()); } @Override public Set<UID<Account>> getAccountURIs(final UID<AccountGroup> groupURI) { // TODO Auto-generated method stub return null; } }
unifiedjs/design-system
src/theme.js
<reponame>unifiedjs/design-system export const fontSizes = [14, 16, 18, 24, 32, 48, 64] export const fontFamilies = { sans: ` system-ui, -apple-system, BlinkMacSystemFont, Roboto, "Helvetica Neue", "Segoe UI", Oxygen, Ubuntu, Cantarell, "Open Sans", sans-serif `, mono: ` Consolas, "Liberation Mono", Menlo, Courier, monospace ` } export const fontWeights = { light: 300, normal: 400, bold: 500 } export const lineHeights = { solid: 1, title: 1.1, copy: 1.6 } export const maxWidths = { container: 1028, measure: 512, measureWide: 720, measureNarrow: 360 } export const space = [0, 4, 8, 16, 32, 64, 128, 256, 512] export const colors = { // Projects unified: '#0367d8', remark: '#d80303', rehype: '#d8a303', retext: '#03d803', redot: '#d803d8', mdx: '#f9ac00', // Base black: '#000', white: '#fff', gray: '#fafafa', blue: '#0367d8', // Scales grays: [ '#f8f9f9', '#ebedee', '#dee1e3', '#cfd3d6', '#bec4c8', '#acb4b9', '#97a1a7', '#7f8a93', '#5f6e78', '#374047' ], blues: [ '#e4f0f9', '#c6e1f3', '#a5cfed', '#7db9e5', '#4a9eda', '#0077cc', '#006bb7', '#005da0', '#004d84', '#00365d' ], indigos: [ '#eaebfa', '#d2d5f6', '#b7bbf0', '#959ce9', '#6872e0', '#0011cc', '#000fb7', '#000da0', '#000a83', '#00075c' ], violets: [ '#f0e9fa', '#e1d2f6', '#ceb6f0', '#b894e9', '#9966e0', '#5500cc', '#4c00b8', '#4300a1', '#370084', '#27005e' ], fuschias: [ '#f9e9fa', '#f2d1f5', '#ebb5f0', '#e293e9', '#d665e0', '#bb00cc', '#a900b8', '#9400a2', '#7b0086', '#580061' ], pinks: [ '#fae9f3', '#f5d1e6', '#f0b6d8', '#e994c6', '#e066ad', '#cc0077', '#b8006b', '#a2005e', '#86004e', '#610038' ], reds: [ '#faeaeb', '#f6d2d5', '#f0b7bc', '#ea969d', '#e16973', '#cc0011', '#b8000f', '#a2000d', '#86000b', '#610008' ], oranges: [ '#f9ede4', '#f3d9c6', '#ecc2a4', '#e4a87c', '#da864a', '#cc5500', '#b84c00', '#a04300', '#843700', '#5e2700' ], yellows: [ '#f8f6de', '#f1ecba', '#e9e293', '#e0d668', '#d7c938', '#ccbb00', '#b8a900', '#a29400', '#867b00', '#615800' ], limes: [ '#eef8df', '#dcf1bd', '#c7ea97', '#b1e16c', '#96d73b', '#77cc00', '#6bb800', '#5ea200', '#4e8600', '#386100' ], greens: [ '#e5f9e4', '#c9f3c6', '#a9eca3', '#84e47b', '#54da48', '#11cc00', '#0fb800', '#0da200', '#0b8600', '#086100' ], teals: [ '#e3f9ec', '#c5f3d8', '#a2ecc1', '#79e4a6', '#46da84', '#00cc55', '#00b84c', '#00a243', '#008638', '#006128' ], cyans: [ '#e3f9f7', '#c4f3ef', '#a0ece5', '#77e3da', '#44d9cd', '#00ccbb', '#00b8a9', '#00a294', '#00867b', '#006159' ] } export default { fontSizes, fontFamilies, fontWeights, lineHeights, maxWidths, space, colors }
daichi-yoshikawa/vue-boilerplate
src/router/public-routes.js
// Do not try lazy loading components because // it may experience "Failed to resolved async component" error. import HomeView from '@entry/home/home-view' import InviteView from '@auth/invite/invite-view' import LoginView from '@auth/login/login-view' import PrivacyView from '@legal/privacy/privacy-view' import ResetView from '@auth/reset/reset-view' import SignupView from '@auth/signup/signup-view' import TosView from '@legal/tos/tos-view' const routes = [ { path: '/entry', name: 'public-home', component: HomeView, meta: { title: 'Landing', requireAuth: false, labelOfPublicNavItem: 'Home', }, }, { path: '/auth/password/reset/:passwordResetCode?', name: 'password-reset', component: ResetView, meta: { title: 'Reset Password', requireAuth: false, }, }, { path: '/auth/login', name: 'login', component: LoginView, meta: { title: 'Login', requireAuth: false, }, }, { path: '/auth/signup/:emailVerificationCode?', name: 'signup', component: SignupView, meta: { title: 'Signup', requireAuth: false, }, }, { path: '/auth/invite/:invitationCode', name: 'invite', component: InviteView, meta: { title: 'Invite', requireAuth: false, }, }, { path: '/legal/privacy', name: 'privacy', component: PrivacyView, meta: { title: 'Privacy', requireAuth: false, }, }, { path: '/legal/tos', name: 'tos', component: TosView, meta: { title: 'Terms of Service', requireAuth: false, }, }, ]; export default routes;
qitianersheng/sensitive-word
src/main/java/com/github/houbb/sensitive/word/support/format/IgnoreEnglishStyleFormat.java
package com.github.houbb.sensitive.word.support.format; import com.github.houbb.heaven.annotation.ThreadSafe; import com.github.houbb.sensitive.word.api.ICharFormat; import com.github.houbb.sensitive.word.api.IWordContext; import com.github.houbb.sensitive.word.utils.CharUtils; /** * 忽略英文的各种格式 * @author binbin.hou * @since 0.0.6 */ @ThreadSafe public class IgnoreEnglishStyleFormat implements ICharFormat { @Override public char format(char original, IWordContext context) { return CharUtils.getMappingChar(original); } }
infiniteblock/CalemiUtils-1.12.2
src/main/java/calemiutils/gui/base/GuiRect.java
package calemiutils.gui.base; public class GuiRect { public int x; public int y; public final int width; public final int height; public GuiRect(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } public boolean contains(int px, int py) { return px > x - 1 && px < (x + width) + 1 && py > y - 1 && py < (y + height) + 1; } }
kapseliboi/boxwood
src/transpilers/html/tags/try.js
<reponame>kapseliboi/boxwood const AbstractSyntaxTree = require('abstract-syntax-tree') const { ReturnStatement, BlockStatement, TryStatement, CatchClause } = AbstractSyntaxTree function mapTryStatement (htmlNode, parent, index, transpileNode) { function mapCurrentNodeToBlockStatement (htmlNode) { const body = htmlNode.children.map((node, index) => transpileNode({ node, parent: htmlNode.children, index })).filter(Boolean) const argument = body.pop() body.push(new ReturnStatement({ argument })) return new BlockStatement({ body }) } function mapNextNodeToCatchClause (nextNode) { if (nextNode && nextNode.tagName === 'catch') { const body = nextNode.children.map((node, index) => transpileNode({ node, parent: htmlNode.children, index })).filter(Boolean) const argument = body.pop() body.push(new ReturnStatement({ argument })) return new CatchClause({ body: new BlockStatement({ body }) }) } return null } return new TryStatement({ block: mapCurrentNodeToBlockStatement(htmlNode), handler: mapNextNodeToCatchClause(parent[index + 1]) }) } module.exports = mapTryStatement
hydratk/hydratk-lib-network
src/hydratk/lib/network/email/imap_client.py
<reponame>hydratk/hydratk-lib-network # -*- coding: utf-8 -*- """IMAP email client .. module:: network.email.imap_client :platform: Unix :synopsis: IMAP email client .. moduleauthor:: <NAME> <<EMAIL>> """ """ Events: ------- email_before_connect email_after_connect email_before_receive_email email_after_receive_email """ from hydratk.core.masterhead import MasterHead from hydratk.core import event from imaplib import IMAP4, IMAP4_SSL from socket import error, setdefaulttimeout from sys import version_info if (version_info[0] == 2): from string import replace class EmailClient(object): """Class EmailClient """ _mh = None _client = None _secured = None _host = None _port = None _user = None _passw = None _verbose = None _is_connected = None def __init__(self, secured=False, verbose=False): """Class constructor Called when the object is initialized Args: secured (bool): secured IMAP verbose (bool): verbose mode """ self._mh = MasterHead.get_head() self._secured = secured self._verbose = verbose @property def client(self): """ IMAP client property getter """ return self._client @property def secured(self): """ secured property getter """ return self._secured @property def host(self): """ server host property getter """ return self._host @property def port(self): """ server port property getter """ return self._port @property def user(self): """ username property getter """ return self._user @property def passw(self): """ user password property getter """ return self._passw @property def verbose(self): """ verbose mode property getter """ return self._verbose @property def is_connected(self): """ is_connected property getter """ return self._is_connected def connect(self, host, port=None, user=None, passw=None, timeout=10): """Method connects to server Args: host (str): server host port (str): server port, default protocol port user (str): username passw (str): password timeout (int): timeout Returns: bool: result Raises: event: email_before_connect event: email_after_connect """ try: if (port == None): port = 143 if (not self._secured) else 993 message = '{0}/{1}@{2}:{3} timeout:{4}'.format( user, passw, host, port, timeout) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_email_connecting', message), self._mh.fromhere()) ev = event.Event( 'email_before_connect', host, port, user, passw, timeout) if (self._mh.fire_event(ev) > 0): host = ev.argv(0) port = ev.argv(1) user = ev.argv(2) passw = ev.argv(3) timeout = ev.argv(4) self._host = host self._port = port self._user = user self._passw = <PASSWORD> if (ev.will_run_default()): setdefaulttimeout(timeout) if (not self._secured): self._client = IMAP4(self._host, self._port) else: self._client = IMAP4_SSL(self._host, self._port) if (self._verbose): self._client.debug = 4 if (self._user != None): self._client.login(self._user, self._passw) self._is_connected = True self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_email_connected'), self._mh.fromhere()) ev = event.Event('email_after_connect') self._mh.fire_event(ev) return True except (IMAP4.error, error) as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False def disconnect(self): """Method disconnects from server Args: none Returns: bool: result """ try: if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_email_not_connected'), self._mh.fromhere()) return False else: self._client.shutdown() self._is_connected = False self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_email_disconnected'), self._mh.fromhere()) return True except (IMAP4.error, error) as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return False def email_count(self): """Method gets email count Args: none Returns: int: count """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_email_counting'), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_email_not_connected'), self._mh.fromhere()) return None count = int(self._client.select()[1][0]) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_email_count', count), self._mh.fromhere()) return count except (IMAP4.error, error) as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return None def list_emails(self): """Method gets email list Args: none Returns: list: email ids """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_email_listing'), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_email_not_connected'), self._mh.fromhere()) return None self._client.select() msg_list = self._client.search(None, 'ALL')[1][0] emails = msg_list.split(' ') if ( version_info[0] == 2) else msg_list.split(b' ') if (version_info[0] == 3): for i in range(0, len(emails)): emails[i] = emails[i].decode() self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_email_listed'), self._mh.fromhere()) return emails except (IMAP4.error, error) as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return None def receive_email(self, msg_id): """Method receives email Args: msg_id (str) - email id Returns: tuple: sender (str), recipients (list), cc (list), subject (str), message (str) Raises: event: email_before_receive_email event: email_after_receive_email """ try: self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_email_receiving', msg_id), self._mh.fromhere()) if (not self._is_connected): self._mh.demsg('htk_on_warning', self._mh._trn.msg( 'htk_email_not_connected'), self._mh.fromhere()) return None ev = event.Event('email_before_receive_email', msg_id) if (self._mh.fire_event(ev) > 0): msg_id = ev.argv(0) if (ev.will_run_default()): self._client.select() msg = self._client.fetch(str(msg_id), '(RFC822)')[1][0][1] msg = msg.split('\r\n') if ( version_info[0] == 2) else msg.split(b'\r\n') msg_found = False sender = None recipients = None cc = None subject = None message = '' for line in msg: if (not msg_found): if (version_info[0] == 3): line = line.decode() if ('From: ' in line): sender = replace(line, ('From: '), '') if ( version_info[0] == 2) else line.replace('From: ', '') elif ('To: ' in line): recipients = replace(line, ('To: '), '') if ( version_info[0] == 2) else line.replace('To: ', '') recipients = recipients.split(',') elif ('CC: ' in line): cc = replace(line, ('CC: '), '') if ( version_info[0] == 2) else line.replace('CC: ', '') cc = cc.split(',') elif ('Subject: ' in line): subject = replace(line, ('Subject: '), '') if ( version_info[0] == 2) else line.replace('Subject: ', '') elif ('Inbound message' in line): msg_found = True else: message += str(line) + '\r\n' ev = event.Event('email_after_receive_email') self._mh.fire_event(ev) self._mh.demsg('htk_on_debug_info', self._mh._trn.msg( 'htk_email_received'), self._mh.fromhere()) return (sender, recipients, cc, subject, message) except (IMAP4.error, error) as ex: self._mh.demsg( 'htk_on_error', 'error: {0}'.format(ex), self._mh.fromhere()) return None
ptyped/kit
lib/core/template.test.integration.js
const fs = require('fs') const glob = require('glob') const path = require('path') const remove = require('rimraf') const Config = require('./config') const Template = require('./template') describe('Run integration tests on template create', () => { let cwd, pkgPath, nodeModulesDir, kitDir, templateDir, appDir, staticDir, dataDir, dependencyDir, jsDir, cssDir, scssDir, template const initialize = async () => { const kitModule = path.resolve(process.cwd()) const rand = String(new Date().getUTCMilliseconds()) cwd = path.resolve(process.cwd(), "lib/fixtures/.tmp", rand) const configInstance = new Config({cwd: cwd, kitModule: kitModule}) config = configInstance.config template = new Template(config) template = new Template(config) await template.getDependency() cwd = config.get('cwd') pkgPath = path.resolve(cwd, "./package.json") nodeModulesDir = path.resolve(cwd, "./node_modules") kitDir = path.resolve(nodeModulesDir, config.get('kitModule')) templateDir = path.resolve(nodeModulesDir, template.dependency.name) appDir = config.get('dirs.input') staticDir = config.get('dirs.static') dataDir = config.get('dirs.data') dependencyDir = config.get('dirs.data') jsDir = config.get('dirs.assets.js') cssDir = config.get('dirs.assets.css') scssDir = config.get('dirs.assets.scss') } beforeEach(() => { return initialize() }) afterEach(() => { remove.sync(cwd) }) test(`Expect only "cwd" to exist`, async () => { await template.createProject() expect(fs.existsSync(cwd)).toBe(true) expect(fs.existsSync(pkgPath)).toBe(true) expect(fs.existsSync(nodeModulesDir)).toBe(false) expect(fs.existsSync(appDir)).toBe(false) expect(fs.existsSync(staticDir)).toBe(false) }) test(`Expect node_modules to install correctly`, async () => { await template.createProject() await template.install() expect(fs.existsSync(cwd)).toBe(true) expect(fs.existsSync(nodeModulesDir)).toBe(true) expect(fs.existsSync(pkgPath)).toBe(true) expect(fs.existsSync(templateDir)).toBe(true) expect(fs.existsSync(appDir)).toBe(false) expect(fs.existsSync(staticDir)).toBe(false) }) test(`Expect all template files and dirs to exist`, async () => { await template.createProject() await template.install() await template.copy() const files = glob.sync(template.dependency.output + "/**/*").filter(p => !fs.lstatSync(p).isDirectory()) expect(fs.existsSync(cwd)).toBe(true) expect(fs.existsSync(nodeModulesDir)).toBe(true) expect(fs.existsSync(pkgPath)).toBe(true) expect(fs.existsSync(templateDir)).toBe(true) expect(fs.existsSync(appDir)).toBe(true) expect(fs.existsSync(jsDir)).toBe(true) expect(fs.existsSync(dataDir)).toBe(true) expect(fs.existsSync(jsDir)).toBe(true) expect(fs.existsSync(cssDir)).toBe(true) expect(fs.existsSync(scssDir)).toBe(true) expect(fs.existsSync(staticDir)).toBe(true) expect(fs.existsSync(dependencyDir)).toBe(true) for (var key in files) { const file = files[key] expect(fs.existsSync(file)).toBe(true) } }) })
AlexeyMochalov/firebird
src/jrd/dpm_proto.h
/* * PROGRAM: JRD Access Method * MODULE: dpm_proto.h * DESCRIPTION: Prototype header file for dpm.cpp * * The contents of this file are subject to the Interbase Public * License Version 1.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.Inprise.com/IPL.html * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * The Original Code was created by Inprise Corporation * and its predecessors. Portions created by Inprise Corporation are * Copyright (C) Inprise Corporation. * * All Rights Reserved. * Contributor(s): ______________________________________. */ #ifndef JRD_DPM_PROTO_H #define JRD_DPM_PROTO_H #include "../jrd/RecordNumber.h" #include "../jrd/sbm.h" // fwd. decl. namespace Jrd { class blb; class jrd_rel; struct record_param; class Record; class jrd_tra; struct win; // Store allocation policy types. Parameter to DPM_store() // I don't see it stored, but since the first constant was 1, I'm using the same values in the enum. enum RecordStorageType { DPM_primary = 1, // New primary record DPM_secondary, // Chained version of primary record DPM_other // Independent (or don't care) record }; } namespace Ods { struct pag; struct data_page; } Ods::pag* DPM_allocate(Jrd::thread_db*, Jrd::win*); void DPM_backout(Jrd::thread_db*, Jrd::record_param*); void DPM_backout_mark(Jrd::thread_db*, Jrd::record_param*, const Jrd::jrd_tra*); double DPM_cardinality(Jrd::thread_db*, Jrd::jrd_rel*, const Jrd::Format*); bool DPM_chain(Jrd::thread_db*, Jrd::record_param*, Jrd::record_param*); void DPM_create_relation(Jrd::thread_db*, Jrd::jrd_rel*); ULONG DPM_data_pages(Jrd::thread_db*, Jrd::jrd_rel*); void DPM_delete(Jrd::thread_db*, Jrd::record_param*, ULONG); void DPM_delete_relation(Jrd::thread_db*, Jrd::jrd_rel*); bool DPM_fetch(Jrd::thread_db*, Jrd::record_param*, USHORT); bool DPM_fetch_back(Jrd::thread_db*, Jrd::record_param*, USHORT, SSHORT); void DPM_fetch_fragment(Jrd::thread_db*, Jrd::record_param*, USHORT); SINT64 DPM_gen_id(Jrd::thread_db*, SLONG, bool, SINT64); bool DPM_get(Jrd::thread_db*, Jrd::record_param*, SSHORT); ULONG DPM_get_blob(Jrd::thread_db*, Jrd::blb*, RecordNumber, bool, ULONG); bool DPM_next(Jrd::thread_db*, Jrd::record_param*, USHORT, bool); void DPM_pages(Jrd::thread_db*, SSHORT, int, ULONG, ULONG); #ifdef SUPERSERVER_V2 SLONG DPM_prefetch_bitmap(Jrd::thread_db*, Jrd::jrd_rel*, Jrd::PageBitmap*, SLONG); #endif void DPM_scan_pages(Jrd::thread_db*); void DPM_store(Jrd::thread_db*, Jrd::record_param*, Jrd::PageStack&, const Jrd::RecordStorageType type); RecordNumber DPM_store_blob(Jrd::thread_db*, Jrd::blb*, Jrd::Record*); void DPM_rewrite_header(Jrd::thread_db*, Jrd::record_param*); void DPM_update(Jrd::thread_db*, Jrd::record_param*, Jrd::PageStack*, const Jrd::jrd_tra*); void DPM_create_relation_pages(Jrd::thread_db*, Jrd::jrd_rel*, Jrd::RelationPages*); void DPM_delete_relation_pages(Jrd::thread_db*, Jrd::jrd_rel*, Jrd::RelationPages*); #endif // JRD_DPM_PROTO_H
zhangshoug/czipline
zipline/api.py
# # Copyright 2014 Quantopian, 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. # Note that part of the API is implemented in TradingAlgorithm as # methods (e.g. order). These are added to this namespace via the # decorator ``api_method`` inside of algorithm.py. from .finance.asset_restrictions import ( Restriction, StaticRestrictions, HistoricalRestrictions, RESTRICTION_STATES, ) from .finance import commission, execution, slippage, cancel_policy from .finance.cancel_policy import (NeverCancel, EODCancel) from .finance.slippage import ( FixedSlippage, FixedBasisPointsSlippage, VolumeShareSlippage, ) from .utils import math_utils, events from .utils.events import (calendars, date_rules, time_rules) __all__ = [ 'EODCancel', 'FixedSlippage', 'FixedBasisPointsSlippage', 'NeverCancel', 'VolumeShareSlippage', 'Restriction', 'StaticRestrictions', 'HistoricalRestrictions', 'RESTRICTION_STATES', 'cancel_policy', 'commission', 'date_rules', 'events', 'execution', 'math_utils', 'slippage', 'time_rules', 'calendars', ]
moben/kopia
internal/ownwrites/ownwrites_test.go
package ownwrites import ( "testing" "time" "github.com/stretchr/testify/require" "github.com/kopia/kopia/internal/blobtesting" "github.com/kopia/kopia/internal/faketime" "github.com/kopia/kopia/internal/gather" "github.com/kopia/kopia/internal/testlogging" "github.com/kopia/kopia/repo/blob" ) const testCacheDuration = 15 * time.Minute func TestOwnWrites(t *testing.T) { realStorageTime := faketime.NewTimeAdvance(time.Date(2000, 1, 2, 3, 4, 5, 6, time.UTC), 0) realStorage := blobtesting.NewMapStorage(blobtesting.DataMap{}, nil, realStorageTime.NowFunc()) cacheTime := faketime.NewTimeAdvance(time.Date(2020, 1, 2, 3, 4, 5, 6, time.UTC), 0) cachest := blobtesting.NewMapStorage(blobtesting.DataMap{}, nil, cacheTime.NowFunc()) ec := blobtesting.NewEventuallyConsistentStorage(realStorage, 1*time.Hour, realStorageTime.NowFunc()) ow := NewWrapper(ec, cachest, []blob.ID{"n"}, testCacheDuration) ow.(*CacheStorage).cacheTimeFunc = cacheTime.NowFunc() ctx := testlogging.Context(t) // seed some blobs into storage and advance time so they are reliably settled. require.NoError(t, ec.PutBlob(ctx, "npreexisting", gather.FromSlice([]byte("pre-existing")))) realStorageTime.Advance(1 * time.Hour) require.NoError(t, ow.PutBlob(ctx, "n123", gather.FromSlice([]byte("not-important")))) // verify we wrote the marker into cache. blobtesting.AssertGetBlob(ctx, t, cachest, "addn123", []byte("marker")) require.NoError(t, ow.PutBlob(ctx, "x123", gather.FromSlice([]byte("not-important")))) blobtesting.AssertGetBlobNotFound(ctx, t, cachest, "addx123") // make sure eventual consistency wrapper won't return the item yet. blobtesting.AssertListResultsIDs(ctx, t, ec, "n", "npreexisting") // despite that our wrapper will have it blobtesting.AssertListResultsIDs(ctx, t, ow, "n", "n123", "npreexisting") // move time now, so that eventual consistency is settled. realStorageTime.Advance(1 * time.Hour) // both storages will now agree blobtesting.AssertListResultsIDs(ctx, t, ec, "n", "n123", "npreexisting") blobtesting.AssertListResultsIDs(ctx, t, ow, "n", "n123", "npreexisting") cacheTime.Advance(1 * time.Minute) require.NoError(t, ow.DeleteBlob(ctx, "n123")) // verify we wrote the marker into cache. blobtesting.AssertGetBlob(ctx, t, cachest, "deln123", []byte("marker")) // ec still has the deleted blob blobtesting.AssertListResultsIDs(ctx, t, ec, "n", "n123", "npreexisting") // but we hide it from results. blobtesting.AssertListResultsIDs(ctx, t, ow, "n", "npreexisting") blobtesting.AssertListResultsIDs(ctx, t, cachest, "", "addn123", "deln123") cacheTime.Advance(24 * time.Hour) realStorageTime.Advance(24 * time.Hour) blobtesting.AssertListResultsIDs(ctx, t, ow, "n", "npreexisting") // make sure cache got sweeped blobtesting.AssertListResultsIDs(ctx, t, cachest, "") }
jtduchesne/Nestled
app/src/hooks/index.js
export { useStatus } from "../contexts/Status";
lanz/Tenable.io-SDK-for-Python
tenable_io/api/access_groups.py
from json import loads from tenable_io.api.base import BaseApi from tenable_io.api.base import BaseRequest from tenable_io.api.models import AccessGroup, AccessGroupList, AssetRule, AssetRuleFilter, AssetRulePrincipal, Filters class AccessGroupsApi(BaseApi): def list(self, f=None, ft='and', w=None, wf=None, limit=None, offset=0, sort=None): """Return the access groups without associated rules. :param f: A list of :class:`tenable_io.api.models.AssetFilter` instances. :param ft: The action to apply if multiple 'f' parameters are provided. Supported values are **and** and **or**. :param w: The search value to be applied across wildcard fields specified with the 'wf' parameter. :param wf: The list of fields where the search values specified in the 'w' parameter are applied. :param limit: The maximum number of records to be retrieved. :param offset: The offset from request. :param sort: A list of fields on which the results are sorted. :raise TenableIOApiException: When API error is encountered. :return: An instance of :class:`tenable_io.api.models.AccessGroupList`. """ fgen = (i.field + ':' + i.operator + ':' + i.value for i in f) if f is not None else None response = self._client.get('access-groups', params={'f': '&'.join(fgen) if fgen is not None else None, 'ft': ft, 'w': w, 'wf': ','.join(wf) if wf is not None else None, 'limit': limit, 'offset': offset, 'sort': ','.join(sort) if sort is not None else None}) return AccessGroupList.from_json(response.text) def create(self, access_group_request): """Create a new access group. :param Access_group_request: An instance of :class:`AccessGroupRequest`. :raise TenableIOApiException: When API error is encountered. :return: An instance of :class:`tenable_io.api.models.AccessGroup` without the rules information. """ response = self._client.post('access-groups', access_group_request) return AccessGroup.from_json(response.text) def details(self, id): """Returns details for a specific access group :param id: The id of the access group :raise TenableIOApiException: When API error is encountered. :return: An instance of :class:`tenable_io.api.models.AccessGroup`. """ response = self._client.get('access-groups/%(id)s', path_params={'id': id}) return AccessGroup.from_json(response.text) def delete(self, id): """Delete an access group. :param id: The id of the access group to delete. :raise TenableIOApiException: When API error is encountered. :return: True if successful. """ self._client.delete('access-groups/%(id)s', path_params={'id': id}) return True def edit(self, id, access_group_request): """Modifies an access group. This method overwrites the existing data. :param id: The id of the access group to be edited. :param access_group_request: An instance of :class:`AccessGroupRequest`. :raise TenableIOApiException: When API error is encountered. :return: An instance of :class:`tenable_io.api.models.AccessGroup`. """ response = self._client.put('access-groups/%(id)s', payload=access_group_request, path_params={'id': id}) return AccessGroup.from_json(response.text) def filters(self): """List available filters for access groups. :raise TenableIOApiException: When API error is encountered. :return: An instance of :class:`tenable_io.api.models.Filters`. """ response = self._client.get('access-groups/filters') return Filters.from_json(response.text) def rule_filters(self): """List available filters for asset rules. :raise TenableIOApiException: When API error is encountered. :return: An instance of :class:`tenable_io.api.models.Filters`. """ response = self._client.get('access-groups/rules/filters') return AssetRuleFilter.from_list(loads(response.text).get('rules', {})) class AccessGroupRequest(BaseRequest): def __init__( self, name=None, all_assets=False, all_users=False, rules=None, principals=None ): """Request for AccessGroupsApi.create and AccessGroupsApi.edit. :param name: The name of the access group. Must be unique within the container, a maximum of 255 characters, and alphanumeric, but can include limited special characters (underscore, dash, parenthesis, brackets, colon). You can add a maximum of 5,000 access groups to an individual container. :type name: string :param all_assets: Specifies whether the access group is the All Assets group or a user-defined group. A create request with this parameter set to 'true' will fail. Set to 'true' to edit membership in the All Assets access group. In which case, any rules are ignored, but existing principals are overwritten based on the all_users and principals parameters. Set to 'false' to edit a user-defined access group. The existing rules are overwritten with the new rules, and existing principals are overwritten based on the all_users and principals parameters. :type all_assets: boolean :param all_users: Specifies whether assets in the access group can be viewed by all or only some users. Default is 'False'. If 'true', all users in your organization have Can View access to the assets defined in the rules parameter and any principal parameters is ignored. If 'false', only specified users have Can View access to the assets defined in the rules parameter. You define which users or user groups have access in the principals parameter of the request. :type all_users: boolean :param rules: An array of asset rules. Tenable.io uses these rules to assign assets to the access group. You can only add rules to access groups if the all_assets parameter is set to 'false'. :type rules: list :param principals: A list of principals. Each representing a user or user group assigned to the access group. Data in this array is handled based on the all_users parameter. If all_users is 'true', any principal data is ignored and you can omit this parameter. If all_users is 'false', the principal data is added to the access group. :type principals: list """ for r in rules: assert isinstance(r, AssetRule) self.name = name self.all_assets = all_assets self.all_users = all_users self.rules = rules self.principals = principals def as_payload(self, filter_=None): payload = super(AccessGroupRequest, self).as_payload(True) rule_list = [] for r in self.rules: rule_list.append(r.as_payload()) payload.__setitem__('rules', rule_list) if not self.all_users and self.principals: principal_list = [] for p in self.principals: assert isinstance(p, AssetRulePrincipal) principal_list.append(p.as_payload()) payload.__setitem__('principals', principal_list) return payload
lechium/tvOS10Headers
System/Library/PrivateFrameworks/PhotoAnalysis.framework/Frameworks/PhotosGraph.framework/Frameworks/MediaMiningKit.framework/CLSCalendar.h
<filename>System/Library/PrivateFrameworks/PhotoAnalysis.framework/Frameworks/PhotosGraph.framework/Frameworks/MediaMiningKit.framework/CLSCalendar.h<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.0 * on Wednesday, March 22, 2017 at 9:09:43 AM Mountain Standard Time * Operating System: Version 10.1 (Build 14U593) * Image Source: /System/Library/PrivateFrameworks/PhotoAnalysis.framework/Frameworks/PhotosGraph.framework/Frameworks/MediaMiningKit.framework/MediaMiningKit * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <MediaMiningKit/MediaMiningKit-Structs.h> @interface CLSCalendar : NSObject +(void)initialize; +(id)components:(unsigned long long)arg1 fromDate:(id)arg2 ; +(NSRange)rangeOfUnit:(unsigned long long)arg1 inUnit:(unsigned long long)arg2 forDate:(id)arg3 ; +(long long)compareDate:(id)arg1 toDate:(id)arg2 toUnitGranularity:(unsigned long long)arg3 ; +(id)startOfDayForDate:(id)arg1 ; +(id)dateComponentsWithUniversalDate:(id)arg1 atLocation:(id)arg2 ; +(id)dateFromComponents:(id)arg1 inTimeZone:(id)arg2 ; +(id)currentLocalDate; +(long long)yearFromDate:(id)arg1 ; +(id)dateFromComponents:(unsigned long long)arg1 ofDate:(id)arg2 ; +(id)dateComponentsWithUniversalDates:(id)arg1 atLocation:(id)arg2 ; +(id)dateByAddingDays:(long long)arg1 toDate:(id)arg2 ; +(long long)weekdayFromDate:(id)arg1 ; +(long long)monthFromDate:(id)arg1 ; +(id)componentsFromDate:(id)arg1 inTimeZone:(id)arg2 ; +(id)localDateFromUniversalDate:(id)arg1 atLocation:(id)arg2 ; +(id)universalDateFromLocalDate:(id)arg1 inTimeZone:(id)arg2 ; +(id)localDateFromUniversalDate:(id)arg1 inTimeZone:(id)arg2 ; +(id)components:(unsigned long long)arg1 fromDateComponents:(id)arg2 toDateComponents:(id)arg3 options:(unsigned long long)arg4 ; +(id)universalDateFromLocalDate:(id)arg1 atLocation:(id)arg2 ; +(id)dateBySettingYear:(long long)arg1 ofDate:(id)arg2 ; +(long long)yearForWeekOfYearFromDate:(id)arg1 ; +(long long)weekOfYearFromDate:(id)arg1 ; +(long long)dayFromDate:(id)arg1 ; +(long long)hourFromDate:(id)arg1 ; +(id)dateByAddingMonths:(long long)arg1 toDate:(id)arg2 ; +(id)dateByAddingYears:(long long)arg1 toDate:(id)arg2 ; +(id)dateByAddingWeeksOfYear:(long long)arg1 toDate:(id)arg2 ; @end
Diablohu/WhoCallsTheFleet-React
src/api/preferences/index.js
<filename>src/api/preferences/index.js // import localforage from 'localforage/dist/localforage.min.js' import localforage from './localforage'; import defaults from './defaults'; let isInit = false; localforage.config({ name: 'WhoCallsTheFleet', }); const prefs = {}; const store = {}; Object.defineProperty(prefs, 'init', { enumerable: false, writable: false, value: () => { if (__CLIENT__ && !isInit) { if (__DEV__) console.log('Preferences initiation...'); const remainDefaults = Object.assign({}, defaults); const keys = []; const keysToDelete = []; for (const key in defaults) { keys.push(key); } const define = (key, value) => { // prefs[key] = value store[key] = value; Object.defineProperty(prefs, key, { enumerable: true, get: () => store[key], set: (value) => { store[key] = value; localforage.setItem(key, value); }, }); }; return localforage .iterate((value, key /*, iterationNumber*/) => { // console.log('iterate', key, value) define(key, value); if (!keys.includes(key)) keysToDelete.push(key); delete remainDefaults[key]; }) .then( () => new Promise((resolve) => { let chain = new Promise((resolve) => resolve()); keysToDelete.forEach((key) => { chain = chain.then(() => localforage.removeItem(key) ); }); chain = chain.then(() => resolve()); }) ) .then( () => new Promise((resolve) => { let chain = new Promise((resolve) => resolve()); for (const key in remainDefaults) { chain = chain .then(() => localforage.setItem( key, remainDefaults[key] ) ) .then(() => { define(key, remainDefaults[key]); return true; }); } chain = chain.then(() => resolve()); }) ) .then(() => { isInit = true; if (__DEV__) console.log('Preferences initiation complete!', prefs); }) .catch((err) => { isInit = true; console.log('Preferences initiation error!', err); }); } else { isInit = true; } }, }); export default prefs;
fuxs/aepctl
cmd/helper/file.go
/* Package helper consists of helping functions. Copyright 2021 <NAME> 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 helper import ( "bufio" "encoding/json" "os" "path/filepath" "strings" "github.com/spf13/cobra" "gopkg.in/yaml.v2" ) // Decoder is either a YAML or JSON decoder type Decoder interface { Decode(v interface{}) error } // FileConfig provides the path and format of a file type FileConfig struct { Path string Format string } // AddFileFlag adds the required file flags to the passed command func (c *FileConfig) AddFileFlag(cmd *cobra.Command) { flags := cmd.PersistentFlags() flags.StringVarP(&c.Path, "file", "f", "", "a file") flags.StringVarP(&c.Format, "input", "i", "yaml", "the input format (yaml|yaml-raw)") } // AddMandatoryFileFlag adds the required file flags to the passed command. --file becomes mandatory. func (c *FileConfig) AddMandatoryFileFlag(cmd *cobra.Command) { c.AddFileFlag(cmd) if err := cmd.MarkPersistentFlagRequired("file"); err != nil { fatal("Error in AddMandatoryFileFlag", 1) } } // IsYAML checks if format is YAML func (c *FileConfig) IsYAML() bool { return strings.ToLower(c.Format) == "yaml" } // IsSet returns true if the path is set func (c *FileConfig) IsSet() bool { return len(c.Path) > 0 } // Open opens the file and returns a *FileIterator func (c *FileConfig) Open() (*FileIterator, error) { if !c.IsSet() { return nil, nil } file := os.Stdin result := &FileIterator{} if c.Path != "-" { var err error if file, err = os.Open(c.Path); err != nil { return nil, err } } reader := bufio.NewReader(file) if strings.ToLower(filepath.Ext(c.Path)) == "json" { result.Decoder = json.NewDecoder(reader) } else { dec := yaml.NewDecoder(reader) //dec.SetStrict(true) result.Decoder = dec } return result, nil } // FileIterator helps iterating multiple YAML documents in one file type FileIterator struct { Decoder Decoder } // Load loads the next available document in the file func (c *FileIterator) Load(obj interface{}) error { if c.Decoder != nil { err := c.Decoder.Decode(obj) if err != nil { return err } } return nil }
ace53thntu/cookie-sync-demo
src/components/shop/LeftBanner.js
<filename>src/components/shop/LeftBanner.js import { Col, Divider, Row } from "antd"; import Link from "next/link"; import Container from "../other/Container"; export default function LefBanner({ containerType }) { return ( <div className="banners"> <Container type={containerType}> <Row gutter={30}>ahehehe</Row> </Container> </div> ); }
impastasyndrome/Lambda-Resource-Static-Assets
2-content/15-Sandbox/javascript101-master/types/7.1_builtinTypes.js
//JavaScript 有七种内置类型: // • 空值( null ) // • 未定义( undefined ) // • 布尔值( boolean ) // • 数字( number ) // • 字符串( string ) // • 对象( object ) // • 符号( symbol ,ES6 中新增) //除对象之外,其他统称为“基本类型”。 typeof undefined === "undefined"; // true typeof true === "boolean"; // true typeof 56 === "number"; // true typeof "abc" === "string"; // true typeof { life: 11 } === "object"; // true // ES6中新加入的类型 typeof Symbol() === "symbol"; // true // null 比较特殊 typeof null === "object"; // true // function (函数)也是 JavaScript 的一个内置类型。它实际上是 object 的一个“子类型”。 typeof function a() { /* .. */ } === "function"; // true function a(b, c) { /* .. */ } // 函数对象的 length 属性是其声明的参数的个数: a.length; // 2 typeof [1, 2, 3] === "object"; // true // 数组也是对象。它也是 object 的一个“子类型”。 ///////////////////////////////////////////////////////////////////////// // JavaScript 中的变量是没有类型的,只有值才有。变量可以随时持有任何类型的值。 var a = 42; typeof a; // "number" a = true; typeof a; // "boolean" ///////////////////////////////////////////////////////////////////////// // undefined 和 undeclared // 已在作用域中声明但还没有赋值的变量,是 undefined 的。 // 相反,还没有在作用域中声明过的变量,是 undeclared 的。 // 变量在未持有值的时候为 undefined 。此时 typeof 返回 "undefined" var a; typeof a; // "undefined" var a; a; // undefined -->undefined b; // ReferenceError: b is not defined -->undeclared // “undefined”和“is not defined” 是两回事 // typeof 特殊的安全防范机制(阻止报错)。 var a; typeof a; // "undefined" typeof b; // "undefined"
jklwan/NoteApplication
app/src/main/java/com/chends/note/business/ViewBindingActivity.java
package com.chends.note.business; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import com.chends.note.R; import com.chends.note.base.BaseActivity; import com.chends.note.databinding.ActivityViewBindingBinding; /** * @author cds created on 2019/10/27. */ public class ViewBindingActivity extends BaseActivity<ActivityViewBindingBinding> { @Override protected void initViewBinding() { viewBinding = ActivityViewBindingBinding.inflate(LayoutInflater.from(this)); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); viewBinding.text.setText("view binding"); viewBinding.image.setImageResource(R.color.black); } }
Stanford-PERTS/triton
src/components/SceneTitle/index.js
<reponame>Stanford-PERTS/triton import React from 'react'; import Section from 'components/Section'; export default props => <Section type="scene" {...props} />;
yuanping/HackerRank_solutions
Cracking the Coding Interview/Techniques, Concepts/Recursion - Davis' Staircase/solution.rb
<reponame>yuanping/HackerRank_solutions #!/bin/ruby require 'json' require 'stringio' # Complete the stepPerms function below. # def stepPerms(n) # cache = {0 => 1} # ways(n, cache) # end # # def ways(n, cache) # return 0 if n < 0 # return cache[n] if cache[n] # # total = ways(n - 1, cache) + ways(n - 2, cache) + ways(n - 3, cache) # cache[n] = total # total # end def stepPerms(n) ways = [] ways[0] = 1 ways[1] = 1 ways[2] = 2 (3..n).each do |i| ways[i] = ways[i - 1] + ways[i - 2] + ways[i - 3] end ways[n] end fptr = File.open(ENV['OUTPUT_PATH'], 'w') s = gets.to_i s.times do |s_itr| n = gets.to_i res = stepPerms n fptr.write res fptr.write "\n" end fptr.close()
ansi88/weixin4j
weixin4j-serverX/src/main/java/com/zone/weixin4j/controller/WxController.java
package com.zone.weixin4j.controller; import com.zone.weixin4j.exception.HttpResponseException; import com.zone.weixin4j.exception.MessageInterceptorException; import com.zone.weixin4j.exception.WeixinException; import com.zone.weixin4j.response.WeixinResponse; import com.zone.weixin4j.service.WeiXin4jContextAware; import com.zone.weixin4j.service.WxService; import com.zone.weixin4j.util.AesToken; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; /** * Created by Yz on 2017/3/14. * WxController * Spring 主入口需继承的类 / 模版 */ public abstract class WxController { private final Log logger = LogFactory.getLog(getClass()); private final String defaultCharset = "UTF-8"; @Autowired protected WxService wxService; @Autowired protected WeiXin4jContextAware weiXin4jContextAware; protected abstract void doRequest(HttpServletRequest request, HttpServletResponse response, @RequestParam(required = false) String encrypt_type, @RequestParam(required = false) String echostr, @RequestParam(required = false) String timestamp, @RequestParam(required = false) String nonce, @RequestParam(required = false) String signature, @RequestParam(required = false) String msg_signature, @RequestParam(required = false) String weixin_id); protected void processMessage(HttpServletRequest request, HttpServletResponse response, String encrypt_type, String echostr, String timestamp, String nonce, String signature, String msg_signature, String weixin_id) { String messageContent = getMessageContent(request); logger.info("read original message {}" + messageContent); AesToken aesToken = weiXin4jContextAware.getAesTokenMap().get(StringUtils.isEmpty(weixin_id) ? "" : weixin_id); WeixinResponse weixinResponse = null; try { weixinResponse = wxService.processRequest(request.getRequestURI(), encrypt_type, echostr, timestamp, nonce, signature, msg_signature, messageContent, aesToken, request); response.setCharacterEncoding(defaultCharset); writeMessage(wxService.transferResponse(weixinResponse), response); } catch (WeixinException e) { logger.error("errorCode : " + e.getErrorCode() + " , errorMsg : " + e.getErrorMsg(), e.getCause()); e.printStackTrace(); writeMessage("", response); } catch (HttpResponseException e) { logger.error(e.getMessage(), e.getCause()); response.setStatus(e.getHttpResponseStatus().getCode()); response.setContentType(e.getHttpResponseStatus().getReasonPhrase()); writeMessage("", response); } catch (MessageInterceptorException e) { logger.error("errorCode : " + e.getErrorCode() + " , errorMsg : " + e.getErrorMsg(), e.getCause()); writeMessage("", response); } } protected String getMessageContent(HttpServletRequest request) { try { // 从request中取得输入流 InputStream inputStream = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, defaultCharset)); String line; StringBuilder buf = new StringBuilder(); while ((line = reader.readLine()) != null) { buf.append(line); } reader.close(); inputStream.close(); return buf.toString(); } catch (IOException e) { logger.error(e.getMessage(), e.getCause()); } return ""; } protected void writeMessage(String result, HttpServletResponse response) { response.setContentType("application/xml"); response.setCharacterEncoding("UTF-8"); try { PrintWriter writer = response.getWriter(); writer.write(result); writer.flush(); writer.close(); } catch (IOException e) { logger.error(e.getMessage(), e.getCause()); } } public void setWxService(WxService wxService) { this.wxService = wxService; } public void setWeiXin4jContextAware(WeiXin4jContextAware weiXin4jContextAware) { this.weiXin4jContextAware = weiXin4jContextAware; } public WeiXin4jContextAware getWeiXin4jContextAware() { return weiXin4jContextAware; } }
jxjnjjn/chromium
src/content/browser/resources/indexed_db/indexeddb_internals.js
<gh_stars>1-10 // Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. cr.define('indexeddb', function() { 'use strict'; function initialize() { chrome.send('getAllOrigins'); } function onOriginsReady(origins, path) { var template = jstGetTemplate('indexeddb-list-template'); var container = $('indexeddb-list'); container.appendChild(template); jstProcess(new JsEvalContext({ idbs: origins, path: path}), template); } return { initialize: initialize, onOriginsReady: onOriginsReady, }; }); document.addEventListener('DOMContentLoaded', indexeddb.initialize);
535205856/summerframework
summerframework-monitor/platform-monitor-core/src/main/java/com/bkjk/platform/monitor/metric/MicrometerUtil.java
package com.bkjk.platform.monitor.metric; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import org.springframework.util.StringUtils; import com.bkjk.platform.monitor.util.RequestUtil; import com.hazelcast.core.IMap; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.Metrics; import io.micrometer.core.instrument.Tag; import io.micrometer.core.instrument.Tags; import io.micrometer.core.instrument.binder.cache.HazelcastCacheMetrics; import io.micrometer.core.lang.Nullable; public class MicrometerUtil { private static final RequestUtil requestUtil = new RequestUtil(); private static final Tag EXCEPTION_NONE = tag("exception", "none"); private static final String METHOD_WITH_URL_COUNT = "method_with_url_count"; private static final String METHOD_WITH_URL_TIMER = "method_with_url_timer"; private static final String TRACE_EVENT_COUNT = "trace_event_count"; public final static String EMPTY_STRING = "none"; private static ConcurrentHashMap<String, Tag> tagCache; public static final Tag TAG_STATUS_KEY_TRUE = tag("status_key", "true"); public static final Tag TAG_STATUS_KEY_FALSE = tag("status_key", "false"); public static void eventCount(String event) { String url = requestUtil.getCurrentRequestUrlOrDefault("none"); Metrics.counter(TRACE_EVENT_COUNT, "event", event).increment(); } public static Tag exception(@Nullable Throwable exception) { if (exception == null) { return EXCEPTION_NONE; } String simpleName = exception.getClass().getSimpleName(); return tag("exception", simpleName.isEmpty() ? exception.getClass().getName() : simpleName); } public static Tags exceptionAndStatusKey(@Nullable Throwable exception) { return Tags.of(exception(exception), statusKey(exception)); } public static final long getNanosecondsAfter(long start) { return Metrics.globalRegistry.config().clock().monotonicTime() - start; } public static void methodCount(String methodName, Throwable throwable) { String url = requestUtil.getCurrentRequestUrlOrDefault("none"); Tags tags = Tags.of(Tag.of("method", methodName)).and(MicrometerUtil.exceptionAndStatusKey(throwable)); Metrics.counter(METHOD_WITH_URL_COUNT, tags).increment(); } public static void methodTimer(String methodName, long time, Throwable throwable) { String url = requestUtil.getCurrentRequestUrlOrDefault("none"); Tags tags = Tags.of(Tag.of("method", methodName)).and(MicrometerUtil.exceptionAndStatusKey(throwable)); Metrics.timer(METHOD_WITH_URL_TIMER, tags).record(time, TimeUnit.MILLISECONDS); } public static final void monitor(IMap iMap, String... tags) { HazelcastCacheMetrics.monitor(registry(), iMap, tags); } public static final long monotonicTime() { return Metrics.globalRegistry.config().clock().monotonicTime(); } public static final MeterRegistry registry() { return Metrics.globalRegistry; } public static Tag statusKey(@Nullable Throwable exception) { return exception == null ? TAG_STATUS_KEY_TRUE : TAG_STATUS_KEY_FALSE; } public static final Tag tag(String key, String value) { if (tagCache == null) { tagCache = new ConcurrentHashMap<>(); } if (StringUtils.isEmpty(value)) { value = EMPTY_STRING; } String cacheKey = key + value; Tag catchTag = tagCache.get(cacheKey); if (null != catchTag) { return catchTag; } Tag tag = Tag.of(key, value); tagCache.put(cacheKey, tag); return tag; } public static final Tags tags(String... keyValues) { if (keyValues.length == 0) { return Tags.empty(); } if (keyValues.length % 2 == 1) { throw new IllegalArgumentException("size must be even, it is a set of key=value pairs"); } Tag[] tags = new Tag[keyValues.length / 2]; for (int i = 0; i < keyValues.length; i += 2) { tags[i / 2] = tag(keyValues[i], keyValues[i + 1]); } return Tags.of(tags); } }
FMMazur/skift
userspace/utilities/piano.cpp
<gh_stars>1-10 #include <libsystem/io/Filesystem.h> #include <libsystem/io/Stream.h> #include <libio/Path.h> // piano utility takes a file that has notes data for eg: // echo "c5d5e5g5a5b5c6" > new.txt // piano new.txt struct spkr { int length; int frequency; }; void note(int length, int frequency, Stream *spkrstream) { struct spkr s = { .length = length, .frequency = frequency, }; stream_write(spkrstream, &s, sizeof(s)); } int main(int argc, char *argv[]) { if (argc == 1) { stream_format(err_stream, "%s: Missing notes file operand\n Info : Write notes eg \"c5e5g5\" to a file and supply that files' path to this utility \n", argv[0]); return PROCESS_FAILURE; } CLEANUP(stream_cleanup) Stream *streamin = stream_open(argv[1], OPEN_READ); if (handle_has_error(streamin)) { return handle_get_error(streamin); } CLEANUP(stream_cleanup) Stream *streamout = stream_open("/Devices/speaker", OPEN_WRITE | OPEN_CREATE); if (handle_has_error(streamout)) { return handle_get_error(streamout); } char c; char num; int read = 0; while ((read = stream_read(streamin, &c, 1)) != 0) { read = stream_read(streamin, &num, 1); switch (c) { case 'c': switch (num) { case '5': note(500, 523, streamout); break; case '6': note(500, 1046, streamout); break; case '7': note(500, 2093, streamout); break; case '8': note(500, 4186, streamout); break; } break; case 'd': switch (num) { case '5': note(500, 587, streamout); break; case '6': note(500, 1175, streamout); break; case '7': note(500, 2349, streamout); break; } break; case 'e': switch (num) { case '5': note(500, 659, streamout); break; case '6': note(500, 1319, streamout); break; case '7': note(500, 2637, streamout); break; } break; case 'f': switch (num) { case '5': note(500, 698, streamout); break; case '6': note(500, 1397, streamout); break; case '7': note(500, 2793, streamout); break; } break; case 'g': switch (num) { case '5': note(500, 784, streamout); break; case '6': note(500, 1568, streamout); break; case '7': note(500, 3136, streamout); break; } break; case 'a': switch (num) { case '5': note(500, 880, streamout); break; case '6': note(500, 1760, streamout); break; case '7': note(500, 3520, streamout); break; } break; case 'b': switch (num) { case '5': note(500, 988, streamout); break; case '6': note(500, 1976, streamout); break; case '7': note(500, 3951, streamout); break; } break; } } return 0; }
Yasujizr/rss-reader
src/base/favicon-service/cache.js
<reponame>Yasujizr/rss-reader import assert from '/src/base/assert.js'; import * as indexeddb from '/src/base/indexeddb.js'; // NOTE: this file is undergoing development and is unstable!!!! DO NOT USE! // This module provides storage functionality for the favicon service. // // This module is considered private to favicon-service.js and its test module. // Do not directly import this module. Only access cache functionality via the // service. const DEFAULT_NAME = 'favicon'; const DEFAULT_VERSION = 1; const DEFAULT_TIMEOUT = 500; export function Entry() { this.origin = undefined; this.icon_url = undefined; this.expires = undefined; this.failures = 0; } // Return a promise that resolves to a connection export function open( name = DEFAULT_NAME, version = DEFAULT_VERSION, timeout = DEFAULT_TIMEOUT) { return indexeddb.open(name, version, on_upgrade_needed, timeout); } // Create or upgrade the database function on_upgrade_needed(event) { const request = event.target; const conn = request.result; const txn = request.transaction; if (event.oldVersion) { console.debug( 'Upgrading database from %d to %d', event.oldVersion, conn.version); } else { console.debug('Creating database with version %d', conn.version); } // This code does not make use of store at the moment, but its coded so as to // be easy to extend. let store; if (event.oldVersion) { store = txn.objectStore('entries'); } else { store = conn.createObjectStore('entries', {keyPath: 'origin'}); } } // Remove all data from the database export function clear(conn) { return new Promise((resolve, reject) => { const txn = conn.transaction('entries', 'readwrite'); txn.oncomplete = resolve; txn.onerror = event => reject(event.target.error); txn.objectStore('entries').clear(); }); } // Removes expired entries from the database // NOTE: unsure how this will look. For now I am focusing on using the new // expires property approach. // TODO: the lookup code should check expires and consider uncached if expired, // so that it avoids finding expired-but-not-yet-cleared entries, because the // lookup should not be concerned with removing expired and paying that cost export function compact(conn) { return new Promise((resolve, reject) => { const txn = conn.transaction('entries', 'readwrite'); txn.oncomplete = resolve; txn.onerror = event => reject(event.target.error); const store = txn.objectStore('entries'); const request = store.openCursor(); const now = new Date(); request.onsuccess = event => { const cursor = event.target.result; if (!cursor) { return; } const entry = cursor.value; if (entry.expires && entry.expires > now) { console.debug('Deleting expired entry', entry); cursor.delete(); } cursor.continue(); }; }); } // Find and return an entry corresponding to the given origin. Note this does // not care if expired. |origin| must be a URL. export function find_entry(conn, origin) { return new Promise((resolve, reject) => { // For convenience, no-op disconnected checks if (!conn) { resolve(); return; } if (!origin || !origin.href) { reject(new TypeError('Invalid origin ' + origin)); return; } const txn = conn.transaction('entries'); const store = txn.objectStore('entries'); const request = store.get(origin.href); request.onsuccess = _ => resolve(request.result); request.onerror = _ => reject(request.error); }); } export function put_entry(conn, entry) { return new Promise((resolve, reject) => { if (!conn) { resolve(); return; } if (!entry || typeof entry !== 'object') { return reject(new TypeError('Invalid entry parameter ' + entry)); } if (!entry.origin) { return reject(new TypeError('Missing origin property ' + entry)); } let result; const txn = conn.transaction('entries', 'readwrite'); txn.oncomplete = _ => resolve(result); txn.onerror = event => reject(event.target.error); const store = txn.objectStore('entries'); const request = store.put(entry); request.onsuccess = _ => result = request.result; }); }
jeremylarner/keyteki-1
test/server/cards/03-WC/IgonTheGreen.spec.js
describe('Igon The Green', function () { describe("Igon The Green's ability", function () { beforeEach(function () { this.setupTest({ player1: { house: 'brobnar', hand: ['igon-the-terrible', 'igon-the-terrible'], inPlay: ['igon-the-green'] }, player2: { inPlay: ['mother', 'troll', 'dextre'] } }); this.igonTheTerrible1 = this.player1.hand[0]; this.igonTheTerrible2 = this.player1.hand[1]; }); it('should purge Igon the Green and not return any Igon The Terrible', function () { this.player1.fightWith(this.igonTheGreen, this.troll); expect(this.igonTheGreen.location).toBe('purged'); }); it('should purge Igon the Green and not return Igon The Terrible since it is archived', function () { this.player1.moveCard(this.igonTheTerrible1, 'archives'); expect(this.igonTheTerrible1.location).toBe('archives'); expect(this.igonTheTerrible2.location).toBe('hand'); this.player1.fightWith(this.igonTheGreen, this.troll); expect(this.igonTheGreen.location).toBe('purged'); }); it('should purge Igon the Green and return Igon The Terrible to hand', function () { this.player1.playCreature(this.igonTheTerrible1); expect(this.igonTheTerrible1.location).toBe('discard'); expect(this.igonTheTerrible2.location).toBe('hand'); this.player1.fightWith(this.igonTheGreen, this.troll); expect(this.igonTheGreen.location).toBe('purged'); expect(this.igonTheTerrible1.location).toBe('hand'); expect(this.igonTheTerrible2.location).toBe('hand'); }); it('should purge Igon the Green and return an Igon The Terrible to hand', function () { this.player1.playCreature(this.igonTheTerrible1); this.player1.playCreature(this.igonTheTerrible2); expect(this.igonTheTerrible1.location).toBe('discard'); expect(this.igonTheTerrible2.location).toBe('discard'); this.player1.fightWith(this.igonTheGreen, this.troll); expect(this.igonTheGreen.location).toBe('purged'); expect(this.igonTheTerrible1.location).toBe('discard'); expect(this.igonTheTerrible2.location).toBe('hand'); }); it('should remove ward from Igon the Green and not return any Igon The Terrible', function () { this.player1.playCreature(this.igonTheTerrible1); this.player1.playCreature(this.igonTheTerrible2); expect(this.igonTheTerrible1.location).toBe('discard'); expect(this.igonTheTerrible2.location).toBe('discard'); this.igonTheGreen.ward(); this.player1.fightWith(this.igonTheGreen, this.troll); expect(this.igonTheGreen.location).toBe('play area'); expect(this.igonTheTerrible1.location).toBe('discard'); expect(this.igonTheTerrible2.location).toBe('discard'); }); }); });
mmaico/ddd-reflection
src/test/java/com/github/mmaico/test_objects/hibernate_entities/Document.java
<reponame>mmaico/ddd-reflection package com.github.mmaico.test_objects.hibernate_entities; public class Document { public enum DocumentTypeEnum {PASSPORT, SOCIAL_SECURITY_CARD} private String document; private DocumentTypeEnum type; public Document(){} public Document(String document, DocumentTypeEnum type) { this.document = document; this.type = type; } public String getDocument() { return document; } public void setDocument(String document) { this.document = document; } public DocumentTypeEnum getType() { return type; } public void setType(DocumentTypeEnum type) { this.type = type; } }
dew-uff/phoenix
src/main/java/gems/ic/uff/br/modelo/algorithm/AbstractAlgorithm.java
package gems.ic.uff.br.modelo.algorithm; import gems.ic.uff.br.modelo.similar.Similar; import gems.ic.uff.br.settings.SettingsHelper; public abstract class AbstractAlgorithm<VALUE extends Similar> { float similarThreshold = SettingsHelper.getSimilarityThreshold(); protected abstract int lengthOfX(); protected abstract int lengthOfY(); protected abstract VALUE valueOfX(int index); protected abstract VALUE valueOfY(int index); private VALUE valueOfXInternal(int i) { return valueOfX(i - 1); } private VALUE valueOfYInternal(int j) { return valueOfY(j - 1); } protected float similar(VALUE x1, VALUE y1) { float similarity = 0; if (x1 != null && y1 != null) { similarity = x1.similar(y1).getSimilarity(); } return similarity; } protected boolean isXYSimilar(int i, int j) { float similarity = similar(valueOfXInternal(i), valueOfYInternal(j)); if (similarity == 0) { return false; } return similarity >= similarThreshold; } public abstract float similaridade(); }
vadymshymko/react-football-app
src/common/reducers/players.js
import { FETCH_PLAYER_REQUEST, FETCH_PLAYER_SUCCESS, FETCH_PLAYER_FAILURE, } from 'actionsTypes'; import createReducer from './createReducer'; const initialState = {}; const players = createReducer(initialState, { [FETCH_PLAYER_REQUEST]: (state, action) => ({ ...state, [action.payload.id]: { isInitialized: false, ...(state[action.payload.id] || {}), id: action.payload.id, errorCode: null, isFetching: true, isRequestFailed: false, }, }), [FETCH_PLAYER_SUCCESS]: (state, action) => ({ ...state, [action.payload.id]: { ...state[action.payload.id], ...action.payload, isFetching: false, isInitialized: true, }, }), [FETCH_PLAYER_FAILURE]: (state, action) => ({ ...state, [action.payload.id]: { ...state[action.payload.id], errorCode: action.payload.errorCode, isFetching: false, isRequestFailed: true, isInitialized: true, }, }), }); export default players;
librarysong/practice-cloud
practice-master/src/main/java/cn/swf/practice/practicemaster/controller/IndexController.java
package cn.swf.practice.practicemaster.controller; import cn.hutool.crypto.digest.MD5; import cn.swf.practice.pracricecommon.utils.JsonResultUtil; import cn.swf.practice.practicemaster.book.entity.TUser; import cn.swf.practice.practicemaster.book.mapper.TUserMapper; import cn.swf.practice.practicemaster.entity.User; import cn.swf.practice.practicemaster.mapper.UserMapper; import cn.swf.practice.practicemaster.remote.TestFeign; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * Created by 宋维飞 * 2019/8/1 9:38 */ @RestController @Slf4j public class IndexController { @Autowired private UserMapper userMapper; @Autowired private TUserMapper tUserMapper; @Autowired private TestFeign testFeign; @RequestMapping("/") public String Index() { log.info("practice-master is startup!"); return "practice-master is startup!"; } @RequestMapping("practice/save") public String testDataSourceP() { User user = new User(); user.setUserName("practice"); user.setPassWord("<PASSWORD>"); userMapper.insert(user); return JsonResultUtil.getSuccessJson().toJSONString(); } @RequestMapping("/practice/get") public String getDataSourceP(String name) { User user = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", name)); return JsonResultUtil.getSuccessJson(user).toJSONString(); } @RequestMapping("book/save") public String testDataSourceB() { TUser user = new TUser(); user.setNickname("book"); user.setPassword("<PASSWORD>"); tUserMapper.insert(user); return JsonResultUtil.getSuccessJson().toJSONString(); } @RequestMapping("/book/get") public String getDataSourceB(String name) { TUser user = tUserMapper.selectOne(new QueryWrapper<TUser>().eq("nickname", name)); return JsonResultUtil.getSuccessJson(user).toJSONString(); } @RequestMapping("/feign") public String FeignTest(String name) { log.info("zuul 调用了"); String feignTest = testFeign.hello(name); return JsonResultUtil.getSuccessJson(feignTest).toJSONString(); } public static void main(String[] args) { String queryString = appendQueryString(); System.out.println(queryString); } private static String appendQueryString() { Map<String, String> params = new HashMap<>(); params.put("uuid", UUID.randomUUID().toString()); params.put("sign", new MD5().digestHex("test")); return "https://www.baidu.com" + params.entrySet().stream().map(i -> i.getKey() + "=" + i.getValue()).reduce((p1, p2) -> p1 + "&" + p2).map(s -> "?" + s).orElse(""); } }
126RockStar/Feeding-fish-view
src/components/LiveTabComponents/global_consts.js
<gh_stars>1-10 module.exports = 45; // The offset of the title div - Set in the draggable.css
IYoreI/Algorithm
Codes/yore/offer2/Offer105.java
package com.yore.offer2; import java.util.Deque; import java.util.LinkedList; /** * @author Yore * @date 2022/2/23 16:42 * @description */ public class Offer105 { public static void main(String[] args) { Offer105 o = new Offer105(); int[][] grid = new int[][]{{0,0,1,0,0,0,0,1,0,0,0,0,0},{0,0,0,0,0,0,0,1,1,1,0,0,0}, {0,1,1,0,1,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,1,0,1,0,0},{0,1,0,0,1,1,0,0,1,1,1,0,0}, {0,0,0,0,0,0,0,0,0,0,1,0,0},{0,0,0,0,0,0,0,1,1,1,0,0,0},{0,0,0,0,0,0,0,1,1,0,0,0,0}}; System.out.println(o.maxAreaOfIsland(grid)); } public int maxAreaOfIsland(int[][] grid) { int maxArea = 0; int m = grid.length; int n = grid[0].length; int[][] cal = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (cal[i][j] == 1) { continue; } if (grid[i][j] == 0) { cal[i][j] = 1; continue; } cal[i][j] = 1; maxArea = Math.max(maxArea, searchArea(grid, i, j, cal)); System.out.println(maxArea); } } return maxArea; } public int searchArea(int[][] grid, int row, int col, int[][] cal) { int curArea = 0; int m = grid.length; int n = grid[0].length; Deque<Candidate> queue = new LinkedList<>(); queue.offerLast(new Candidate(row, col)); while (!queue.isEmpty()) { Candidate cad = queue.pollFirst(); int r = cad.x; int c = cad.y; curArea++; if (r - 1 >= 0 && grid[r - 1][c] == 1 && cal[r - 1][c] != 1) { cal[r - 1][c] = 1; queue.offerLast(new Candidate(r - 1, c)); } if (r + 1 < m && grid[r + 1][c] == 1 && cal[r + 1][c] != 1) { cal[r + 1][c] = 1; queue.offerLast(new Candidate(r + 1, c)); } if (c - 1 >= 0 && grid[r][c - 1] == 1 && cal[r][c - 1] != 1) { cal[r][c - 1] = 1; queue.offerLast(new Candidate(r, c - 1)); } if (c + 1 < n && grid[r][c + 1] == 1 && cal[r][c + 1] != 1) { cal[r][c + 1] = 1; queue.offerLast(new Candidate(r, c + 1)); } } return curArea; } class Candidate { int x; int y; Candidate(int _x, int _y) { this.x = _x; this.y = _y; } } }
SlimKatLegacy/android_external_chromium_org
content/browser/service_worker/service_worker_registration.cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/service_worker/service_worker_registration.h" #include "content/public/browser/browser_thread.h" namespace content { ServiceWorkerRegistration::ServiceWorkerRegistration(const GURL& pattern, const GURL& script_url, int64 registration_id) : pattern_(pattern), script_url_(script_url), registration_id_(registration_id), is_shutdown_(false) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); } ServiceWorkerRegistration::~ServiceWorkerRegistration() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(is_shutdown_); } void ServiceWorkerRegistration::Shutdown() { DCHECK(!is_shutdown_); if (active_version_) active_version_->Shutdown(); active_version_ = NULL; if (pending_version_) pending_version_->Shutdown(); pending_version_ = NULL; is_shutdown_ = true; } void ServiceWorkerRegistration::ActivatePendingVersion() { active_version_->Shutdown(); active_version_ = pending_version_; pending_version_ = NULL; } } // namespace content
ScalablyTyped/SlinkyTyped
s/sip_dot_js/src/main/scala/typingsSlinky/sipJs/messageMod.scala
<reponame>ScalablyTyped/SlinkyTyped package typingsSlinky.sipJs import typingsSlinky.sipJs.coreMod.IncomingRequestMessage import typingsSlinky.sipJs.methodsMessageMod.IncomingMessageRequest import typingsSlinky.sipJs.outgoingResponseMod.ResponseOptions import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object messageMod { @JSImport("sip.js/lib/api/message", "Message") @js.native class Message protected () extends StObject { /** @internal */ def this(incomingMessageRequest: IncomingMessageRequest) = this() /** Accept the request. */ def accept(): js.Promise[Unit] = js.native def accept(options: ResponseOptions): js.Promise[Unit] = js.native var incomingMessageRequest: js.Any = js.native /** Reject the request. */ def reject(): js.Promise[Unit] = js.native def reject(options: ResponseOptions): js.Promise[Unit] = js.native /** Incoming MESSAGE request message. */ def request: IncomingRequestMessage = js.native } }
xmil9/geomcpp
poisson_disc_sampling.h
// // geomcpp // Generation of evenly distributed points. // // Aug-2020, <NAME> // MIT license // #pragma once #include "point2.h" #include "rect.h" #include "ring.h" #include "essentutils/rand_util.h" #include <cmath> #include <optional> #include <vector> namespace geom { namespace internals { /////////////////// using SampleIdx = int; /////////////////// // Grid that divides the domain into cells each containing either the index of a // sample that lies within the cell or an empty marker. Allows to quickly lookup // if another sample is nearby. template <typename T> class BackgroundGrid { public: BackgroundGrid(const Rect<T>& domain, T minDist); // Inserts the given index of a given sample into the grid. void insert(const Point2<T>& sample, SampleIdx sampleIdx); // Checks whether another sample is within the minimal distance of a given // test point. bool haveSampleWithinMinDistance(const Point2<T>& test) const; private: using Grid = std::vector<std::vector<SampleIdx>>; using CellIdx = int; static CellIdx calcGridRows(const Rect<T>& domain, T cellSize); static CellIdx calcGridColumns(const Rect<T>& domain, T cellSize); CellIdx calcRow(T y) const; CellIdx calcCol(T x) const; bool isCellOccupied(CellIdx r, CellIdx c) const; private: static constexpr T SqrtOfTwo = static_cast<T>(1.414213562373); static constexpr SampleIdx EmptyCell = -1; const Rect<T> m_domain; const T m_minDist; T m_cellSize; Grid m_grid; }; template <typename T> BackgroundGrid<T>::BackgroundGrid(const Rect<T>& domain, T minDist) : m_domain{domain}, m_minDist{minDist}, // Pick cell size so that when checking whether another point is within the // min distance of a given point only a small number of cells has to be // checked. // Using minDist/sqrt(2) means that the diagonal of a cell is minDist long: // len(diagonal) = sqrt(cellSize^2 + cellSize^2) // = sqrt((minDist/sqrt(2))^2 + (minDist/sqrt(2))^2) // = sqrt(minDist^2 / 2 + minDist^2 / 2) // = sqrt(minDist^2) // = minDist // Therefore, for a given point only the following cells need to be checked: // - cell of point itself // - 2 cells in each direction (because cellSize < minDist < 2*cellSize) // - 1 cell in each diagonal (because len(diagonal) == minDist) m_cellSize{minDist / SqrtOfTwo}, m_grid(calcGridRows(m_domain, m_cellSize), std::vector<SampleIdx>(calcGridColumns(m_domain, m_cellSize), EmptyCell)) { } template <typename T> void BackgroundGrid<T>::insert(const Point2<T>& sample, SampleIdx sampleIdx) { const CellIdx r = calcRow(sample.y()); const CellIdx c = calcCol(sample.x()); m_grid[r][c] = sampleIdx; } template <typename T> bool BackgroundGrid<T>::haveSampleWithinMinDistance(const Point2<T>& test) const { const CellIdx testRow = calcRow(test.y()); const CellIdx testCol = calcCol(test.x()); const CellIdx topMostRow = calcRow(test.y() - m_minDist); const CellIdx bottomMostRow = calcRow(test.y() + m_minDist); const CellIdx leftMostCol = calcCol(test.x() - m_minDist); const CellIdx rightMostCol = calcCol(test.x() + m_minDist); // Depending on where within its cell the test point is located we have to // check one or two cells into each direction, e.g. if the test point is // located in the top, left quadrant of its cell we have to check two cells // to the left and top of the test cell but only one cell to the right and // bottom. We have to do this for a strip of cells three cells thick // horizontally and vertically. // Proceed from the top most row to the bottom most. // If necessary, row of cells two cells above the test cell. if (topMostRow < testRow - 1) { for (CellIdx c = testCol - 1; c <= testCol + 1; ++c) if (isCellOccupied(topMostRow, c)) return true; } // Center block of rows. for (CellIdx r = testRow - 1; r <= testRow + 1; ++r) { for (CellIdx c = leftMostCol; c <= rightMostCol; ++c) if (isCellOccupied(r, c)) return true; } // If necessary, row of cells two cells below the test cell. if (bottomMostRow > testRow + 1) { for (CellIdx c = testCol - 1; c <= testCol + 1; ++c) if (isCellOccupied(bottomMostRow, c)) return true; } return false; } template <typename T> typename BackgroundGrid<T>::CellIdx BackgroundGrid<T>::calcGridRows(const Rect<T>& domain, T cellSize) { return static_cast<CellIdx>(std::ceil(domain.height() / cellSize)); } template <typename T> typename BackgroundGrid<T>::CellIdx BackgroundGrid<T>::calcGridColumns(const Rect<T>& domain, T cellSize) { return static_cast<CellIdx>(std::ceil(domain.width() / cellSize)); } template <typename T> typename BackgroundGrid<T>::CellIdx BackgroundGrid<T>::calcRow(T y) const { return static_cast<CellIdx>(std::floor((y - m_domain.top()) / m_cellSize)); } template <typename T> typename BackgroundGrid<T>::CellIdx BackgroundGrid<T>::calcCol(T x) const { return static_cast<CellIdx>(std::floor((x - m_domain.left()) / m_cellSize)); } // Checks if a cell at given coordinates is occupied. template <typename T> bool BackgroundGrid<T>::isCellOccupied(CellIdx r, CellIdx c) const { if (r < 0 || r >= m_grid.size()) return false; if (c < 0 || c >= m_grid[r].size()) return false; return m_grid[r][c] != EmptyCell; } /////////////////// // Represents the ring-shaped area around a given point that candidate samples // are taken from. template <typename T> class Annulus { public: Annulus(const Point2<T>& center, T innerRadius, T outerRadius, const Rect<T>& domain, sutil::Random<T>& rand); Point2<T> generatePointInRing(); private: Point2<T> generatePointInBounds(); private: Ring<T> m_ring; // Overlap of ring bounds and domain area. Rect<T> m_bounds; sutil::Random<T>& m_rand; }; template <typename T> Annulus<T>::Annulus(const Point2<T>& center, T innerRadius, T outerRadius, const Rect<T>& domain, sutil::Random<T>& rand) : m_ring{center, innerRadius, outerRadius}, m_bounds{intersect(m_ring.bounds(), domain)}, m_rand{rand} { } template <typename T> Point2<T> Annulus<T>::generatePointInRing() { Point2<T> pt = generatePointInBounds(); while (!isPointInRing(m_ring, pt)) pt = generatePointInBounds(); return pt; } template <typename T> Point2<T> Annulus<T>::generatePointInBounds() { const T x = m_bounds.left() + m_rand.next() * m_bounds.width(); const T y = m_bounds.top() + m_rand.next() * m_bounds.height(); return {x, y}; } } // namespace internals /////////////////// // Algorithm for generating evenly distributed points. // Implements Bridson's Algorithm: // - Time: O(n) // https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf template <typename T> class PoissonDiscSampling { public: // Number of candidates that are generated when trying to find a new sample. static constexpr std::size_t NumCandidatesDefault = 30; PoissonDiscSampling(const Rect<T>& domain, T minDist, std::size_t numCandidatePoints, sutil::Random<T>& rand); // Generates samples by picking a random initial samples. std::vector<Point2<T>> generate(); // Generates samples with given initial sample. std::vector<Point2<T>> generate(const Point2<T>& initialSample); private: using SampleIdx = internals::SampleIdx; // Generates random sample. Point2<T> generateSample(); // Abstracts the process of choosing the next seed sample to generate // candidates for. Returns index into sample array. SampleIdx chooseSeed() const; // Stores a given sample in the internal data structures. void storeSample(const Point2<T>& sample); // Marks a given sample as not active anymore void deactivateSample(SampleIdx sampleIdx); // Checks if it is possible to find new samples around the given seed. bool canFindSamples(const Point2<T>& seedSample) const; // Finds a new sample for a given seed sample. std::optional<Point2<T>> findNewSample(const Point2<T>& seedSample) const; private: Rect<T> m_domain; // Min distance that samples are allowed to be from each other. T m_minDist; std::size_t m_numCandidates; // Max distance from seed sample that candidate samples are looked for. T m_maxCandidateDist; sutil::Random<T>& m_rand; std::vector<Point2<T>> m_samples; // Active samples. Holds indices into sample collection. std::vector<SampleIdx> m_active; internals::BackgroundGrid<T> m_grid; }; template <typename T> PoissonDiscSampling<T>::PoissonDiscSampling(const Rect<T>& domain, T minDist, std::size_t numCandidatePoints, sutil::Random<T>& rand) : m_domain{domain}, m_minDist{minDist}, m_numCandidates{numCandidatePoints}, m_maxCandidateDist{2 * minDist}, m_rand{rand}, m_grid{domain, minDist} { } template <typename T> std::vector<Point2<T>> PoissonDiscSampling<T>::generate() { return generate(generateSample()); } template <typename T> std::vector<Point2<T>> PoissonDiscSampling<T>::generate(const Point2<T>& initialSample) { storeSample(initialSample); while (!m_active.empty()) { const SampleIdx seedIdx = chooseSeed(); const Point2<T> seedSample = m_samples[seedIdx]; const auto newSample = findNewSample(seedSample); if (!newSample) deactivateSample(seedIdx); else storeSample(*newSample); } return m_samples; } template <typename T> Point2<T> PoissonDiscSampling<T>::generateSample() { const T x = m_domain.left() + m_rand.next() * m_domain.width(); const T y = m_domain.top() + m_rand.next() * m_domain.height(); return {x, y}; } template <typename T> typename PoissonDiscSampling<T>::SampleIdx PoissonDiscSampling<T>::chooseSeed() const { return m_active[0]; } template <typename T> void PoissonDiscSampling<T>::storeSample(const Point2<T>& sample) { m_samples.push_back(sample); const SampleIdx sampleIdx = static_cast<SampleIdx>(m_samples.size() - 1); m_active.push_back(sampleIdx); m_grid.insert(sample, sampleIdx); } template <typename T> void PoissonDiscSampling<T>::deactivateSample(SampleIdx sampleIdx) { const auto pos = std::find(m_active.begin(), m_active.end(), sampleIdx); m_active.erase(pos); } template <typename T> bool PoissonDiscSampling<T>::canFindSamples(const Point2<T>& seedSample) const { return seedSample.x() - m_minDist > m_domain.left() || seedSample.x() + m_minDist < m_domain.right() || seedSample.y() - m_minDist > m_domain.top() || seedSample.y() + m_minDist < m_domain.bottom(); } template <typename T> std::optional<Point2<T>> PoissonDiscSampling<T>::findNewSample(const Point2<T>& seedSample) const { if (!canFindSamples(seedSample)) return std::nullopt; internals::Annulus annulus{seedSample, m_minDist, m_maxCandidateDist, m_domain, m_rand}; for (std::size_t i = 0; i < m_numCandidates; ++i) { const Point2<T> candidate = annulus.generatePointInRing(); if (!m_grid.haveSampleWithinMinDistance(candidate)) return candidate; } return std::nullopt; } } // namespace geom
jamoma/JamomaCore
Modular/library/includes/TTModular.h
<filename>Modular/library/includes/TTModular.h<gh_stars>10-100 /** @file * * @ingroup modularLibrary * * @brief the Modular Application Programming Interface * * @details The Modular API allows to use Modular inside any application @n@n * * @see TTModularIncludes * * @authors <NAME> * * @copyright Copyright © 2013, <NAME> @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #ifndef __TT_MODULAR_H__ #define __TT_MODULAR_H__ #include "TTModularIncludes.h" class TTApplicationManager; typedef TTApplicationManager* TTApplicationManagerPtr; #if 0 #pragma mark - #pragma mark Initialisation #endif /** Initialize the Modular library and intanciate the TTModular object @param binaries path to the Jamoma libraries and extensions binaries folder to load them */ void TTMODULAR_EXPORT TTModularInit(const char* binaries = nullptr, bool loadFromBuiltinPaths = false); #if 0 #pragma mark - #pragma mark Application management #endif /** Export a pointer to a #TTApplicationManager instance @details this pointer is automatically filled when a #TTApplicationManager is instanciated */ extern TTMODULAR_EXPORT TTApplicationManagerPtr TTModularApplicationManager; #if 0 #pragma mark - #pragma mark Selection management #endif extern TTMODULAR_EXPORT TTHashPtr TTModularSelections; /** Get a selection or create one if it doesn't exist yet @param selectionName a symbol */ TTAddressItemPtr TTMODULAR_EXPORT TTModularSelectionLookup(const TTSymbol selectionName); #if 0 #pragma mark - #pragma mark Addresses edition #endif /** Edit a specific integer instance address using an integer format address @param integerFormatAddress a symbol as integer format address : /any/level/name.%d @param instanceNumber an unsigned integer @return #TTAddress like /any/level/name.1 */ TTAddress TTMODULAR_EXPORT TTModularAddressEditNumericInstance(const TTSymbol integerFormatAddress, const TTUInt32 instanceNumber); /** Edit a specific symbol instance address using an symbol format address @param symbolFormatAddress a symbol as symbol format address : /any/level/name.%s @param instanceSymbol a symbol @return #TTAddress like /any/level/name.foo */ TTAddress TTMODULAR_EXPORT TTModularAddressEditSymbolInstance(const TTSymbol symbolFormatAddress, const TTSymbol instanceSymbol); /** Get all intances at an address @param address an address without instance part : - /any/level/name - distantApp:/any/level/name @param instances the returned instances symbols @return #kTTErrGeneric if the address doesn't exist */ TTErr TTMODULAR_EXPORT TTModularAddressGetInstances(const TTAddress address, TTValue& instances); #endif // __TT_MODULAR_H__
TimDovg/Sales.CRM
Backend/src/main/java/com/andersenlab/crm/rest/facade/SourceFacadeImpl.java
<reponame>TimDovg/Sales.CRM package com.andersenlab.crm.rest.facade; import com.andersenlab.crm.convertservice.ConversionService; import com.andersenlab.crm.model.entities.Source; import com.andersenlab.crm.rest.request.SourceCreateRequest; import com.andersenlab.crm.rest.response.SourceResponse; import com.andersenlab.crm.services.SourceService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; @Service @RequiredArgsConstructor public class SourceFacadeImpl implements SourceFacade{ private final SourceService sourceService; private final ConversionService conversionService; @Override public SourceResponse create(SourceCreateRequest request){ Source converted = conversionService.convert(request, Source.class); return conversionService.convert(sourceService.createSource(converted), SourceResponse.class); } }
smashwidget/dl-1
adv/yuya.py
<reponame>smashwidget/dl-1 import adv.adv_test from adv import * def module(): return Yuya class Yuya(Adv): conf = {} conf['acl'] = """ `s3, not this.s3_buff_on `s1 `fs, seq=4 """ a3 = ('primed_crit_chance',(0.5,5)) def prerun(this): if this.condition('hp60'): Selfbuff('a1',0.2,-1,'att','passive').on() else: Selfbuff('a1',-0.2,-1,'att','passive').on() def s1_proc(this, e): Spdbuff("s2",0.2, 10) if __name__ == '__main__': conf = {} adv.adv_test.test(module(), conf, verbose=0, mass=0)
bronxc/refinery
refinery/units/strings/cupper.py
<filename>refinery/units/strings/cupper.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- from refinery.units import Unit class cupper(Unit): """ Transforms the input data to uppercase. """ def process(self, data): return data.upper()
jiktim/oldprojects
sol-ram/src/listeners/commandHandler/commandStarted.js
<gh_stars>1-10 const { Listener } = require('discord-akairo'); const Logger = require('../../util/Logger'); class CommandStartedListener extends Listener { constructor() { super('commandStarted', { event: 'commandStarted', emitter: 'commandHandler', category: 'commandHandler' }); } exec(message, command) { Logger.log(`=> ${command.id}`, { tag: message.guild ? `${message.guild.name} (${message.guild.id}) by ${message.author.tag} (${message.author.id})` : `${message.author.tag}/PM` }); } } module.exports = CommandStartedListener;
rajeevbbqq/snet-dapp-monorepo
packages/publisher-dapp/src/Pages/AiServiceCreation/EditHeader.js
<gh_stars>1-10 import React from "react"; import InfoIcon from "@material-ui/icons/Info"; import Typography from "@material-ui/core/Typography"; import SNETButton from "shared/dist/components/SNETButton"; import { withStyles } from "@material-ui/core/styles"; import { useStyles } from "./styles"; const EditHeader = ({ classes, onBack, allowSubmit, onSubmit }) => { return ( <div className={classes.editHeaderContainer}> <div className={classes.editHeaderTitleContainer}> <InfoIcon /> <Typography className={classes.editHeaderTitle}>Edit Service</Typography> </div> <div className={classes.editHeaderBtns}> <SNETButton color="white" variant="outlined" children="back to dashboard" onClick={onBack} /> <SNETButton color="white" variant="contained" children="submit" onClick={onSubmit} disabled={!allowSubmit} /> </div> </div> ); }; export default withStyles(useStyles)(EditHeader);
18F/michigan-benefits
spec/controllers/household_more_info_controller_spec.rb
# frozen_string_literal: true require "rails_helper" RSpec.describe HouseholdMoreInfoController do let(:step) { assigns(:step) } let(:invalid_params) { { step: { everyone_a_citizen: "" } } } let(:step_class) { HouseholdMoreInfo } before { session[:snap_application_id] = current_app.id } include_examples "step controller", "param validation" def current_app @_current_app ||= create(:snap_application) end end
yihangyang/react_blog
project/service/app/middleware/adminauth.js
module.exports = options => { return async function adminauth(ctx, next) { console.log(ctx.session.openId) if(ctx.session.openId){ await next() } else { ctx.body={data: 'You must login first'} } } }
scalqa/scalqa
core/src/scalqa/lang/string/z/Table.scala
package scalqa; package lang; package string; package z; import language.implicitConversions private[scalqa] class Table(val name: String=VOID): /**/ def newRow : Row = new Row(Rows.size).self( Rows += _ ) /**/ def +=(v: Stream[Any]): Unit = newRow.fill(v) /**/ def separator : String = Header.cells.stream.map(c => "".padEndTo(c.column.width, "-")).makeString(" ") object Header extends Row(-1): protected override def mkCell = cells += new Column(cells.size) class Column(index: Int, var width: Int = 1) extends Cell(index, "?") override def toString: String = separator + '\n' + super.toString + '\n' + separator object Rows extends AnyRef.G.Buffer[Row] class Row(val index: Int): /**/ val cells = Buffer[Cell]() /**/ def apply(i: Int): Cell = { while(i >= cells.size) mkCell; cells(i) } /**/ def update(i: Int, v: Any) = { while(i >= cells.size) mkCell; cells(i).value = v } /**/ def fill(vals: Stream[Any], from: Int = 0) = { var i = from; vals.foreach(v => { apply(i).value = v; i += 1 }) } protected def mkCell = cells += new Cell(cells.size) override def toString = cells.stream.makeString(" ") class Cell(val index: Int, _val: String = ""): private var _value: String = _val /**/ def value = _value /**/ def value_=(v: Any) = { _value = if (v == null) "null" else v.toString; column.width = column.width.max(value.length) } /**/ def column: Header.Column = Header(index).cast[Header.Column] override def toString = value.padEndTo(column.width) // ------------------------------------------------------------------------------------------------ override def toString: String = if (Rows.isEmpty) "empty" else String.Builder().self(b => { b += Header += '\n' Rows.stream.foreach(r => b += r += '\n' ) b += separator }).tag /*___________________________________________________________________________ __________ ____ __ ______ ____ / __/ ___// _ | / / / __ / / _ | Scala Quick API __\ \/ /___/ __ |/ /__/ /_/ /_/ __ | (c) 2021, Scalqa.org Inc /_____/\____/_/ |_/____/\______/_/ |_| github.com/scalqa ___________________________________________________________________________*/
harshanu11/Love-Babbar-450-In-CSharp
Love-Babbar-450-In-CPPTest/08_greedy/31_K_centers_problem.cpp
/* link: https://www.geeksforgeeks.org/k-centers-problem-set-1-greedy-approximate-algorithm/ The greedy solution works only if the distances between cities follow Triangular Inequality (Distance between two points is always smaller than sum of distances through a third point). */ // ----------------------------------------------------------------------------------------------------------------------- // // C++ program for the above approach #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"; // } // }; } using namespace std; int maxindex(int* dist, int n) { int mi = 0; for (int i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi; } void selectKcities(int n, int weights[4][4], int k) { int* dist = new int[n]; vector<int> centers; for (int i = 0; i < n; i++) { dist[i] = INT_MAX; } // index of city having the // maximum distance to it's // closest center int max = 0; for (int i = 0; i < k; i++) { centers.push_back(max); for (int j = 0; j < n; j++) { // updating the distance // of the cities to their // closest centers dist[j] = min(dist[j], weights[max][j]); } // updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer cout << endl << dist[max] << endl; // Printing the cities that // were chosen to be made // centers for (int i = 0; i < centers.size(); i++) { cout << centers[i] << " "; } cout << endl; } // Driver Code int main59() { int n = 4; int weights[4][4] = { { 0, 4, 8, 5 }, { 4, 0, 10, 7 }, { 8, 10, 0, 9 }, { 5, 7, 9, 0 } }; int k = 2; // Function Call selectKcities(n, weights, k); return 0; }
Ayfri/Challenge-Go
revparams/main.go
<filename>revparams/main.go package main import ( "os" "github.com/01-edu/z01" ) func main() { args := os.Args[1:] for i, j := 0, len(args)-1; i < j; i, j = i+1, j-1 { args[i], args[j] = args[j], args[i] } for _, arg := range args { for _, char := range arg { z01.PrintRune(char) } z01.PrintRune('\n') } }
grgrzybek/camel
examples/camel-example-gae/src/main/java/org/apache/camel/example/gae/ResponseProcessor.java
/** * 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.example.gae; import com.google.appengine.api.users.UserServiceFactory; import org.apache.camel.Exchange; import org.apache.camel.Processor; public class ResponseProcessor implements Processor { public void process(Exchange exchange) throws Exception { ReportData request = exchange.getIn().getBody(ReportData.class); String logoutUrl = UserServiceFactory.getUserService().createLogoutURL("/"); String logoutLink = "<a href=\"" + logoutUrl + "\">" + "logout</a>"; String homeLink = "<a href=\"/\">home</a>"; String body = "Weather report for " + request.getCity() + " will be sent to " + request.getRecipient() + " (" + homeLink + ", " + logoutLink + ")"; exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "text/html"); exchange.getOut().setBody(body); } }
SferaDev/ui
components/organisation-unit-tree/src/features/loading_state/index.js
import { Given, When, Then } from 'cypress-cucumber-preprocessor/steps' Given('a OrganisationUnitTree with two levels is rendered', () => { cy.visitStory('OrganisationUnitTree', 'A0000000001 loading') }) Given('the root level is closed', () => { cy.getOrgUnitByLabel('Org Unit 1').as('rootUnit').shouldBeAClosedNode() }) When('the root level is opened', () => { cy.get('@rootUnit').openOrgUnitNode() }) Then( 'there is a loading indicator rendered on the first child of the second level', () => { cy.getOrgUnitByLabel('Org Unit 2') .find('[data-test="dhis2-uicore-circularloader"]') .should('exist') cy.getOrgUnitByLabel('Org Unit 2') .find('[data-test="dhis2-uiwidgets-orgunittree-node-leaves"]:empty') .should('exist') } )
ArturVasilov/AndroidCourses
Android Testing/GoogleAnalytics/app/src/main/java/ru/guar7387/googleanalytics/database/DatabaseConstants.java
package ru.guar7387.googleanalytics.database; public interface DatabaseConstants { String TODO_TABLE_NAME = "todos"; String TODO_TEXT = "content"; String TODO_TIME = "time"; }