max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
486
<reponame>rsn8887/xerces-c-1 /* * 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. */ /* * $Id$ */ #include <xercesc/util/NetAccessors/WinSock/BinHTTPURLInputStream.hpp> #include <windows.h> #ifdef WITH_IPV6 #include <ws2tcpip.h> #endif #include <stdio.h> #include <string.h> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLNetAccessor.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLExceptMsgs.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLUniDefs.hpp> #include <xercesc/util/Mutexes.hpp> XERCES_CPP_NAMESPACE_BEGIN typedef u_short (WSAAPI * LPFN_HTONS)(u_short hostshort); typedef SOCKET (WSAAPI * LPFN_SOCKET)(int af, int type, int protocol); typedef int (WSAAPI * LPFN_CONNECT)(SOCKET s, const struct sockaddr* name, int namelen); typedef int (WSAAPI * LPFN_SEND)(SOCKET s, const char* buf, int len, int flags); typedef int (WSAAPI * LPFN_RECV)(SOCKET s, char* buf, int len, int flags); typedef int (WSAAPI * LPFN_SHUTDOWN)(SOCKET s, int how); typedef int (WSAAPI * LPFN_CLOSESOCKET)(SOCKET s); typedef int (WSAAPI * LPFN_WSACLEANUP)(); typedef int (WSAAPI * LPFN_WSASTARTUP)(WORD wVersionRequested, LPWSADATA lpWSAData); #ifdef WITH_IPV6 typedef int (WSAAPI * LPFN_GETADDRINFO)(const char* nodename, const char * servname, const struct addrinfo * hints, struct addrinfo ** res); typedef void (WSAAPI * LPFN_FREEADDRINFO)(struct addrinfo * ai); #else typedef struct hostent *(WSAAPI * LPFN_GETHOSTBYNAME)(const char* name); typedef struct hostent *(WSAAPI * LPFN_GETHOSTBYADDR)(const char* addr, int len, int type); typedef unsigned long (WSAAPI * LPFN_INET_ADDR)(const char* cp); #endif static HMODULE gWinsockLib = NULL; static LPFN_HTONS gWShtons = NULL; static LPFN_SOCKET gWSsocket = NULL; static LPFN_CONNECT gWSconnect = NULL; static LPFN_SEND gWSsend = NULL; static LPFN_RECV gWSrecv = NULL; static LPFN_SHUTDOWN gWSshutdown = NULL; static LPFN_CLOSESOCKET gWSclosesocket = NULL; static LPFN_WSACLEANUP gWSACleanup = NULL; #ifdef WITH_IPV6 static LPFN_GETADDRINFO gWSgetaddrinfo = NULL; static LPFN_FREEADDRINFO gWSfreeaddrinfo = NULL; #else static LPFN_GETHOSTBYNAME gWSgethostbyname = NULL; static LPFN_GETHOSTBYADDR gWSgethostbyaddr = NULL; static LPFN_INET_ADDR gWSinet_addr = NULL; #endif static u_short wrap_htons(u_short hostshort) { return (*gWShtons)(hostshort); } static SOCKET wrap_socket(int af,int type,int protocol) { return (*gWSsocket)(af,type,protocol); } static int wrap_connect(SOCKET s,const struct sockaddr* name,int namelen) { return (*gWSconnect)(s,name,namelen); } static int wrap_send(SOCKET s,const char* buf,int len,int flags) { return (*gWSsend)(s,buf,len,flags); } static int wrap_recv(SOCKET s,char* buf,int len,int flags) { return (*gWSrecv)(s,buf,len,flags); } static int wrap_shutdown(SOCKET s,int how) { return (*gWSshutdown)(s,how); } static int wrap_closesocket(SOCKET socket) { return (*gWSclosesocket)(socket); } #ifdef WITH_IPV6 static int wrap_getaddrinfo(const char* nodename,const char* servname,const struct addrinfo* hints,struct addrinfo** res) { return (*gWSgetaddrinfo)(nodename,servname,hints,res); } static void wrap_freeaddrinfo(struct addrinfo* ai) { (*gWSfreeaddrinfo)(ai); } #else static struct hostent* wrap_gethostbyname(const char* name) { return (*gWSgethostbyname)(name); } static struct hostent* wrap_gethostbyaddr(const char* addr,int len,int type) { return (*gWSgethostbyaddr)(addr,len,type); } static unsigned long wrap_inet_addr(const char* cp) { return (*gWSinet_addr)(cp); } #endif class SocketJanitor { public: // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- SocketJanitor(SOCKET* toDelete) : fData(toDelete) {} ~SocketJanitor() { reset(); } SOCKET* get() const { return fData; } SOCKET* release() { SOCKET* p = fData; fData = 0; return p; } void reset(SOCKET* p = 0) { if(fData) { wrap_shutdown(*fData, SD_BOTH); wrap_closesocket(*fData); } fData = p; } bool isDataNull() { return (fData == 0); } private : // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- SocketJanitor(); SocketJanitor(const SocketJanitor&); SocketJanitor& operator=(const SocketJanitor&); // ----------------------------------------------------------------------- // Private data members // // fData // This is the pointer to the socket that must be closed when // this object is destroyed. // ----------------------------------------------------------------------- SOCKET* fData; }; bool BinHTTPURLInputStream::fInitialized = false; void BinHTTPURLInputStream::Initialize(MemoryManager* const manager) { // // Initialize the WinSock library here. // WORD wVersionRequested; WSADATA wsaData; LPFN_WSASTARTUP startup = NULL; if(gWinsockLib == NULL) { #ifdef WITH_IPV6 gWinsockLib = LoadLibraryA("WS2_32"); #else gWinsockLib = LoadLibraryA("WSOCK32"); #endif if(gWinsockLib == NULL) { ThrowXMLwithMemMgr(NetAccessorException, XMLExcepts::NetAcc_InitFailed, manager); } else { startup = (LPFN_WSASTARTUP) GetProcAddress(gWinsockLib,"WSAStartup"); gWSACleanup = (LPFN_WSACLEANUP) GetProcAddress(gWinsockLib,"WSACleanup"); gWShtons = (LPFN_HTONS) GetProcAddress(gWinsockLib,"htons"); gWSsocket = (LPFN_SOCKET) GetProcAddress(gWinsockLib,"socket"); gWSconnect = (LPFN_CONNECT) GetProcAddress(gWinsockLib,"connect"); gWSsend = (LPFN_SEND) GetProcAddress(gWinsockLib,"send"); gWSrecv = (LPFN_RECV) GetProcAddress(gWinsockLib,"recv"); gWSshutdown = (LPFN_SHUTDOWN) GetProcAddress(gWinsockLib,"shutdown"); gWSclosesocket = (LPFN_CLOSESOCKET) GetProcAddress(gWinsockLib,"closesocket"); #ifdef WITH_IPV6 gWSgetaddrinfo = (LPFN_GETADDRINFO) GetProcAddress(gWinsockLib,"getaddrinfo"); gWSfreeaddrinfo = (LPFN_FREEADDRINFO) GetProcAddress(gWinsockLib,"freeaddrinfo"); #else gWSgethostbyname = (LPFN_GETHOSTBYNAME) GetProcAddress(gWinsockLib,"gethostbyname"); gWSgethostbyaddr = (LPFN_GETHOSTBYADDR) GetProcAddress(gWinsockLib,"gethostbyaddr"); gWSinet_addr = (LPFN_INET_ADDR) GetProcAddress(gWinsockLib,"inet_addr"); #endif if(startup == NULL || gWSACleanup == NULL || gWShtons == NULL || gWSsocket == NULL || gWSconnect == NULL || gWSsend == NULL || gWSrecv == NULL || gWSshutdown == NULL || gWSclosesocket == NULL #ifdef WITH_IPV6 || gWSgetaddrinfo == NULL || gWSfreeaddrinfo == NULL #else || gWSgethostbyname == NULL || gWSgethostbyaddr == NULL || gWSinet_addr == NULL #endif ) { gWSACleanup = NULL; Cleanup(); ThrowXMLwithMemMgr(NetAccessorException, XMLExcepts::NetAcc_InitFailed, manager); } } } wVersionRequested = MAKEWORD( 2, 2 ); int err = (*startup)(wVersionRequested, &wsaData); if (err != 0) { // Call WSAGetLastError() to get the last error. ThrowXMLwithMemMgr(NetAccessorException, XMLExcepts::NetAcc_InitFailed, manager); } fInitialized = true; } void BinHTTPURLInputStream::Cleanup() { XMLMutexLock lock(XMLPlatformUtils::fgAtomicMutex); if(fInitialized) { if(gWSACleanup) (*gWSACleanup)(); gWSACleanup = NULL; FreeLibrary(gWinsockLib); gWinsockLib = NULL; gWShtons = NULL; gWSsocket = NULL; gWSconnect = NULL; gWSsend = NULL; gWSrecv = NULL; gWSshutdown = NULL; gWSclosesocket = NULL; #ifdef WITH_IPV6 gWSgetaddrinfo = NULL; gWSfreeaddrinfo = NULL; #else gWSgethostbyname = NULL; gWSgethostbyaddr = NULL; gWSinet_addr = NULL; #endif fInitialized = false; } } BinHTTPURLInputStream::BinHTTPURLInputStream(const XMLURL& urlSource, const XMLNetHTTPInfo* httpInfo /*=0*/) : BinHTTPInputStreamCommon(urlSource.getMemoryManager()) , fSocketHandle(0) { MemoryManager *memoryManager = urlSource.getMemoryManager(); // Check if we need to load the winsock library. While locking the // mutex every time may be somewhat slow, we don't care in this // particular case since the next operation will most likely be // the network access which is a lot slower. // { XMLMutexLock lock(XMLPlatformUtils::fgAtomicMutex); if (!fInitialized) Initialize(memoryManager); } // // Pull all of the parts of the URL out of th urlSource object, and transcode them // and transcode them back to ASCII. // const XMLCh* hostName = urlSource.getHost(); if (hostName == 0) ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::File_CouldNotOpenFile, urlSource.getURLText(), memoryManager); char* hostNameAsCharStar = XMLString::transcode(hostName, memoryManager); ArrayJanitor<char> janHostNameAsCharStar(hostNameAsCharStar, memoryManager); XMLURL url(urlSource); int redirectCount = 0; SocketJanitor janSock(0); do { // // Set up a socket. // #ifdef WITH_IPV6 struct addrinfo hints, *res, *ai; CharBuffer portBuffer(10, memoryManager); portBuffer.appendDecimalNumber(url.getPortNum()); memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; int n = wrap_getaddrinfo(hostNameAsCharStar,portBuffer.getRawBuffer(),&hints, &res); if(n != 0) { hints.ai_flags = AI_NUMERICHOST; n = wrap_getaddrinfo(hostNameAsCharStar,(const char*)tempbuf,&hints, &res); if(n != 0) ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::NetAcc_TargetResolution, hostName, memoryManager); } janSock.reset(); for (ai = res; ai != NULL; ai = ai->ai_next) { // Open a socket with the correct address family for this address. fSocketHandle = wrap_socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); if (fSocketHandle == INVALID_SOCKET) continue; janSock.reset(&fSocketHandle); if (wrap_connect(fSocketHandle, ai->ai_addr, (int)ai->ai_addrlen) == SOCKET_ERROR) { wrap_freeaddrinfo(res); // Call WSAGetLastError() to get the error number. ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, url.getURLText(), memoryManager); } break; } wrap_freeaddrinfo(res); if (fSocketHandle == INVALID_SOCKET) { // Call WSAGetLastError() to get the error number. ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::NetAcc_CreateSocket, url.getURLText(), memoryManager); } #else struct hostent* hostEntPtr = 0; struct sockaddr_in sa; if ((hostEntPtr = wrap_gethostbyname(hostNameAsCharStar)) == NULL) { unsigned long numAddress = wrap_inet_addr(hostNameAsCharStar); if (numAddress == INADDR_NONE) { // Call WSAGetLastError() to get the error number. ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::NetAcc_TargetResolution, hostName, memoryManager); } if ((hostEntPtr = wrap_gethostbyaddr((const char *) &numAddress, sizeof(unsigned long), AF_INET)) == NULL) { // Call WSAGetLastError() to get the error number. ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::NetAcc_TargetResolution, hostName, memoryManager); } } memcpy((void *) &sa.sin_addr, (const void *) hostEntPtr->h_addr, hostEntPtr->h_length); sa.sin_family = hostEntPtr->h_addrtype; sa.sin_port = wrap_htons((unsigned short)url.getPortNum()); janSock.reset(); fSocketHandle = wrap_socket(hostEntPtr->h_addrtype, SOCK_STREAM, 0); if (fSocketHandle == INVALID_SOCKET) { // Call WSAGetLastError() to get the error number. ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::NetAcc_CreateSocket, url.getURLText(), memoryManager); } janSock.reset(&fSocketHandle); if (wrap_connect(fSocketHandle, (struct sockaddr *) &sa, sizeof(sa)) == SOCKET_ERROR) { // Call WSAGetLastError() to get the error number. ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::NetAcc_ConnSocket, url.getURLText(), memoryManager); } #endif int status = sendRequest(url, httpInfo); if(status == 200) { // HTTP 200 OK response means we're done. // We're done break; } // a 3xx response means there was an HTTP redirect else if(status >= 300 && status <= 307) { redirectCount++; XMLCh *newURLString = findHeader("Location"); ArrayJanitor<XMLCh> janNewURLString(newURLString, memoryManager); if(newURLString == 0 || *newURLString == 0) { ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::File_CouldNotOpenFile, url.getURLText(), memoryManager); } XMLURL newURL(memoryManager); newURL.setURL(url, newURLString); if(newURL.getProtocol() != XMLURL::HTTP) { ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::File_CouldNotOpenFile, newURL.getURLText(), memoryManager); } url = newURL; hostName = newURL.getHost(); if (hostName == 0) ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::File_CouldNotOpenFile, newURL.getURLText(), memoryManager); janHostNameAsCharStar.release(); hostNameAsCharStar = XMLString::transcode(hostName, memoryManager); janHostNameAsCharStar.reset(hostNameAsCharStar, memoryManager); } else { // Most likely a 404 Not Found error. ThrowXMLwithMemMgr1(NetAccessorException, XMLExcepts::File_CouldNotOpenFile, url.getURLText(), memoryManager); } } while(redirectCount < 6); janSock.release(); } BinHTTPURLInputStream::~BinHTTPURLInputStream() { wrap_shutdown(fSocketHandle, SD_BOTH); wrap_closesocket(fSocketHandle); } bool BinHTTPURLInputStream::send(const char *buf, XMLSize_t len) { XMLSize_t done = 0; int ret; while(done < len) { ret = wrap_send(fSocketHandle, buf + done, (int)(len - done), 0); if(ret == SOCKET_ERROR) return false; done += ret; } return true; } int BinHTTPURLInputStream::receive(char *buf, XMLSize_t len) { int iLen = wrap_recv(fSocketHandle, buf, (int)len, 0); if (iLen == SOCKET_ERROR) return -1; return iLen; } XERCES_CPP_NAMESPACE_END
7,270
640
<reponame>ahjelm/z88dk #ifndef __CONFIG_Z88DK_H_ #define __CONFIG_Z88DK_H_ // Automatically Generated at Library Build Time #undef __Z88DK #define __Z88DK 2100 #undef __Z80 #define __Z80 0x02 #define __Z80_NMOS 0x01 #define __Z80_CMOS 0x02 #define __CPU_INFO 0x00 #define __CPU_INFO_ENABLE_SLL 0x01 #define __IO_APU_DATA 0x42 #define __IO_APU_CONTROL 0x43 #define __IO_APU_STATUS 0x43 #define __IO_APU_STATUS_BUSY 0x80 #define __IO_APU_STATUS_SIGN 0x40 #define __IO_APU_STATUS_ZERO 0x20 #define __IO_APU_STATUS_DIV0 0x10 #define __IO_APU_STATUS_NEGRT 0x08 #define __IO_APU_STATUS_UNDFL 0x04 #define __IO_APU_STATUS_OVRFL 0x02 #define __IO_APU_STATUS_CARRY 0x01 #define __IO_APU_STATUS_ERROR 0x1E #define __IO_APU_COMMAND_SVREQ 0x80 #define __IO_APU_OP_ENT 0x40 #define __IO_APU_OP_REM 0x50 #define __IO_APU_OP_ENT16 0x40 #define __IO_APU_OP_ENT32 0x41 #define __IO_APU_OP_REM16 0x50 #define __IO_APU_OP_REM32 0x51 #define __IO_APU_OP_SADD 0x6C #define __IO_APU_OP_SSUB 0x6D #define __IO_APU_OP_SMUL 0x6E #define __IO_APU_OP_SMUU 0x76 #define __IO_APU_OP_SDIV 0x6F #define __IO_APU_OP_DADD 0x2C #define __IO_APU_OP_DSUB 0x2D #define __IO_APU_OP_DMUL 0x2E #define __IO_APU_OP_DMUU 0x36 #define __IO_APU_OP_DDIV 0x2F #define __IO_APU_OP_FADD 0x10 #define __IO_APU_OP_FSUB 0x11 #define __IO_APU_OP_FMUL 0x12 #define __IO_APU_OP_FDIV 0x13 #define __IO_APU_OP_SQRT 0x01 #define __IO_APU_OP_SIN 0x02 #define __IO_APU_OP_COS 0x03 #define __IO_APU_OP_TAN 0x04 #define __IO_APU_OP_ASIN 0x05 #define __IO_APU_OP_ACOS 0x06 #define __IO_APU_OP_ATAN 0x07 #define __IO_APU_OP_LOG 0x08 #define __IO_APU_OP_LN 0x09 #define __IO_APU_OP_EXP 0x0A #define __IO_APU_OP_PWR 0x0B #define __IO_APU_OP_NOP 0x00 #define __IO_APU_OP_FIXS 0x1F #define __IO_APU_OP_FIXD 0x1E #define __IO_APU_OP_FLTS 0x1D #define __IO_APU_OP_FLTD 0x1C #define __IO_APU_OP_CHSS 0x74 #define __IO_APU_OP_CHSD 0x34 #define __IO_APU_OP_CHSF 0x15 #define __IO_APU_OP_PTOS 0x77 #define __IO_APU_OP_PTOD 0x37 #define __IO_APU_OP_PTOF 0x17 #define __IO_APU_OP_POPS 0x78 #define __IO_APU_OP_POPD 0x38 #define __IO_APU_OP_POPF 0x18 #define __IO_APU_OP_XCHS 0x79 #define __IO_APU_OP_XCHD 0x39 #define __IO_APU_OP_XCHF 0x19 #define __IO_APU_OP_PUPI 0x1A #define __IO_APU0_DATA 0x42 #define __IO_APU0_CONTROL 0x43 #define __IO_APU0_STATUS 0x43 #define __IO_APU1_DATA 0x62 #define __IO_APU1_CONTROL 0x63 #define __IO_APU1_STATUS 0x63 #define __IO_APU2_DATA 0xc2 #define __IO_APU2_CONTROL 0xc3 #define __IO_APU2_STATUS 0xc3 #define __IO_APU3_DATA 0xe2 #define __IO_APU3_CONTROL 0xe3 #define __IO_APU3_STATUS 0xe3 #endif
1,470
2,151
<filename>src/test/projects/support4demos/src/main/java/com/example/android/supportv4/app/FragmentRetainInstanceSupport.java /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.supportv4.app; import com.example.android.supportv4.R; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ProgressBar; /** * This example shows how you can use a Fragment to easily propagate state * (such as threads) across activity instances when an activity needs to be * restarted due to, for example, a configuration change. This is a lot * easier than using the raw Activity.onRetainNonConfiguratinInstance() API. */ public class FragmentRetainInstanceSupport extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // First time init, create the UI. if (savedInstanceState == null) { getSupportFragmentManager().beginTransaction().add(android.R.id.content, new UiFragment()).commit(); } } /** * This is a fragment showing UI that will be updated from work done * in the retained fragment. */ public static class UiFragment extends Fragment { RetainedFragment mWorkFragment; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_retain_instance, container, false); // Watch for button clicks. Button button = (Button)v.findViewById(R.id.restart); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { mWorkFragment.restart(); } }); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); FragmentManager fm = getFragmentManager(); // Check to see if we have retained the worker fragment. mWorkFragment = (RetainedFragment)fm.findFragmentByTag("work"); // If not retained (or first time running), we need to create it. if (mWorkFragment == null) { mWorkFragment = new RetainedFragment(); // Tell it who it is working with. mWorkFragment.setTargetFragment(this, 0); fm.beginTransaction().add(mWorkFragment, "work").commit(); } } } /** * This is the Fragment implementation that will be retained across * activity instances. It represents some ongoing work, here a thread * we have that sits around incrementing a progress indicator. */ public static class RetainedFragment extends Fragment { ProgressBar mProgressBar; int mPosition; boolean mReady = false; boolean mQuiting = false; /** * This is the thread that will do our work. It sits in a loop running * the progress up until it has reached the top, then stops and waits. */ final Thread mThread = new Thread() { @Override public void run() { // We'll figure the real value out later. int max = 10000; // This thread runs almost forever. while (true) { // Update our shared state with the UI. synchronized (this) { // Our thread is stopped if the UI is not ready // or it has completed its work. while (!mReady || mPosition >= max) { if (mQuiting) { return; } try { wait(); } catch (InterruptedException e) { } } // Now update the progress. Note it is important that // we touch the progress bar with the lock held, so it // doesn't disappear on us. mPosition++; max = mProgressBar.getMax(); mProgressBar.setProgress(mPosition); } // Normally we would be doing some work, but put a kludge // here to pretend like we are. synchronized (this) { try { wait(50); } catch (InterruptedException e) { } } } } }; /** * Fragment initialization. We way we want to be retained and * start our thread. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Tell the framework to try to keep this fragment around // during a configuration change. setRetainInstance(true); // Start up the worker thread. mThread.start(); } /** * This is called when the Fragment's Activity is ready to go, after * its content view has been installed; it is called both after * the initial fragment creation and after the fragment is re-attached * to a new activity. */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Retrieve the progress bar from the target's view hierarchy. mProgressBar = (ProgressBar)getTargetFragment().getView().findViewById( R.id.progress_horizontal); // We are ready for our thread to go. synchronized (mThread) { mReady = true; mThread.notify(); } } /** * This is called when the fragment is going away. It is NOT called * when the fragment is being propagated between activity instances. */ @Override public void onDestroy() { // Make the thread go away. synchronized (mThread) { mReady = false; mQuiting = true; mThread.notify(); } super.onDestroy(); } /** * This is called right before the fragment is detached from its * current activity instance. */ @Override public void onDetach() { // This fragment is being detached from its activity. We need // to make sure its thread is not going to touch any activity // state after returning from this function. synchronized (mThread) { mProgressBar = null; mReady = false; mThread.notify(); } super.onDetach(); } /** * API for our UI to restart the progress thread. */ public void restart() { synchronized (mThread) { mPosition = 0; mThread.notify(); } } } }
3,700
793
//===--- RefactoringOptionSet.h - A container for the refactoring options -===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_TOOLING_REFACTOR_REFACTORING_OPTION_SET_H #define LLVM_CLANG_TOOLING_REFACTOR_REFACTORING_OPTION_SET_H #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Error.h" namespace llvm { namespace yaml { class IO; } // end namespace yaml } // end namespace llvm namespace clang { namespace tooling { struct OldRefactoringOption { virtual ~OldRefactoringOption() = default; struct SerializationContext { llvm::yaml::IO &IO; SerializationContext(llvm::yaml::IO &IO) : IO(IO) {} }; virtual void serialize(const SerializationContext &Context); }; /// \brief A set of refactoring options that can be given to a refactoring /// operation. class RefactoringOptionSet final { llvm::StringMap<std::unique_ptr<OldRefactoringOption>> Options; public: RefactoringOptionSet() {} template <typename T> RefactoringOptionSet(const T &Option) { add(Option); } RefactoringOptionSet(RefactoringOptionSet &&) = default; RefactoringOptionSet &operator=(RefactoringOptionSet &&) = default; RefactoringOptionSet(const RefactoringOptionSet &) = delete; RefactoringOptionSet &operator=(const RefactoringOptionSet &) = delete; template <typename T> void add(const T &Option) { auto It = Options.try_emplace(StringRef(T::Name), nullptr); if (It.second) It.first->getValue().reset(new T(Option)); } template <typename T> const T *get() const { auto It = Options.find(StringRef(T::Name)); if (It == Options.end()) return nullptr; return static_cast<const T *>(It->getValue().get()); } template <typename T> const T &get(const T &Default) const { const auto *Ptr = get<T>(); return Ptr ? *Ptr : Default; } void print(llvm::raw_ostream &OS) const; static llvm::Expected<RefactoringOptionSet> parse(StringRef Source); }; } // end namespace tooling } // end namespace clang #endif // LLVM_CLANG_TOOLING_REFACTOR_REFACTORING_OPTION_SET_H
801
1,607
import annotations.metric_annotations as metric_result import annotations.parameter_annotations as params import datetime import os import shutil import time from annotations.metric_annotations import metric from annotations.parameter_annotations import parameter from keras import optimizers from keras.applications import ResNet50 from keras.callbacks import ReduceLROnPlateau, CSVLogger from keras.layers import Dense, Flatten, Dropout from keras.models import Sequential from keras.preprocessing.image import ImageDataGenerator def data_flow(images_path, training_split, validation_split, class_mode): """ Using Keras ImageDataGenerator to create dataflows from directory provided by the user. """ data_generator = ImageDataGenerator(rescale=1. / 255, validation_split=validation_split) train_generator = data_generator.flow_from_directory( directory=images_path, target_size=(height, width), color_mode=color_mode(), batch_size=batch_size, class_mode=class_mode, shuffle=True, subset='training' ) DIR = images_path num_images = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))]) os.makedirs(DIR + 'test_temp_dir/') images = os.listdir(DIR) num_file_to_move = num_images - num_images * training_split for index, file in enumerate(images): if index == num_file_to_move: break shutil.copy(DIR + file, DIR + 'test/') # TODO: Delete the extra files and folder after training validation_generator = data_generator.flow_from_directory( directory=images_path, target_size=(height, width), color_mode=color_mode(), batch_size=batch_size, class_mode=class_mode, shuffle=True, subset='validation' ) testing_generator = data_generator.flow_from_directory( directory=DIR + 'test_temp_dir/', target_size=(height, width), color_mode=color_mode(), batch_size=batch_size, class_mode=class_mode, shuffle=True, subset='testing' ) return train_generator, testing_generator, validation_generator def resnet_model(height, width, channels, color_mode, use_pretrained, trainGenerator, validationGenerator, loss, epochs, learning_rate): """ Using the Keras implementation of the ResNet50 model with and without pretrained weights """ if use_pretrained == 'True': url = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.2/resnet50_weights_tf_dim_ordering' \ '_tf_kernels_notop.h5' os.system("wget -c --read-timeout=5 --tries=0 {}".format(url)) print("Using pre-trained ResNet model \n") base_model = ResNet50(weights='resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', include_top=False, input_shape=(height, width, channels) ) else: base_model = ResNet50(weights=None, include_top=False, input_shape=(height, width, channels) ) model = Sequential() model.add(base_model) # Freeze the layers except the last 4 layers model.add(Dropout(0.40)) model.add(Flatten()) model.add(Dense(512, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(len(trainGenerator.class_indices), activation='softmax')) # Check len feature learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', patience=3, verbose=1, factor=0.5, min_lr=0.00001) model.compile(optimizer=optimizers.adam(lr=learning_rate), loss=loss, metrics=["accuracy"]) csv_logger = CSVLogger('training.log', append=False) history_callback = model.fit_generator(generator=trainGenerator, steps_per_epoch=trainGenerator.samples // trainGenerator.batch_size, verbose=1, epochs=epochs, validation_data=validationGenerator, validation_steps=validationGenerator.samples // validationGenerator.batch_size, callbacks=[learning_rate_reduction, csv_logger, Metrics()]) model.save_weights("{}/model_Resnet50_{}_epochs_{}.h5".format(output_path, datetime.datetime.fromtimestamp( time.time()).strftime('%Y-%m-%d-%H:%M:%S'), epochs)) return model, history_callback # TODO FIXME: @V: Add dataOperation annotation please. Dont ignore my comments. @data_processor( name="Resnet 2.0 Filter", author="MLReef", type="ALGORITHM", description="Transforms images with lots of magic", visibility="PUBLIC", input_type="IMAGE", output_type="IMAGE" ) @parameter('images_path', "str", required=True, defaultValue='.') @parameter('output_path', type="str", required=True, defaultValue='.') @parameter('height', "int", True, defaultValue=256) @parameter('width', "int", True, 256) @parameter('epochs', "int", defaultValue=5, required=True) @parameter('channels', required=False, defaultValue=3, type="int") @parameter(required=False, defaultValue='False', name='use_pretrained', type="str", description="use pretrained?") @parameter(name='batch_size', required=False, type="int", defaultValue=32) @parameter(defaultValue=0.8, name='training_split', type='float', required=False, ) @parameter(type='float', defaultValue=0.2, name='validation_split', required=False, ) @parameter('learning_rate', required=False, defaultValue=.0001, type='float') @parameter(name='loss', type='float', required=False, defaultValue=0.1, description="Loss of stuff") def init_parameters(): pass if __name__ == '__main__': init_parameters() # To avoid this, all variables that are injected should be used as params.variable_name in the rest of the file images_path = params.images_path output_path = params.output_path height = params.height width = params.width epochs = params.epochs channels = params.channels use_pretrained = params.use_pretrained batch_size = params.batch_size training_split = params.training_split validation_split = params.validation_split learning_rate = params.learning_rate class_mode = params.class_mode loss = params.loss color_mode = lambda: 'rbga' if channels == 4 else ( 'grayscale' if channels == 1 else 'rgb') # handle this potential error trainGenerator, testGenerator, validationGenerator = data_flow(images_path, training_split, validation_split, class_mode) model, history = resnet_model(height, width, channels, color_mode, use_pretrained, trainGenerator, validationGenerator, loss, epochs, learning_rate) test_pred = model.predict(testGenerator) test_truth = testGenerator.classes @metric(name='recall', ground_truth=test_truth, prediction=test_pred) def call_metric(): pass call_metric() recall = metric_result.result pass
3,156
316
#pragma once #include "global.h" #include <algorithm> #include <vector> #include <utility> class ADAM { public: ADAM(); ADAM(std::vector<std::pair<int,int>> dims2d, std::vector<int> dims1d, double lr_=0); void init(std::vector<std::pair<int,int>> dims2d, std::vector<int> dims1d); void update(std::vector<s_data2d_ds*> weights, std::vector<s_data2d_ds*> d_weights, std::vector<s_data1d_ds*> biases, std::vector<s_data1d_ds*> d_biases); private: double lr; double beta1; double beta2; double epsilon; std::vector<s_data2d_ds> ss2d; std::vector<s_data1d_ds> ss1d; std::vector<s_data2d_ds> rs2d; std::vector<s_data1d_ds> rs1d; t_idx t; };
345
799
<filename>Packs/GoogleChronicleBackstory/Scripts/ChronicleAssetEventsForMACWidgetScript/ChronicleAssetEventsForMACWidgetScript_test.py from unittest.mock import patch import ChronicleAssetEventsForMACWidgetScript def test_main_success(mocker): """ When main function is called, set_arguments_for_widget_view should be called. """ mocker.patch.object(ChronicleAssetEventsForMACWidgetScript, 'set_arguments_for_widget_view', return_value={}) ChronicleAssetEventsForMACWidgetScript.main() assert ChronicleAssetEventsForMACWidgetScript.set_arguments_for_widget_view.called @patch('ChronicleAssetEventsForMACWidgetScript.return_error') def test_main_failure(mock_return_error, capfd, mocker): """ When main function gets some exception then valid message should be printed. """ mocker.patch.object(ChronicleAssetEventsForMACWidgetScript, 'set_arguments_for_widget_view', side_effect=Exception) with capfd.disabled(): ChronicleAssetEventsForMACWidgetScript.main() mock_return_error.assert_called_once_with('Could not load widget:\n') def test_set_arguments_for_widget_view_when_mac_is_empty(): """ When chronicleassetmac indicator field is kept empty, set_arguments_for_widget_view should return empty argument dictionary. """ # set arguments for command indicator_data = { 'CustomFields': { } } # Execute arguments = ChronicleAssetEventsForMACWidgetScript.set_arguments_for_widget_view(indicator_data) # Assert assert {} == arguments def test_set_arguments_for_widget_view_when_mac_is_valid(): """ When chronicleassetmac indicator field has valid value, set_arguments_for_widget_view should set the arguments successfully. """ # set argument for command indicator_data = { 'CustomFields': { 'chronicleassetmac': '01:XX:XX:XX:XX:XX' } } # set expected output expected_arguments = { 'asset_identifier': '01:XX:XX:XX:XX:XX', 'asset_identifier_type': 'MAC Address', 'preset_time_range': 'Last 30 days' } # Execute arguments = ChronicleAssetEventsForMACWidgetScript.set_arguments_for_widget_view(indicator_data) # Assert assert expected_arguments == arguments
855
1,338
/*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2001 <NAME> (<EMAIL>) * All rights reserved. * * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $FreeBSD: releng/12.0/sys/dev/mii/acphyreg.h 326255 2017-11-27 14:52:40Z pfg $ */ #ifndef _DEV_MII_ACPHYREG_H_ #define _DEV_MII_ACPHYREG_H_ /* * Register definitions for the Altima Communications AC101 */ #define MII_ACPHY_POL 0x10 /* Polarity int level */ /* High byte is interrupt mask register */ #define MII_ACPHY_INT 0x11 /* Interrupt control/status */ #define AC_INT_ACOMP 0x0001 /* Autoneg complete */ #define AC_INT_REM_FLT 0x0002 /* Remote fault */ #define AC_INT_LINK_DOWN 0x0004 /* Link not OK */ #define AC_INT_LP_ACK 0x0008 /* FLP ack recved */ #define AC_INT_PD_FLT 0x0010 /* Parallel detect fault */ #define AC_INT_PAGE_RECV 0x0020 /* New page recved */ #define AC_INT_RX_ER 0x0040 /* RX_ER transitions high */ #define AC_INT_JAB 0x0080 /* Jabber detected */ #define MII_ACPHY_DIAG 0x12 /* Diagnostic */ #define AC_DIAG_RX_LOCK 0x0100 #define AC_DIAG_RX_PASS 0x0200 #define AC_DIAG_SPEED 0x0400 /* Aneg speed result */ #define AC_DIAG_DUPLEX 0x0800 /* Aneg duplex result */ #define MII_ACPHY_PWRLOOP 0x13 /* Power/Loopback */ #define MII_ACPHY_CBLMEAS 0x14 /* Cable meas. */ #define MII_ACPHY_MCTL 0x15 /* Mode control */ #define AC_MCTL_FX_SEL 0x0001 /* FX mode */ #define AC_MCTL_BYP_PCS 0x0002 /* Bypass PCS */ #define AC_MCTL_SCRMBL 0x0004 /* Data scrambling */ #define AC_MCTL_REM_LOOP 0x0008 /* Remote loopback */ #define AC_MCTL_DIS_WDT 0x0010 /* Disable watchdog timer */ #define AC_MCTL_DIS_REC 0x0020 /* Disable recv error counter */ #define AC_MCTL_REC_FULL 0x0040 /* Recv error counter full */ #define AC_MCTL_FRC_FEF 0x0080 /* Force Far End Fault Insert. */ #define AC_MCTL_DIS_FEF 0x0100 /* Disable FEF Insertion */ #define AC_MCTL_LED_SEL 0x0200 /* Compat LED config */ #define AC_MCTL_ALED_SEL 0x0400 /* ActLED RX&TX - RX only */ #define AC_MCTL_10BT_SEL 0x0800 /* Enable 7-wire interface */ #define AC_MCTL_DIS_JAB 0x1000 /* Disable jabber */ #define AC_MCTL_FRC_LINK 0x2000 /* Force TX link up */ #define AC_MCTL_DIS_NLP 0x4000 /* Disable NLP check */ #define MII_ACPHY_REC 0x18 /* Recv error counter */ #endif /* _DEV_MII_ACPHYREG_H_ */
1,388
1,056
<filename>enterprise/web.jsf.editor/src/org/netbeans/modules/web/jsf/editor/facelets/EmptyServletContext.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.netbeans.modules.web.jsf.editor.facelets; import com.sun.faces.config.processor.AbstractConfigProcessor; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.EventListener; import java.util.Map; import java.util.Set; import javax.faces.application.ProjectStage; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.ServletRegistration.Dynamic; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; /** * Since JSF 2.2 {@link AbstractConfigProcessor#loadClass} requires to obtain ServletContext. For needs of tag * libraries scanning almost empty {@code ServletContext} should be sufficient. This class is created in the way * to prevent raising exceptions from the JSF 2.2 binaries. * * @author <NAME> <<EMAIL>> */ class EmptyServletContext implements ServletContext { @Override public String getContextPath() { return ""; } @Override public ServletContext getContext(String string) { return this; } @Override public int getMajorVersion() { return -1; } @Override public int getMinorVersion() { return -1; } @Override public int getEffectiveMajorVersion() { return -1; } @Override public int getEffectiveMinorVersion() { return -1; } @Override public String getMimeType(String string) { return ""; } @Override public Set<String> getResourcePaths(String string) { return Collections.emptySet(); } @Override public URL getResource(String string) throws MalformedURLException { return null; } @Override public InputStream getResourceAsStream(String string) { return null; } @Override public RequestDispatcher getRequestDispatcher(String string) { return null; } @Override public RequestDispatcher getNamedDispatcher(String string) { return null; } @Override public Servlet getServlet(String string) throws ServletException { return null; } @Override public Enumeration<Servlet> getServlets() { return null; } @Override public Enumeration<String> getServletNames() { return null; } @Override public void log(String string) { } @Override public void log(Exception excptn, String string) { } @Override public void log(String string, Throwable thrwbl) { } @Override public String getRealPath(String string) { return ""; } @Override public String getServerInfo() { return ""; } @Override public String getInitParameter(String string) { return ""; } @Override public Enumeration<String> getInitParameterNames() { return null; } @Override public boolean setInitParameter(String string, String string1) { return false; } @Override public Object getAttribute(String attribute) { final String projectStageKey = AbstractConfigProcessor.class.getName() + ".PROJECTSTAGE"; if (attribute.equals(projectStageKey)) { return ProjectStage.Development; } return null; } @Override public Enumeration<String> getAttributeNames() { return null; } @Override public void setAttribute(String string, Object o) { } @Override public void removeAttribute(String string) { } @Override public String getServletContextName() { return ""; } @Override public Dynamic addServlet(String string, String string1) { return null; } @Override public Dynamic addServlet(String string, Servlet srvlt) { return null; } @Override public Dynamic addServlet(String string, Class<? extends Servlet> type) { return null; } @Override public <T extends Servlet> T createServlet(Class<T> type) throws ServletException { return null; } @Override public ServletRegistration getServletRegistration(String string) { return null; } @Override public Map<String, ? extends ServletRegistration> getServletRegistrations() { return null; } @Override public FilterRegistration.Dynamic addFilter(String string, String string1) { return null; } @Override public FilterRegistration.Dynamic addFilter(String string, Filter filter) { return null; } @Override public FilterRegistration.Dynamic addFilter(String string, Class<? extends Filter> type) { return null; } @Override public <T extends Filter> T createFilter(Class<T> type) throws ServletException { return null; } @Override public FilterRegistration getFilterRegistration(String string) { return null; } @Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { return Collections.emptyMap(); } @Override public SessionCookieConfig getSessionCookieConfig() { return null; } @Override public void setSessionTrackingModes(Set<SessionTrackingMode> set) { } @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { return Collections.emptySet(); } @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { return Collections.emptySet(); } @Override public void addListener(String string) { } @Override public <T extends EventListener> void addListener(T t) { } @Override public void addListener(Class<? extends EventListener> type) { } @Override public <T extends EventListener> T createListener(Class<T> type) throws ServletException { return null; } @Override public JspConfigDescriptor getJspConfigDescriptor() { return null; } @Override public ClassLoader getClassLoader() { return null; } @Override public void declareRoles(String... strings) { } @Override public String getVirtualServerName() { return ""; } }
2,630
17,004
<reponame>TylerPham2000/zulip<filename>zerver/webhooks/buildbot/fixtures/finished_failure.json { "event": "finished", "buildid": 34, "buildername": "runtests", "url": "http://exampleurl.com/#builders/1/builds/34", "project": "", "timestamp": 1553911142, "results": 2 }
113
377
<reponame>myhoa99/blurTestAndroid<filename>BlurBenchmark/src/main/java/at/favre/app/blurbenchmark/blur/algorithms/RenderScriptStackBlur.java package at.favre.app.blurbenchmark.blur.algorithms; import android.content.Context; import android.graphics.Bitmap; import androidx.renderscript.Allocation; import androidx.renderscript.Element; import androidx.renderscript.RenderScript; import at.favre.app.blurbenchmark.ScriptC_stackblur; import at.favre.app.blurbenchmark.blur.IBlur; /** * by kikoso * from https://github.com/kikoso/android-stackblur/blob/master/StackBlur/src/blur.rs */ public class RenderScriptStackBlur implements IBlur { private RenderScript _rs; private Context ctx; public RenderScriptStackBlur(RenderScript rs, Context ctx) { this.ctx = ctx; this._rs = rs; } @Override public Bitmap blur(int radius, Bitmap blurred) { int width = blurred.getWidth(); int height = blurred.getHeight(); ScriptC_stackblur blurScript = new ScriptC_stackblur(_rs); Allocation inAllocation = Allocation.createFromBitmap(_rs, blurred); blurScript.set_gIn(inAllocation); blurScript.set_width(width); blurScript.set_height(height); blurScript.set_radius(radius); int[] row_indices = new int[height]; for (int i = 0; i < height; i++) { row_indices[i] = i; } Allocation rows = Allocation.createSized(_rs, Element.U32(_rs), height, Allocation.USAGE_SCRIPT); rows.copyFrom(row_indices); row_indices = new int[width]; for (int i = 0; i < width; i++) { row_indices[i] = i; } Allocation columns = Allocation.createSized(_rs, Element.U32(_rs), width, Allocation.USAGE_SCRIPT); columns.copyFrom(row_indices); blurScript.forEach_blur_h(rows); blurScript.forEach_blur_v(columns); inAllocation.copyTo(blurred); return blurred; } }
825
737
<gh_stars>100-1000 /* decision_tree.h -*- C++ -*- <NAME>, 22 March 2004 Copyright (c) 2004 <NAME>. All rights reserved. $Source$ Decision tree classifier. */ #ifndef __boosting__decision_tree_h__ #define __boosting__decision_tree_h__ #include "classifier.h" #include "feature_set.h" #include <boost/pool/object_pool.hpp> #include "tree.h" #include "boolean_expression.h" namespace ML { class Training_Data; /*****************************************************************************/ /* DECISION_TREE */ /*****************************************************************************/ /** This is a tree of arbitrary depth as a classifier. Based upon the CART algorithm. We are not yet doing any pruning. As a result, capacity control needs to be done by using the max_depth property, rather than relying on held out data. The correct depth can still be evaluated on this held out data, though. */ class Decision_Tree : public Classifier_Impl { public: /** Default construct. Must be initialised before use. */ Decision_Tree(); /** Construct it by reconstituting it from a store. */ Decision_Tree(DB::Store_Reader & store, const std::shared_ptr<const Feature_Space> & fs); /** Construct not filled in yet. */ Decision_Tree(std::shared_ptr<const Feature_Space> feature_space, const Feature & predicted); virtual ~Decision_Tree(); void swap(Decision_Tree & other); Tree tree; ///< The tree we have learned Output_Encoding encoding; ///< How the outputs are represented bool optimized_; ///< Is predict() optimized? using Classifier_Impl::predict; virtual float predict(int label, const Feature_Set & features, PredictionContext * context = 0) const; virtual distribution<float> predict(const Feature_Set & features, PredictionContext * context = 0) const; /** Is optimization supported by the classifier? */ virtual bool optimization_supported() const; /** Is predict optimized? Default returns false; those classifiers which a) support optimized predict and b) have had optimize_predict() called will override to return true in this case. */ virtual bool predict_is_optimized() const; /** Function to override to perform the optimization. Default will simply modify the optimization info to indicate that optimization had failed. */ virtual bool optimize_impl(Optimization_Info & info); void optimize_recursive(Optimization_Info & info, const Tree::Ptr & ptr); /** Optimized predict for a dense feature vector. This is the worker function that all classifiers that implement the optimized predict should override. The default implementation will convert to a Feature_Set and will call the non-optimized predict. */ virtual Label_Dist optimized_predict_impl(const float * features, const Optimization_Info & info, PredictionContext * context = 0) const; virtual void optimized_predict_impl(const float * features, const Optimization_Info & info, double * accum, double weight, PredictionContext * context = 0) const; virtual float optimized_predict_impl(int label, const float * features, const Optimization_Info & info, PredictionContext * context = 0) const; template<class GetFeatures, class Results> void predict_recursive_impl(const GetFeatures & get_features, Results & results, const Tree::Ptr & ptr, double weight = 1.0) const; virtual Explanation explain(const Feature_Set & feature_set, int label, double weight = 1.0, PredictionContext * context = 0) const; void explain_recursive(Explanation & explanation, const Feature_Set & fset, int label, double weight, const Tree::Ptr & ptr, const Tree::Node * parent) const; /** Convert the decision tree to a disjuction of conjunctions form of boolean rules. */ virtual Disjunction<Tree::Leaf> to_rules() const; void to_rules_recursive(Disjunction<Tree::Leaf> & result, std::vector<std::shared_ptr<Predicate> > & path, const Tree::Ptr & ptr) const; virtual std::string print() const; virtual std::string summary() const; virtual std::vector<Feature> all_features() const; virtual Output_Encoding output_encoding() const; std::string print_recursive(int level, const Tree::Ptr & ptr, float total_weight) const; virtual void serialize(DB::Store_Writer & store) const; virtual void reconstitute(DB::Store_Reader & store, const std::shared_ptr<const Feature_Space> & feature_space); virtual std::string class_id() const; virtual Decision_Tree * make_copy() const; }; } // namespace ML #endif /* __boosting__decision_tree_h__ */
2,379
11,775
package hello; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class HelloController { @RequestMapping("/") public String sayHello() { String name = new RestTemplate().getForEntity("http://name-service", String.class).getBody(); return "Hello " + name; } }
131
1,738
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <GraphCanvas/Widgets/EditorContextMenu/ContextMenuActions/ContextMenuAction.h> #include <GraphCanvas/Components/SceneBus.h> namespace GraphCanvas { ////////////////////// // ContextMenuAction ////////////////////// ContextMenuAction::ContextMenuAction(AZStd::string_view actionName, QObject* parent) : QAction(actionName.data(), parent) { } void ContextMenuAction::SetTarget(const GraphId& graphId, const AZ::EntityId& targetId) { m_graphId = graphId; m_targetId = targetId; RefreshAction(); } bool ContextMenuAction::IsInSubMenu() const { return false; } AZStd::string ContextMenuAction::GetSubMenuPath() const { return ""; } const AZ::EntityId& ContextMenuAction::GetTargetId() const { return m_targetId; } const GraphId& ContextMenuAction::GetGraphId() const { return m_graphId; } EditorId ContextMenuAction::GetEditorId() const { EditorId editorId; SceneRequestBus::EventResult(editorId, GetGraphId(), &SceneRequests::GetEditorId); return editorId; } void ContextMenuAction::RefreshAction() { RefreshAction(m_graphId, m_targetId); } void ContextMenuAction::RefreshAction(const GraphId& graphId, const AZ::EntityId& targetId) { AZ_UNUSED(graphId); AZ_UNUSED(targetId); setEnabled(true); } #include <StaticLib/GraphCanvas/Widgets/EditorContextMenu/ContextMenuActions/ContextMenuAction.moc> }
750
1,947
#include "gurka.h" #include "test.h" using namespace valhalla; class DeadendBarrier : public testing::TestWithParam<std::string> { protected: static gurka::nodelayout layout; static gurka::ways ways; static void SetUpTestSuite() { constexpr double gridsize = 100; const std::string ascii_map = R"( A-----1----B )"; layout = gurka::detail::map_to_coordinates(ascii_map, gridsize); ways = { {"A1", {{"highway", "primary"}}}, {"1B", {{"highway", "primary"}}}, }; } }; gurka::nodelayout DeadendBarrier::layout = {}; gurka::ways DeadendBarrier::ways = {}; TEST_P(DeadendBarrier, DeniedAccess) { const gurka::nodes nodes = { {"1", {{"barrier", GetParam()}, {"access", "no"}}}, }; const gurka::map map = gurka::buildtiles(layout, ways, nodes, {}, "test/data/deadend_barrier_no_access"); try { auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "auto"); gurka::assert::raw::expect_path(result, {"Unexpected path found"}); } catch (const std::runtime_error& e) { EXPECT_STREQ(e.what(), "No path could be found for input"); } } TEST_P(DeadendBarrier, AllowedAccess) { const gurka::nodes nodes = { {"1", {{"barrier", GetParam()}, {"access", "yes"}}}, }; const gurka::map map = gurka::buildtiles(layout, ways, nodes, {}, "test/data/deadend_barrier_allowed_access"); auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "auto"); gurka::assert::raw::expect_path(result, {"A1", "1B"}); } TEST_P(DeadendBarrier, PrivateAccess) { const gurka::nodes nodes = { {"1", {{"barrier", GetParam()}, {"access", "private"}}}, }; const gurka::map map = gurka::buildtiles(layout, ways, nodes, {}, "test/data/deadend_barrier_private_access"); // auto auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "auto"); gurka::assert::raw::expect_path(result, {"A1", "1B"}); // pedestrian result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "pedestrian"); gurka::assert::raw::expect_path(result, {"A1", "1B"}); } class GateBarrier : public DeadendBarrier {}; TEST_P(GateBarrier, NoInfoBarrierAccess) { const gurka::nodes nodes = { {"1", {{"barrier", GetParam()}}}, }; const gurka::map map = gurka::buildtiles(layout, ways, nodes, {}, "test/data/deadend_gate_no_info_access"); auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "auto"); gurka::assert::raw::expect_path(result, {"A1", "1B"}); } TEST_P(GateBarrier, BikeRestricted) { const gurka::nodes nodes = { {"1", {{"barrier", GetParam()}, {"bicycle", "no"}}}, }; const gurka::map map = gurka::buildtiles(layout, ways, nodes, {}, "test/data/deadend_gate_bike_restricted_barrier"); // auto auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "auto"); gurka::assert::raw::expect_path(result, {"A1", "1B"}); // bicycle try { result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "bicycle"); gurka::assert::raw::expect_path(result, {"Unexpected path found"}); } catch (const std::runtime_error& e) { EXPECT_STREQ(e.what(), "No path could be found for input"); } } TEST_P(GateBarrier, BikeAllowedNoOtherInformation) { const gurka::nodes nodes = { {"1", {{"barrier", GetParam()}, {"bicycle", "yes"}}}, }; const gurka::map map = gurka::buildtiles(layout, ways, nodes, {}, "test/data/deadend_gate_bike_allowed_barrier"); // auto auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "auto"); gurka::assert::raw::expect_path(result, {"A1", "1B"}); // bicycle result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "bicycle"); gurka::assert::raw::expect_path(result, {"A1", "1B"}); } class BollardBarrier : public DeadendBarrier {}; TEST_P(BollardBarrier, NoInfoBarrierAccess) { const gurka::nodes nodes = { {"1", {{"barrier", GetParam()}}}, }; const gurka::map map = gurka::buildtiles(layout, ways, nodes, {}, "test/data/deadend_bollard_no_info_access"); try { auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "auto"); gurka::assert::raw::expect_path(result, {"Unexpected path found"}); } catch (const std::runtime_error& e) { EXPECT_STREQ(e.what(), "No path could be found for input"); } auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "pedestrian"); gurka::assert::raw::expect_path(result, {"A1", "1B"}); } TEST_P(BollardBarrier, BikeRestricted) { const gurka::nodes nodes = { {"1", {{"barrier", GetParam()}, {"bicycle", "no"}}}, }; const gurka::map map = gurka::buildtiles(layout, ways, nodes, {}, "test/data/deadend_bollarrd_bike_restricted_barrier"); // auto try { auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "auto"); gurka::assert::raw::expect_path(result, {"Unexpected path found"}); } catch (const std::runtime_error& e) { EXPECT_STREQ(e.what(), "No path could be found for input"); } // bicycle try { auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "bicycle"); gurka::assert::raw::expect_path(result, {"Unexpected path found"}); } catch (const std::runtime_error& e) { EXPECT_STREQ(e.what(), "No path could be found for input"); } } TEST_P(BollardBarrier, BikeAllowedNoOtherInformation) { const gurka::nodes nodes = { {"1", {{"barrier", GetParam()}, {"bicycle", "yes"}}}, }; const gurka::map map = gurka::buildtiles(layout, ways, nodes, {}, "test/data/deadend_bollard_bike_allowed_barrier"); // auto try { auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "auto"); gurka::assert::raw::expect_path(result, {"Unexpected path found"}); } catch (const std::runtime_error& e) { EXPECT_STREQ(e.what(), "No path could be found for input"); } // bicycle auto result = gurka::do_action(valhalla::Options::route, map, {"A", "B"}, "bicycle"); gurka::assert::raw::expect_path(result, {"A1", "1B"}); } const std::vector<std::string> gates = {"gate", "yes", "lift_gate", "swing_gate"}; const std::vector<std::string> bollards = {"bollard", "block", "jersey_barrier"}; INSTANTIATE_TEST_SUITE_P(GateBasicAccess, DeadendBarrier, testing::ValuesIn(gates)); INSTANTIATE_TEST_SUITE_P(BollardBasicAccess, DeadendBarrier, testing::ValuesIn(bollards)); INSTANTIATE_TEST_SUITE_P(GateAccess, GateBarrier, testing::ValuesIn(gates)); INSTANTIATE_TEST_SUITE_P(BollardAccess, BollardBarrier, testing::ValuesIn(bollards));
2,672
682
<reponame>HackerFoo/vtr-verilog-to-routing<filename>abc/src/misc/mvc/mvcOpBool.c<gh_stars>100-1000 /**CFile**************************************************************** FileName [mvcProc.c] PackageName [MVSIS 2.0: Multi-valued logic synthesis system.] Synopsis [Various boolean procedures working with covers.] Author [MVSIS Group] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - February 1, 2003.] Revision [$Id: mvcOpBool.c,v 1.4 2003/04/16 01:55:37 alanmi Exp $] ***********************************************************************/ #include "mvc.h" ABC_NAMESPACE_IMPL_START //////////////////////////////////////////////////////////////////////// /// DECLARATIONS /// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// FUNCTION DEFINITIONS /// //////////////////////////////////////////////////////////////////////// /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Mvc_Cover_t * Mvc_CoverBooleanOr( Mvc_Cover_t * pCover1, Mvc_Cover_t * pCover2 ) { Mvc_Cover_t * pCover; Mvc_Cube_t * pCube, * pCubeCopy; // make sure the covers are compatible assert( pCover1->nBits == pCover2->nBits ); // clone the cover pCover = Mvc_CoverClone( pCover1 ); // create the cubes by making pair-wise products // of cubes in pCover1 and pCover2 Mvc_CoverForEachCube( pCover1, pCube ) { pCubeCopy = Mvc_CubeDup( pCover, pCube ); Mvc_CoverAddCubeTail( pCover, pCubeCopy ); } Mvc_CoverForEachCube( pCover2, pCube ) { pCubeCopy = Mvc_CubeDup( pCover, pCube ); Mvc_CoverAddCubeTail( pCover, pCubeCopy ); } return pCover; } #if 0 /**Function************************************************************* Synopsis [] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ Mvc_Cover_t * Mvc_CoverBooleanAnd( Mvc_Data_t * p, Mvc_Cover_t * pCover1, Mvc_Cover_t * pCover2 ) { Mvc_Cover_t * pCover; Mvc_Cube_t * pCube1, * pCube2, * pCubeCopy; // make sure the covers are compatible assert( pCover1->nBits == pCover2->nBits ); // clone the cover pCover = Mvc_CoverClone( pCover1 ); // create the cubes by making pair-wise products // of cubes in pCover1 and pCover2 Mvc_CoverForEachCube( pCover1, pCube1 ) { Mvc_CoverForEachCube( pCover2, pCube2 ) { if ( Mvc_CoverDist0Cubes( p, pCube1, pCube2 ) ) { pCubeCopy = Mvc_CubeAlloc( pCover ); Mvc_CubeBitAnd( pCubeCopy, pCube1, pCube2 ); Mvc_CoverAddCubeTail( pCover, pCubeCopy ); } } // if the number of cubes in the new cover is too large // try compressing them if ( Mvc_CoverReadCubeNum( pCover ) > 500 ) Mvc_CoverContain( pCover ); } return pCover; } /**Function************************************************************* Synopsis [Returns 1 if the two covers are equal.] Description [] SideEffects [] SeeAlso [] ***********************************************************************/ int Mvc_CoverBooleanEqual( Mvc_Data_t * p, Mvc_Cover_t * pCover1, Mvc_Cover_t * pCover2 ) { Mvc_Cover_t * pSharp; pSharp = Mvc_CoverSharp( p, pCover1, pCover2 ); if ( Mvc_CoverReadCubeNum( pSharp ) ) { Mvc_CoverContain( pSharp ); printf( "Sharp \n" ); Mvc_CoverPrint( pSharp ); Mvc_CoverFree( pSharp ); return 0; } Mvc_CoverFree( pSharp ); pSharp = Mvc_CoverSharp( p, pCover2, pCover1 ); if ( Mvc_CoverReadCubeNum( pSharp ) ) { Mvc_CoverContain( pSharp ); printf( "Sharp \n" ); Mvc_CoverPrint( pSharp ); Mvc_CoverFree( pSharp ); return 0; } Mvc_CoverFree( pSharp ); return 1; } #endif //////////////////////////////////////////////////////////////////////// /// END OF FILE /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_IMPL_END
1,756
513
<reponame>trajano/google-fonts<filename>font-packages/noto-sans-jp/metadata.json { "family": "Noto Sans JP", "variants": ["100", "300", "regular", "500", "700", "900"], "subsets": ["japanese", "latin"], "version": "v28", "lastModified": "2020-11-12", "files": { "100": "http://fonts.gstatic.com/s/notosansjp/v28/-F6ofjtqLzI2JPCgQBnw7HFQoggM-FNthvIU.otf", "300": "http://fonts.gstatic.com/s/notosansjp/v28/-F6pfjtqLzI2JPCgQBnw7HFQaioq1H1hj-sNFQ.otf", "500": "http://fonts.gstatic.com/s/notosansjp/v28/-F6pfjtqLzI2JPCgQBnw7HFQMisq1H1hj-sNFQ.otf", "700": "http://fonts.gstatic.com/s/notosansjp/v28/-F6pfjtqLzI2JPCgQBnw7HFQei0q1H1hj-sNFQ.otf", "900": "http://fonts.gstatic.com/s/notosansjp/v28/-F6pfjtqLzI2JPCgQBnw7HFQQi8q1H1hj-sNFQ.otf", "regular": "http://fonts.gstatic.com/s/notosansjp/v28/-F62fjtqLzI2JPCgQBnw7HFowAIO2lZ9hg.otf" }, "category": "sans-serif", "kind": "webfonts#webfont" }
510
5,169
<reponame>Gantios/Specs<gh_stars>1000+ { "name": "UIKit-macOS", "version": "0.0.1", "summary": "macOS use UIKit", "description": "macOS use UIKit", "homepage": "https://github.com/fangandyuan/UIKit-MacOS", "license": "MIT", "authors": { "<EMAIL>": "<EMAIL>" }, "platforms": { "osx": "10.11" }, "source": { "git": "https://github.com/fangandyuan/UIKit-MacOS.git", "tag": "0.0.1" }, "source_files": "UIKit/UISlider/*.swift", "frameworks": "Cocoa" }
229
670
<gh_stars>100-1000 { "definitions": { "session_id": { "$ref": "Session.schema.json#/definitions/id" }, "expire": { "$ref": "Utils.schema.json#/definitions/numbers/unix_time" } }, "type": "object", "properties": { "session_id": { "$ref": "#/definitions/session_id" }, "expire": { "$ref": "#/definitions/expire" } }, "required": ["session_id", "expire"], "additionalProperties": false }
165
1,837
package com.dianping.zebra.administrator.dto; /** * @author Created by tong.xin on 18/1/19. */ public class ResultDto<T> { String status; String message; T result; public ResultDto() { } public ResultDto(String status, String message) { this.status = status; this.message = message; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getResult() { return result; } public void setResult(T result) { this.result = result; } }
310
1,338
/* * Copyright 2006, Haiku. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ #include "PathContainer.h" #include <stdio.h> #include <string.h> #include <OS.h> #include "VectorPath.h" #ifdef ICON_O_MATIC PathContainerListener::PathContainerListener() {} PathContainerListener::~PathContainerListener() {} #endif // constructor PathContainer::PathContainer(bool ownsPaths) : fPaths(16), fOwnsPaths(ownsPaths) #ifdef ICON_O_MATIC , fListeners(2) #endif { } // destructor PathContainer::~PathContainer() { #ifdef ICON_O_MATIC int32 count = fListeners.CountItems(); if (count > 0) { debugger("~PathContainer() - there are still" "listeners attached\n"); } #endif // ICON_O_MATIC _MakeEmpty(); } // #pragma mark - // AddPath bool PathContainer::AddPath(VectorPath* path) { return AddPath(path, CountPaths()); } // AddPath bool PathContainer::AddPath(VectorPath* path, int32 index) { if (!path) return false; // prevent adding the same path twice if (HasPath(path)) return false; if (fPaths.AddItem((void*)path, index)) { #ifdef ICON_O_MATIC _NotifyPathAdded(path, index); #endif return true; } fprintf(stderr, "PathContainer::AddPath() - out of memory!\n"); return false; } // RemovePath bool PathContainer::RemovePath(VectorPath* path) { if (fPaths.RemoveItem((void*)path)) { #ifdef ICON_O_MATIC _NotifyPathRemoved(path); #endif return true; } return false; } // RemovePath VectorPath* PathContainer::RemovePath(int32 index) { VectorPath* path = (VectorPath*)fPaths.RemoveItem(index); #ifdef ICON_O_MATIC if (path) { _NotifyPathRemoved(path); } #endif return path; } // MakeEmpty void PathContainer::MakeEmpty() { _MakeEmpty(); } // #pragma mark - // CountPaths int32 PathContainer::CountPaths() const { return fPaths.CountItems(); } // HasPath bool PathContainer::HasPath(VectorPath* path) const { return fPaths.HasItem((void*)path); } // IndexOf int32 PathContainer::IndexOf(VectorPath* path) const { return fPaths.IndexOf((void*)path); } // PathAt VectorPath* PathContainer::PathAt(int32 index) const { return (VectorPath*)fPaths.ItemAt(index); } // PathAtFast VectorPath* PathContainer::PathAtFast(int32 index) const { return (VectorPath*)fPaths.ItemAtFast(index); } // #pragma mark - #ifdef ICON_O_MATIC // AddListener bool PathContainer::AddListener(PathContainerListener* listener) { if (listener && !fListeners.HasItem((void*)listener)) return fListeners.AddItem(listener); return false; } // RemoveListener bool PathContainer::RemoveListener(PathContainerListener* listener) { return fListeners.RemoveItem(listener); } #endif // ICON_O_MATIC // #pragma mark - // _MakeEmpty void PathContainer::_MakeEmpty() { int32 count = CountPaths(); for (int32 i = 0; i < count; i++) { VectorPath* path = PathAtFast(i); #ifdef ICON_O_MATIC _NotifyPathRemoved(path); if (fOwnsPaths) path->ReleaseReference(); #else if (fOwnsPaths) delete path; #endif } fPaths.MakeEmpty(); } // #pragma mark - #ifdef ICON_O_MATIC // _NotifyPathAdded void PathContainer::_NotifyPathAdded(VectorPath* path, int32 index) const { BList listeners(fListeners); int32 count = listeners.CountItems(); for (int32 i = 0; i < count; i++) { PathContainerListener* listener = (PathContainerListener*)listeners.ItemAtFast(i); listener->PathAdded(path, index); } } // _NotifyPathRemoved void PathContainer::_NotifyPathRemoved(VectorPath* path) const { BList listeners(fListeners); int32 count = listeners.CountItems(); for (int32 i = 0; i < count; i++) { PathContainerListener* listener = (PathContainerListener*)listeners.ItemAtFast(i); listener->PathRemoved(path); } } #endif // ICON_O_MATIC
1,400
337
<gh_stars>100-1000 // Copyright 2018 <NAME> // Distributed under the Boost license, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See https://github.com/danielaparker/jsoncons for latest version #ifndef JSONCONS_RESULT_HPP #define JSONCONS_RESULT_HPP #include <stdexcept> #include <string> #include <vector> #include <ostream> #include <cmath> #include <exception> #include <memory> // std::addressof #include <cstring> // std::memcpy #include <jsoncons/config/jsoncons_config.hpp> #include <jsoncons/detail/type_traits.hpp> namespace jsoncons { // stream_result template <class CharT> class stream_result { public: typedef CharT value_type; typedef std::basic_ostream<CharT> output_type; private: static const size_t default_buffer_length = 16384; std::basic_ostream<CharT>* os_; std::vector<CharT> buffer_; CharT * begin_buffer_; const CharT* end_buffer_; CharT* p_; // Noncopyable stream_result(const stream_result&) = delete; stream_result& operator=(const stream_result&) = delete; public: stream_result(stream_result&&) = default; stream_result(std::basic_ostream<CharT>& os) : os_(std::addressof(os)), buffer_(default_buffer_length), begin_buffer_(buffer_.data()), end_buffer_(begin_buffer_+buffer_.size()), p_(begin_buffer_) { } stream_result(std::basic_ostream<CharT>& os, size_t buflen) : os_(std::addressof(os)), buffer_(buflen), begin_buffer_(buffer_.data()), end_buffer_(begin_buffer_+buffer_.size()), p_(begin_buffer_) { } ~stream_result() { os_->write(begin_buffer_, buffer_length()); os_->flush(); } stream_result& operator=(stream_result&&) = default; void flush() { os_->write(begin_buffer_, buffer_length()); os_->flush(); p_ = buffer_.data(); } void append(const CharT* s, size_t length) { size_t diff = end_buffer_ - p_; if (diff >= length) { std::memcpy(p_, s, length*sizeof(CharT)); p_ += length; } else { os_->write(begin_buffer_, buffer_length()); os_->write(s,length); p_ = begin_buffer_; } } void push_back(CharT ch) { if (p_ < end_buffer_) { *p_++ = ch; } else { os_->write(begin_buffer_, buffer_length()); p_ = begin_buffer_; push_back(ch); } } private: size_t buffer_length() const { return p_ - begin_buffer_; } }; // binary_stream_result class binary_stream_result { public: typedef uint8_t value_type; typedef std::basic_ostream<char> output_type; private: static const size_t default_buffer_length = 16384; std::basic_ostream<char>* os_; std::vector<uint8_t> buffer_; uint8_t * begin_buffer_; const uint8_t* end_buffer_; uint8_t* p_; // Noncopyable binary_stream_result(const binary_stream_result&) = delete; binary_stream_result& operator=(const binary_stream_result&) = delete; public: binary_stream_result(binary_stream_result&&) = default; binary_stream_result(std::basic_ostream<char>& os) : os_(std::addressof(os)), buffer_(default_buffer_length), begin_buffer_(buffer_.data()), end_buffer_(begin_buffer_+buffer_.size()), p_(begin_buffer_) { } binary_stream_result(std::basic_ostream<char>& os, size_t buflen) : os_(std::addressof(os)), buffer_(buflen), begin_buffer_(buffer_.data()), end_buffer_(begin_buffer_+buffer_.size()), p_(begin_buffer_) { } ~binary_stream_result() { os_->write((char*)begin_buffer_, buffer_length()); os_->flush(); } binary_stream_result& operator=(binary_stream_result&&) = default; void flush() { os_->write((char*)begin_buffer_, buffer_length()); p_ = buffer_.data(); } void append(const uint8_t* s, size_t length) { size_t diff = end_buffer_ - p_; if (diff >= length) { std::memcpy(p_, s, length*sizeof(uint8_t)); p_ += length; } else { os_->write((char*)begin_buffer_, buffer_length()); os_->write((const char*)s,length); p_ = begin_buffer_; } } void push_back(uint8_t ch) { if (p_ < end_buffer_) { *p_++ = ch; } else { os_->write((char*)begin_buffer_, buffer_length()); p_ = begin_buffer_; push_back(ch); } } private: size_t buffer_length() const { return p_ - begin_buffer_; } }; // string_result template <class StringT> class string_result { public: typedef typename StringT::value_type value_type; typedef StringT output_type; private: output_type* s_; // Noncopyable string_result(const string_result&) = delete; string_result& operator=(const string_result&) = delete; public: string_result(string_result&& val) : s_(nullptr) { std::swap(s_,val.s_); } string_result(output_type& s) : s_(std::addressof(s)) { } string_result& operator=(string_result&& val) { std::swap(s_, val.s_); } void flush() { } void append(const value_type* s, size_t length) { s_->insert(s_->end(), s, s+length); } void push_back(value_type ch) { s_->push_back(ch); } }; // bytes_result class bytes_result { public: typedef uint8_t value_type; typedef std::vector<uint8_t> output_type; private: output_type& s_; // Noncopyable bytes_result(const bytes_result&) = delete; bytes_result& operator=(const bytes_result&) = delete; public: bytes_result(bytes_result&&) = default; bytes_result(output_type& s) : s_(s) { } bytes_result& operator=(bytes_result&&) = default; void flush() { } void append(const uint8_t* s, size_t length) { s_.insert(s_.end(), s, s+length); } void push_back(uint8_t ch) { s_.push_back(ch); } }; } #endif
2,943
836
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.test.espresso.action; import static androidx.test.espresso.Espresso.onView; import static androidx.test.espresso.action.ViewActions.pressImeActionButton; import static androidx.test.espresso.action.ViewActions.scrollTo; import static androidx.test.espresso.action.ViewActions.typeText; import static androidx.test.espresso.action.ViewActions.typeTextIntoFocusedView; import static androidx.test.espresso.assertion.ViewAssertions.matches; import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed; import static androidx.test.espresso.matcher.ViewMatchers.withId; import static androidx.test.espresso.matcher.ViewMatchers.withParent; import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.junit.rules.ExpectedException.none; import androidx.test.espresso.PerformException; import androidx.test.ext.junit.rules.ActivityScenarioRule; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.filters.LargeTest; import androidx.test.ui.app.R; import androidx.test.ui.app.SendActivity; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; /** {@link TypeTextAction} integration tests. */ @LargeTest @RunWith(AndroidJUnit4.class) public class TypeTextActionIntegrationTest { @Rule public ExpectedException expectedException = none(); @Rule public ActivityScenarioRule<SendActivity> rule = new ActivityScenarioRule<>(SendActivity.class); @Test public void typeTextActionPerform() { onView(withId(is(R.id.send_data_to_call_edit_text))).perform(typeText("Hello!")); } @Test public void typeTextActionPerformWithEnter() { onView(withId(R.id.enter_data_edit_text)).perform(typeText("Hello World!\n")); onView(allOf(withId(R.id.enter_data_response_text), withText("Hello World!"))) .check(matches(isDisplayed())); } @Test public void typeTextInFocusedView() { onView(withId(is(R.id.send_data_to_call_edit_text))) .perform(typeText("Hello World How Are You Today? I have alot of text to type.")); onView(withId(is(R.id.send_data_to_call_edit_text))) .perform(typeTextIntoFocusedView("Jolly good!")); onView(withId(is(R.id.send_data_to_call_edit_text))) .check( matches( withText( "Hello World How Are You Today? I have alot of text to type.Jolly good!"))); } /** * Test only passes if run in isolation. Unless Gradle supports a single instrumentation per test * this test is ignored" */ @Test public void typeTextInFocusedView_constraintBreakage() { onView(withId(is(R.id.send_data_to_call_edit_text))) .perform(typeText("Hello World How Are You Today? I have alot of text to type.")); expectedException.expect(PerformException.class); onView(withId(is(R.id.edit_text_message))) .perform(scrollTo(), typeTextIntoFocusedView("Jolly good!")); } @Test public void typeTextInDelegatedEditText() { String toType = "honeybadger doesn't care"; onView(allOf(withParent(withId(R.id.delegating_edit_text)), withId(R.id.delegate_edit_text))) .perform(scrollTo(), typeText(toType), pressImeActionButton()); onView(withId(R.id.edit_text_message)) .perform(scrollTo()) .check(matches(withText(containsString(toType)))); } /** * Test only passes if run in isolation. Unless Gradle supports a single instrumentation per test * this test is ignored" */ @Test public void testTypeText_NonEnglish() { expectedException.expect(RuntimeException.class); String toType = "在一个月之内的话"; onView(allOf(withParent(withId(R.id.delegating_edit_text)), withId(R.id.delegate_edit_text))) .perform(scrollTo(), typeText(toType)); } }
1,584
412
/* Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "graphd/graphd.h" #include "graphd/graphd-hash.h" #include <errno.h> #include <limits.h> #include <stdio.h> #include <string.h> graphd_constraint *graphd_constraint_or_prototype_root( graphd_constraint const *con) { while (con != NULL && con->con_or != NULL && con->con_or->or_prototype != NULL) con = con->con_or->or_prototype; return (graphd_constraint *)con; } graphd_constraint_or *graphd_constraint_or_create(graphd_request *greq, graphd_constraint *prototype, bool short_circuit) { graphd_constraint_or *o; o = cm_malloc(greq->greq_req.req_cm, sizeof(*o)); if (o == NULL) return NULL; memset(o, 0, sizeof *o); o->or_prototype = prototype; graphd_constraint_initialize(graphd_request_graphd(greq), &o->or_head); if (prototype != NULL) o->or_head.con_parent = prototype->con_parent; return o; } /* Append a set of alternatives to the "prototype" constraint * that all those alternatives have in common. */ void graphd_constraint_or_append_to_prototype(graphd_constraint *prototype, graphd_constraint_or *new_or) { *prototype->con_or_tail = new_or; prototype->con_or_tail = &new_or->or_next; new_or->or_next = NULL; } /* Return the "or" above "sub" that's directly below * "prototype". */ graphd_constraint_or *graphd_constraint_or_below( graphd_constraint const *prototype, graphd_constraint const *sub) { graphd_constraint_or *cor; graphd_constraint *proto; if (sub == NULL || sub == prototype) return NULL; for (cor = sub->con_or; cor != NULL; cor = proto->con_or) { proto = cor->or_prototype; if (proto == NULL || proto == prototype) break; } return cor; } /* A single { ... } has just finished parsing. */ int graphd_constraint_or_complete_parse(graphd_request *greq, graphd_constraint *prototype, graphd_constraint *sub) { size_t i; cl_handle *cl = graphd_request_cl(greq); graphd_constraint_or *cor; cl_log(cl, CL_LEVEL_VERBOSE, "graphd_constraint_or_complete_parse (proto=%p,sub=%p)", (void *)prototype, (void *)sub); sub->con_parent = prototype->con_parent; sub->con_next = NULL; /* Certain things can't be set in the "or" * subconstraint. */ if (sub->con_result != NULL) { graphd_request_errprintf( greq, 0, "SEMANTICS can't change result=... in an or-branch"); return GRAPHD_ERR_SEMANTICS; } if (sub->con_linkage != 0) { graphd_request_errprintf(greq, 0, "SEMANTICS can't change linkage in an or-branch"); return GRAPHD_ERR_SEMANTICS; } if (sub->con_sort != NULL && sub->con_sort_valid) { graphd_request_errprintf( greq, 0, "SEMANTICS can't change sort order in an or-branch"); return GRAPHD_ERR_SEMANTICS; } if (sub->con_sort_comparators.gcl_used) { graphd_request_errprintf( greq, 0, "SEMANTICS can't change comparator list in an or-branch"); return GRAPHD_ERR_SEMANTICS; } if (sub->con_pagesize_valid) { graphd_request_errprintf(greq, 0, "SEMANTIC can't change pagesize in an or-branch"); return GRAPHD_ERR_SEMANTICS; } if (sub->con_resultpagesize_parsed_valid) { graphd_request_errprintf( greq, 0, "SEMANTICS can't change resultpagesize in an or-branch"); return GRAPHD_ERR_SEMANTICS; } if (sub->con_countlimit_valid) { graphd_request_errprintf( greq, 0, "SEMANTICS can't change countlimit in an or-branch"); return GRAPHD_ERR_SEMANTICS; } if (sub->con_cursor_s != NULL) { graphd_request_errprintf(greq, 0, "SEMANTICS can't use a cursor in an or-branch"); return GRAPHD_ERR_SEMANTICS; } if (prototype->con_linkage != 0) { if (sub->con_linkage != 0 && sub->con_linkage != prototype->con_linkage) { graphd_request_errprintf(greq, 0, "SEMANTICS conflicting linkage inside " "and outside or-constraint"); return GRAPHD_ERR_SEMANTICS; } sub->con_linkage = prototype->con_linkage; } sub->con_parent = prototype->con_parent; sub->con_next = NULL; /* For anything that's unset, copy a default * from the prototype. */ sub->con_forward = prototype->con_forward; if (prototype->con_false) sub->con_false = true; if (sub->con_live == GRAPHD_FLAG_UNSPECIFIED) sub->con_live = prototype->con_live; if (sub->con_archival == GRAPHD_FLAG_UNSPECIFIED) sub->con_archival = prototype->con_archival; /* Generational constraints. */ if (!sub->con_newest.gencon_valid) sub->con_newest = prototype->con_newest; if (!sub->con_oldest.gencon_valid) sub->con_oldest = prototype->con_oldest; if (!sub->con_timestamp_valid) { sub->con_timestamp_valid = prototype->con_timestamp_valid; sub->con_timestamp_min = prototype->con_timestamp_min; sub->con_timestamp_max = prototype->con_timestamp_max; } if (sub->con_meta == GRAPHD_META_UNSPECIFIED) sub->con_meta = prototype->con_meta; if (prototype->con_linkage != 0) { if (sub->con_linkage != 0 && sub->con_linkage != prototype->con_linkage) { graphd_request_errprintf(greq, 0, "SEMANTICS conflicting linkage inside " "and outside or-constraint"); return GRAPHD_ERR_SEMANTICS; } sub->con_linkage = prototype->con_linkage; } for (i = 0; i < PDB_LINKAGE_N; i++) { if (!GRAPH_GUID_IS_NULL(prototype->con_linkguid[i])) { if (GRAPH_GUID_IS_NULL(sub->con_linkguid[i])) sub->con_linkguid[i] = prototype->con_linkguid[i]; else if (!GRAPH_GUID_EQ(sub->con_linkguid[i], prototype->con_linkguid[i])) prototype->con_false = true; } } if (sub->con_valuetype == 0) sub->con_valuetype = prototype->con_valuetype; if (sub->con_comparator == NULL || sub->con_comparator == graphd_comparator_default) sub->con_comparator = prototype->con_comparator; if (sub->con_value_comparator == NULL || sub->con_value_comparator == graphd_comparator_default) sub->con_value_comparator = prototype->con_value_comparator; #if 0 graphd_string_constraint_queue con_type; graphd_string_constraint_queue con_name; graphd_string_constraint_queue con_value; graphd_string_constraint con_strcon_buf[1]; size_t con_strcon_n; graphd_guid_constraint con_guid; graphd_guid_constraint con_linkcon[PDB_LINKAGE_N]; /* The next two are pseudoconstraints that eventually * translate into GUID restrictions. */ graphd_guid_constraint con_version_previous; graphd_guid_constraint con_version_next; graphd_count_constraint con_count; /* This expression uses "contents" somewhere -- in a sort, * assignment, or return (possibly an implicit return). */ unsigned int con_uses_contents: 1; int con_unique; int con_key; /* There are up to assignment_n + 2 pframes in total. * * pframe 0..n-1 are the first assignment_n pframes. * pframe N is the returned result. * pframe N + 1 is the unnamed temporary. */ graphd_pattern_frame * con_pframe; size_t con_pframe_n; cm_hashtable con_pframe_by_name; size_t con_pframe_temporary; unsigned int con_pframe_want_count: 1; unsigned int con_pframe_want_cursor: 1; unsigned int con_pframe_want_data: 1; graphd_sort_root con_sort_root; /* The estimated maximum number of matches for this * constraint, given any fixed parent. */ unsigned long long con_setsize; size_t con_start; /* Some IDs that don't match this. */ graphd_bad_cache con_bad_cache; graphd_dateline_constraint con_dateline; /* The constraint title. Used to * identify this constraint in log entries. */ char * con_title; char con_title_buf[256]; /* (READ) * * A counted chain that keeps track of the variables assigned * to via $tag=value statements. */ graphd_assignment * con_assignment_head; graphd_assignment ** con_assignment_tail; size_t con_assignment_n; /* How many variables in this context are assigned to in * subconstraints. */ size_t con_local_n; /* Map the variable name to an index into the temporary * local results. */ cm_hashtable con_local_hash; /* (READ) Variables declared (i.e., used) in this constraint. * * The hashtable hashes their name to a * graphd_variable_declaration record. */ cm_hashtable con_variable_declaration; unsigned int con_variable_declaration_valid: 1; /* (READ) An iterator that produces candidates for this * constraint (not taking into account the parent). */ graphd_freezable_iterator con_frit; /* (READ) low, high boundaries */ unsigned long long con_low; unsigned long long con_high; #endif /* If I have little ORs below me, let those copy from me. */ for (cor = sub->con_or_head; cor != NULL; cor = cor->or_next) { graphd_constraint_or_complete_parse(greq, sub, &cor->or_head); if (cor->or_tail != NULL) graphd_constraint_or_complete_parse(greq, sub, cor->or_tail); } return 0; } /* Initialize or re-initialize the "read-or-map" that, * for a given ID, tracks which of the OR branches * in the ID's constraint evaluate to true. */ size_t graphd_constraint_or_index(graphd_request *greq, graphd_constraint *con, size_t n) { graphd_constraint_or *cor; con->con_or_index = n++; for (cor = con->con_or_head; cor != NULL; cor = cor->or_next) { n = graphd_constraint_or_index(greq, &cor->or_head, n); if (cor->or_tail != NULL) n = graphd_constraint_or_index(greq, cor->or_tail, n); } return n; } /* Declare the variable <name_s..name_e> in the constraint * <orcon>. * * This actually declares <name_s..name_e[con_or_index]> instead, * and adds a __pick__ entry in <name_s..name_e> in the arch prototype. */ int graphd_constraint_or_declare(graphd_request *greq, graphd_constraint *orcon, char const *name_s, char const *name_e, graphd_variable_declaration **lhs_vdecl_out, graphd_variable_declaration **new_vdecl_out) { cl_handle *cl = graphd_request_cl(greq); cm_handle *cm = greq->greq_req.req_cm; graphd_variable_declaration *arch_vdecl, *indexed_vdecl; graphd_assignment *arch_a; char *tmp_name; char const *tmp_name_e; graphd_pattern *pick; graphd_constraint *arch; size_t need; *new_vdecl_out = NULL; cl_assert(cl, orcon->con_or_index > 0); arch = graphd_constraint_or_prototype_root(orcon); cl_assert(cl, arch != NULL); cl_assert(cl, arch->con_or_index == 0); /* Transform into a local assignment to a temporary. * * orcon[con_or_index]: $var = ((pattern)) * -> * orcon[0]: $var[con_or_index] = ((pattern)) * orcon[0]: $var = __pick__($var[con_or_index], ...) */ /* Get, or make, the declaration of the protovariable * in the arch constraint. */ arch_vdecl = graphd_variable_declaration_by_name(arch, name_s, name_e); if (arch_vdecl == NULL) { arch_vdecl = graphd_variable_declaration_add(cm, cl, arch, name_s, name_e); if (arch_vdecl == NULL) return ENOMEM; /* This newly created declaration in the arch * constraint is what the caller is interested in as * a new vdecl (which may require further promotion). */ *new_vdecl_out = arch_vdecl; } /* Create a renamed or-specific version of the variable name. */ need = (name_e - name_s) + 42 + 2; if ((tmp_name = cm_malloc(greq->greq_req.req_cm, need)) == NULL) return ENOMEM; snprintf(tmp_name, need, "%.*s [or#%zu]", (int)(name_e - name_s), name_s, orcon->con_or_index); tmp_name_e = tmp_name + strlen(tmp_name); indexed_vdecl = graphd_variable_declaration_add(cm, cl, arch, tmp_name, tmp_name_e); if (indexed_vdecl == NULL) return ENOMEM; *lhs_vdecl_out = indexed_vdecl; /* Share or create an assignment to the protovariable in the * arch constraint. */ arch_a = graphd_assignment_by_declaration(arch, arch_vdecl); if (arch_a == NULL) { arch_a = graphd_assignment_alloc_declaration(greq, arch, arch_vdecl); if (arch_a == NULL) return ENOMEM; } /* Pick-ify, if necessary, the prototype assignment. */ if (arch_a->a_result == NULL) { arch_a->a_result = graphd_pattern_alloc(greq, NULL, GRAPHD_PATTERN_PICK); if (arch_a->a_result == NULL) goto mem; } if (arch_a->a_result->pat_type != GRAPHD_PATTERN_PICK) { graphd_pattern *tmp; tmp = graphd_pattern_alloc(greq, NULL, GRAPHD_PATTERN_PICK); if (tmp == NULL) goto mem; graphd_pattern_append(greq, tmp, arch_a->a_result); arch_a->a_result = tmp; } cl_assert(cl, arch_a->a_result != NULL); cl_assert(cl, arch_a->a_result->pat_type == GRAPHD_PATTERN_PICK); /* Append the new $tmp to the pick. */ pick = graphd_pattern_alloc_variable(greq, /* parent result */ arch_a->a_result, indexed_vdecl); if (pick == NULL) goto mem; pick->pat_or_index = orcon->con_or_index; /* tmp_name is now pointed to by the variable; we * mustn't free it. * It will be free()d as part of the request heap. */ return 0; mem: if (tmp_name != NULL) cm_free(cm, tmp_name); return ENOMEM; } int graphd_constraint_or_compile_declaration( graphd_request *greq, graphd_constraint *arch, graphd_variable_declaration *old_vdecl, graphd_variable_declaration **new_vdecl_out) { cl_handle *cl = graphd_request_cl(greq); cm_handle *cm = greq->greq_req.req_cm; graphd_constraint *con = old_vdecl->vdecl_constraint; graphd_variable_declaration *arch_vdecl, *indexed_vdecl; graphd_assignment *arch_a; char *tmp_name; char const *tmp_name_e; graphd_pattern *pick; size_t need; char const *name_s, *name_e; *new_vdecl_out = NULL; cl_assert(cl, con->con_or_index > 0); cl_assert(cl, arch->con_or_index == 0); /* Transform into a local assignment to a temporary. * * con[con_or_index]: $var = ((pattern)) * -> * con[0]: $var[con_or_index] = ((pattern)) * con[0]: $var = __pick__($var[con_or_index], ...) */ /* Get the name of the protovariable. */ graphd_variable_declaration_name(old_vdecl, &name_s, &name_e); /* Get, or make, the declaration of the protovariable * in the arch constraint. */ arch_vdecl = graphd_variable_declaration_by_name(arch, name_s, name_e); if (arch_vdecl == NULL) { arch_vdecl = graphd_variable_declaration_add(cm, cl, arch, name_s, name_e); if (arch_vdecl == NULL) return ENOMEM; /* This newly created declaration in the arch * constraint is what the caller is interested in as * a new vdecl (which may require further promotion). */ *new_vdecl_out = arch_vdecl; } /* Create a renamed or-specific version of the variable name. */ need = (name_e - name_s) + 42 + 2; if ((tmp_name = cm_malloc(greq->greq_req.req_cm, need)) == NULL) return ENOMEM; snprintf(tmp_name, need, "%.*s [or#%zu]", (int)(name_e - name_s), name_s, con->con_or_index); tmp_name_e = tmp_name + strlen(tmp_name); indexed_vdecl = graphd_variable_declaration_add(cm, cl, arch, tmp_name, tmp_name_e); if (indexed_vdecl == NULL) return ENOMEM; /* Rename the variable to the new temporary in the "or" and below. */ graphd_variable_rename(greq, con, old_vdecl, indexed_vdecl); /* Share or create an assignment to the protovariable in the * arch constraint. */ arch_a = graphd_assignment_by_declaration(arch, arch_vdecl); if (arch_a == NULL) { arch_a = graphd_assignment_alloc_declaration(greq, arch, arch_vdecl); if (arch_a == NULL) return ENOMEM; } /* Pick-ify, if necessary, the prototype assignment. */ if (arch_a->a_result == NULL) { arch_a->a_result = graphd_pattern_alloc(greq, NULL, GRAPHD_PATTERN_PICK); if (arch_a->a_result == NULL) goto mem; } if (arch_a->a_result->pat_type != GRAPHD_PATTERN_PICK) { graphd_pattern *tmp; tmp = graphd_pattern_alloc(greq, NULL, GRAPHD_PATTERN_PICK); if (tmp == NULL) goto mem; graphd_pattern_append(greq, tmp, arch_a->a_result); arch_a->a_result = tmp; } cl_assert(cl, arch_a->a_result != NULL); cl_assert(cl, arch_a->a_result->pat_type == GRAPHD_PATTERN_PICK); /* Append the new $tmp to the pick. */ pick = graphd_pattern_alloc_variable(greq, /* parent result */ arch_a->a_result, indexed_vdecl); if (pick == NULL) goto mem; pick->pat_or_index = con->con_or_index; /* tmp_name is now pointed to by the variable; we * mustn't free it. * It will be free()d as part of the request heap. */ return 0; mem: if (tmp_name != NULL) cm_free(cm, tmp_name); return ENOMEM; } void graphd_constraint_or_move_assignments(graphd_request *greq, graphd_constraint *arch, graphd_constraint *con) { (void)greq; /* If this is inside an "or" branch ... */ if (con->con_or == NULL) return; /* Move the assignments to the now or-indexed variables * into the arch constraint. */ *arch->con_assignment_tail = con->con_assignment_head; if (*arch->con_assignment_tail != NULL) arch->con_assignment_tail = con->con_assignment_tail; arch->con_assignment_n += con->con_assignment_n; con->con_assignment_n = 0; con->con_assignment_head = NULL; con->con_assignment_tail = &con->con_assignment_head; } int graphd_constraint_or_move_declarations(graphd_request *greq, graphd_constraint *arch, graphd_constraint *con) { graphd_variable_declaration *vdecl, *arch_vdecl; (void)greq; /* If this is inside an "or" branch ... */ if (con->con_or == NULL) return 0; /* Move any declarations that weren't indexed as part * of an OR-dependent assignment into the arch constraint. */ vdecl = NULL; while ((vdecl = cm_hnext(&con->con_variable_declaration, graphd_variable_declaration, vdecl)) != NULL) { char const *name_s, *name_e; /* Get the variable's name. */ graphd_variable_declaration_name(vdecl, &name_s, &name_e); /* Get, or make, the declaration of the protovariable * in the arch constraint. */ arch_vdecl = graphd_variable_declaration_by_name(arch, name_s, name_e); if (arch_vdecl == NULL) { arch_vdecl = graphd_variable_declaration_add( greq->greq_req.req_cm, graphd_request_cl(greq), arch, name_s, name_e); if (arch_vdecl == NULL) return ENOMEM; } graphd_variable_rename(greq, con, vdecl, arch_vdecl); } return 0; }
8,399
505
<filename>FAP_tools/zmac_example/ass.py import os import sys os.system("clear") if len(sys.argv) != 2: print(__file__ + " z80_asm_file") exit() filename = sys.argv[1] print("assembling " + filename + "...") if(os.system("zmac " + filename) != 0): exit() print("generiting hex file...") if(os.system("cp ./zout/*.hex ./") != 0): exit() print("generiting bin file...") if(os.system("hex2bin *.hex") != 0): exit() os.system("rm ./*.hex")
182
1,567
#pragma once #include <vector> #include "tiny_rpc/tiny_rpc.h" #include "utils/co_lock.h" #include "utils/routine_worker.h" namespace certain { class TinyServer : public RoutineWorker<TcpSocket> { public: TinyServer(std::string local_addr, google::protobuf::Service* service) : RoutineWorker<TcpSocket>("tiny_server", 64), local_addr_(local_addr), service_(service) {} int Init(); void Stop(); private: std::unique_ptr<TcpSocket> GetJob() final; void DoJob(std::unique_ptr<TcpSocket> job) final; void Tick() final { Tick::Run(); } private: std::string local_addr_; google::protobuf::Service* service_; std::unique_ptr<TcpSocket> listen_socket_; }; } // namespace certain
269
471
#include "plane.h" #include "ray3.h" kmRay3* kmRay3Fill(kmRay3* ray, kmScalar px, kmScalar py, kmScalar pz, kmScalar vx, kmScalar vy, kmScalar vz) { ray->start.x = px; ray->start.y = py; ray->start.z = pz; ray->dir.x = vx; ray->dir.y = vy; ray->dir.z = vz; return ray; } kmRay3* kmRay3FromPointAndDirection(kmRay3* ray, const kmVec3* point, const kmVec3* direction) { kmVec3Assign(&ray->start, point); kmVec3Assign(&ray->dir, direction); return ray; } kmBool kmRay3IntersectPlane(kmVec3* pOut, const kmRay3* ray, const kmPlane* plane) { /*t = - (A*org.x + B*org.y + C*org.z + D) / (A*dir.x + B*dir.y + C*dir.z )*/ kmScalar d = (plane->a * ray->dir.x + plane->b * ray->dir.y + plane->c * ray->dir.z); if(d == 0) { return KM_FALSE; } kmScalar t = -(plane->a * ray->start.x + plane->b * ray->start.y + plane->c * ray->start.z + plane->d) / d; if(t < 0) { return KM_FALSE; } kmVec3 scaled_dir; kmVec3Scale(&scaled_dir, &ray->dir, t); kmVec3Add(pOut, &ray->start, &scaled_dir); return KM_TRUE; }
627
771
from mock import patch from scrapyrt.decorators import deprecated from scrapyrt.exceptions import ScrapyrtDeprecationWarning class TestDecorators(object): def test_deprecated(self): @deprecated def test_func(*args, **kwargs): return (args, kwargs) with patch('warnings.warn') as w: args, kwargs = test_func('foo', 'bar', keyword='blue') msg = 'Call to deprecated function test_func.' w.assert_called_once_with(msg, category=ScrapyrtDeprecationWarning, stacklevel=2) assert args == ('foo', 'bar') assert kwargs['keyword'] == 'blue'
316
10,225
<gh_stars>1000+ package io.quarkus.annotation.processor.generate_doc; import java.util.Objects; import javax.lang.model.element.TypeElement; final public class ConfigRootInfo { private final String name; private final TypeElement clazz; private final ConfigPhase configPhase; private final String fileName; public ConfigRootInfo(String name, TypeElement clazz, ConfigPhase visibility, String fileName) { this.name = name; this.clazz = clazz; this.configPhase = visibility; this.fileName = fileName; } public String getFileName() { return fileName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ConfigRootInfo that = (ConfigRootInfo) o; return Objects.equals(name, that.name) && Objects.equals(clazz, that.clazz) && configPhase == that.configPhase && Objects.equals(fileName, that.fileName); } @Override public int hashCode() { return Objects.hash(name, clazz, configPhase, fileName); } @Override public String toString() { return "ConfigRootInfo{" + "name='" + name + '\'' + ", clazz=" + clazz + ", configPhase=" + configPhase + ", fileName='" + fileName + '\'' + '}'; } public String getName() { return name; } public TypeElement getClazz() { return clazz; } public ConfigPhase getConfigPhase() { return configPhase; } }
726
542
/** * Modified MIT License * <p> * Copyright 2020 OneSignal * <p> * 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: * <p> * 1. The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p> * 2. All copies of substantial portions of the Software may only be used in connection * with services provided by OneSignal. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.onesignal; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import androidx.annotation.RequiresApi; import com.onesignal.AndroidSupportV4Compat.ContextCompat; abstract class OSBackgroundSync { protected static final Object LOCK = new Object(); protected boolean needsJobReschedule = false; private Thread syncBgThread; protected abstract String getSyncTaskThreadId(); protected abstract int getSyncTaskId(); protected abstract Class getSyncServiceJobClass(); protected abstract Class getSyncServicePendingIntentClass(); protected abstract void scheduleSyncTask(Context context); // Entry point from SyncJobService and SyncService when the job is kicked off void doBackgroundSync(Context context, Runnable runnable) { OneSignal.onesignalLog(OneSignal.LOG_LEVEL.DEBUG, "OSBackground sync, calling initWithContext"); OneSignal.initWithContext(context); syncBgThread = new Thread(runnable, getSyncTaskThreadId()); syncBgThread.start(); } boolean stopSyncBgThread() { if (syncBgThread == null) return false; if (!syncBgThread.isAlive()) return false; syncBgThread.interrupt(); return true; } /** * The main schedule method for all SyncTasks - this method differentiates between * Legacy Android versions (pre-LOLLIPOP 21) and 21+ to execute an Alarm (<21) or a Job (>=21) * * @param context - Any context type * @param delayMs - How long to wait before doing work */ protected void scheduleBackgroundSyncTask(Context context, long delayMs) { synchronized (LOCK) { if (useJob()) scheduleSyncServiceAsJob(context, delayMs); else scheduleSyncServiceAsAlarm(context, delayMs); } } private boolean hasBootPermission(Context context) { return ContextCompat.checkSelfPermission( context, "android.permission.RECEIVE_BOOT_COMPLETED" ) == PackageManager.PERMISSION_GRANTED; } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) private boolean isJobIdRunning(Context context) { final JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); for (JobInfo jobInfo : jobScheduler.getAllPendingJobs()) { if (jobInfo.getId() == getSyncTaskId() && syncBgThread != null && syncBgThread.isAlive()) { return true; } } return false; } @RequiresApi(21) private void scheduleSyncServiceAsJob(Context context, long delayMs) { OneSignal.Log(OneSignal.LOG_LEVEL.VERBOSE, "OSBackgroundSync scheduleSyncServiceAsJob:atTime: " + delayMs); if (isJobIdRunning(context)) { OneSignal.Log(OneSignal.LOG_LEVEL.VERBOSE, "OSBackgroundSync scheduleSyncServiceAsJob Scheduler already running!"); // If a JobScheduler is schedule again while running it will stop current job. We will schedule again when finished. // This will avoid InterruptionException due to thread.join() or queue.take() running. needsJobReschedule = true; return; } JobInfo.Builder jobBuilder = new JobInfo.Builder( getSyncTaskId(), new ComponentName(context, getSyncServiceJobClass()) ); jobBuilder .setMinimumLatency(delayMs) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); if (hasBootPermission(context)) jobBuilder.setPersisted(true); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); try { int result = jobScheduler.schedule(jobBuilder.build()); OneSignal.Log(OneSignal.LOG_LEVEL.INFO, "OSBackgroundSync scheduleSyncServiceAsJob:result: " + result); } catch (NullPointerException e) { // Catch for buggy Oppo devices // https://github.com/OneSignal/OneSignal-Android-SDK/issues/487 OneSignal.Log(OneSignal.LOG_LEVEL.ERROR, "scheduleSyncServiceAsJob called JobScheduler.jobScheduler which " + "triggered an internal null Android error. Skipping job.", e); } } private void scheduleSyncServiceAsAlarm(Context context, long delayMs) { OneSignal.Log(OneSignal.LOG_LEVEL.VERBOSE, this.getClass().getSimpleName() + " scheduleServiceSyncTask:atTime: " + delayMs); PendingIntent pendingIntent = syncServicePendingIntent(context); AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); long triggerAtMs = OneSignal.getTime().getCurrentTimeMillis() + delayMs; alarm.set(AlarmManager.RTC_WAKEUP, triggerAtMs, pendingIntent); } protected void cancelBackgroundSyncTask(Context context) { OneSignal.onesignalLog(OneSignal.LOG_LEVEL.DEBUG, this.getClass().getSimpleName() + " cancel background sync"); synchronized (LOCK) { if (useJob()) { JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.cancel(getSyncTaskId()); } else { AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(syncServicePendingIntent(context)); } } } private PendingIntent syncServicePendingIntent(Context context) { // KEEP - PendingIntent.FLAG_UPDATE_CURRENT // Some Samsung devices will throw the below exception otherwise. // "java.lang.SecurityException: !@Too many alarms (500) registered" return PendingIntent.getService( context, getSyncTaskId(), new Intent(context, getSyncServicePendingIntentClass()), PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE ); } private static boolean useJob() { return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP; } }
2,927
325
package com.box.l10n.mojito.service.assetExtraction; /** * * @author jyi */ public class AssetExtractionConflictException extends RuntimeException { public AssetExtractionConflictException(String message) { super(message); } public AssetExtractionConflictException(String message, Throwable cause) { super(message, cause); } }
126
1,504
/* * 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.lucene.luke.models.documents; import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexableField; import org.apache.lucene.index.MultiDocValues; import org.apache.lucene.index.NumericDocValues; import org.apache.lucene.util.BytesRef; import java.io.IOException; import java.util.Objects; /** * Holder for a document field's information and data. */ public final class DocumentField { // field name private String name; // index options private IndexOptions idxOptions; private boolean hasTermVectors; private boolean hasPayloads; private boolean hasNorms; private long norm; // stored value private boolean isStored; private String stringValue; private BytesRef binaryValue; private Number numericValue; // doc values private DocValuesType dvType; // point values private int pointDimensionCount; private int pointNumBytes; static DocumentField of(FieldInfo finfo, IndexReader reader, int docId) throws IOException { return of(finfo, null, reader, docId); } static DocumentField of(FieldInfo finfo, IndexableField field, IndexReader reader, int docId) throws IOException { Objects.requireNonNull(finfo); Objects.requireNonNull(reader); DocumentField dfield = new DocumentField(); dfield.name = finfo.name; dfield.idxOptions = finfo.getIndexOptions(); dfield.hasTermVectors = finfo.hasVectors(); dfield.hasPayloads = finfo.hasPayloads(); dfield.hasNorms = finfo.hasNorms(); if (finfo.hasNorms()) { NumericDocValues norms = MultiDocValues.getNormValues(reader, finfo.name); if (norms.advanceExact(docId)) { dfield.norm = norms.longValue(); } } dfield.dvType = finfo.getDocValuesType(); dfield.pointDimensionCount = finfo.getPointDataDimensionCount(); dfield.pointNumBytes = finfo.getPointNumBytes(); if (field != null) { dfield.isStored = field.fieldType().stored(); dfield.stringValue = field.stringValue(); if (field.binaryValue() != null) { dfield.binaryValue = BytesRef.deepCopyOf(field.binaryValue()); } dfield.numericValue = field.numericValue(); } return dfield; } public String getName() { return name; } public IndexOptions getIdxOptions() { return idxOptions; } public boolean hasTermVectors() { return hasTermVectors; } public boolean hasPayloads() { return hasPayloads; } public boolean hasNorms() { return hasNorms; } public long getNorm() { return norm; } public boolean isStored() { return isStored; } public String getStringValue() { return stringValue; } public BytesRef getBinaryValue() { return binaryValue; } public Number getNumericValue() { return numericValue; } public DocValuesType getDvType() { return dvType; } public int getPointDimensionCount() { return pointDimensionCount; } public int getPointNumBytes() { return pointNumBytes; } @Override public String toString() { return "DocumentField{" + "name='" + name + '\'' + ", idxOptions=" + idxOptions + ", hasTermVectors=" + hasTermVectors + ", isStored=" + isStored + ", dvType=" + dvType + ", pointDimensionCount=" + pointDimensionCount + '}'; } private DocumentField() { } }
1,452
366
import pyglet import esper FPS = 60 RESOLUTION = 720, 480 ################################## # Define some Components: ################################## class Velocity: def __init__(self, x=0.0, y=0.0): self.x = x self.y = y class Renderable: def __init__(self, sprite): self.sprite = sprite self.w = sprite.width self.h = sprite.height ################################ # Define some Processors: ################################ class MovementProcessor(esper.Processor): def __init__(self, minx, maxx, miny, maxy): super().__init__() self.minx = minx self.miny = miny self.maxx = maxx self.maxy = maxy def process(self, dt): # This will iterate over every Entity that has BOTH of these components: for ent, (vel, rend) in self.world.get_components(Velocity, Renderable): # Update the Renderable Component's position by it's Velocity: # An example of keeping the sprite inside screen boundaries. Basically, # adjust the position back inside screen boundaries if it is outside: new_x = max(self.minx, rend.sprite.x + vel.x) new_y = max(self.miny, rend.sprite.y + vel.y) new_x = min(self.maxx - rend.w, new_x) new_y = min(self.maxy - rend.h, new_y) rend.sprite.position = new_x, new_y ############################################### # Initialize pyglet window and graphics batch: ############################################### window = pyglet.window.Window(width=RESOLUTION[0], height=RESOLUTION[1], caption="Esper pyglet example") batch = pyglet.graphics.Batch() # Initialize Esper world, and create a "player" Entity with a few Components: world = esper.World() player = world.create_entity() world.add_component(player, Velocity(x=0, y=0)) player_image = pyglet.resource.image("redsquare.png") world.add_component(player, Renderable(sprite=pyglet.sprite.Sprite(img=player_image, x=100, y=100, batch=batch))) # Another motionless Entity: enemy = world.create_entity() enemy_image = pyglet.resource.image("bluesquare.png") world.add_component(enemy, Renderable(sprite=pyglet.sprite.Sprite(img=enemy_image, x=400, y=250, batch=batch))) # Create some Processor instances, and asign them to the World to be processed: movement_processor = MovementProcessor(minx=0, miny=0, maxx=RESOLUTION[0], maxy=RESOLUTION[1]) world.add_processor(movement_processor) ################################################ # Set up pyglet events for input and rendering: ################################################ @window.event def on_key_press(key, mod): if key == pyglet.window.key.RIGHT: world.component_for_entity(player, Velocity).x = 3 if key == pyglet.window.key.LEFT: world.component_for_entity(player, Velocity).x = -3 if key == pyglet.window.key.UP: world.component_for_entity(player, Velocity).y = 3 if key == pyglet.window.key.DOWN: world.component_for_entity(player, Velocity).y = -3 @window.event def on_key_release(key, mod): if key in (pyglet.window.key.RIGHT, pyglet.window.key.LEFT): world.component_for_entity(player, Velocity).x = 0 if key in (pyglet.window.key.UP, pyglet.window.key.DOWN): world.component_for_entity(player, Velocity).y = 0 @window.event def on_draw(): # Clear the window: window.clear() # Draw the batch of Renderables: batch.draw() #################################################### # Schedule a World update and start the pyglet app: #################################################### if __name__ == "__main__": # NOTE! schedule_interval will automatically pass a "delta time" argument # to world.process, so you must make sure that your Processor classes # account for this. See the example Processors above. pyglet.clock.schedule_interval(world.process, interval=1.0/FPS) pyglet.app.run()
1,893
2,389
<gh_stars>1000+ /* Copyright 2020 The Kubernetes 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 io.cert.manager.models; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Objects; /** * Cloud specifies the Venafi cloud configuration settings. Only one of TPP or Cloud may be * specified. */ @ApiModel( description = "Cloud specifies the Venafi cloud configuration settings. Only one of TPP or Cloud may be specified.") @javax.annotation.Generated( value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-08-18T19:55:23.947Z[Etc/UTC]") public class V1alpha2IssuerSpecVenafiCloud { public static final String SERIALIZED_NAME_API_TOKEN_SECRET_REF = "apiTokenSecretRef"; @SerializedName(SERIALIZED_NAME_API_TOKEN_SECRET_REF) private V1alpha2IssuerSpecVenafiCloudApiTokenSecretRef apiTokenSecretRef; public static final String SERIALIZED_NAME_URL = "url"; @SerializedName(SERIALIZED_NAME_URL) private String url; public V1alpha2IssuerSpecVenafiCloud apiTokenSecretRef( V1alpha2IssuerSpecVenafiCloudApiTokenSecretRef apiTokenSecretRef) { this.apiTokenSecretRef = apiTokenSecretRef; return this; } /** * Get apiTokenSecretRef * * @return apiTokenSecretRef */ @ApiModelProperty(required = true, value = "") public V1alpha2IssuerSpecVenafiCloudApiTokenSecretRef getApiTokenSecretRef() { return apiTokenSecretRef; } public void setApiTokenSecretRef( V1alpha2IssuerSpecVenafiCloudApiTokenSecretRef apiTokenSecretRef) { this.apiTokenSecretRef = apiTokenSecretRef; } public V1alpha2IssuerSpecVenafiCloud url(String url) { this.url = url; return this; } /** * URL is the base URL for Venafi Cloud. Defaults to \&quot;https://api.venafi.cloud/v1\&quot;. * * @return url */ @javax.annotation.Nullable @ApiModelProperty( value = "URL is the base URL for Venafi Cloud. Defaults to \"https://api.venafi.cloud/v1\".") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } V1alpha2IssuerSpecVenafiCloud v1alpha2IssuerSpecVenafiCloud = (V1alpha2IssuerSpecVenafiCloud) o; return Objects.equals(this.apiTokenSecretRef, v1alpha2IssuerSpecVenafiCloud.apiTokenSecretRef) && Objects.equals(this.url, v1alpha2IssuerSpecVenafiCloud.url); } @Override public int hashCode() { return Objects.hash(apiTokenSecretRef, url); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class V1alpha2IssuerSpecVenafiCloud {\n"); sb.append(" apiTokenSecretRef: ").append(toIndentedString(apiTokenSecretRef)).append("\n"); sb.append(" url: ").append(toIndentedString(url)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
1,340
4,904
/* * Copyright (c) 2018 AsyncHttpClient Project. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at * http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package org.asynchttpclient.request.body.multipart; import java.io.InputStream; import java.nio.charset.Charset; import static org.asynchttpclient.util.Assertions.assertNotNull; public class InputStreamPart extends FileLikePart { private final InputStream inputStream; private final long contentLength; public InputStreamPart(String name, InputStream inputStream, String fileName) { this(name, inputStream, fileName, -1); } public InputStreamPart(String name, InputStream inputStream, String fileName, long contentLength) { this(name, inputStream, fileName, contentLength, null); } public InputStreamPart(String name, InputStream inputStream, String fileName, long contentLength, String contentType) { this(name, inputStream, fileName, contentLength, contentType, null); } public InputStreamPart(String name, InputStream inputStream, String fileName, long contentLength, String contentType, Charset charset) { this(name, inputStream, fileName, contentLength, contentType, charset, null); } public InputStreamPart(String name, InputStream inputStream, String fileName, long contentLength, String contentType, Charset charset, String contentId) { this(name, inputStream, fileName, contentLength, contentType, charset, contentId, null); } public InputStreamPart(String name, InputStream inputStream, String fileName, long contentLength, String contentType, Charset charset, String contentId, String transferEncoding) { super(name, contentType, charset, fileName, contentId, transferEncoding); this.inputStream = assertNotNull(inputStream, "inputStream"); this.contentLength = contentLength; } public InputStream getInputStream() { return inputStream; } public long getContentLength() { return contentLength; } }
799
863
<gh_stars>100-1000 /* * Copyright 2018 Confluent Inc. * * Licensed under the Confluent Community License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of the * License at * * http://www.confluent.io/confluent-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package io.confluent.connect.jdbc.sink.metadata; import org.apache.kafka.connect.data.Schema; import java.util.Map; public class SinkRecordField { private final Schema schema; private final String name; private final boolean isPrimaryKey; public SinkRecordField(Schema schema, String name, boolean isPrimaryKey) { this.schema = schema; this.name = name; this.isPrimaryKey = isPrimaryKey; } public Schema schema() { return schema; } public String schemaName() { return schema.name(); } public Map<String, String> schemaParameters() { return schema.parameters(); } public Schema.Type schemaType() { return schema.type(); } public String name() { return name; } public boolean isOptional() { return !isPrimaryKey && schema.isOptional(); } public Object defaultValue() { return schema.defaultValue(); } public boolean isPrimaryKey() { return isPrimaryKey; } @Override public String toString() { return "SinkRecordField{" + "schema=" + schema + ", name='" + name + '\'' + ", isPrimaryKey=" + isPrimaryKey + '}'; } }
563
1,475
/* * 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.geode.redis.internal.executor.key; import static org.apache.geode.redis.internal.netty.StringBytesGlossary.bRADISH_DUMP_HEADER; import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import org.junit.ClassRule; import org.junit.Test; import redis.clients.jedis.Protocol; import org.apache.geode.redis.GeodeRedisServerRule; public class DumpRestoreIntegrationTest extends AbstractDumpRestoreIntegrationTest { @ClassRule public static GeodeRedisServerRule server = new GeodeRedisServerRule(); @Override public int getPort() { return server.getPort(); } @Test public void restoreWithIdletime_isNotSupported() { assertThatThrownBy( () -> jedis.sendCommand("key", Protocol.Command.RESTORE, "key", "0", "", "IDLETIME", "1")) .hasMessageContaining("ERR syntax error"); } @Test public void restoreWithFreq_isNotSupported() { assertThatThrownBy( () -> jedis.sendCommand("key", Protocol.Command.RESTORE, "key", "0", "", "FREQ", "1")) .hasMessageContaining("ERR syntax error"); } @Test public void restoreWithUnknownVersion_isNotSupported() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(bRADISH_DUMP_HEADER.length + 2); DataOutputStream output = new DataOutputStream(baos); output.write(bRADISH_DUMP_HEADER); output.writeShort(0); assertThatThrownBy( () -> jedis.restore("key", 0L, baos.toByteArray())) .hasMessageContaining("ERR DUMP payload version or checksum are wrong"); } }
788
669
# Copyright 2020 The TensorFlow Runtime 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. """Lit site configuration.""" from __future__ import absolute_import import os import lit.llvm cfg_path = os.path.join('mlir_tests', 'lit.cfg.py') # pylint: disable=undefined-variable # Let the main config do the real work. lit.llvm.initialize(lit_config, config) lit_config.load_config(config, cfg_path) # pylint: enable=undefined-variable
274
10,225
<reponame>mweber03/quarkus package io.quarkus.rest.data.panache.runtime.sort; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import java.util.Collections; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; @Provider @SortQueryParamValidator public class SortQueryParamFilter implements ContainerRequestFilter { private static final String SORT_REGEX = "-?([a-z]|[A-Z]|_|\\$|[\u0080-\ufffe])([a-z]|[A-Z]|_|\\$|[0-9]|[\u0080-\ufffe])*"; /** * Verifies that sort query parameters are valid. * Valid examples: * * ?sort=name,surname * * ?sort=$surname&sort=-age * * ?sort=_id */ @Override public void filter(ContainerRequestContext requestContext) { MultivaluedMap<String, String> queryParams = requestContext.getUriInfo().getQueryParameters(); for (String sort : queryParams.getOrDefault("sort", Collections.emptyList())) { for (String sortPart : sort.split(",")) { String trimmed = sortPart.trim(); if (trimmed.length() > 0 && !trimmed.matches(SORT_REGEX)) { requestContext.abortWith( Response.status(BAD_REQUEST) .entity(String.format("Invalid sort parameter '%s'", sort)) .build()); } } } } }
705
1,056
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.api.java.source.gen; import com.sun.source.tree.*; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import org.netbeans.api.java.source.JavaSource; import org.netbeans.api.java.source.JavaSource.Phase; import org.netbeans.api.java.source.Task; import org.netbeans.api.java.source.TreeMaker; import org.netbeans.api.java.source.WorkingCopy; import org.netbeans.junit.NbTestSuite; import org.openide.filesystems.FileStateInvalidException; /** * * @author <NAME> */ public class ClashingImportsTest extends GeneratorTestBase { /** Creates a new instance of ClashingImportsTest */ public ClashingImportsTest(String name) { super(name); } public static NbTestSuite suite() { NbTestSuite suite = new NbTestSuite(ClashingImportsTest.class); return suite; } public void testAddImport() throws IOException { testFile = getFile(getSourceDir(), getSourcePckg() + "ClashingImports.java"); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree node = (MethodTree) clazz.getMembers().get(0); BlockTree body = node.getBody(); List<StatementTree> stats = new ArrayList<StatementTree>(); for(StatementTree st : body.getStatements()) stats.add(st); TypeElement e = workingCopy.getElements().getTypeElement("java.awt.List"); ExpressionTree type = make.QualIdent(e); stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "awtList", type, null)); workingCopy.rewrite(body, make.Block(stats, false)); } }; src.runModificationTask(task).commit(); assertFiles("testAddImport_ClashingImports.pass"); } public void testAddClashingImport() throws IOException { testFile = getFile(getSourceDir(), getSourcePckg() + "ClashingImports2.java"); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree node = (MethodTree) clazz.getMembers().get(0); BlockTree body = node.getBody(); List<StatementTree> stats = new ArrayList<StatementTree>(); for(StatementTree st : body.getStatements()) stats.add(st); TypeElement e = workingCopy.getElements().getTypeElement("java.util.List"); ExpressionTree type = make.QualIdent(e); stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "list", type, null)); workingCopy.rewrite(body, make.Block(stats, false)); } }; src.runModificationTask(task).commit(); assertFiles("testAddClashingImport_ClashingImports.pass"); } public void testAddClashingImport2() throws IOException { testFile = getFile(getSourceDir(), getSourcePckg() + "ClashingImports3.java"); JavaSource src = getJavaSource(testFile); Task<WorkingCopy> task = new Task<WorkingCopy>() { public void run(WorkingCopy workingCopy) throws IOException { workingCopy.toPhase(Phase.RESOLVED); CompilationUnitTree cut = workingCopy.getCompilationUnit(); TreeMaker make = workingCopy.getTreeMaker(); ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0); MethodTree node = (MethodTree) clazz.getMembers().get(0); BlockTree body = node.getBody(); List<StatementTree> stats = new ArrayList<StatementTree>(); for(StatementTree st : body.getStatements()) stats.add(st); TypeElement e = workingCopy.getElements().getTypeElement("java.awt.List"); ExpressionTree type = make.QualIdent(e); stats.add(make.Variable(make.Modifiers(Collections.<Modifier>emptySet()), "awtList", type, null)); workingCopy.rewrite(body, make.Block(stats, false)); } }; src.runModificationTask(task).commit(); assertFiles("testAddClashingImport2.pass"); } String getSourcePckg() { return "org/netbeans/test/codegen/"; } String getGoldenPckg() { return "org/netbeans/jmi/javamodel/codegen/ClashingImportsTest/"; } @Override void assertFiles(final String aGoldenFile) throws IOException, FileStateInvalidException { assertFile("File is not correctly generated.", getTestFile(), getFile(getGoldenDir(), getGoldenPckg() + aGoldenFile), getWorkDir(), new WhitespaceIgnoringDiff() ); } }
2,597
19,529
<reponame>funrunskypalace/vnpy<gh_stars>1000+ TapAPITradeLoginAuth = { "UserNo": "string", "ISModifyPassword": "char", "Password": "string", "NewPassword": "string", } TapAPITradeLoginRspInfo = { "UserNo": "string", "UserType": "int", "UserName": "string", "ReservedInfo": "string", "LastLoginIP": "string", "LastLoginProt": "unsigned int", "LastLoginTime": "string", "LastLogoutTime": "string", "TradeDate": "string", "LastSettleTime": "string", "StartTime": "string", "InitTime": "string", } TapAPIRequestVertificateCodeRsp = { "SecondSerialID": "string", "Effective": "int", } TapAPIAccQryReq = { } TapAPIAccountInfo = { "AccountNo": "string", "AccountType": "char", "AccountState": "char", "AccountTradeRight": "char", "CommodityGroupNo": "string", "AccountShortName": "string", "AccountEnShortName": "string", } TapAPINewOrder = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "ContractNo2": "string", "StrikePrice2": "string", "CallOrPutFlag2": "char", "OrderType": "char", "OrderSource": "char", "TimeInForce": "char", "ExpireTime": "string", "IsRiskOrder": "char", "OrderSide": "char", "PositionEffect": "char", "PositionEffect2": "char", "InquiryNo": "string", "HedgeFlag": "char", "OrderPrice": "double", "OrderPrice2": "double", "StopPrice": "double", "OrderQty": "unsigned int", "OrderMinQty": "unsigned int", "MinClipSize": "unsigned int", "MaxClipSize": "unsigned int", "RefInt": "int", "RefDouble": "double", "RefString": "string", "ClientID": "string", "TacticsType": "char", "TriggerCondition": "char", "TriggerPriceType": "char", "AddOneIsValid": "char", } TapAPIOrderInfo = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "ContractNo2": "string", "StrikePrice2": "string", "CallOrPutFlag2": "char", "OrderType": "char", "OrderSource": "char", "TimeInForce": "char", "ExpireTime": "string", "IsRiskOrder": "char", "OrderSide": "char", "PositionEffect": "char", "PositionEffect2": "char", "InquiryNo": "string", "HedgeFlag": "char", "OrderPrice": "double", "OrderPrice2": "double", "StopPrice": "double", "OrderQty": "unsigned int", "OrderMinQty": "unsigned int", "RefInt": "int", "RefDouble": "double", "RefString": "string", "MinClipSize": "unsigned int", "MaxClipSize": "unsigned int", "LicenseNo": "string", "ServerFlag": "char", "OrderNo": "string", "ClientOrderNo": "string", "ClientID": "string", "TacticsType": "char", "TriggerCondition": "char", "TriggerPriceType": "char", "AddOneIsValid": "char", "ClientLocalIP": "string", "ClientMac": "string", "ClientIP": "string", "OrderStreamID": "unsigned int", "UpperNo": "string", "UpperChannelNo": "string", "OrderLocalNo": "string", "UpperStreamID": "unsigned int", "OrderSystemNo": "string", "OrderExchangeSystemNo": "string", "OrderParentSystemNo": "string", "OrderInsertUserNo": "string", "OrderInsertTime": "string", "OrderCommandUserNo": "string", "OrderUpdateUserNo": "string", "OrderUpdateTime": "string", "OrderState": "char", "OrderMatchPrice": "double", "OrderMatchPrice2": "double", "OrderMatchQty": "unsigned int", "OrderMatchQty2": "unsigned int", "ErrorCode": "unsigned int", "ErrorText": "string", "IsBackInput": "char", "IsDeleted": "char", "IsAddOne": "char", } TapAPIOrderInfoNotice = { "SessionID": "unsigned int", "ErrorCode": "unsigned int", "OrderInfo": "dict", } TapAPIOrderActionRsp = { "ActionType": "char", "OrderInfo": "dict", } TapAPIAmendOrder = { "ReqData": "dict", "ServerFlag": "char", "OrderNo": "string", } TapAPIOrderCancelReq = { "RefInt": "int", "RefDouble": "double", "RefString": "string", "ServerFlag": "char", "OrderNo": "string", } TapAPIOrderDeactivateReq = TapAPIOrderCancelReq TapAPIOrderActivateReq = TapAPIOrderCancelReq TapAPIOrderDeleteReq = TapAPIOrderCancelReq TapAPIOrderQryReq = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "OrderType": "char", "OrderSource": "char", "TimeInForce": "char", "ExpireTime": "string", "IsRiskOrder": "char", "ServerFlag": "char", "OrderNo": "string", "IsBackInput": "char", "IsDeleted": "char", "IsAddOne": "char", } TapAPIOrderProcessQryReq = { "ServerFlag": "char", "OrderNo": "string", } TapAPIFillQryReq = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "MatchSource": "char", "MatchSide": "char", "PositionEffect": "char", "ServerFlag": "char", "OrderNo": "string", "UpperNo": "string", "IsDeleted": "char", "IsAddOne": "char", } TapAPIFillInfo = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "MatchSource": "char", "MatchSide": "char", "PositionEffect": "char", "ServerFlag": "char", "OrderNo": "string", "OrderSystemNo": "string", "MatchNo": "string", "UpperMatchNo": "string", "ExchangeMatchNo": "string", "MatchDateTime": "string", "UpperMatchDateTime": "string", "UpperNo": "string", "MatchPrice": "double", "MatchQty": "unsigned int", "IsDeleted": "char", "IsAddOne": "char", "FeeCurrencyGroup": "string", "FeeCurrency": "string", "FeeValue": "double", "IsManualFee": "char", "ClosePrositionPrice": "double", } TapAPICloseQryReq = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", } TapAPICloseInfo = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "CloseSide": "char", "CloseQty": "unsigned int", "OpenPrice": "double", "ClosePrice": "double", "OpenMatchNo": "string", "OpenMatchDateTime": "string", "CloseMatchNo": "string", "CloseMatchDateTime": "string", "CloseStreamId": "unsigned int", "CommodityCurrencyGroup": "string", "CommodityCurrency": "string", "CloseProfit": "double", } TapAPIPositionQryReq = { "AccountNo": "string", } TapAPIPositionInfo = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "MatchSide": "char", "HedgeFlag": "char", "PositionNo": "string", "ServerFlag": "char", "OrderNo": "string", "MatchNo": "string", "UpperNo": "string", "PositionPrice": "double", "PositionQty": "unsigned int", "PositionStreamId": "unsigned int", "CommodityCurrencyGroup": "string", "CommodityCurrency": "string", "CalculatePrice": "double", "AccountInitialMargin": "double", "AccountMaintenanceMargin": "double", "UpperInitialMargin": "double", "UpperMaintenanceMargin": "double", "PositionProfit": "double", "LMEPositionProfit": "double", "OptionMarketValue": "double", "IsHistory": "char", } TapAPIPositionProfit = { "PositionNo": "string", "PositionStreamId": "unsigned int", "PositionProfit": "double", "LMEPositionProfit": "double", "OptionMarketValue": "double", "CalculatePrice": "double", } TapAPIPositionProfitNotice = { "IsLast": "char", "Data": "dict", } TapAPIPositionSummary = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "MatchSide": "char", "PositionPrice": "double", "PositionQty": "unsigned int", "HisPositionQty": "unsigned int", } TapAPIFundReq = { "AccountNo": "string", } TapAPIFundData = { "AccountNo": "string", "CurrencyGroupNo": "string", "CurrencyNo": "string", "TradeRate": "double", "FutureAlg": "char", "OptionAlg": "char", "PreBalance": "double", "PreUnExpProfit": "double", "PreLMEPositionProfit": "double", "PreEquity": "double", "PreAvailable1": "double", "PreMarketEquity": "double", "CashInValue": "double", "CashOutValue": "double", "CashAdjustValue": "double", "CashPledged": "double", "FrozenFee": "double", "FrozenDeposit": "double", "AccountFee": "double", "SwapInValue": "double", "SwapOutValue": "double", "PremiumIncome": "double", "PremiumPay": "double", "CloseProfit": "double", "FrozenFund": "double", "UnExpProfit": "double", "ExpProfit": "double", "PositionProfit": "double", "LmePositionProfit": "double", "OptionMarketValue": "double", "AccountIntialMargin": "double", "AccountMaintenanceMargin": "double", "UpperInitalMargin": "double", "UpperMaintenanceMargin": "double", "Discount": "double", "Balance": "double", "Equity": "double", "Available": "double", "CanDraw": "double", "MarketEquity": "double", "AuthMoney": "double", } TapAPICommodityInfo = { "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "CommodityName": "string", "CommodityEngName": "string", "RelateExchangeNo": "string", "RelateCommodityType": "char", "RelateCommodityNo": "string", "RelateExchangeNo2": "string", "RelateCommodityType2": "char", "RelateCommodityNo2": "string", "CurrencyGroupNo": "string", "TradeCurrency": "string", "ContractSize": "double", "OpenCloseMode": "char", "StrikePriceTimes": "double", "CommodityTickSize": "double", "CommodityDenominator": "int", "CmbDirect": "char", "DeliveryMode": "char", "DeliveryDays": "int", "AddOneTime": "string", "CommodityTimeZone": "int", "IsAddOne": "char", } TapAPITradeContractInfo = { "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo1": "string", "StrikePrice1": "string", "CallOrPutFlag1": "char", "ContractNo2": "string", "StrikePrice2": "string", "CallOrPutFlag2": "char", "ContractType": "char", "QuoteUnderlyingContract": "string", "ContractName": "string", "ContractExpDate": "string", "LastTradeDate": "string", "FirstNoticeDate": "string", } TapAPICurrencyInfo = { "CurrencyNo": "string", "CurrencyGroupNo": "string", "TradeRate": "double", "TradeRate2": "double", "FutureAlg": "char", "OptionAlg": "char", } TapAPITradeMessageReq = { "AccountNo": "string", "AccountAttributeNo": "string", "BenginSendDateTime": "string", "EndSendDateTime": "string", } TapAPITradeMessage = { "SerialID": "unsigned int", "AccountNo": "string", "TMsgValidDateTime": "string", "TMsgTitle": "string", "TMsgContent": "string", "TMsgType": "char", "TMsgLevel": "char", "IsSendBySMS": "char", "IsSendByEMail": "char", "Sender": "string", "SendDateTime": "string", } TapAPIBillQryReq = { "UserNo": "string", "BillType": "char", "BillDate": "string", "BillFileType": "char", } TapAPIBillQryRsp = { "Reqdata": "dict", "BillLen": "int", "BillText": "char", } TapAPIHisOrderQryReq = { "AccountNo": "string", "AccountAttributeNo": "string", "BeginDate": "string", "EndDate": "string", } TapAPIHisOrderQryRsp = { "Date": "string", "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "ContractNo2": "string", "StrikePrice2": "string", "CallOrPutFlag2": "char", "OrderType": "char", "OrderSource": "char", "TimeInForce": "char", "ExpireTime": "string", "IsRiskOrder": "char", "OrderSide": "char", "PositionEffect": "char", "PositionEffect2": "char", "InquiryNo": "string", "HedgeFlag": "char", "OrderPrice": "double", "OrderPrice2": "double", "StopPrice": "double", "OrderQty": "unsigned int", "OrderMinQty": "unsigned int", "OrderCanceledQty": "unsigned int", "RefInt": "int", "RefDouble": "double", "RefString": "string", "ServerFlag": "char", "OrderNo": "string", "OrderStreamID": "unsigned int", "UpperNo": "string", "UpperChannelNo": "string", "OrderLocalNo": "string", "UpperStreamID": "unsigned int", "OrderSystemNo": "string", "OrderExchangeSystemNo": "string", "OrderParentSystemNo": "string", "OrderInsertUserNo": "string", "OrderInsertTime": "string", "OrderCommandUserNo": "string", "OrderUpdateUserNo": "string", "OrderUpdateTime": "string", "OrderState": "char", "OrderMatchPrice": "double", "OrderMatchPrice2": "double", "OrderMatchQty": "unsigned int", "OrderMatchQty2": "unsigned int", "ErrorCode": "unsigned int", "ErrorText": "string", "IsBackInput": "char", "IsDeleted": "char", "IsAddOne": "char", "AddOneIsValid": "char", "MinClipSize": "unsigned int", "MaxClipSize": "unsigned int", "LicenseNo": "string", "TacticsType": "char", "TriggerCondition": "char", "TriggerPriceType": "char", } TapAPIHisMatchQryReq = { "AccountNo": "string", "AccountAttributeNo": "string", "BeginDate": "string", "EndDate": "string", "CountType": "char", } TapAPIHisMatchQryRsp = { "SettleDate": "string", "TradeDate": "string", "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "MatchSource": "char", "MatchSide": "char", "PositionEffect": "char", "HedgeFlag": "char", "MatchPrice": "double", "MatchQty": "unsigned int", "OrderNo": "string", "MatchNo": "string", "MatchStreamID": "unsigned int", "UpperNo": "string", "MatchCmbNo": "string", "ExchangeMatchNo": "string", "MatchUpperStreamID": "unsigned int", "CommodityCurrencyGroup": "string", "CommodityCurrency": "string", "Turnover": "double", "PremiumIncome": "double", "PremiumPay": "double", "AccountFee": "double", "AccountFeeCurrencyGroup": "string", "AccountFeeCurrency": "string", "IsManualFee": "char", "AccountOtherFee": "double", "UpperFee": "double", "UpperFeeCurrencyGroup": "string", "UpperFeeCurrency": "string", "IsUpperManualFee": "char", "UpperOtherFee": "double", "MatchDateTime": "string", "UpperMatchDateTime": "string", "CloseProfit": "double", "ClosePrice": "double", "CloseQty": "unsigned int", "SettleGroupNo": "string", "OperatorNo": "string", "OperateTime": "string", } TapAPIHisOrderProcessQryReq = { "Date": "string", "OrderNo": "string", } TapAPIHisOrderProcessQryRsp = TapAPIHisOrderQryRsp TapAPIHisPositionQryReq = { "AccountNo": "string", "AccountAttributeNo": "dict", "Date": "string", "CountType": "dict", "SettleFlag": "char", } TapAPIHisPositionQryRsp = { "SettleDate": "string", "OpenDate": "string", "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "MatchSide": "char", "HedgeFlag": "char", "PositionPrice": "double", "PositionQty": "unsigned int", "OrderNo": "string", "PositionNo": "string", "UpperNo": "string", "CurrencyGroup": "string", "Currency": "string", "PreSettlePrice": "double", "SettlePrice": "double", "PositionDProfit": "double", "LMEPositionProfit": "double", "OptionMarketValue": "double", "AccountInitialMargin": "double", "AccountMaintenanceMargin": "double", "UpperInitialMargin": "double", "UpperMaintenanceMargin": "double", "SettleGroupNo": "string", } TapAPIHisDeliveryQryReq = { "AccountNo": "string", "AccountAttributeNo": "string", "BeginDate": "string", "EndDate": "string", "CountType": "char", } TapAPIHisDeliveryQryRsp = { "DeliveryDate": "string", "OpenDate": "string", "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "MatchSource": "char", "OpenSide": "char", "OpenPrice": "double", "DeliveryPrice": "double", "DeliveryQty": "unsigned int", "FrozenQty": "unsigned int", "OpenNo": "string", "UpperNo": "string", "CommodityCurrencyGroupy": "string", "CommodityCurrency": "string", "PreSettlePrice": "double", "DeliveryProfit": "double", "AccountFrozenInitialMargin": "double", "AccountFrozenMaintenanceMargin": "double", "UpperFrozenInitialMargin": "double", "UpperFrozenMaintenanceMargin": "double", "AccountFeeCurrencyGroup": "string", "AccountFeeCurrency": "string", "AccountDeliveryFee": "double", "UpperFeeCurrencyGroup": "string", "UpperFeeCurrency": "string", "UpperDeliveryFee": "double", "DeliveryMode": "char", "OperatorNo": "string", "OperateTime": "string", "SettleGourpNo": "string", } TapAPIAccountCashAdjustQryReq = { "SerialID": "unsigned int", "AccountNo": "string", "AccountAttributeNo": "string", "BeginDate": "string", "EndDate": "string", } TapAPIAccountCashAdjustQryRsp = { "Date": "string", "AccountNo": "string", "CashAdjustType": "char", "CurrencyGroupNo": "string", "CurrencyNo": "string", "CashAdjustValue": "double", "CashAdjustRemark": "string", "OperateTime": "string", "OperatorNo": "string", "AccountBank": "string", "BankAccount": "string", "AccountLWFlag": "char", "CompanyBank": "string", "InternalBankAccount": "string", "CompanyLWFlag": "char", } TapAPIAccountFeeRentQryReq = { "AccountNo": "string", } TapAPIAccountFeeRentQryRsp = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "MatchSource": "char", "CalculateMode": "char", "CurrencyGroupNo": "string", "CurrencyNo": "string", "OpenCloseFee": "double", "CloseTodayFee": "double", } TapAPIAccountMarginRentQryReq = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", } TapAPIAccountMarginRentQryRsp = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "CalculateMode": "char", "CurrencyGroupNo": "string", "CurrencyNo": "string", "InitialMargin": "double", "MaintenanceMargin": "double", "SellInitialMargin": "double", "SellMaintenanceMargin": "double", "LockMargin": "double", } TapAPIOrderQuoteMarketNotice = { "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "OrderSide": "char", "OrderQty": "unsigned int", } TapAPIOrderMarketInsertReq = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "OrderType": "char", "TimeInForce": "char", "ExpireTime": "string", "OrderSource": "char", "BuyPositionEffect": "char", "SellPositionEffect": "char", "AddOneIsValid": "char", "OrderBuyPrice": "double", "OrderSellPrice": "double", "OrderBuyQty": "unsigned int", "OrderSellQty": "unsigned int", "ClientBuyOrderNo": "string", "ClientSellOrderNo": "string", "RefInt": "int", "RefDouble": "double", "RefString": "string", "Remark": "string", } TapAPIOrderMarketInsertRsp = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "OrderType": "char", "TimeInForce": "char", "ExpireTime": "string", "OrderSource": "char", "BuyPositionEffect": "char", "SellPositionEffect": "char", "OrderBuyPrice": "double", "OrderSellPrice": "double", "OrderBuyQty": "unsigned int", "OrderSellQty": "unsigned int", "ServerFlag": "char", "OrderBuyNo": "string", "OrderSellNo": "string", "AddOneIsValid": "char", "OrderMarketUserNo": "string", "OrderMarketTime": "string", "RefInt": "int", "RefDouble": "double", "RefString": "string", "ClientBuyOrderNo": "string", "ClientSellOrderNo": "string", "ErrorCode": "unsigned int", "ErrorText": "string", "ClientLocalIP": "string", "ClientMac": "string", "ClientIP": "string", "Remark": "string", } TapAPIOrderMarketDeleteReq = { "ServerFlag": "char", "OrderBuyNo": "string", "OrderSellNo": "string", } TapAPIOrderMarketDeleteRsp = TapAPIOrderMarketInsertRsp TapAPIOrderLocalRemoveReq = { "ServerFlag": "char", "OrderNo": "string", } TapAPIOrderLocalRemoveRsp = { "req": "dict", "ClientLocalIP": "string", "ClientMac": "string", "ClientIP": "string", } TapAPIOrderLocalInputReq = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "ContractNo2": "string", "StrikePrice2": "string", "CallOrPutFlag2": "char", "OrderType": "char", "OrderSource": "char", "TimeInForce": "char", "ExpireTime": "string", "IsRiskOrder": "char", "OrderSide": "char", "PositionEffect": "char", "PositionEffect2": "char", "InquiryNo": "string", "HedgeFlag": "char", "OrderPrice": "double", "OrderPrice2": "double", "StopPrice": "double", "OrderQty": "unsigned int", "OrderMinQty": "unsigned int", "OrderSystemNo": "string", "OrderExchangeSystemNo": "string", "UpperNo": "string", "OrderMatchPrice": "double", "OrderMatchPrice2": "double", "OrderMatchQty": "unsigned int", "OrderMatchQty2": "unsigned int", "OrderState": "char", "IsAddOne": "char", } TapAPIOrderLocalInputRsp = TapAPIOrderInfo TapAPIOrderLocalModifyReq = { "req": "dict", "ServerFlag": "char", "OrderNo": "string", } TapAPIOrderLocalModifyRsp = TapAPIOrderInfo TapAPIOrderLocalTransferReq = { "AccountNo": "string", "ServerFlag": "char", "OrderNo": "string", } TapAPIOrderLocalTransferRsp = TapAPIOrderInfo TapAPIFillLocalInputReq = { "AccountNo": "string", "ExchangeNo": "string", "CommodityType": "char", "CommodityNo": "string", "ContractNo": "string", "StrikePrice": "string", "CallOrPutFlag": "char", "MatchSide": "char", "PositionEffect": "char", "HedgeFlag": "char", "MatchPrice": "double", "MatchQty": "unsigned int", "OrderSystemNo": "string", "UpperMatchNo": "string", "MatchDateTime": "string", "UpperMatchDateTime": "string", "UpperNo": "string", "IsAddOne": "char", "FeeCurrencyGroup": "string", "FeeCurrency": "string", "FeeValue": "double", "IsManualFee": "char", "ClosePositionPrice": "double", } TapAPIFillLocalInputRsp = TapAPIFillLocalInputReq TapAPIFillLocalRemoveReq = { "ServerFlag": "char", "MatchNo": "string", } TapAPIFillLocalRemoveRsp = TapAPIFillLocalRemoveReq TapAPITradingCalendarQryRsp = { "CurrTradeDate": "string", "LastSettlementDate": "string", "PromptDate": "string", "LastPromptDate": "string", }
10,258
6,224
/* * Copyright (c) 2018 Synopsys, Inc. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 */ #ifndef _ARC_IOT_SOC_IRQ_H_ #define _ARC_IOT_SOC_IRQ_H_ #define IRQ_WATCHDOG 18 #define IRQ_GPIO_4B0 19 #define IRQ_DMA0_DONE 20 #define IRQ_DMA1_DONE 21 #define IRQ_DMA2_DONE 22 #define IRQ_DMA3_DONE 23 #define IRQ_DMA4_DONE 24 #define IRQ_DMA5_DONE 25 #define IRQ_DMA6_DONE 26 #define IRQ_DMA7_DONE 27 #define IRQ_DMA8_DONE 28 #define IRQ_DMA9_DONE 29 #define IRQ_DMA10_DONE 30 #define IRQ_DMA11_DONE 31 #define IRQ_DMA12_DONE 32 #define IRQ_DMA13_DONE 33 #define IRQ_DMA14_DONE 34 #define IRQ_DMA15_DONE 35 #define IRQ_DMA0_ERR 36 #define IRQ_DMA1_ERR 37 #define IRQ_DMA2_ERR 38 #define IRQ_DMA3_ERR 39 #define IRQ_DMA4_ERR 40 #define IRQ_DMA5_ERR 41 #define IRQ_DMA6_ERR 42 #define IRQ_DMA7_ERR 43 #define IRQ_DMA8_ERR 44 #define IRQ_DMA9_ERR 45 #define IRQ_DMA10_ERR 46 #define IRQ_DMA11_ERR 47 #define IRQ_DMA12_ERR 48 #define IRQ_DMA13_ERR 49 #define IRQ_DMA14_ERR 50 #define IRQ_DMA15_ERR 51 #define IRQ_GPIO_4B1 52 #define IRQ_GPIO_4B2 53 #define IRQ_GPIO_8B0 54 #define IRQ_GPIO_8B1 55 #define IRQ_GPIO_8B2 56 #define IRQ_GPIO_8B3 57 #define IRQ_I2CMST0_MST_ERR 58 #define IRQ_I2CMST0_MST_RX_AVAIL 59 #define IRQ_I2CMST0_MST_TX_REQ 60 #define IRQ_I2CMST0_MST_STOP_DET 61 #define IRQ_I2CMST1_MST_ERR 62 #define IRQ_I2CMST1_MST_RX_AVAIL 63 #define IRQ_I2CMST1_MST_TX_REQ 64 #define IRQ_I2CMST1_MST_STOP_DET 65 #define IRQ_I2CMST2_MST_ERR 66 #define IRQ_I2CMST2_MST_RX_AVAIL 67 #define IRQ_I2CMST2_MST_TX_REQ 68 #define IRQ_I2CMST2_MST_STOP_DET 69 /* SPI */ #define IRQ_SPIMST0_MST_ERR 70 #define IRQ_SPIMST0_MST_RX_AVAIL 71 #define IRQ_SPIMST0_MST_TX_REQ 72 #define IRQ_SPIMST0_MST_IDLE 73 #define IRQ_SPIMST1_MST_ERR 74 #define IRQ_SPIMST1_MST_RX_AVAIL 75 #define IRQ_SPIMST1_MST_TX_REQ 76 #define IRQ_SPIMST1_MST_IDLE 77 #define IRQ_SPIMST2_MST_ERR 78 #define IRQ_SPIMST2_MST_RX_AVAIL 79 #define IRQ_SPIMST2_MST_TX_REQ 80 #define IRQ_SPIMST2_MST_IDLE 81 #define IRQ_SPISLV0_SLV_ERR 82 #define IRQ_SPISLV0_SLV_RX_AVAIL 83 #define IRQ_SPISLV0_SLV_TX_REQ 84 #define IRQ_SPISLV0_SLV_IDLE 85 /* UART */ #define IRQ_UART0_UART 86 #define IRQ_UART1_UART 87 #define IRQ_UART2_UART 88 #define IRQ_UART3_UART 89 #define IRQ_EXT_WAKE_UP 90 #define IRQ_SDIO 91 /* I2S */ #define IRQ_I2S_TX_EMP_0 92 #define IRQ_I2S_TX_OR_0 93 #define IRQ_I2S_RX_DA_0 94 #define IRQ_I2S_RX_OR_0 95 #define IRQ_USB 96 #define IRQ_ADC 97 #define IRQ_DW_TIMER0 98 #define IRQ_DW_TIMER1 99 #define IRQ_DW_TIMER2 100 #define IRQ_DW_TIMER3 101 #define IRQ_DW_TIMER4 102 #define IRQ_DW_TIMER5 103 #define IRQ_DW_RTC 104 #define IRQ_DW_I3C 105 #define IRQ_RESERVED0 106 #define IRQ_RESERVED1 107 #define IRQ_RESERVED2 108 #define IRQ_RESERVED3 109 #define IRQ_RESERVED4 110 #endif /* _ARC_IOT_SOC_IRQ_H_ */
1,813
337
import java.util.ArrayList; import java.util.List; public class Owner { public List<String> list = new ArrayList<>(); } public class Updater { public void update(Owner owner) { owner.list.add(""); } }
83
30,023
<reponame>liangleslie/core { "config": { "error": { "need_lower_upper": "Os limites inferior e superior n\u00e3o podem estar vazios" }, "step": { "user": { "data": { "entity_id": "Sensor de entrada", "hysteresis": "Histerese", "lower": "Limite inferior", "name": "Nome", "upper": "Limite superior" }, "description": "Crie um sensor bin\u00e1rio que liga e desliga dependendo do valor de um sensor \n\n Somente limite inferior configurado - Liga quando o valor do sensor de entrada for menor que o limite inferior.\n Somente limite superior configurado - Liga quando o valor do sensor de entrada for maior que o limite superior.\n Ambos os limites inferior e superior configurados - Liga quando o valor do sensor de entrada est\u00e1 na faixa [limite inferior .. limite superior].", "title": "Adicionar sensor Threshold" } } }, "options": { "error": { "need_lower_upper": "Os limites inferior e superior n\u00e3o podem estar vazios" }, "step": { "init": { "data": { "entity_id": "Sensor de entrada", "hysteresis": "Histerese", "lower": "Limite inferior", "name": "Nome", "upper": "Limite superior" }, "description": "Somente o limite inferior \u00e9 configurado - Liga quando o valor do sensor de entrada for menor que o limite inferior.\nSomente o limite superior \u00e9 configurado - Liga quando o valor do sensor de entrada for maior que o limite superior.\nAmbos os limites inferior e superior s\u00e3o configurados - Liga quando o valor do sensor de entrada est\u00e1 na faixa [limite inferior .. limite superior]." } } }, "title": "Sensor Threshold" }
967
387
/* * Copyright (C) 2014, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The Java Pathfinder core (jpf-core) platform is 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 gov.nasa.jpf.test.vm.threads; import gov.nasa.jpf.annotation.FilterField; import gov.nasa.jpf.util.test.TestJPF; import gov.nasa.jpf.vm.Verify; import org.junit.Test; /** * threading test */ public class ThreadTest extends TestJPF { static String didRunThread = null; @Test public void testDaemon () { if (verifyNoPropertyViolation()) { Runnable r = new Runnable() { @Override public void run() { Thread t = Thread.currentThread(); if (!t.isDaemon()) { throw new RuntimeException("isDaemon failed"); } didRunThread = t.getName(); } }; didRunThread = null; Thread t = new Thread(r); t.setDaemon(true); t.start(); try { t.join(); } catch (InterruptedException ix) { throw new RuntimeException("thread was interrupted"); } String tname = Thread.currentThread().getName(); if ((didRunThread == null) || (didRunThread.equals(tname))) { throw new RuntimeException("thread did not execute: " + didRunThread); } } } @Test public void testDaemonTermination () { if (verifyNoPropertyViolation("+cg.threads.break_start=true", "+cg.threads.break_yield=true")) { final Thread mainThread = Thread.currentThread(); Runnable r = new Runnable() { @FilterField // without this, we have a perfectly open state space and never finish in JPF int n = 0; @Override public void run() { while (true) { // loop forever or until main finishes n++; // NOTE: this does not necessarily hold outside of JPF, since the daemon might still run for a few cycles assert (n < 100) || mainThread.isAlive() : "main terminated but daemon still running"; System.out.println(" daemon running in round: " + n); Thread.yield(); } } }; Thread t = new Thread(r); t.setDaemon(true); t.start(); Thread.yield(); // finishing this thread should also (eventually) terminate the daemon System.out.println("main terminating"); } } @Test public void testMain () { if (verifyNoPropertyViolation()) { Thread t = Thread.currentThread(); String refName = "main"; String name = t.getName(); if (!name.equals(refName)) { throw new RuntimeException("wrong main thread name, is: " + name + ", expected: " + refName); } refName = "my-main-thread"; t.setName(refName); name = t.getName(); if (!name.equals(refName)) { throw new RuntimeException("Thread.setName() failed, is: " + name + ", expected: " + refName); } int refPrio = Thread.NORM_PRIORITY; int prio = t.getPriority(); if (prio != refPrio) { throw new RuntimeException("main thread has no NORM_PRIORITY: " + prio); } refPrio++; t.setPriority(refPrio); prio = t.getPriority(); if (prio != refPrio) { throw new RuntimeException("main thread setPriority failed: " + prio); } if (t.isDaemon()) { throw new RuntimeException("main thread is daemon"); } } } @Test public void testName () { if (verifyNoPropertyViolation()) { Runnable r = new Runnable() { @Override public void run() { Thread t = Thread.currentThread(); String name = t.getName(); if (!name.equals("my-thread")) { throw new RuntimeException("wrong Thread name: " + name); } didRunThread = name; } }; didRunThread = null; Thread t = new Thread(r, "my-thread"); //Thread t = new Thread(r); t.start(); try { t.join(); } catch (InterruptedException ix) { throw new RuntimeException("thread was interrupted"); } String tname = Thread.currentThread().getName(); if ((didRunThread == null) || (didRunThread.equals(tname))) { throw new RuntimeException("thread did not execute: " + didRunThread); } } } public void testSingleYield () { Thread.yield(); } @Test public void testYield () { if (verifyNoPropertyViolation("+cg.threads.break_start=true", "+cg.threads.break_yield=true")) { Runnable r = new Runnable() { @Override public void run() { Thread t = Thread.currentThread(); while (!didRunThread.equals("blah")) { Thread.yield(); } didRunThread = t.getName(); } }; didRunThread = "blah"; Thread t = new Thread(r); t.start(); while (didRunThread.equals("blah")) { Thread.yield(); } String tname = Thread.currentThread().getName(); if ((didRunThread == null) || (didRunThread.equals(tname))) { throw new RuntimeException("thread did not execute: " + didRunThread); } } } @Test public void testPriority () { if (verifyNoPropertyViolation()) { Runnable r = new Runnable() { @Override public void run() { Thread t = Thread.currentThread(); int prio = t.getPriority(); if (prio != (Thread.MIN_PRIORITY + 2)) { throw new RuntimeException("wrong Thread priority: " + prio); } didRunThread = t.getName(); } }; didRunThread = null; Thread t = new Thread(r); t.setPriority(Thread.MIN_PRIORITY + 2); t.start(); try { t.join(); } catch (InterruptedException ix) { throw new RuntimeException("thread was interrupted"); } String tname = Thread.currentThread().getName(); if ((didRunThread == null) || (didRunThread.equals(tname))) { throw new RuntimeException("thread did not execute: " + didRunThread); } } } @Test public void testJoin () { if (verifyNoPropertyViolation()) { Runnable r = new Runnable() { @Override public synchronized void run() { didRunThread = Thread.currentThread().getName(); } }; Thread t = new Thread(r); synchronized (r) { t.start(); Thread.yield(); if (didRunThread != null) { throw new RuntimeException("sync thread did execute before lock release"); } } try { t.join(); } catch (InterruptedException ix) { throw new RuntimeException("main thread was interrupted"); } if (didRunThread == null) { throw new RuntimeException("sync thread did not run after lock release"); } } } @Test public void testTimeoutJoin () { if (!isJPFRun()){ Verify.resetCounter(0); Verify.resetCounter(1); } if (verifyNoPropertyViolation()) { Runnable r = new Runnable() { @Override public void run() { synchronized(this){ System.out.println("[t] started"); } didRunThread = Thread.currentThread().getName(); // this causes a CG System.out.println("[t] finished"); } }; Thread t = new Thread(r); synchronized (r) { t.start(); Thread.yield(); if (didRunThread != null) { throw new RuntimeException("sync thread did execute before lock release"); } } try { System.out.println("[main] joining.."); t.join(42); System.out.println("[main] joined, t state: " + t.getState()); // we should get here for both terminated and non-terminated t switch (t.getState()) { case TERMINATED: if (didRunThread != null){ Verify.incrementCounter(0); } break; case RUNNABLE: Verify.incrementCounter(1); break; default: throw new RuntimeException("infeasible thread state: " + t.getState()); } } catch (InterruptedException ix) { throw new RuntimeException("main thread was interrupted"); } } if (!isJPFRun()){ assert Verify.getCounter(0) > 0; assert Verify.getCounter(1) > 0; } } @Test public void testInterrupt() { if (verifyNoPropertyViolation()) { Runnable r = new Runnable() { @Override public synchronized void run() { try { didRunThread = Thread.currentThread().getName(); System.out.println("-- t waiting"); wait(); } catch (InterruptedException x) { System.out.println("-- t interrupted"); didRunThread = null; } System.out.println("-- t terminated"); } }; Thread t = new Thread(r); t.start(); while (didRunThread == null) { Thread.yield(); } synchronized (r) { System.out.println("-- main thread interrupting..."); t.interrupt(); } try { t.join(); } catch (InterruptedException ix) { throw new RuntimeException("main thread was interrupted"); } if (didRunThread != null) { throw new RuntimeException("t did not get interrupted"); } System.out.println("-- main thread terminated"); } } @Test public void testSimpleThreadGroup () { if (verifyNoPropertyViolation()) { System.out.println("-- main thread started"); Thread mainThread = Thread.currentThread(); final ThreadGroup sysGroup = mainThread.getThreadGroup(); assert sysGroup != null && sysGroup.getName().equals("main"); int active = sysGroup.activeCount(); assert active == 1; Thread[] list = new Thread[active]; int n = sysGroup.enumerate(list); assert (n == active); assert list[0] == mainThread; Runnable r = new Runnable() { @Override public void run() { System.out.println("-- t started"); didRunThread = Thread.currentThread().getName(); Thread t = Thread.currentThread(); ThreadGroup group = t.getThreadGroup(); assert group != null && group == sysGroup; int active = group.activeCount(); assert active == 2; Thread[] list = new Thread[active]; int n = group.enumerate(list); assert (n == active); assert list[1] == t; System.out.println("-- t terminated"); } }; Thread t = new Thread(r); t.start(); try { t.join(); } catch (InterruptedException ix) { throw new RuntimeException("main thread was interrupted"); } if (didRunThread == null) { throw new RuntimeException("t did not run"); } System.out.println("-- main thread terminated"); } } }
4,942
1,056
<reponame>timfel/netbeans /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.api.debugger.jpda.testapps; /** * Sample step application. * * @author <NAME> */ public class AsynchStepApp { public static void main(String[] args) { AsynchStepApp sa = new AsynchStepApp(); // LBREAKPOINT x += sa.m1(); x += sa.m1(); x += sa.m1(); x += sa.m1(); x += sa.m1(); } public AsynchStepApp() { // STOP Into1 } // STOP Over1 private int m1() { int im1 = 10; // STOP Into2 m2(); // STOP Over2 return im1; } private int m2() { int im2 = 20; // STOP Into3 m3(); return im2; } private int m3() { int im3 = 30; return im3; } static int x = 20; private int longMethod() { try { Thread.currentThread().sleep(1000); } catch (InterruptedException iex) {} return 0; } }
715
986
from public import public from ...common import exceptions as com from .. import datatypes as dt from .. import rules as rlz from ..signature import Argument as Arg from .core import ValueOp @public class MapLength(ValueOp): arg = Arg(rlz.mapping) output_type = rlz.shape_like('arg', dt.int64) @public class MapValueForKey(ValueOp): arg = Arg(rlz.mapping) key = Arg(rlz.one_of([rlz.string, rlz.integer])) def output_type(self): return rlz.shape_like(tuple(self.args), self.arg.type().value_type) @public class MapValueOrDefaultForKey(ValueOp): arg = Arg(rlz.mapping) key = Arg(rlz.one_of([rlz.string, rlz.integer])) default = Arg(rlz.any) def output_type(self): arg = self.arg default = self.default map_type = arg.type() value_type = map_type.value_type default_type = default.type() if default is not None and not dt.same_kind(default_type, value_type): raise com.IbisTypeError( "Default value\n{}\nof type {} cannot be cast to map's value " "type {}".format(default, default_type, value_type) ) result_type = dt.highest_precedence((default_type, value_type)) return rlz.shape_like(tuple(self.args), result_type) @public class MapKeys(ValueOp): arg = Arg(rlz.mapping) def output_type(self): arg = self.arg return rlz.shape_like(arg, dt.Array(arg.type().key_type)) @public class MapValues(ValueOp): arg = Arg(rlz.mapping) def output_type(self): arg = self.arg return rlz.shape_like(arg, dt.Array(arg.type().value_type)) @public class MapConcat(ValueOp): left = Arg(rlz.mapping) right = Arg(rlz.mapping) output_type = rlz.typeof('left')
766
526
<gh_stars>100-1000 /* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.openmetadata.userinterface.uichassis.springboot.auth.ldap; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider; @EnableWebSecurity @Configuration("securityConfig") @Order(Ordered.HIGHEST_PRECEDENCE) @ConditionalOnProperty(value = "authentication.source", havingValue = "ad") public class ActiveDirectoryLdapSecurityConfig extends LdapSecurityConfig { @Value("${ldap.domain}") private String ldapDomain; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { ActiveDirectoryLdapAuthenticationProvider adProvider = new ActiveDirectoryLdapAuthenticationProvider( ldapDomain, ldapURL, userSearchBase); adProvider.setSearchFilter(userSearchFilter); adProvider.setUserDetailsContextMapper(userContextMapper()); adProvider.setConvertSubErrorCodesToExceptions(true); adProvider.setUseAuthenticationRequestCredentials(true); auth.authenticationProvider(adProvider); } }
575
6,036
<filename>nodejs/src/run_options_helper.h // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include <napi.h> namespace Ort { struct RunOptions; } // parse a Javascript run options object and fill the native RunOptions object. void ParseRunOptions(const Napi::Object options, Ort::RunOptions &runOptions);
107
2,919
#!/usr/bin/env python3 # Copyright (c) 2020 VMware, 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. # Breaks lines read from stdin into groups using blank lines as # group separators, then sorts lines within the groups for # reproducibility. import re import sys # This is copied out of the Python Sorting HOWTO at # https://docs.python.org/3/howto/sorting.html#sortinghowto def cmp_to_key(mycmp): 'Convert a cmp= function into a key= function' class K(object): def __init__(self, obj, *args): self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(self, other): return mycmp(self.obj, other.obj) > 0 def __eq__(self, other): return mycmp(self.obj, other.obj) == 0 def __le__(self, other): return mycmp(self.obj, other.obj) <= 0 def __ge__(self, other): return mycmp(self.obj, other.obj) >= 0 def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 return K u = '[0-9a-fA-F]' uuid_re = re.compile(r'%s{8}-%s{4}-%s{4}-%s{4}-%s{12}' % ((u,) * 5)) def cmp(a, b): return (a > b) - (a < b) def compare_lines(a, b): if uuid_re.match(a): if uuid_re.match(b): return cmp(a[36:], b[36:]) else: return 1 elif uuid_re.match(b): return -1 else: return cmp(a, b) def output_group(group, dst): for x in sorted(group, key=cmp_to_key(compare_lines)): dst.write(x) def ovsdb_monitor_sort(src, dst): group = [] while True: line = src.readline() if not line: break if line.rstrip() == '': output_group(group, dst) group = [] dst.write(line) elif line.startswith(',') and group: group[len(group) - 1] += line else: group.append(line) if group: output_group(group, dst) if __name__ == '__main__': ovsdb_monitor_sort(sys.stdin, sys.stdout)
1,135
872
""" Given an integer matrix, find the length of the longest increasing path. From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed). Example 1: nums = [ [9,9,4], [6,6,8], [2,1,1] ] Return 4 The longest increasing path is [1, 2, 6, 9]. Example 2: nums = [ [3,4,5], [3,2,6], [2,2,1] ] Return 4 The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed. """ __author__ = 'Daniel' class Solution(object): def __init__(self): self.cache = None self.dirs = ((-1, 0), (1, 0), (0, -1), (0, 1),) def longestIncreasingPath(self, matrix): """ dfs + cache :type matrix: List[List[int]] :rtype: int """ if not matrix: return 0 m, n = len(matrix), len(matrix[0]) self.cache = [[None for _ in xrange(n)] for _ in xrange(m)] gmax = 1 for i in xrange(m): for j in xrange(n): gmax = max(gmax, self.longest(matrix, i, j)) return gmax def longest(self, matrix, i, j): """ Strictly increasing, thus no need to have a visited matrix """ if not self.cache[i][j]: m, n = len(matrix), len(matrix[0]) maxa = 1 for d in self.dirs: I, J = i + d[0], j + d[1] if 0 <= I < m and 0 <= J < n and matrix[I][J] > matrix[i][j]: maxa = max(maxa, 1 + self.longest(matrix, I, J)) self.cache[i][j] = maxa return self.cache[i][j] if __name__ == "__main__": assert Solution().longestIncreasingPath([ [9, 9, 4], [6, 6, 8], [2, 1, 1] ]) == 4
873
866
from unittest import TestCase from terraform_compliance.common.bdd_tags import look_for_bdd_tags from terraform_compliance.common.exceptions import Failure from tests.mocks import MockedStep, MockedTags class TestBddTags(TestCase): def test_unchanged_step_object(self): step = MockedStep() look_for_bdd_tags(step) self.assertFalse(step.context.no_failure) self.assertIsNone(step.context.failure_class) def test_warning_case(self): step = MockedStep() step.all_tags = [MockedTags(name='warning')] look_for_bdd_tags(step) self.assertTrue(step.context.no_failure) self.assertEqual(step.context.failure_class, 'warning')
282
918
/* * 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.gobblin.configuration.workunit; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.List; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.io.Closer; import org.apache.gobblin.source.workunit.MultiWorkUnit; import org.apache.gobblin.source.workunit.WorkUnit; /** * Unit tests for {@link MultiWorkUnit}. */ @Test(groups = {"gobblin.configuration.workunit"}) public class MultiWorkUnitTest { private MultiWorkUnit multiWorkUnit; @BeforeClass public void setUp() { this.multiWorkUnit = new MultiWorkUnit(); WorkUnit workUnit1 = WorkUnit.createEmpty(); workUnit1.setHighWaterMark(1000); workUnit1.setLowWaterMark(0); workUnit1.setProp("k1", "v1"); this.multiWorkUnit.addWorkUnit(workUnit1); WorkUnit workUnit2 = WorkUnit.createEmpty(); workUnit2.setHighWaterMark(2000); workUnit2.setLowWaterMark(1001); workUnit2.setProp("k2", "v2"); this.multiWorkUnit.addWorkUnit(workUnit2); } @Test public void testSerDe() throws IOException { Closer closer = Closer.create(); try { ByteArrayOutputStream baos = closer.register(new ByteArrayOutputStream()); DataOutputStream dos = closer.register(new DataOutputStream(baos)); this.multiWorkUnit.write(dos); ByteArrayInputStream bais = closer.register((new ByteArrayInputStream(baos.toByteArray()))); DataInputStream dis = closer.register((new DataInputStream(bais))); MultiWorkUnit copy = new MultiWorkUnit(); copy.readFields(dis); List<WorkUnit> workUnitList = copy.getWorkUnits(); Assert.assertEquals(workUnitList.size(), 2); Assert.assertEquals(workUnitList.get(0).getHighWaterMark(), 1000); Assert.assertEquals(workUnitList.get(0).getLowWaterMark(), 0); Assert.assertEquals(workUnitList.get(0).getProp("k1"), "v1"); Assert.assertEquals(workUnitList.get(1).getHighWaterMark(), 2000); Assert.assertEquals(workUnitList.get(1).getLowWaterMark(), 1001); Assert.assertEquals(workUnitList.get(1).getProp("k2"), "v2"); } catch (Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } } }
1,064
13,057
/* * Copyright (c) 2016 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.stubbing; /** * Generic interface to be used for configuring mock's answer for a two argument invocation. * * Answer specifies an action that is executed and a return value that is returned when you interact with the mock. * <p> * Example of stubbing a mock with this custom answer: * * <pre class="code"><code class="java"> * import static org.mockito.AdditionalAnswers.answer; * * when(mock.someMethod(anyString(), anyChar())).then(answer( * new Answer2&lt;String, String, Character&gt;() { * public String answer(String s, Character c) { * return s.replace('f', c); * } * })); * * //Following will print "bar" * System.out.println(mock.someMethod("far", 'b')); * </code></pre> * * @param <T> return type * @param <A0> type of the first argument * @param <A1> type of the second argument * @see Answer */ public interface Answer2<T, A0, A1> { /** * @param argument0 the first argument. * @param argument1 the second argument. * * @return the value to be returned. * * @throws Throwable the throwable to be thrown */ T answer(A0 argument0, A1 argument1) throws Throwable; }
443
1,097
// // HCPDataDownloader.h // // Created by <NAME> on 04.11.16. // #import <Foundation/Foundation.h> /** * Complition block for data download. * * @param data downloaded data * @param error error information; <code>nil</code> - if everything is fine */ typedef void (^HCPDataDownloadCompletionBlock)(NSData *data, NSError *error); /** * Helper class to download data. */ @interface HCPDataDownloader : NSObject /** * Download data asynchronously. * * @param url url to the downloaded file * @param headers request headers to send with the request * @param block data download completion block, called with the data when it is available. */ - (void) downloadDataFromUrl:(NSURL*)url requestHeaders:(NSDictionary *)headers completionBlock:(HCPDataDownloadCompletionBlock) block; @end
277
1,511
<filename>tests/cluecode/data/ics/netperf/nettest_sctp.c #ifndef lint char nettest_sctp[]="\ @(#)nettest_sctp.c (c) Copyright 2005-2007 Hewlett-<NAME>. Version 2.4.3"; #else #define DIRTY /* first, use the form "first," (see the routine break_args.. */ while ((c= getopt(argc, argv, SOCKETS_ARGS)) != EOF) { switch (c) { case '?': case '4':
165
471
from corehq.apps.linked_domain.keywords import create_linked_keyword, update_keyword from corehq.apps.app_manager.models import Module from corehq.apps.linked_domain.tests.test_linked_apps import BaseLinkedAppsTest from corehq.apps.reminders.models import METHOD_SMS from corehq.apps.sms.models import Keyword, KeywordAction class TestLinkedKeywords(BaseLinkedAppsTest): def setUp(self): super(TestLinkedKeywords, self).setUp() module = self.master1.add_module(Module.new_module("M1", None)) master_form = module.new_form("f1", None, self.get_xml("very_simple_form").decode("utf-8")) self.keyword = Keyword( domain=self.domain_link.master_domain, keyword="ping", description="The description", override_open_sessions=True, ) self.keyword.save() self.keyword.keywordaction_set.create( recipient=KeywordAction.RECIPIENT_SENDER, action=METHOD_SMS, message_content="pong", app_id=self.master1.get_id, form_unique_id=master_form.unique_id, ) def tearDown(self): self.keyword.delete() super(TestLinkedKeywords, self).tearDown() def test_create_keyword_link(self): new_keyword_id = create_linked_keyword(self.domain_link, self.keyword.id) new_keyword = Keyword.objects.get(id=new_keyword_id) self.assertEqual(new_keyword.keyword, self.keyword.keyword) new_keyword_action = new_keyword.keywordaction_set.first() self.assertEqual( new_keyword_action.message_content, self.keyword.keywordaction_set.first().message_content, ) self.assertEqual(new_keyword_action.app_id, self.linked_app.get_id) def test_update_keyword_link(self): new_keyword_id = create_linked_keyword(self.domain_link, self.keyword.id) self.keyword.keyword = "foo" self.keyword.save() keyword_action = self.keyword.keywordaction_set.first() keyword_action.message_content = "bar" keyword_action.save() update_keyword(self.domain_link, new_keyword_id) linked_keyword = Keyword.objects.get(id=new_keyword_id) self.assertEqual(linked_keyword.keyword, "foo") self.assertEqual(linked_keyword.keywordaction_set.first().message_content, "bar")
1,036
14,668
<filename>remoting/tools/remote_test_helper/rth_server.py # Copyright 2014 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. import jsonrpclib import SimpleJSONRPCServer as _server class RequestHandler(_server.SimpleJSONRPCRequestHandler): """Custom JSON-RPC request handler.""" FILES = { 'client.html': {'content-type': 'text/html'}, 'host.html': {'content-type': 'text/html'}, 'client.js': {'content-type': 'application/javascript'}, 'host.js': {'content-type': 'application/javascript'}, 'jsonrpc.js': {'content-type': 'application/javascript'} } def do_GET(self): """Custom GET handler to return default pages.""" filename = self.path.lstrip('/') if filename not in self.FILES: self.report_404() return with open(filename) as f: data = f.read() self.send_response(200) for key, value in self.FILES[filename].iteritems(): self.send_header(key, value) self.end_headers() self.wfile.write(data) class RPCHandler(object): """Class to define and handle RPC calls.""" CLEARED_EVENT = {'action': 0, 'event': 0, 'modifiers': 0} def __init__(self): self.last_event = self.CLEARED_EVENT def ClearLastEvent(self): """Clear the last event.""" self.last_event = self.CLEARED_EVENT return True def SetLastEvent(self, action, value, modifier): """Set the last action, value, and modifiers.""" self.last_event = { 'action': action, 'value': value, 'modifiers': modifier } return True def GetLastEvent(self): return self.last_event def main(): server = _server.SimpleJSONRPCServer( ('', 3474), requestHandler=RequestHandler, logRequests=True, allow_none=True) server.register_instance(RPCHandler()) server.serve_forever() if __name__ == '__main__': main()
727
1,821
<reponame>hangqiu/pixie /* * Copyright 2018- The Pixie 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. * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include <string> #include "src/common/base/statusor.h" namespace px { std::string FileContentsOrDie(const std::string& filename); StatusOr<std::string> ReadFileToString(const std::string& filename, std::ios_base::openmode mode = std::ios_base::in); Status WriteFileFromString(const std::string& filename, std::string_view contents, std::ios_base::openmode mode = std::ios_base::out); } // namespace px
389
575
<filename>third_party/blink/renderer/core/layout/layout_shift_tracker.cc // Copyright 2018 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 "third_party/blink/renderer/core/layout/layout_shift_tracker.h" #include "cc/layers/heads_up_display_layer.h" #include "cc/layers/picture_layer.h" #include "cc/trees/layer_tree_host.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/common/input/web_pointer_event.h" #include "third_party/blink/renderer/core/dom/dom_node_ids.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/local_frame_client.h" #include "third_party/blink/renderer/core/frame/location.h" #include "third_party/blink/renderer/core/frame/visual_viewport.h" #include "third_party/blink/renderer/core/geometry/dom_rect_read_only.h" #include "third_party/blink/renderer/core/layout/layout_object.h" #include "third_party/blink/renderer/core/layout/layout_view.h" #include "third_party/blink/renderer/core/page/chrome_client.h" #include "third_party/blink/renderer/core/page/page.h" #include "third_party/blink/renderer/core/timing/dom_window_performance.h" #include "third_party/blink/renderer/core/timing/performance_entry.h" #include "third_party/blink/renderer/core/timing/window_performance.h" #include "third_party/blink/renderer/platform/graphics/graphics_layer.h" #include "third_party/blink/renderer/platform/graphics/paint/geometry_mapper.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "ui/gfx/geometry/rect.h" namespace blink { using ReattachHookScope = LayoutShiftTracker::ReattachHookScope; ReattachHookScope* ReattachHookScope::top_ = nullptr; using ContainingBlockScope = LayoutShiftTracker::ContainingBlockScope; ContainingBlockScope* ContainingBlockScope::top_ = nullptr; namespace { constexpr base::TimeDelta kTimerDelay = base::TimeDelta::FromMilliseconds(500); const float kMovementThreshold = 3.0; // CSS pixels. // Calculates the physical coordinates of the starting point in the current // coordinate space. |paint_offset| is the physical offset of the top-left // corner. The starting point can be any of the four corners of the box, // depending on the writing mode and text direction. Note that the result is // still in physical coordinates, just may be of a different corner. // See https://wicg.github.io/layout-instability/#starting-point. FloatPoint StartingPoint(const PhysicalOffset& paint_offset, const LayoutBox& box, const LayoutSize& size) { PhysicalOffset starting_point = paint_offset; auto writing_direction = box.StyleRef().GetWritingDirection(); if (UNLIKELY(writing_direction.IsFlippedBlocks())) starting_point.left += size.Width(); if (UNLIKELY(writing_direction.IsRtl())) { if (writing_direction.IsHorizontal()) starting_point.left += size.Width(); else starting_point.top += size.Height(); } return FloatPoint(starting_point); } // Returns the part a rect logically below a starting point. PhysicalRect RectBelowStartingPoint(const PhysicalRect& rect, const PhysicalOffset& starting_point, LayoutUnit logical_height, WritingDirectionMode writing_direction) { PhysicalRect result = rect; if (writing_direction.IsHorizontal()) { result.ShiftTopEdgeTo(starting_point.top); result.SetHeight(logical_height); } else { result.SetWidth(logical_height); if (writing_direction.IsFlippedBlocks()) result.ShiftRightEdgeTo(starting_point.left); else result.ShiftLeftEdgeTo(starting_point.left); } return result; } float GetMoveDistance(const FloatPoint& old_starting_point, const FloatPoint& new_starting_point) { FloatSize location_delta = new_starting_point - old_starting_point; return std::max(fabs(location_delta.Width()), fabs(location_delta.Height())); } bool EqualWithinMovementThreshold(const FloatPoint& a, const FloatPoint& b, float threshold_physical_px) { return fabs(a.X() - b.X()) < threshold_physical_px && fabs(a.Y() - b.Y()) < threshold_physical_px; } bool SmallerThanRegionGranularity(const LayoutRect& rect) { // Normally we paint by snapping to whole pixels, so rects smaller than half // a pixel may be invisible. return rect.Width() < 0.5 || rect.Height() < 0.5; } void RectToTracedValue(const IntRect& rect, TracedValue& value, const char* key = nullptr) { if (key) value.BeginArray(key); else value.BeginArray(); value.PushInteger(rect.X()); value.PushInteger(rect.Y()); value.PushInteger(rect.Width()); value.PushInteger(rect.Height()); value.EndArray(); } void RegionToTracedValue(const LayoutShiftRegion& region, TracedValue& value) { Region blink_region; for (IntRect rect : region.GetRects()) blink_region.Unite(Region(rect)); value.BeginArray("region_rects"); for (const IntRect& rect : blink_region.Rects()) RectToTracedValue(rect, value); value.EndArray(); } bool ShouldLog(const LocalFrame& frame) { if (!VLOG_IS_ON(1)) return false; DCHECK(frame.GetDocument()); const String& url = frame.GetDocument()->Url().GetString(); return !url.StartsWith("devtools:"); } } // namespace LayoutShiftTracker::LayoutShiftTracker(LocalFrameView* frame_view) : frame_view_(frame_view), // This eliminates noise from the private Page object created by // SVGImage::DataChanged. is_active_( !frame_view->GetFrame().GetChromeClient().IsSVGImageChromeClient()), enable_m90_improvements_( base::FeatureList::IsEnabled(features::kCLSM90Improvements)), score_(0.0), weighted_score_(0.0), timer_(frame_view->GetFrame().GetTaskRunner(TaskType::kInternalDefault), this, &LayoutShiftTracker::TimerFired), frame_max_distance_(0.0), overall_max_distance_(0.0), observed_input_or_scroll_(false), most_recent_input_timestamp_initialized_(false) {} bool LayoutShiftTracker::NeedsToTrack(const LayoutObject& object) const { if (!is_active_) return false; if (object.GetDocument().IsPrintingOrPaintingPreview()) return false; // SVG elements don't participate in the normal layout algorithms and are // more likely to be used for animations. if (object.IsSVGChild()) return false; if (object.StyleRef().Visibility() != EVisibility::kVisible) return false; if (object.IsText()) { if (!ContainingBlockScope::top_) return false; if (object.IsBR()) return false; if (enable_m90_improvements_) { if (To<LayoutText>(object).ContainsOnlyWhitespaceOrNbsp() == OnlyWhitespaceOrNbsp::kYes) return false; if (object.StyleRef().GetFont().ShouldSkipDrawing()) return false; } return true; } if (!object.IsBox()) return false; const auto& box = To<LayoutBox>(object); if (SmallerThanRegionGranularity(box.VisualOverflowRect())) return false; if (auto* display_lock_context = box.GetDisplayLockContext()) { if (display_lock_context->IsAuto() && display_lock_context->IsLocked()) return false; } // Don't report shift of anonymous objects. Will report the children because // we want report real DOM nodes. if (box.IsAnonymous()) return false; // Ignore sticky-positioned objects that move on scroll. // TODO(skobes): Find a way to detect when these objects shift. if (box.IsStickyPositioned()) return false; // A LayoutView can't move by itself. if (box.IsLayoutView()) return false; if (Element* element = DynamicTo<Element>(object.GetNode())) { if (element->IsSliderThumbElement()) return false; } if (enable_m90_improvements_ && box.IsLayoutBlock()) { // Just check the simplest case. For more complex cases, we should suggest // the developer to use visibility:hidden. if (To<LayoutBlock>(box).FirstChild()) return true; if (box.HasBoxDecorationBackground() || box.GetScrollableArea() || box.StyleRef().HasVisualOverflowingEffect()) return true; return false; } return true; } void LayoutShiftTracker::ObjectShifted( const LayoutObject& object, const PropertyTreeStateOrAlias& property_tree_state, const PhysicalRect& old_rect, const PhysicalRect& new_rect, const FloatPoint& old_starting_point, const FloatSize& translation_delta, const FloatSize& scroll_delta, const FloatPoint& new_starting_point) { // The caller should ensure these conditions. DCHECK(!old_rect.IsEmpty()); DCHECK(!new_rect.IsEmpty()); float threshold_physical_px = kMovementThreshold * object.StyleRef().EffectiveZoom(); if (enable_m90_improvements_) { // Check shift of starting point, including 2d-translation and scroll // deltas. if (EqualWithinMovementThreshold(old_starting_point, new_starting_point, threshold_physical_px)) return; // Check shift of 2d-translation-indifferent starting point. if (!translation_delta.IsZero() && EqualWithinMovementThreshold(old_starting_point + translation_delta, new_starting_point, threshold_physical_px)) return; // Check shift of scroll-indifferent starting point. if (!scroll_delta.IsZero() && EqualWithinMovementThreshold(old_starting_point + scroll_delta, new_starting_point, threshold_physical_px)) return; } // Check shift of 2d-translation-and-scroll-indifferent starting point. FloatSize translation_and_scroll_delta = scroll_delta + translation_delta; if (!translation_and_scroll_delta.IsZero() && EqualWithinMovementThreshold( old_starting_point + translation_and_scroll_delta, new_starting_point, threshold_physical_px)) return; const auto& root_state = object.View()->FirstFragment().LocalBorderBoxProperties(); FloatClipRect clip_rect = GeometryMapper::LocalToAncestorClipRect(property_tree_state, root_state); if (frame_view_->GetFrame().IsMainFrame()) { // Apply the visual viewport clip. clip_rect.Intersect(FloatClipRect( frame_view_->GetPage()->GetVisualViewport().VisibleRect())); } // If the clip region is empty, then the resulting layout shift isn't visible // in the viewport so ignore it. if (clip_rect.Rect().IsEmpty()) return; auto transform = GeometryMapper::SourceToDestinationProjection( property_tree_state.Transform(), root_state.Transform()); // TODO(crbug.com/1187979): Shift by |scroll_delta| to keep backward // compatibility in https://crrev.com/c/2754969. See the bug for details. FloatPoint old_starting_point_in_root = transform.MapPoint( old_starting_point + (enable_m90_improvements_ ? scroll_delta : translation_and_scroll_delta)); FloatPoint new_starting_point_in_root = transform.MapPoint(new_starting_point); if (EqualWithinMovementThreshold(old_starting_point_in_root, new_starting_point_in_root, threshold_physical_px)) return; if (enable_m90_improvements_) { DCHECK(frame_scroll_delta_.IsZero()); } else if (EqualWithinMovementThreshold( old_starting_point_in_root + frame_scroll_delta_, new_starting_point_in_root, threshold_physical_px)) { // TODO(skobes): Checking frame_scroll_delta_ is an imperfect solution to // allowing counterscrolled layout shifts. Ideally, we would map old_rect // to viewport coordinates using the previous frame's scroll tree. return; } FloatRect old_rect_in_root(old_rect); // TODO(crbug.com/1187979): Shift by |scroll_delta| to keep backward // compatibility in https://crrev.com/c/2754969. See the bug for details. old_rect_in_root.Move( enable_m90_improvements_ ? scroll_delta : translation_and_scroll_delta); transform.MapRect(old_rect_in_root); FloatRect new_rect_in_root(new_rect); transform.MapRect(new_rect_in_root); IntRect visible_old_rect = RoundedIntRect(Intersection(old_rect_in_root, clip_rect.Rect())); IntRect visible_new_rect = RoundedIntRect(Intersection(new_rect_in_root, clip_rect.Rect())); if (visible_old_rect.IsEmpty() && visible_new_rect.IsEmpty()) return; // If the object moved from or to out of view, ignore the shift if it's in // the inline direction only. if (enable_m90_improvements_ && (visible_old_rect.IsEmpty() || visible_new_rect.IsEmpty())) { FloatPoint old_inline_direction_indifferent_starting_point_in_root = old_starting_point_in_root; if (object.IsHorizontalWritingMode()) { old_inline_direction_indifferent_starting_point_in_root.SetX( new_starting_point_in_root.X()); } else { old_inline_direction_indifferent_starting_point_in_root.SetY( new_starting_point_in_root.Y()); } if (EqualWithinMovementThreshold( old_inline_direction_indifferent_starting_point_in_root, new_starting_point_in_root, threshold_physical_px)) { return; } } // Compute move distance based on unclipped rects, to accurately determine how // much the element moved. float move_distance = GetMoveDistance(old_starting_point_in_root, new_starting_point_in_root); frame_max_distance_ = std::max(frame_max_distance_, move_distance); LocalFrame& frame = frame_view_->GetFrame(); if (ShouldLog(frame)) { VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ") << frame.GetDocument()->Url() << ", " << object << " moved from " << old_rect_in_root << " to " << new_rect_in_root << " (visible from " << visible_old_rect << " to " << visible_new_rect << ")"; if (old_starting_point_in_root != old_rect_in_root.Location() || new_starting_point_in_root != new_rect_in_root.Location() || !translation_delta.IsZero() || !scroll_delta.IsZero()) { VLOG(1) << " (starting point from " << old_starting_point_in_root << " to " << new_starting_point_in_root << ")"; } } region_.AddRect(visible_old_rect); region_.AddRect(visible_new_rect); if (Node* node = object.GetNode()) { MaybeRecordAttribution( {DOMNodeIds::IdForNode(node), visible_old_rect, visible_new_rect}); } } LayoutShiftTracker::Attribution::Attribution() : node_id(kInvalidDOMNodeId) {} LayoutShiftTracker::Attribution::Attribution(DOMNodeId node_id_arg, IntRect old_visual_rect_arg, IntRect new_visual_rect_arg) : node_id(node_id_arg), old_visual_rect(old_visual_rect_arg), new_visual_rect(new_visual_rect_arg) {} LayoutShiftTracker::Attribution::operator bool() const { return node_id != kInvalidDOMNodeId; } bool LayoutShiftTracker::Attribution::Encloses(const Attribution& other) const { return old_visual_rect.Contains(other.old_visual_rect) && new_visual_rect.Contains(other.new_visual_rect); } int LayoutShiftTracker::Attribution::Area() const { int old_area = old_visual_rect.Width() * old_visual_rect.Height(); int new_area = new_visual_rect.Width() * new_visual_rect.Height(); IntRect intersection = Intersection(old_visual_rect, new_visual_rect); int shared_area = intersection.Width() * intersection.Height(); return old_area + new_area - shared_area; } bool LayoutShiftTracker::Attribution::MoreImpactfulThan( const Attribution& other) const { return Area() > other.Area(); } void LayoutShiftTracker::MaybeRecordAttribution( const Attribution& attribution) { Attribution* smallest = nullptr; for (auto& slot : attributions_) { if (!slot || attribution.Encloses(slot)) { slot = attribution; return; } if (slot.Encloses(attribution)) return; if (!smallest || smallest->MoreImpactfulThan(slot)) smallest = &slot; } // No empty slots or redundancies. Replace smallest existing slot if larger. if (attribution.MoreImpactfulThan(*smallest)) *smallest = attribution; } void LayoutShiftTracker::NotifyBoxPrePaint( const LayoutBox& box, const PropertyTreeStateOrAlias& property_tree_state, const PhysicalRect& old_rect, const PhysicalRect& new_rect, const PhysicalOffset& old_paint_offset, const FloatSize& translation_delta, const FloatSize& scroll_delta, const PhysicalOffset& new_paint_offset) { DCHECK(NeedsToTrack(box)); ObjectShifted(box, property_tree_state, old_rect, new_rect, StartingPoint(old_paint_offset, box, box.PreviousSize()), translation_delta, scroll_delta, StartingPoint(new_paint_offset, box, box.Size())); } void LayoutShiftTracker::NotifyTextPrePaint( const LayoutText& text, const PropertyTreeStateOrAlias& property_tree_state, const LogicalOffset& old_starting_point, const LogicalOffset& new_starting_point, const PhysicalOffset& old_paint_offset, const FloatSize& translation_delta, const FloatSize& scroll_delta, const PhysicalOffset& new_paint_offset, LayoutUnit logical_height) { DCHECK(NeedsToTrack(text)); auto* block = ContainingBlockScope::top_; DCHECK(block); auto writing_direction = text.StyleRef().GetWritingDirection(); PhysicalOffset old_physical_starting_point = old_paint_offset + old_starting_point.ConvertToPhysical(writing_direction, block->old_size_, PhysicalSize()); PhysicalOffset new_physical_starting_point = new_paint_offset + new_starting_point.ConvertToPhysical(writing_direction, block->new_size_, PhysicalSize()); PhysicalRect old_rect = RectBelowStartingPoint(block->old_rect_, old_physical_starting_point, logical_height, writing_direction); if (old_rect.IsEmpty()) return; PhysicalRect new_rect = RectBelowStartingPoint(block->new_rect_, new_physical_starting_point, logical_height, writing_direction); if (new_rect.IsEmpty()) return; ObjectShifted(text, property_tree_state, old_rect, new_rect, FloatPoint(old_physical_starting_point), translation_delta, scroll_delta, FloatPoint(new_physical_starting_point)); } double LayoutShiftTracker::SubframeWeightingFactor() const { LocalFrame& frame = frame_view_->GetFrame(); if (frame.IsMainFrame()) return 1; // Map the subframe view rect into the coordinate space of the local root. FloatClipRect subframe_cliprect = FloatClipRect(FloatRect(FloatPoint(), FloatSize(frame_view_->Size()))); GeometryMapper::LocalToAncestorVisualRect( frame_view_->GetLayoutView()->FirstFragment().LocalBorderBoxProperties(), PropertyTreeState::Root(), subframe_cliprect); auto subframe_rect = PhysicalRect::EnclosingRect(subframe_cliprect.Rect()); // Intersect with the portion of the local root that overlaps the main frame. frame.LocalFrameRoot().View()->MapToVisualRectInRemoteRootFrame( subframe_rect); IntSize subframe_visible_size = subframe_rect.PixelSnappedSize(); IntSize main_frame_size = frame.GetPage()->GetVisualViewport().Size(); // TODO(crbug.com/940711): This comparison ignores page scale and CSS // transforms above the local root. return static_cast<double>(subframe_visible_size.Area()) / main_frame_size.Area(); } void LayoutShiftTracker::NotifyPrePaintFinishedInternal() { if (!is_active_) return; if (region_.IsEmpty()) return; IntRect viewport = frame_view_->GetScrollableArea()->VisibleContentRect(); if (viewport.IsEmpty()) return; double viewport_area = double(viewport.Width()) * double(viewport.Height()); double impact_fraction = region_.Area() / viewport_area; DCHECK_GT(impact_fraction, 0); DCHECK_GT(frame_max_distance_, 0.0); double viewport_max_dimension = std::max(viewport.Width(), viewport.Height()); double move_distance_factor = (frame_max_distance_ < viewport_max_dimension) ? double(frame_max_distance_) / viewport_max_dimension : 1.0; double score_delta = impact_fraction * move_distance_factor; double weighted_score_delta = score_delta * SubframeWeightingFactor(); overall_max_distance_ = std::max(overall_max_distance_, frame_max_distance_); LocalFrame& frame = frame_view_->GetFrame(); if (ShouldLog(frame)) { VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ") << frame.GetDocument()->Url() << ", viewport was " << (impact_fraction * 100) << "% impacted with distance fraction " << move_distance_factor; } if (pointerdown_pending_data_.saw_pointerdown) { pointerdown_pending_data_.score_delta += score_delta; pointerdown_pending_data_.weighted_score_delta += weighted_score_delta; } else { ReportShift(score_delta, weighted_score_delta); } if (!region_.IsEmpty() && !timer_.IsActive()) SendLayoutShiftRectsToHud(region_.GetRects()); } void LayoutShiftTracker::NotifyPrePaintFinished() { NotifyPrePaintFinishedInternal(); // Reset accumulated state. region_.Reset(); frame_max_distance_ = 0.0; frame_scroll_delta_ = ScrollOffset(); attributions_.fill(Attribution()); } LayoutShift::AttributionList LayoutShiftTracker::CreateAttributionList() const { LayoutShift::AttributionList list; for (const Attribution& att : attributions_) { if (att.node_id == kInvalidDOMNodeId) break; list.push_back(LayoutShiftAttribution::Create( DOMNodeIds::NodeForId(att.node_id), DOMRectReadOnly::FromIntRect(att.old_visual_rect), DOMRectReadOnly::FromIntRect(att.new_visual_rect))); } return list; } void LayoutShiftTracker::SubmitPerformanceEntry(double score_delta, bool had_recent_input) const { LocalDOMWindow* window = frame_view_->GetFrame().DomWindow(); if (!window) return; WindowPerformance* performance = DOMWindowPerformance::performance(*window); DCHECK(performance); double input_timestamp = LastInputTimestamp(); LayoutShift* entry = LayoutShift::Create(performance->now(), score_delta, had_recent_input, input_timestamp, CreateAttributionList()); performance->AddLayoutShiftEntry(entry); } void LayoutShiftTracker::ReportShift(double score_delta, double weighted_score_delta) { LocalFrame& frame = frame_view_->GetFrame(); bool had_recent_input = timer_.IsActive(); if (!had_recent_input) { score_ += score_delta; if (weighted_score_delta > 0) { weighted_score_ += weighted_score_delta; frame.Client()->DidObserveLayoutShift(weighted_score_delta, observed_input_or_scroll_); } } SubmitPerformanceEntry(score_delta, had_recent_input); TRACE_EVENT_INSTANT2( "loading", "LayoutShift", TRACE_EVENT_SCOPE_THREAD, "data", PerFrameTraceData(score_delta, weighted_score_delta, had_recent_input), "frame", ToTraceValue(&frame)); if (ShouldLog(frame)) { VLOG(1) << "in " << (frame.IsMainFrame() ? "" : "subframe ") << frame.GetDocument()->Url().GetString() << ", layout shift of " << score_delta << (had_recent_input ? " excluded by recent input" : " reported") << "; cumulative score is " << score_; } } void LayoutShiftTracker::NotifyInput(const WebInputEvent& event) { const WebInputEvent::Type type = event.GetType(); const bool saw_pointerdown = pointerdown_pending_data_.saw_pointerdown; const bool pointerdown_became_tap = saw_pointerdown && type == WebInputEvent::Type::kPointerUp; const bool event_type_stops_pointerdown_buffering = type == WebInputEvent::Type::kPointerUp || type == WebInputEvent::Type::kPointerCausedUaAction || type == WebInputEvent::Type::kPointerCancel; // Only non-hovering pointerdown requires buffering. const bool is_hovering_pointerdown = type == WebInputEvent::Type::kPointerDown && static_cast<const WebPointerEvent&>(event).hovering; const bool should_trigger_shift_exclusion = type == WebInputEvent::Type::kMouseDown || type == WebInputEvent::Type::kKeyDown || type == WebInputEvent::Type::kRawKeyDown || // We need to explicitly include tap, as if there are no listeners, we // won't receive the pointer events. type == WebInputEvent::Type::kGestureTap || is_hovering_pointerdown || pointerdown_became_tap; if (should_trigger_shift_exclusion) { observed_input_or_scroll_ = true; // This cancels any previously scheduled task from the same timer. timer_.StartOneShot(kTimerDelay, FROM_HERE); UpdateInputTimestamp(event.TimeStamp()); } if (saw_pointerdown && event_type_stops_pointerdown_buffering) { double score_delta = pointerdown_pending_data_.score_delta; if (score_delta > 0) ReportShift(score_delta, pointerdown_pending_data_.weighted_score_delta); pointerdown_pending_data_ = PointerdownPendingData(); } if (type == WebInputEvent::Type::kPointerDown && !is_hovering_pointerdown) pointerdown_pending_data_.saw_pointerdown = true; } void LayoutShiftTracker::UpdateInputTimestamp(base::TimeTicks timestamp) { if (!most_recent_input_timestamp_initialized_) { most_recent_input_timestamp_ = timestamp; most_recent_input_timestamp_initialized_ = true; } else if (timestamp > most_recent_input_timestamp_) { most_recent_input_timestamp_ = timestamp; } LocalFrame& frame = frame_view_->GetFrame(); frame.Client()->DidObserveInputForLayoutShiftTracking(timestamp); } void LayoutShiftTracker::NotifyScroll(mojom::blink::ScrollType scroll_type, ScrollOffset delta) { if (!enable_m90_improvements_) frame_scroll_delta_ += delta; // Only set observed_input_or_scroll_ for user-initiated scrolls, and not // other scrolls such as hash fragment navigations. if (scroll_type == mojom::blink::ScrollType::kUser || scroll_type == mojom::blink::ScrollType::kCompositor) observed_input_or_scroll_ = true; } void LayoutShiftTracker::NotifyViewportSizeChanged() { UpdateTimerAndInputTimestamp(); } void LayoutShiftTracker::NotifyFindInPageInput() { UpdateTimerAndInputTimestamp(); } void LayoutShiftTracker::NotifyChangeEvent() { UpdateTimerAndInputTimestamp(); } void LayoutShiftTracker::UpdateTimerAndInputTimestamp() { // This cancels any previously scheduled task from the same timer. timer_.StartOneShot(kTimerDelay, FROM_HERE); UpdateInputTimestamp(base::TimeTicks::Now()); } double LayoutShiftTracker::LastInputTimestamp() const { LocalDOMWindow* window = frame_view_->GetFrame().DomWindow(); if (!window) return 0.0; WindowPerformance* performance = DOMWindowPerformance::performance(*window); DCHECK(performance); return most_recent_input_timestamp_initialized_ ? performance->MonotonicTimeToDOMHighResTimeStamp( most_recent_input_timestamp_) : 0.0; } std::unique_ptr<TracedValue> LayoutShiftTracker::PerFrameTraceData( double score_delta, double weighted_score_delta, bool input_detected) const { auto value = std::make_unique<TracedValue>(); value->SetDouble("score", score_delta); value->SetDouble("weighted_score_delta", weighted_score_delta); value->SetDouble("cumulative_score", score_); value->SetDouble("overall_max_distance", overall_max_distance_); value->SetDouble("frame_max_distance", frame_max_distance_); RegionToTracedValue(region_, *value); value->SetBoolean("is_main_frame", frame_view_->GetFrame().IsMainFrame()); value->SetBoolean("had_recent_input", input_detected); value->SetDouble("last_input_timestamp", LastInputTimestamp()); AttributionsToTracedValue(*value); return value; } void LayoutShiftTracker::AttributionsToTracedValue(TracedValue& value) const { const Attribution* it = attributions_.begin(); if (!*it) return; bool should_include_names; TRACE_EVENT_CATEGORY_GROUP_ENABLED( TRACE_DISABLED_BY_DEFAULT("layout_shift.debug"), &should_include_names); value.BeginArray("impacted_nodes"); while (it != attributions_.end() && it->node_id != kInvalidDOMNodeId) { value.BeginDictionary(); value.SetInteger("node_id", it->node_id); RectToTracedValue(it->old_visual_rect, value, "old_rect"); RectToTracedValue(it->new_visual_rect, value, "new_rect"); if (should_include_names) { Node* node = DOMNodeIds::NodeForId(it->node_id); value.SetString("debug_name", node ? node->DebugName() : ""); } value.EndDictionary(); it++; } value.EndArray(); } void LayoutShiftTracker::SendLayoutShiftRectsToHud( const Vector<IntRect>& int_rects) { // Store the layout shift rects in the HUD layer. auto* cc_layer = frame_view_->RootCcLayer(); if (cc_layer && cc_layer->layer_tree_host()) { if (!cc_layer->layer_tree_host()->GetDebugState().show_layout_shift_regions) return; if (cc_layer->layer_tree_host()->hud_layer()) { WebVector<gfx::Rect> rects; Region blink_region; for (IntRect rect : int_rects) blink_region.Unite(Region(rect)); for (const IntRect& rect : blink_region.Rects()) rects.emplace_back(rect); cc_layer->layer_tree_host()->hud_layer()->SetLayoutShiftRects( rects.ReleaseVector()); cc_layer->layer_tree_host()->hud_layer()->SetNeedsPushProperties(); } } } void LayoutShiftTracker::Trace(Visitor* visitor) const { visitor->Trace(frame_view_); visitor->Trace(timer_); } ReattachHookScope::ReattachHookScope(const Node& node) : outer_(top_) { if (node.GetLayoutObject()) top_ = this; } ReattachHookScope::~ReattachHookScope() { top_ = outer_; } void ReattachHookScope::NotifyDetach(const Node& node) { if (!top_) return; auto* layout_object = node.GetLayoutObject(); if (!layout_object || layout_object->ShouldSkipNextLayoutShiftTracking() || !layout_object->IsBox()) return; auto& map = top_->geometries_before_detach_; auto& fragment = layout_object->GetMutableForPainting().FirstFragment(); // Save the visual rect for restoration on future reattachment. const auto& box = To<LayoutBox>(*layout_object); PhysicalRect visual_overflow_rect = box.PreviousPhysicalVisualOverflowRect(); if (visual_overflow_rect.IsEmpty() && box.PreviousSize().IsEmpty()) return; bool has_paint_offset_transform = false; if (auto* properties = fragment.PaintProperties()) has_paint_offset_transform = properties->PaintOffsetTranslation(); map.Set(&node, Geometry{fragment.PaintOffset(), box.PreviousSize(), visual_overflow_rect, has_paint_offset_transform}); } void ReattachHookScope::NotifyAttach(const Node& node) { if (!top_) return; auto* layout_object = node.GetLayoutObject(); if (!layout_object || !layout_object->IsBox()) return; auto& map = top_->geometries_before_detach_; // Restore geometries that was saved during detach. Note: this does not // affect paint invalidation; we will fully invalidate the new layout object. auto iter = map.find(&node); if (iter == map.end()) return; To<LayoutBox>(layout_object) ->GetMutableForPainting() .SetPreviousGeometryForLayoutShiftTracking( iter->value.paint_offset, iter->value.size, iter->value.visual_overflow_rect); layout_object->SetShouldSkipNextLayoutShiftTracking(false); layout_object->SetShouldAssumePaintOffsetTranslationForLayoutShiftTracking( iter->value.has_paint_offset_translation); } } // namespace blink
12,025
356
{ "cve": ["CVE-2021-22939"], "vulnerable": "12.x || 14.x || 16.x", "patched": "^12.22.5 || ^14.17.5 || ^16.6.2", "ref": "https://https://nodejs.org/en/blog/vulnerability/aug-2021-security-releases/", "overview": "If the Node.js https API was used incorrectly and \"undefined\" was in passed for the \"rejectUnauthorized\" parameter, no error was returned and connections to servers with an expired certificate would have been accepted. You can read more about it in: https://nvd.nist.gov/vuln/detail/CVE-2021-22939" }
185
410
/* * Copyright (C) 2018 The Sylph 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 ideal.sylph.runner.spark; import org.apache.spark.sql.SparkSession; import org.apache.spark.streaming.StreamingContext; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.util.function.Supplier; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; /** * spark on yarn main Class */ public final class SparkAppMain { private SparkAppMain() {} public static void main(String[] args) throws Exception { System.out.println("spark on yarn app starting..."); @SuppressWarnings("unchecked") Supplier<?> sparkJobHandle = (Supplier<?>) byteToObject(new FileInputStream("job.graph")); Object appContext = requireNonNull(sparkJobHandle, "sparkJobHandle is null").get(); if (appContext instanceof SparkSession) { checkArgument(((SparkSession) appContext).streams().active().length > 0, "no stream pipeline"); ((SparkSession) appContext).streams().awaitAnyTermination(); } else if (appContext instanceof StreamingContext) { ((StreamingContext) appContext).start(); ((StreamingContext) appContext).awaitTermination(); } } private static Object byteToObject(InputStream inputStream) throws IOException, ClassNotFoundException { try (ObjectInputStream oi = new ObjectInputStream(inputStream) ) { return oi.readObject(); } } }
739
892
{ "schema_version": "1.2.0", "id": "GHSA-784j-h234-m56x", "modified": "2022-05-13T01:15:19Z", "published": "2022-05-13T01:15:19Z", "aliases": [ "CVE-2019-1003000" ], "details": "A sandbox bypass vulnerability exists in Script Security Plugin 1.49 and earlier in src/main/java/org/jenkinsci/plugins/scriptsecurity/sandbox/groovy/GroovySandbox.java that allows attackers with the ability to provide sandboxed scripts to execute arbitrary code on the Jenkins master JVM.", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2019-1003000" }, { "type": "WEB", "url": "https://access.redhat.com/errata/RHBA-2019:0326" }, { "type": "WEB", "url": "https://access.redhat.com/errata/RHBA-2019:0327" }, { "type": "WEB", "url": "https://jenkins.io/security/advisory/2019-01-08/#SECURITY-1266" }, { "type": "WEB", "url": "https://www.exploit-db.com/exploits/46453/" }, { "type": "WEB", "url": "https://www.exploit-db.com/exploits/46572/" }, { "type": "WEB", "url": "http://packetstormsecurity.com/files/152132/Jenkins-ACL-Bypass-Metaprogramming-Remote-Code-Execution.html" }, { "type": "WEB", "url": "http://www.rapid7.com/db/modules/exploit/multi/http/jenkins_metaprogramming" } ], "database_specific": { "cwe_ids": [ ], "severity": "HIGH", "github_reviewed": false } }
779
5,964
<filename>third_party/sfntly/src/cpp/src/sfntly/font_factory.cc<gh_stars>1000+ /* * Copyright 2011 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sfntly/font_factory.h" #include <string.h> #include "sfntly/tag.h" namespace sfntly { FontFactory::~FontFactory() { } CALLER_ATTACH FontFactory* FontFactory::GetInstance() { FontFactoryPtr instance = new FontFactory(); return instance.Detach(); } void FontFactory::FingerprintFont(bool fingerprint) { fingerprint_ = fingerprint; } bool FontFactory::FingerprintFont() { return fingerprint_; } void FontFactory::LoadFonts(InputStream* is, FontArray* output) { assert(output); PushbackInputStream* pbis = down_cast<PushbackInputStream*>(is); if (IsCollection(pbis)) { LoadCollection(pbis, output); return; } FontPtr font; font.Attach(LoadSingleOTF(pbis)); if (font) { output->push_back(font); } } void FontFactory::LoadFonts(ByteVector* b, FontArray* output) { WritableFontDataPtr wfd; wfd.Attach(WritableFontData::CreateWritableFontData(b)); if (IsCollection(wfd)) { LoadCollection(wfd, output); return; } FontPtr font; font.Attach(LoadSingleOTF(wfd)); if (font) { output->push_back(font); } } void FontFactory::LoadFontsForBuilding(InputStream* is, FontBuilderArray* output) { PushbackInputStream* pbis = down_cast<PushbackInputStream*>(is); if (IsCollection(pbis)) { LoadCollectionForBuilding(pbis, output); return; } FontBuilderPtr builder; builder.Attach(LoadSingleOTFForBuilding(pbis)); if (builder) { output->push_back(builder); } } void FontFactory::LoadFontsForBuilding(ByteVector* b, FontBuilderArray* output) { WritableFontDataPtr wfd; wfd.Attach(WritableFontData::CreateWritableFontData(b)); if (IsCollection(wfd)) { LoadCollectionForBuilding(wfd, output); return; } FontBuilderPtr builder; builder.Attach(LoadSingleOTFForBuilding(wfd, 0)); if (builder) { output->push_back(builder); } } void FontFactory::SerializeFont(Font* font, OutputStream* os) { font->Serialize(os, &table_ordering_); } void FontFactory::SetSerializationTableOrdering( const IntegerList& table_ordering) { table_ordering_ = table_ordering; } CALLER_ATTACH Font::Builder* FontFactory::NewFontBuilder() { return Font::Builder::GetOTFBuilder(this); } CALLER_ATTACH Font* FontFactory::LoadSingleOTF(InputStream* is) { FontBuilderPtr builder; builder.Attach(LoadSingleOTFForBuilding(is)); return builder->Build(); } CALLER_ATTACH Font* FontFactory::LoadSingleOTF(WritableFontData* wfd) { FontBuilderPtr builder; builder.Attach(LoadSingleOTFForBuilding(wfd, 0)); return builder->Build(); } void FontFactory::LoadCollection(InputStream* is, FontArray* output) { FontBuilderArray ba; LoadCollectionForBuilding(is, &ba); output->reserve(ba.size()); for (FontBuilderArray::iterator builder = ba.begin(), builders_end = ba.end(); builder != builders_end; ++builder) { FontPtr font; font.Attach((*builder)->Build()); output->push_back(font); } } void FontFactory::LoadCollection(WritableFontData* wfd, FontArray* output) { FontBuilderArray builders; LoadCollectionForBuilding(wfd, &builders); output->reserve(builders.size()); for (FontBuilderArray::iterator builder = builders.begin(), builders_end = builders.end(); builder != builders_end; ++builder) { FontPtr font; font.Attach((*builder)->Build()); output->push_back(font); } } CALLER_ATTACH Font::Builder* FontFactory::LoadSingleOTFForBuilding(InputStream* is) { // UNIMPLEMENTED: SHA-1 hash checking via Java DigestStream Font::Builder* builder = Font::Builder::GetOTFBuilder(this, is); // UNIMPLEMENTED: setDigest return builder; } CALLER_ATTACH Font::Builder* FontFactory::LoadSingleOTFForBuilding(WritableFontData* wfd, int32_t offset_to_offset_table) { // UNIMPLEMENTED: SHA-1 hash checking via Java DigestStream Font::Builder* builder = Font::Builder::GetOTFBuilder(this, wfd, offset_to_offset_table); // UNIMPLEMENTED: setDigest return builder; } void FontFactory::LoadCollectionForBuilding(InputStream* is, FontBuilderArray* builders) { assert(is); assert(builders); WritableFontDataPtr wfd; wfd.Attach(WritableFontData::CreateWritableFontData(is->Available())); wfd->CopyFrom(is); LoadCollectionForBuilding(wfd, builders); } void FontFactory::LoadCollectionForBuilding(WritableFontData* wfd, FontBuilderArray* builders) { int32_t ttc_tag = wfd->ReadULongAsInt(Offset::kTTCTag); UNREFERENCED_PARAMETER(ttc_tag); int32_t version = wfd->ReadFixed(Offset::kVersion); UNREFERENCED_PARAMETER(version); int32_t num_fonts = wfd->ReadULongAsInt(Offset::kNumFonts); builders->reserve(num_fonts); int32_t offset_table_offset = Offset::kOffsetTable; for (int32_t font_number = 0; font_number < num_fonts; font_number++, offset_table_offset += DataSize::kULONG) { int32_t offset = wfd->ReadULongAsInt(offset_table_offset); FontBuilderPtr builder; builder.Attach(LoadSingleOTFForBuilding(wfd, offset)); builders->push_back(builder); } } bool FontFactory::IsCollection(PushbackInputStream* pbis) { ByteVector tag(4); pbis->Read(&tag); pbis->Unread(&tag); return Tag::ttcf == GenerateTag(tag[0], tag[1], tag[2], tag[3]); } bool FontFactory::IsCollection(ReadableFontData* rfd) { ByteVector tag(4); rfd->ReadBytes(0, &(tag[0]), 0, tag.size()); return Tag::ttcf == GenerateTag(tag[0], tag[1], tag[2], tag[3]); } FontFactory::FontFactory() : fingerprint_(false) { } } // namespace sfntly
2,440
10,225
<reponame>mweber03/quarkus package io.quarkus.hibernate.orm.runtime.service; import java.util.Map; import org.hibernate.boot.registry.StandardServiceInitiator; import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.dialect.spi.DialectFactory; import org.hibernate.service.spi.ServiceRegistryImplementor; public class QuarkusStaticDialectFactoryInitiator implements StandardServiceInitiator<DialectFactory> { private final Dialect dialect; public QuarkusStaticDialectFactoryInitiator(Dialect dialect) { this.dialect = dialect; } @Override public Class<DialectFactory> getServiceInitiated() { return DialectFactory.class; } @Override public DialectFactory initiateService(Map configurationValues, ServiceRegistryImplementor registry) { return new QuarkusStaticDialectFactory(dialect); } }
303
16,461
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import <UIKit/UIKit.h> #import <ABI43_0_0React/ABI43_0_0RCTBackedTextInputViewProtocol.h> #import <better/optional.h> #import <ABI43_0_0React/ABI43_0_0renderer/components/iostextinput/primitives.h> NS_ASSUME_NONNULL_BEGIN void ABI43_0_0RCTCopyBackedTextInput( UIView<ABI43_0_0RCTBackedTextInputViewProtocol> *fromTextInput, UIView<ABI43_0_0RCTBackedTextInputViewProtocol> *toTextInput); UITextAutocorrectionType ABI43_0_0RCTUITextAutocorrectionTypeFromOptionalBool(ABI43_0_0facebook::better::optional<bool> autoCorrect); UITextAutocapitalizationType ABI43_0_0RCTUITextAutocapitalizationTypeFromAutocapitalizationType( ABI43_0_0facebook::ABI43_0_0React::AutocapitalizationType autocapitalizationType); UIKeyboardAppearance ABI43_0_0RCTUIKeyboardAppearanceFromKeyboardAppearance( ABI43_0_0facebook::ABI43_0_0React::KeyboardAppearance keyboardAppearance); UITextSpellCheckingType ABI43_0_0RCTUITextSpellCheckingTypeFromOptionalBool(ABI43_0_0facebook::better::optional<bool> spellCheck); UITextFieldViewMode ABI43_0_0RCTUITextFieldViewModeFromTextInputAccessoryVisibilityMode( ABI43_0_0facebook::ABI43_0_0React::TextInputAccessoryVisibilityMode mode); UIKeyboardType ABI43_0_0RCTUIKeyboardTypeFromKeyboardType(ABI43_0_0facebook::ABI43_0_0React::KeyboardType keyboardType); UIReturnKeyType ABI43_0_0RCTUIReturnKeyTypeFromReturnKeyType(ABI43_0_0facebook::ABI43_0_0React::ReturnKeyType returnKeyType); API_AVAILABLE(ios(10.0)) UITextContentType ABI43_0_0RCTUITextContentTypeFromString(std::string const &contentType); API_AVAILABLE(ios(12.0)) UITextInputPasswordRules *ABI43_0_0RCTUITextInputPasswordRulesFromString(std::string const &passwordRules); NS_ASSUME_NONNULL_END
729
506
// https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list void Print(Node *head) { if (head) { std::cout << head->data << std::endl;; Print(head->next); } }
76
1,615
<filename>MLN-Android/mlnservics/src/main/java/com/immomo/mls/fun/lt/LTPreferenceUtils.java /** * Created by MomoLuaNative. * Copyright (c) 2019, Momo Group. All rights reserved. * * This source code is licensed under the MIT. * For the full copyright and license information,please view the LICENSE file in the root directory of this source tree. */ package com.immomo.mls.fun.lt; import android.content.Context; import android.content.SharedPreferences; import com.immomo.mls.LuaViewManager; import com.immomo.mls.annotation.LuaBridge; import com.immomo.mls.annotation.LuaClass; import org.luaj.vm2.Globals; /** * Created by XiongFangyu on 2018/8/21. */ @LuaClass(isStatic = true) public class LTPreferenceUtils { public static final String LUA_CLASS_NAME = "PreferenceUtils"; protected static final String PREFERENCE_NAME = "MLS_PREFERENCE"; //<editor-fold desc="API"> @LuaBridge public static void save(Globals g, String key, String value) { savePreference(g, key, value); } @LuaBridge public static String get(Globals g, String key, String devaultValue) { return getPreference(g, key, devaultValue); } //</editor-fold> private static void savePreference(Globals g, String k, String v) { SharedPreferences.Editor e = getEditor(g); e.putString(k, v); e.apply(); } private static String getPreference(Globals g, String k, String dv) { return getPreferences(g).getString(k, dv); } private static SharedPreferences getPreferences(Globals g) { return ((LuaViewManager) g.getJavaUserdata()).context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE); } private static SharedPreferences.Editor getEditor(Globals g) { return getPreferences(g).edit(); } }
661
2,151
// Copyright (c) 2012 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 "storage/common/database/database_connections.h" #include <stdint.h> #include "base/auto_reset.h" #include "base/bind.h" #include "base/logging.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread_task_runner_handle.h" namespace storage { DatabaseConnections::DatabaseConnections() = default; DatabaseConnections::~DatabaseConnections() { DCHECK(connections_.empty()); } bool DatabaseConnections::IsEmpty() const { return connections_.empty(); } bool DatabaseConnections::IsDatabaseOpened( const std::string& origin_identifier, const base::string16& database_name) const { OriginConnections::const_iterator origin_it = connections_.find(origin_identifier); if (origin_it == connections_.end()) return false; const DBConnections& origin_connections = origin_it->second; return (origin_connections.find(database_name) != origin_connections.end()); } bool DatabaseConnections::IsOriginUsed( const std::string& origin_identifier) const { return (connections_.find(origin_identifier) != connections_.end()); } bool DatabaseConnections::AddConnection( const std::string& origin_identifier, const base::string16& database_name) { int& count = connections_[origin_identifier][database_name].first; return ++count == 1; } bool DatabaseConnections::RemoveConnection( const std::string& origin_identifier, const base::string16& database_name) { return RemoveConnectionsHelper(origin_identifier, database_name, 1); } void DatabaseConnections::RemoveAllConnections() { connections_.clear(); } std::vector<std::pair<std::string, base::string16>> DatabaseConnections::RemoveConnections(const DatabaseConnections& connections) { std::vector<std::pair<std::string, base::string16>> closed_dbs; for (const auto& origin_connections_pair : connections.connections_) { const DBConnections& db_connections = origin_connections_pair.second; for (const auto& count_size_pair : db_connections) { if (RemoveConnectionsHelper(origin_connections_pair.first, count_size_pair.first, count_size_pair.second.first)) { closed_dbs.emplace_back(origin_connections_pair.first, count_size_pair.first); } } } return closed_dbs; } int64_t DatabaseConnections::GetOpenDatabaseSize( const std::string& origin_identifier, const base::string16& database_name) const { DCHECK(IsDatabaseOpened(origin_identifier, database_name)); return connections_[origin_identifier][database_name].second; } void DatabaseConnections::SetOpenDatabaseSize( const std::string& origin_identifier, const base::string16& database_name, int64_t size) { DCHECK(IsDatabaseOpened(origin_identifier, database_name)); connections_[origin_identifier][database_name].second = size; } std::vector<std::pair<std::string, base::string16>> DatabaseConnections::ListConnections() const { std::vector<std::pair<std::string, base::string16>> list; for (const auto& origin_connections_pair : connections_) { const DBConnections& db_connections = origin_connections_pair.second; for (const auto& count_size_pair : db_connections) list.emplace_back(origin_connections_pair.first, count_size_pair.first); } return list; } bool DatabaseConnections::RemoveConnectionsHelper( const std::string& origin_identifier, const base::string16& database_name, int num_connections) { OriginConnections::iterator origin_iterator = connections_.find(origin_identifier); DCHECK(origin_iterator != connections_.end()); DBConnections& db_connections = origin_iterator->second; int& count = db_connections[database_name].first; DCHECK(count >= num_connections); count -= num_connections; if (count) return false; db_connections.erase(database_name); if (db_connections.empty()) connections_.erase(origin_iterator); return true; } DatabaseConnectionsWrapper::DatabaseConnectionsWrapper() = default; DatabaseConnectionsWrapper::~DatabaseConnectionsWrapper() = default; bool DatabaseConnectionsWrapper::HasOpenConnections() { base::AutoLock auto_lock(open_connections_lock_); return !open_connections_.IsEmpty(); } void DatabaseConnectionsWrapper::AddOpenConnection( const std::string& origin_identifier, const base::string16& database_name) { base::AutoLock auto_lock(open_connections_lock_); open_connections_.AddConnection(origin_identifier, database_name); } void DatabaseConnectionsWrapper::RemoveOpenConnection( const std::string& origin_identifier, const base::string16& database_name) { base::AutoLock auto_lock(open_connections_lock_); open_connections_.RemoveConnection(origin_identifier, database_name); if (waiting_to_close_event_ && open_connections_.IsEmpty()) waiting_to_close_event_->Signal(); } bool DatabaseConnectionsWrapper::WaitForAllDatabasesToClose( base::TimeDelta timeout) { base::WaitableEvent waitable_event( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); { base::AutoLock auto_lock(open_connections_lock_); if (open_connections_.IsEmpty()) return true; waiting_to_close_event_ = &waitable_event; } waitable_event.TimedWait(timeout); { base::AutoLock auto_lock(open_connections_lock_); waiting_to_close_event_ = nullptr; return open_connections_.IsEmpty(); } } } // namespace storage
1,905
460
<gh_stars>100-1000 /* * Copyright 2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.swarm.flyway.runtime; import java.util.List; import javax.enterprise.inject.Instance; import javax.inject.Inject; import org.jboss.shrinkwrap.api.Archive; import org.wildfly.swarm.config.datasources.DataSource; import org.wildfly.swarm.datasources.DatasourcesFraction; import org.wildfly.swarm.flyway.FlywayFraction; import org.wildfly.swarm.flyway.deployment.FlywayMigrationServletContextListener; import org.wildfly.swarm.spi.api.DeploymentProcessor; import org.wildfly.swarm.spi.runtime.annotations.DeploymentScoped; import org.wildfly.swarm.undertow.WARArchive; import org.wildfly.swarm.undertow.descriptors.WebXmlAsset; /** * @author <a href="mailto:<EMAIL>"><NAME></a> */ @DeploymentScoped public class FlywayMigrationArchivePreparer implements DeploymentProcessor { private final Archive<?> archive; @Inject private Instance<DatasourcesFraction> dsFractionInstance; @Inject private Instance<FlywayFraction> flywayFractionInstance; @Inject public FlywayMigrationArchivePreparer(Archive archive) { this.archive = archive; } @Override public void process() { if (archive.getName().endsWith(".war")) { WARArchive webArchive = archive.as(WARArchive.class); WebXmlAsset webXml = webArchive.findWebXmlAsset(); webXml.addListener("org.wildfly.swarm.flyway.deployment.FlywayMigrationServletContextListener"); FlywayFraction flywayFraction = flywayFractionInstance.get(); if (flywayFraction.usePrimaryDataSource()) { String dataSourceJndi = getDatasourceNameJndi(); webXml.setContextParam(FlywayMigrationServletContextListener.FLYWAY_JNDI_DATASOURCE, dataSourceJndi); } else { webXml.setContextParam(FlywayMigrationServletContextListener.FLYWAY_JDBC_URL, flywayFraction.jdbcUrl()); webXml.setContextParam(FlywayMigrationServletContextListener.FLYWAY_JDBC_USER, flywayFraction.jdbcUser()); webXml.setContextParam(FlywayMigrationServletContextListener.FLYWAY_JDBC_PASSWORD, flywayFraction.jdbcPassword()); } } } private String getDatasourceNameJndi() { String jndiName = "java:jboss/datasources/ExampleDS"; if (!dsFractionInstance.isUnsatisfied()) { List<DataSource> dataSources = dsFractionInstance.get().subresources().dataSources(); if (dataSources.size() > 0) { jndiName = dataSources.get(0).jndiName(); } } return jndiName; } }
1,237
352
from .aquatone import AquatoneScan from .gobuster import GobusterScan from .targets import GatherWebTargets from .webanalyze import WebanalyzeScan from .waybackurls import WaybackurlsScan from .subdomain_takeover import SubjackScan, TKOSubsScan
77
362
/* * Copyright (c) 2005-2012 by KoanLogic s.r.l. - All rights reserved. */ #include <stdint.h> #include <u/libu.h> #include <toolbox/array.h> /* for C89 implementations */ #ifndef SIZE_MAX #define SIZE_MAX ((size_t) -1) #endif struct u_array_s { size_t nslots; u_array_type_t type; void *base; }; #define U_ARRAY_TYPE_IS_VALID(t) \ (t > U_ARRAY_TYPE_UNSET && t <= U_ARRAY_TYPE_MAX) static size_t sizeof_type[U_ARRAY_TYPE_MAX + 1] = { 0, /* U_ARRAY_TYPE_UNSET = 0 */ #ifdef HAVE__BOOL sizeof(_Bool), /* U_ARRAY_TYPE_BOOL */ #endif /* HAVE__BOOL */ sizeof(char), /* U_ARRAY_TYPE_CHAR */ sizeof(unsigned char), /* U_ARRAY_TYPE_U_CHAR */ sizeof(short), /* U_ARRAY_TYPE_SHORT */ sizeof(unsigned short), /* U_ARRAY_TYPE_U_SHORT */ sizeof(int), /* U_ARRAY_TYPE_INT */ sizeof(unsigned int), /* U_ARRAY_TYPE_U_INT */ sizeof(long), /* U_ARRAY_TYPE_LONG */ sizeof(unsigned long), /* U_ARRAY_TYPE_U_LONG */ #ifdef HAVE_LONG_LONG sizeof(long long), /* U_ARRAY_TYPE_LONG_LONG */ sizeof(unsigned long long), /* U_ARRAY_TYPE_U_LONG_LONG */ #endif /* HAVE_LONG_LONG */ #ifdef HAVE_INTMAX_T sizeof(intmax_t), /* U_ARRAY_TYPE_INTMAX */ sizeof(uintmax_t), /* U_ARRAY_TYPE_U_INTMAX */ #endif /* HAVE_INTMAX_T */ sizeof(float), /* U_ARRAY_TYPE_FLOAT */ sizeof(double), /* U_ARRAY_TYPE_DOUBLE */ #ifdef HAVE_LONG_DOUBLE sizeof(long double), /* U_ARRAY_TYPE_LONG_DOUBLE */ #endif /* HAVE_LONG_DOUBLE */ #ifdef HAVE_FLOAT__COMPLEX sizeof(float _Complex), /* U_ARRAY_TYPE_FLOAT_COMPLEX */ #endif /* HAVE_FLOAT__COMPLEX */ #ifdef HAVE_DOUBLE__COMPLEX sizeof(double _Complex), /* U_ARRAY_TYPE_DOUBLE_COMPLEX */ #endif /* HAVE_DOUBLE__COMPLEX */ #ifdef HAVE_LONG_DOUBLE__COMPLEX sizeof(long double _Complex), /* U_ARRAY_TYPE_LONG_DOUBLE_COMPLEX */ #endif /* HAVE_LONG_DOUBLE__COMPLEX */ sizeof(void *) /* U_ARRAY_TYPE_PTR */ }; #define MAX_NSLOTS(da) (SIZE_MAX / sizeof_type[da->type]) /** \defgroup array Dynamic Arrays \{ A dynamic array has a type, which is the type of its elements. The type of the dynamic array is declared when a new array instance is created via ::u_array_create and must be one of the types in ::u_array_type_t. Available types are the standard C types supported by the target platform, plus a generic pointer type for user defined types. A couple of getter/setter methods is provided for each ::u_array_type_t entry, e.g. see ::u_array_get_char and ::u_array_set_char. The following is some toy code showing basic operations (create, set, get, destroy) using double precision complex numbers (C99): \code u_array_t *a = NULL; size_t idx; long double _Complex c0, c1; // create an array to store double precision complex numbers // array resize is handled transparently con_err_if (u_array_create(U_ARRAY_TYPE_LONG_DOUBLE_COMPLEX, 0, &a)); // insert values from 0+0i to 10+10i at increasing indexes, // also check that what has been inserted matches what we get back for (idx = 0; idx < 10; idx++) { c0 = idx + idx * _Complex_I; con_err_if (u_array_set_long_double_complex(a, idx, c0, NULL)); con_err_if (u_array_get_long_double_complex(a, idx, &c1)); con_err_if (creal(c0) != creal(c1) || cimag(c0) != cimag(c1)); } // now overwrite previously set values with new ones for (idx = 0; idx < 10; idx++) { long double _Complex c2; c0 = (idx + 10) + (idx + 10) * _Complex_I; con_err_if (u_array_set_long_double_complex(a, idx, c0, &c2)); u_con("overwrite %lf + %lfi at %zu with %lf + %lfi", creal(c2), cimag(c2), idx, creal(c0), cimag(c0)); con_err_if (u_array_get_long_double_complex(a, idx, &c1)); con_err_if (creal(c0) != creal(c1) || cimag(c0) != cimag(c1)); } // ok, enough stress, dispose it :) u_array_free(a); \endcode \note The getter/setter interfaces for generic pointers are different from all the other, see ::u_array_get_ptr and ::u_array_set_ptr for details. */ /** * \brief Create a new array object * * \param t the type of the elements in this array, i.e. one of * the standard C types (which have 1:1 mapping with * \c U_ARRAY_TYPE_*'s) or a pointer type (select * \c U_ARRAY_TYPE_PTR in this case) * \param nslots the initial number of slots to be created (set it to \c 0 * if you want the default) * \param pda the newly created array object as a result argument * * \retval 0 on success * \retval -1 on error */ int u_array_create (u_array_type_t t, size_t nslots, u_array_t **pda) { u_array_t *da = NULL; size_t max_nslots; dbg_return_if (pda == NULL, -1); dbg_return_if (!U_ARRAY_TYPE_IS_VALID(t), -1); da = u_zalloc(sizeof(u_array_t)); warn_err_sif (da == NULL); da->type = t; if (nslots == 0) da->nslots = U_ARRAY_NSLOTS_DFL; else if (nslots > (max_nslots = MAX_NSLOTS(da))) da->nslots = max_nslots; else da->nslots = nslots; da->base = u_zalloc(da->nslots * sizeof_type[da->type]); warn_err_sif (da->base == NULL); *pda = da; return 0; err: u_array_free(da); return -1; } /** * \brief Free the array object: the array does not own the pointers in it, * the client must free them explicitly * * \param da the array object that has to be disposed * * \return nothing */ void u_array_free (u_array_t *da) { nop_return_if (da == NULL, ); U_FREE(da->base); u_free(da); return; } /** * \brief Grow the array so that the supplied index can be accomodated * * \param da the array object * \param idx the index that needs to be accomodated/reached * * \retval 0 on success * \retval -1 on error */ int u_array_resize (u_array_t *da, size_t idx) { void *new_base; size_t new_nslots, max_nslots; dbg_return_if (da == NULL, -1); /* no need to resize, go out */ dbg_return_if (idx < da->nslots, 0); /* can't go further, go out */ dbg_return_if (idx >= (max_nslots = MAX_NSLOTS(da)) - 1, -1); /* decide how many new slots are needed */ new_nslots = ((max_nslots - U_ARRAY_RESIZE_PAD - 1) >= idx) ? idx + U_ARRAY_RESIZE_PAD + 1 : max_nslots; /* try to realloc the array base pointer with the new size */ new_base = u_realloc(da->base, new_nslots * sizeof_type[da->type]); warn_err_sif (new_base == NULL); da->base = new_base; da->nslots = new_nslots; return 0; err: return -1; } /** * \} */ #define U_ARRAY_GETSET_F(pfx, dtype, ctype) \ int u_array_set##pfx (u_array_t *da, size_t idx, ctype v, ctype *pold) \ { \ ctype *ep; \ \ dbg_return_if (da == NULL, -1); \ \ /* be strict over what we're assigning */ \ dbg_return_if (da->type != dtype, -1); \ \ /* silently handle resize in case an element is set past the \ * actual index range */ \ if (idx > da->nslots - 1) \ warn_err_if (u_array_resize(da, idx)); \ \ /* get the selected slot */ \ ep = (ctype *) da->base + idx; \ \ /* if requested copy-out the old value before overriding it */ \ if (pold) \ *pold = *ep; \ \ /* assign */ \ *ep = v; \ \ return 0; \ err: \ return -1; \ } \ \ int u_array_get##pfx (u_array_t *da, size_t idx, ctype *pv) \ { \ ctype *ep; \ \ dbg_return_if (da == NULL, -1); \ dbg_return_if (pv == NULL, -1); \ /* be strict over what we're returning */ \ dbg_return_if (da->type != dtype, -1); \ \ /* check overflow */ \ warn_err_if (idx > da->nslots - 1); \ \ ep = (ctype *) da->base + idx; \ \ *pv = *ep; \ \ return 0; \ err: \ return -1; \ } U_ARRAY_GETSET_F(_char, U_ARRAY_TYPE_CHAR, char) U_ARRAY_GETSET_F(_u_char, U_ARRAY_TYPE_U_CHAR, unsigned char) U_ARRAY_GETSET_F(_short, U_ARRAY_TYPE_SHORT, short) U_ARRAY_GETSET_F(_u_short, U_ARRAY_TYPE_U_SHORT, unsigned short) U_ARRAY_GETSET_F(_int, U_ARRAY_TYPE_INT, int) U_ARRAY_GETSET_F(_u_int, U_ARRAY_TYPE_U_INT, unsigned int) U_ARRAY_GETSET_F(_long, U_ARRAY_TYPE_LONG, long) U_ARRAY_GETSET_F(_u_long, U_ARRAY_TYPE_U_LONG, unsigned long) U_ARRAY_GETSET_F(_float, U_ARRAY_TYPE_FLOAT, float) U_ARRAY_GETSET_F(_double, U_ARRAY_TYPE_DOUBLE, double) #ifdef HAVE__BOOL U_ARRAY_GETSET_F(_bool, U_ARRAY_TYPE_BOOL, _Bool) #endif /* HAVE__BOOL */ #ifdef HAVE_LONG_LONG U_ARRAY_GETSET_F(_long_long, U_ARRAY_TYPE_LONG_LONG, long long) U_ARRAY_GETSET_F(_u_long_long, U_ARRAY_TYPE_U_LONG_LONG, unsigned long long) #endif /* HAVE_LONG_LONG */ #ifdef HAVE_INTMAX_T U_ARRAY_GETSET_F(_intmax, U_ARRAY_TYPE_INTMAX, intmax_t) U_ARRAY_GETSET_F(_u_intmax, U_ARRAY_TYPE_U_INTMAX, uintmax_t) #endif /* HAVE_INTMAX_T */ #ifdef HAVE_LONG_DOUBLE U_ARRAY_GETSET_F(_long_double, U_ARRAY_TYPE_LONG_DOUBLE, long double) #endif /* HAVE_LONG_DOUBLE */ #ifdef HAVE_FLOAT__COMPLEX U_ARRAY_GETSET_F(_float_complex, U_ARRAY_TYPE_FLOAT_COMPLEX, float _Complex) #endif /* HAVE_FLOAT__COMPLEX */ #ifdef HAVE_DOUBLE__COMPLEX U_ARRAY_GETSET_F(_double_complex, U_ARRAY_TYPE_DOUBLE_COMPLEX, double _Complex) #endif /* HAVE_DOUBLE__COMPLEX */ #ifdef HAVE_LONG_DOUBLE__COMPLEX U_ARRAY_GETSET_F(_long_double_complex, U_ARRAY_TYPE_LONG_DOUBLE_COMPLEX, long double _Complex) #endif /* HAVE_LONG_DOUBLE__COMPLEX */ /** * \brief Dynamic array setter interface for generic pointer values. * * Try to put some generic pointer \p v at position \p idx into the dyamic * array \p da. If supplied (i.e. non-NULL) the result argument \p *prc will * hold the return code of the whole set operation. * We could not preserve the same interface as all the other standard types * because the \c void** out parameter would be easily abused through an * incorrect cast. The following sample should illustrate how to correctly * use the interface: * * \code * int rc = 0; * size_t i = 231; // some random index * my_t *old_v, *v = NULL; // the value that we are going to store * * // make room for your new object and fill it some way * dbg_err_sif ((v = u_zalloc(sizeof(my_t))) == NULL); * v->somefield = somevalue; * * // set the new value in the array at some conveninent index, * // and dispose the old one in case it was set * old_v = u_array_set_ptr(da, i, v, &rc); * dbg_err_if (rc == -1); * if (old_v) * my_free(old_v); * ... * \endcode * * \param da An already instantiated dynamic array * \param idx The index at which the element \p v shall be stored * \param v The value that must be stored * \param prc If non-NULL this result argument will store the return * code of the whole operation, i.e. \c 0 if successfull, * \c -1 if something went wrong * * \return the old value stored at index \p idx (can be \c NULL) */ void *u_array_set_ptr (u_array_t *da, size_t idx, void *v, int *prc) { void **ep, *old_ep; dbg_err_if (da == NULL); dbg_err_if (da->type != U_ARRAY_TYPE_PTR); if (idx > da->nslots - 1) dbg_err_if (u_array_resize (da, idx)); ep = (void **) da->base + idx; /* save old value (could be NULL) */ old_ep = *ep; /* overwrite with the supplied value */ *ep = v; if (prc) *prc = 0; return old_ep; err: if (prc) *prc = -1; return NULL; } /** * \brief Dynamic array getter interface for generic pointer values. * * Try to retrieve the pointer at position \p idx from the dyamic array \p da. * If supplied (i.e. non-NULL) the result argument \p *prc will hold the * return code of the whole get operation. * We could not preserve the same interface as all the other standard types * because the \c void** out parameter would be easily abused through an * incorrect cast. The following sample should illustrate how to correctly * use the interface: * * \code * int rc = 0; * size_t i = 231; // some random index * my_t *v = NULL; // the value that we are going to retrieve * * // get the new value from the array at some conveninent index, * v = u_array_get_ptr(da, i, &rc); * dbg_err_if (rc == -1); * * // do something with 'v' * ... * \endcode * * \param da An already instantiated dynamic array * \param idx The index at which the element \p v shall be stored * \param prc If non-NULL this result argument will store the return * code of the whole operation, i.e. \c 0 if successfull, * \c -1 if something went wrong * * \return the value stored at index \p idx (note that it can be \c NULL and * therefore it can't be used to distinguish a failed operation. */ void *u_array_get_ptr (u_array_t *da, size_t idx, int *prc) { dbg_err_if (da == NULL); dbg_err_if (da->type != U_ARRAY_TYPE_PTR); warn_err_if (idx > da->nslots - 1); if (prc) *prc = 0; return *((void **) da->base + idx); err: if (prc) *prc = -1; return NULL; }
8,972
1,755
#ifndef PyMPI_COMPAT_MPICH2_H #define PyMPI_COMPAT_MPICH2_H static int PyMPI_MPICH2_MPI_Add_error_class(int *errorclass) { int ierr; char errstr[1] = {0}; ierr = MPI_Add_error_class(errorclass); if (ierr) return ierr; return MPI_Add_error_string(*errorclass,errstr); } #undef MPI_Add_error_class #define MPI_Add_error_class PyMPI_MPICH2_MPI_Add_error_class static int PyMPI_MPICH2_MPI_Add_error_code(int errorclass, int *errorcode) { int ierr; char errstr[1] = {0}; ierr = MPI_Add_error_code(errorclass,errorcode); if (ierr) return ierr; return MPI_Add_error_string(*errorcode,errstr); } #undef MPI_Add_error_code #define MPI_Add_error_code PyMPI_MPICH2_MPI_Add_error_code #if defined(__SICORTEX__) #include "sicortex.h" #endif #endif /* !PyMPI_COMPAT_MPICH2_H */
395
1,738
<reponame>brianherrera/lumberyard /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #ifndef CRYINCLUDE_EDITOR_TIMEOFDAYSLIDER_H #define CRYINCLUDE_EDITOR_TIMEOFDAYSLIDER_H #pragma once #include <AzQtComponents/Components/Widgets/Slider.h> class TimeOfDaySlider : public AzQtComponents::SliderInt { Q_OBJECT public: using AzQtComponents::SliderInt::SliderInt; protected: QString hoverValueText(int sliderValue) const override; }; #endif // CRYINCLUDE_EDITOR_TIMEOFDAYSLIDER_H
344
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport */ #import <OfficeImport/OfficeImport-Structs.h> #import <OfficeImport/ODICycle.h> #import <OfficeImport/XXUnknownSuperclass.h> __attribute__((visibility("hidden"))) @interface ODICycle : XXUnknownSuperclass { } + (BOOL)mapIdentifier:(id)identifier state:(id)state; // 0x2b1add @end @interface ODICycle (Private) + (void)mapWithState:(id)state; // 0x2b3225 + (unsigned)nodeCountWithState:(id)state; // 0x2b31d9 + (CGSize)nodeSizeWithState:(id)state; // 0x2b1a91 + (CGRect)boundingBoxWithIsTight:(BOOL)isTight state:(id)state; // 0x2b338d + (CGRect)nodeBoundsWithIndex:(unsigned)index state:(id)state; // 0x2b3449 + (CGRect)mapGSpaceWithState:(id)state; // 0x2b1aa9 + (void)mapNode:(id)node index:(unsigned)index state:(id)state; // 0x2b1ac5 + (void)mapTransition:(id)transition index:(unsigned)index state:(id)state; // 0x2b1ac9 + (BOOL)map1NodeWithState:(id)state; // 0x2b1acd + (BOOL)map2NodeWithState:(id)state; // 0x2b1ad1 @end
428
809
<filename>lenskit-integration-tests/src/test/groovy/org/lenskit/predict/ordrec/OrdRecAccuracyTest.java /* * LensKit, an open-source toolkit for recommender systems. * Copyright 2014-2017 LensKit contributors (see CONTRIBUTORS.md) * Copyright 2010-2014 Regents of the University of Minnesota * * 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 org.lenskit.predict.ordrec; import org.lenskit.LenskitConfiguration; import org.grouplens.lenskit.iterative.IterationCount; import org.grouplens.lenskit.test.CrossfoldTestSuite; import org.lenskit.util.table.Table; import org.junit.Ignore; import org.lenskit.api.ItemScorer; import org.lenskit.api.RatingPredictor; import org.lenskit.baseline.*; import org.lenskit.mf.funksvd.FeatureCount; import org.lenskit.mf.funksvd.FunkSVDItemScorer; import org.lenskit.transform.quantize.PreferenceDomainQuantizer; import org.lenskit.transform.quantize.Quantizer; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; /** * Do major tests on the OrdRec recommender. */ @Ignore("not ready to really test accuracy") public class OrdRecAccuracyTest extends CrossfoldTestSuite { @SuppressWarnings("unchecked") @Override protected void configureAlgorithm(LenskitConfiguration config) { config.bind(ItemScorer.class) .to(FunkSVDItemScorer.class); config.bind(BaselineScorer.class, ItemScorer.class) .to(UserMeanItemScorer.class); config.bind(UserMeanBaseline.class, ItemScorer.class) .to(ItemMeanRatingItemScorer.class); config.within(BaselineScorer.class, ItemScorer.class) .set(MeanDamping.class) .to(10); config.set(FeatureCount.class).to(25); config.set(IterationCount.class).to(125); config.bind(RatingPredictor.class) .to(OrdRecRatingPredictor.class); config.bind(Quantizer.class) .to(PreferenceDomainQuantizer.class); } @Override protected void checkResults(Table table) { assertThat(table.column("MAE.ByRating").average(), closeTo(0.74, 0.025)); assertThat(table.column("RMSE.ByUser").average(), closeTo(0.92 , 0.05)); } }
1,163
453
/* Copyright (c) 2016 Phoenix Systems All rights reserved. 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. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.*/ #ifndef _SYS_SOCKET_H #define _SYS_SOCKET_H #include <phoenix/netinet.h> #include <phoenix/netinet6.h> #include <phoenix/socket.h> #include <phoenix/sockios.h> #include <sys/types.h> #define _SS_MAXSIZE 128U #define _SS_ALIGNSIZE (sizeof(int64_t)) #define _SS_PAD1SIZE (_SS_ALIGNSIZE - sizeof(unsigned char) - sizeof(sa_family_t)) #define _SS_PAD2SIZE (_SS_MAXSIZE - sizeof(unsigned char) - sizeof(sa_family_t) - _SS_PAD1SIZE - _SS_ALIGNSIZE) struct sockaddr_storage { unsigned char ss_len; /* Aaddress length */ sa_family_t ss_family; /* Address family */ char __ss_pad1[_SS_PAD1SIZE]; int64_t __ss_align; /* Force desired structure storage alignment */ char __ss_pad2[_SS_PAD2SIZE]; }; #define HAVE_STRUCT_SOCKADDR_STORAGE #define HAVE_STRUCT_IN6_ADDR #define HAVE_STRUCT_SOCKADDR_IN6 int socket(int domain, int type, int protocol); int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen); int listen(int sockfd, int backlog); int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); int sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen); int send(int sockfd, const void *buf, size_t len, int flags); int recvfrom(int sockfd, void *buf, size_t len, int flags, struct sockaddr *src_addr, socklen_t *addrlen); int recv(int sockfd, void *buf, size_t len, int flags); int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen); int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen); int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t optlen); int shutdown(int, int); int socketpair(int, int, int, int *); int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen); #endif
1,088
965
<gh_stars>100-1000 #if _DEBUG CStringList li; li.AddHead(_T("item 0")); li.AddHead(_T("item 1")); CString s = _T("test"); int i = 7; long lo = 1000000000L; LONGLONG lolo = 12345678901234i64; afxDump << _T("list=") << &li << _T("string=") << s << _T("int=") << i << _T("long=") << lo << _T("LONGLONG=") << lolo << _T("\n"); #endif
165
516
<reponame>zzwlstarby/parity<filename>libraries/util/src/main/java/com/paritytrading/parity/util/TableHeader.java /* * Copyright 2014 Parity 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 com.paritytrading.parity.util; import static com.paritytrading.parity.util.Strings.*; import java.util.ArrayList; import java.util.List; /** * A table header. */ public class TableHeader { private final List<Column> columns; /** * Construct a new instance. */ public TableHeader() { columns = new ArrayList<>(); } /** * Add a column. * * @param name the column name * @param width the column width */ public void add(String name, int width) { columns.add(new Column(name, width)); } /** * Format this table header for display. * * @return this table header formatted for display */ public String format() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < columns.size(); i++) { Column column = columns.get(i); builder.append(format(column.name, column.width)); builder.append(i == columns.size() - 1 ? '\n' : ' '); } for (int i = 0; i < columns.size(); i++) { Column column = columns.get(i); builder.append(repeat('-', column.width)); builder.append(i == columns.size() - 1 ? '\n' : ' '); } return builder.toString(); } private static class Column { public String name; public int width; public Column(String name, int width) { this.name = name; this.width = width; } } private static String format(String name, int width) { return String.format("%-" + width + "." + width + "s", name); } }
888
14,668
<filename>services/device/serial/serial_device_enumerator_linux_unittest.cc<gh_stars>1000+ // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/device/serial/serial_device_enumerator_linux.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/test/task_environment.h" #include "device/udev_linux/fake_udev_loader.h" #include "testing/gtest/include/gtest/gtest.h" namespace device { constexpr char kSerialDriverInfo[] = R"(/dev/tty /dev/tty 5 0 system:/dev/tty /dev/console /dev/console 5 1 system:console /dev/ptmx /dev/ptmx 5 2 system /dev/vc/0 /dev/vc/0 4 0 system:vtmaster rfcomm /dev/rfcomm 216 0-255 serial acm /dev/ttyACM 166 0-255 serial ttyAMA /dev/ttyAMA 204 64-77 serial ttyprintk /dev/ttyprintk 5 3 console max310x /dev/ttyMAX 204 209-224 serial serial /dev/ttyS 4 64 serial pty_slave /dev/pts 136 0-1048575 pty:slave pty_master /dev/ptm 128 0-1048575 pty:master pty_slave /dev/ttyp 3 0-255 pty:slave pty_master /dev/pty 2 0-255 pty:master unknown /dev/tty 4 1-63 console)"; class SerialDeviceEnumeratorLinuxTest : public testing::Test { public: void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); drivers_file_ = temp_dir_.GetPath().Append("drivers"); ASSERT_TRUE(base::WriteFile(drivers_file_, kSerialDriverInfo)); } std::unique_ptr<SerialDeviceEnumeratorLinux> CreateEnumerator() { return std::make_unique<SerialDeviceEnumeratorLinux>(drivers_file_); } private: base::test::TaskEnvironment task_environment_{ base::test::TaskEnvironment::MainThreadType::IO}; base::ScopedTempDir temp_dir_; base::FilePath drivers_file_; }; TEST_F(SerialDeviceEnumeratorLinuxTest, EnumerateUsb) { testing::FakeUdevLoader fake_udev; fake_udev.AddFakeDevice(/*name=*/"ttyACM0", /*syspath=*/"/sys/class/tty/ttyACM0", /*subsystem=*/"tty", /*devnode=*/absl::nullopt, /*devtype=*/absl::nullopt, /*sysattrs=*/{}, /*properties=*/ { {"DEVNAME", "/dev/ttyACM0"}, {"MAJOR", "166"}, {"MINOR", "0"}, {"ID_VENDOR_ID", "2341"}, {"ID_MODEL_ID", "0043"}, {"ID_MODEL_ENC", "Arduino\\x20Uno"}, {"ID_SERIAL_SHORT", "000001"}, }); std::unique_ptr<SerialDeviceEnumeratorLinux> enumerator = CreateEnumerator(); std::vector<mojom::SerialPortInfoPtr> devices = enumerator->GetDevices(); ASSERT_EQ(devices.size(), 1u); EXPECT_EQ(devices[0]->serial_number, "000001"); EXPECT_EQ(devices[0]->path, base::FilePath("/dev/ttyACM0")); EXPECT_TRUE(devices[0]->has_vendor_id); EXPECT_EQ(devices[0]->vendor_id, 0x2341); EXPECT_TRUE(devices[0]->has_product_id); EXPECT_EQ(devices[0]->product_id, 0x0043); EXPECT_EQ(devices[0]->display_name, "Arduino Uno"); } TEST_F(SerialDeviceEnumeratorLinuxTest, EnumerateRfcomm) { testing::FakeUdevLoader fake_udev; fake_udev.AddFakeDevice(/*name=*/"rfcomm0", /*syspath=*/"/sys/class/tty/rfcomm0", /*subsystem=*/"tty", /*devnode=*/absl::nullopt, /*devtype=*/absl::nullopt, /*sysattrs=*/{}, /*properties=*/ { {"DEVNAME", "/dev/rfcomm0"}, {"MAJOR", "216"}, {"MINOR", "0"}, }); std::unique_ptr<SerialDeviceEnumeratorLinux> enumerator = CreateEnumerator(); std::vector<mojom::SerialPortInfoPtr> devices = enumerator->GetDevices(); ASSERT_EQ(devices.size(), 1u); EXPECT_FALSE(devices[0]->serial_number.has_value()); EXPECT_EQ(devices[0]->path, base::FilePath("/dev/rfcomm0")); EXPECT_FALSE(devices[0]->has_vendor_id); EXPECT_FALSE(devices[0]->has_product_id); EXPECT_FALSE(devices[0]->display_name.has_value()); } } // namespace device
2,282
646
<reponame>Amine-El-Ghaoual/griddb<gh_stars>100-1000 /* Copyright (c) 2017 TOSHIBA Digital Solutions Corporation 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.toshiba.mwcloud.gs.common; import java.util.Set; import com.toshiba.mwcloud.gs.experimental.ContainerAttribute; import com.toshiba.mwcloud.gs.experimental.ContainerCondition; public class ContainerKeyPredicate { public static final int ATTRIBUTE_BASE = ContainerAttribute.BASE.flag(); public static final int ATTRIBUTE_SINGLE = ContainerAttribute.SINGLE.flag(); private static final int[] EMPTY_ATTRIBUTES = new int[0]; private int[] attributes; public ContainerKeyPredicate() { this((int[]) null); } public ContainerKeyPredicate(int[] attributes) { setAttributes(attributes); } public ContainerKeyPredicate(Set<ContainerAttribute> attributes) { this(toAttributes(attributes)); } public ContainerKeyPredicate(ContainerCondition cond) { this(toAttributes(cond.getAttributes())); } public static int[] toAttributes(Set<ContainerAttribute> src) { if (src == null) { return EMPTY_ATTRIBUTES; } else { final int[] dest = new int[src.size()]; int i = 0; for (ContainerAttribute attr : src) { dest[i] = attr.flag(); i++; } return dest; } } public int[] getAttributes() { return attributes; } public void setAttributes(int[] attributes) { if (attributes == null) { this.attributes = EMPTY_ATTRIBUTES; } else { this.attributes = attributes; } } public static ContainerKeyPredicate ofDefaultAttributes(boolean unified) { final ContainerKeyPredicate pred = new ContainerKeyPredicate(); pred.setAttributes(new int[] { (unified ? ATTRIBUTE_SINGLE : ATTRIBUTE_BASE) }); return pred; } }
751
457
package io.purplejs.http.internal.handler; import java.util.Collection; import java.util.Map; import com.google.common.net.HttpHeaders; import io.purplejs.core.json.JsonGenerator; import io.purplejs.core.json.JsonSerializable; import io.purplejs.http.Headers; import io.purplejs.http.Parameters; import io.purplejs.http.Request; final class JsonRequest implements JsonSerializable { private final Request request; JsonRequest( final Request request ) { this.request = request; } @Override public void serialize( final JsonGenerator gen ) { gen.map(); gen.value( "method", this.request.getMethod() ); gen.value( "scheme", this.request.getUri().getScheme() ); gen.value( "host", this.request.getUri().getHost() ); gen.value( "port", this.request.getUri().getPort() ); gen.value( "path", this.request.getUri().getPath() ); gen.value( "uri", this.request.getUri() ); gen.value( "contentType", this.request.getContentType() ); gen.value( "contentLength", this.request.getContentLength() ); gen.value( "webSocket", this.request.isWebSocket() ); gen.value( "wrapped", this.request ); //gen.value( "remoteAddress", this.request.getRemoteAddress() ); serializeParameters( gen, this.request.getParameters() ); serializeHeaders( gen, this.request.getHeaders() ); serializeCookies( gen, this.request.getCookies() ); gen.end(); } private void serializeParameters( final JsonGenerator gen, final Parameters params ) { gen.map( "params" ); for ( final Map.Entry<String, Collection<String>> entry : params.asMap().entrySet() ) { final Collection<String> values = entry.getValue(); if ( values.size() == 1 ) { gen.value( entry.getKey(), values.iterator().next() ); } else { gen.array( entry.getKey() ); values.forEach( gen::value ); gen.end(); } } gen.end(); } private boolean shouldSerializeHeader( final String name ) { return !name.equalsIgnoreCase( HttpHeaders.COOKIE ); } private void serializeHeaders( final JsonGenerator gen, final Headers headers ) { gen.map( "headers" ); headers.entrySet().stream().filter( entry -> shouldSerializeHeader( entry.getKey() ) ).forEach( entry -> gen.value( entry.getKey(), entry.getValue() ) ); gen.end(); } private void serializeCookies( final JsonGenerator gen, final Map<String, String> cookies ) { gen.map( "cookies" ); cookies.forEach( gen::value ); gen.end(); } }
1,169
468
#include "unsuck.hpp" #ifdef _WIN32 #include "TCHAR.h" #include "pdh.h" #include "windows.h" #include "psapi.h" // see https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process MemoryData getMemoryData() { MemoryData data; { MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&memInfo); DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile; DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile;; DWORDLONG totalPhysMem = memInfo.ullTotalPhys; DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys; data.virtual_total = totalVirtualMem; data.virtual_used = virtualMemUsed; data.physical_total = totalPhysMem; data.physical_used = physMemUsed; } { PROCESS_MEMORY_COUNTERS_EX pmc; GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); SIZE_T virtualMemUsedByMe = pmc.PrivateUsage; SIZE_T physMemUsedByMe = pmc.WorkingSetSize; static size_t virtualUsedMax = 0; static size_t physicalUsedMax = 0; virtualUsedMax = max(virtualMemUsedByMe, virtualUsedMax); physicalUsedMax = max(physMemUsedByMe, physicalUsedMax); data.virtual_usedByProcess = virtualMemUsedByMe; data.virtual_usedByProcess_max = virtualUsedMax; data.physical_usedByProcess = physMemUsedByMe; data.physical_usedByProcess_max = physicalUsedMax; } return data; } void printMemoryReport() { auto memoryData = getMemoryData(); double vm = double(memoryData.virtual_usedByProcess) / (1024.0 * 1024.0 * 1024.0); double pm = double(memoryData.physical_usedByProcess) / (1024.0 * 1024.0 * 1024.0); stringstream ss; ss << "memory usage: " << "virtual: " << formatNumber(vm, 1) << " GB, " << "physical: " << formatNumber(pm, 1) << " GB" << endl; cout << ss.str(); } void launchMemoryChecker(int64_t maxMB, double checkInterval) { auto interval = std::chrono::milliseconds(int64_t(checkInterval * 1000)); thread t([maxMB, interval]() { static double lastReport = 0.0; static double reportInterval = 1.0; static double lastUsage = 0.0; static double largestUsage = 0.0; while (true) { auto memdata = getMemoryData(); using namespace std::chrono_literals; std::this_thread::sleep_for(interval); } }); t.detach(); } static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; static HANDLE self; static bool initialized = false; void init() { SYSTEM_INFO sysInfo; FILETIME ftime, fsys, fuser; GetSystemInfo(&sysInfo); // numProcessors = sysInfo.dwNumberOfProcessors; numProcessors = std::thread::hardware_concurrency(); GetSystemTimeAsFileTime(&ftime); memcpy(&lastCPU, &ftime, sizeof(FILETIME)); self = GetCurrentProcess(); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&lastSysCPU, &fsys, sizeof(FILETIME)); memcpy(&lastUserCPU, &fuser, sizeof(FILETIME)); initialized = true; } CpuData getCpuData() { FILETIME ftime, fsys, fuser; ULARGE_INTEGER now, sys, user; double percent; if (!initialized) { init(); } GetSystemTimeAsFileTime(&ftime); memcpy(&now, &ftime, sizeof(FILETIME)); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&sys, &fsys, sizeof(FILETIME)); memcpy(&user, &fuser, sizeof(FILETIME)); percent = (sys.QuadPart - lastSysCPU.QuadPart) + (user.QuadPart - lastUserCPU.QuadPart); percent /= (now.QuadPart - lastCPU.QuadPart); percent /= numProcessors; lastCPU = now; lastUserCPU = user; lastSysCPU = sys; CpuData data; data.numProcessors = numProcessors; data.usage = percent * 100.0; return data; } #elif defined(__linux__) // see https://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process #include "sys/types.h" #include "sys/sysinfo.h" #include "stdlib.h" #include "stdio.h" #include "string.h" int parseLine(char* line){ // This assumes that a digit will be found and the line ends in " Kb". int i = strlen(line); const char* p = line; while (*p < '0' || *p > '9'){ p++; } line[i - 3] = '\0'; i = atoi(p); return i; } int64_t getVirtualMemoryUsedByProcess(){ //Note: this value is in KB! FILE* file = fopen("/proc/self/status", "r"); int64_t result = -1; char line[128]; while (fgets(line, 128, file) != NULL){ if (strncmp(line, "VmSize:", 7) == 0){ result = parseLine(line); break; } } fclose(file); result = result * 1024; return result; } int64_t getPhysicalMemoryUsedByProcess(){ //Note: this value is in KB! FILE* file = fopen("/proc/self/status", "r"); int64_t result = -1; char line[128]; while (fgets(line, 128, file) != NULL){ if (strncmp(line, "VmRSS:", 6) == 0){ result = parseLine(line); break; } } fclose(file); result = result * 1024; return result; } MemoryData getMemoryData() { struct sysinfo memInfo; sysinfo (&memInfo); int64_t totalVirtualMem = memInfo.totalram; totalVirtualMem += memInfo.totalswap; totalVirtualMem *= memInfo.mem_unit; int64_t virtualMemUsed = memInfo.totalram - memInfo.freeram; virtualMemUsed += memInfo.totalswap - memInfo.freeswap; virtualMemUsed *= memInfo.mem_unit; int64_t totalPhysMem = memInfo.totalram; totalPhysMem *= memInfo.mem_unit; long long physMemUsed = memInfo.totalram - memInfo.freeram; physMemUsed *= memInfo.mem_unit; int64_t virtualMemUsedByMe = getVirtualMemoryUsedByProcess(); int64_t physMemUsedByMe = getPhysicalMemoryUsedByProcess(); MemoryData data; static int64_t virtualUsedMax = 0; static int64_t physicalUsedMax = 0; virtualUsedMax = std::max(virtualMemUsedByMe, virtualUsedMax); physicalUsedMax = std::max(physMemUsedByMe, physicalUsedMax); { data.virtual_total = totalVirtualMem; data.virtual_used = virtualMemUsed; data.physical_total = totalPhysMem; data.physical_used = physMemUsed; } { data.virtual_usedByProcess = virtualMemUsedByMe; data.virtual_usedByProcess_max = virtualUsedMax; data.physical_usedByProcess = physMemUsedByMe; data.physical_usedByProcess_max = physicalUsedMax; } return data; } void printMemoryReport() { auto memoryData = getMemoryData(); double vm = double(memoryData.virtual_usedByProcess) / (1024.0 * 1024.0 * 1024.0); double pm = double(memoryData.physical_usedByProcess) / (1024.0 * 1024.0 * 1024.0); stringstream ss; ss << "memory usage: " << "virtual: " << formatNumber(vm, 1) << " GB, " << "physical: " << formatNumber(pm, 1) << " GB" << endl; cout << ss.str(); } void launchMemoryChecker(int64_t maxMB, double checkInterval) { auto interval = std::chrono::milliseconds(int64_t(checkInterval * 1000)); thread t([maxMB, interval]() { static double lastReport = 0.0; static double reportInterval = 1.0; static double lastUsage = 0.0; static double largestUsage = 0.0; while (true) { auto memdata = getMemoryData(); using namespace std::chrono_literals; std::this_thread::sleep_for(interval); } }); t.detach(); } static int numProcessors; static bool initialized = false; static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle; void init() { numProcessors = std::thread::hardware_concurrency(); FILE* file = fopen("/proc/stat", "r"); fscanf(file, "cpu %llu %llu %llu %llu", &lastTotalUser, &lastTotalUserLow, &lastTotalSys, &lastTotalIdle); fclose(file); initialized = true; } double getCpuUsage(){ double percent; FILE* file; unsigned long long totalUser, totalUserLow, totalSys, totalIdle, total; file = fopen("/proc/stat", "r"); fscanf(file, "cpu %llu %llu %llu %llu", &totalUser, &totalUserLow, &totalSys, &totalIdle); fclose(file); if (totalUser < lastTotalUser || totalUserLow < lastTotalUserLow || totalSys < lastTotalSys || totalIdle < lastTotalIdle){ //Overflow detection. Just skip this value. percent = -1.0; }else{ total = (totalUser - lastTotalUser) + (totalUserLow - lastTotalUserLow) + (totalSys - lastTotalSys); percent = total; total += (totalIdle - lastTotalIdle); percent /= total; percent *= 100; } lastTotalUser = totalUser; lastTotalUserLow = totalUserLow; lastTotalSys = totalSys; lastTotalIdle = totalIdle; return percent; } CpuData getCpuData() { if (!initialized) { init(); } CpuData data; data.numProcessors = numProcessors; data.usage = getCpuUsage(); return data; } #endif
3,735
733
<reponame>trisadmeslek/V-Sekai-Blender-tools from rx.core import Observable, AnonymousObservable from rx.concurrency import current_thread_scheduler from rx.internal import extensionclassmethod @extensionclassmethod(Observable, alias="just") def return_value(cls, value, scheduler=None): """Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. There is an alias called 'just'. example res = rx.Observable.return(42) res = rx.Observable.return(42, rx.Scheduler.timeout) Keyword arguments: value -- Single element in the resulting observable sequence. scheduler -- [Optional] Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. Returns an observable sequence containing the single specified element. """ scheduler = scheduler or current_thread_scheduler def subscribe(observer): def action(scheduler, state=None): observer.on_next(value) observer.on_completed() return scheduler.schedule(action) return AnonymousObservable(subscribe) @extensionclassmethod(Observable) def from_callable(cls, supplier, scheduler=None): """Returns an observable sequence that contains a single element generate from a supplier, using the specified scheduler to send out observer messages. example res = rx.Observable.from_callable(lambda: calculate_value()) res = rx.Observable.from_callable(lambda: 1 / 0) # emits an error Keyword arguments: value -- Single element in the resulting observable sequence. scheduler -- [Optional] Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. Returns an observable sequence containing the single specified element derived from the supplier """ scheduler = scheduler or current_thread_scheduler def subscribe(observer): def action(scheduler, state=None): try: observer.on_next(supplier()) observer.on_completed() except Exception: observer.on_error(Exception) return scheduler.schedule(action) return AnonymousObservable(subscribe)
800
4,303
#include "util/error_util.h" #include <cstdlib> namespace hannk { std::ostream &operator<<(std::ostream &stream, const halide_type_t &type) { if (type.code == halide_type_uint && type.bits == 1) { stream << "bool"; } else { static const char *const names[5] = {"int", "uint", "float", "handle", "bfloat"}; assert(type.code >= 0 && type.code < size(names)); stream << names[type.code] << (int)type.bits; } if (type.lanes > 1) { stream << "x" << (int)type.lanes; } return stream; } std::ostream &operator<<(std::ostream &s, const halide_dimension_t &dim) { return s << "{" << dim.min << ", " << dim.extent << ", " << dim.stride << "}"; } namespace internal { namespace { const char *const severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"}; } // namespace Logger::Logger(LogSeverity severity, const char *file, int line) : severity(severity) { assert(severity >= 0 && (size_t)severity < size(severity_names)); msg << severity_names[(int)severity] << ": " << "(" << file << ":" << line << ") "; } Logger::Logger(LogSeverity severity) : severity(severity) { assert(severity >= 0 && (size_t)severity < size(severity_names)); msg << severity_names[(int)severity] << ": "; } void Logger::finish() noexcept(false) { if (!msg.str().empty() && msg.str().back() != '\n') { msg << '\n'; } hannk_log(severity, msg.str().c_str()); // TODO: call iOS-specific logger here? if (severity == FATAL) { std::abort(); } } Logger::~Logger() noexcept(false) { finish(); } Checker::Checker(const char *condition_string) : logger(FATAL) { logger.msg << " Condition Failed: " << condition_string << '\n'; } Checker::Checker(const char *file, int line, const char *condition_string) : logger(FATAL, file, line) { logger.msg << " Condition Failed: " << condition_string << '\n'; } Checker::~Checker() noexcept(false) { logger.finish(); std::abort(); } } // namespace internal } // namespace hannk
838
2,195
<reponame>ZheniaZuser/android-database-sqlcipher package net.sqlcipher; /** * An exception that indicates there was an error accessing a specific row/column. */ public class InvalidRowColumnException extends RuntimeException { public InvalidRowColumnException() {} public InvalidRowColumnException(String error) { super(error); } }
109
1,007
############################################################## # Copyright (c) 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. ############################################################## from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from collections import deque import json # Print lower precision floating point values than default FLOAT_REPR json.encoder.FLOAT_REPR = lambda o: format(o, '.6f') def log_json_stats(stats, json_out_file=None, sort_keys=True): json_str = json.dumps(stats, sort_keys=sort_keys) print('json_stats: {:s}'.format(json_str)) if json_out_file is not None: with open(json_out_file, 'a') as fout: fout.write('{:s}\n'.format(json_str)) class SmoothedValue(object): """Track a series of values and provide access to smoothed values over a window or the global series average. """ def __init__(self, window_size): self.deque = deque(maxlen=window_size) self.series = [] self.total = 0.0 self.count = 0 def AddValue(self, value): self.deque.append(value) self.series.append(value) self.count += 1 self.total += value def GetMedianValue(self): return np.median(self.deque) def GetAverageValue(self): return np.mean(self.deque) def GetGlobalAverageValue(self): return self.total / self.count
572
690
from django.urls import include, path from dynamic_rest.routers import DynamicRouter from tests import viewsets router = DynamicRouter() router.register_resource(viewsets.UserViewSet) router.register_resource(viewsets.GroupViewSet) router.register_resource(viewsets.ProfileViewSet) router.register_resource(viewsets.LocationViewSet) router.register(r'cars', viewsets.CarViewSet) router.register(r'cats', viewsets.CatViewSet) router.register_resource(viewsets.DogViewSet) router.register_resource(viewsets.HorseViewSet) router.register_resource(viewsets.PermissionViewSet) router.register(r'zebras', viewsets.ZebraViewSet) # not canonical router.register(r'user_locations', viewsets.UserLocationViewSet) router.register(r'alternate_locations', viewsets.AlternateLocationViewSet) # the above routes are duplicated to test versioned prefixes router.register_resource(viewsets.CatViewSet, namespace='v2') # canonical router.register(r'v1/user_locations', viewsets.UserLocationViewSet) urlpatterns = [ path('', include(router.urls)) ]
335
357
<filename>vmdns/test/win/dnstest.cpp // dnstest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "../CuTest.h"
60
435
{ "description": "DjangoCon 2019 - Orientation and Welcome by <NAME>\n\nTBD\n\nThis talk was presented at: https://2019.djangocon.us/talk/orientation-and-welcome/\n\nLINKS:\nFollow <NAME> \ud83d\udc47\nOn Twitter: https://twitter.com/Transition\nOfficial homepage: http://kojoidrissa.com/\n\nFollow DjangCon US \ud83d\udc47\nhttps://twitter.com/djangocon\n\nFollow DEFNA \ud83d\udc47\nhttps://twitter.com/defnado\nhttps://www.defna.org/\n\nIntro music: \"This Is How We Quirk It\" by Avocado Junkie.\nVideo production by Confreaks TV.\nCaptions by White Coat Captioning.", "language": "eng", "recorded": "2019-09-23", "speakers": [ "<NAME>" ], "thumbnail_url": "https://i.ytimg.com/vi/LH5Hd5EWTvU/hqdefault.jpg", "title": "Orientation and Welcome", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=LH5Hd5EWTvU" } ] }
367
851
/* * Copyright (c) 2020 NVIDIA CORPORATION. * * 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. * * Please cite "4D Spatio-Temporal ConvNets: Minkowski Convolutional Neural * Networks", CVPR'19 (https://arxiv.org/abs/1904.08755) if you use any part * of the code. */ #ifndef ERRORS_HPP #define ERRORS_HPP #include <string> namespace minkowski { constexpr char const * const ERROR_MAP_NOT_FOUND = "CoordinateMap not found"; constexpr char const * const ERROR_NOT_IMPLEMENTED = "Not implemented"; constexpr char const * const ERROR_CPU_ONLY = "Compiled with only CPU backend."; } // end minkowski #endif
463
399
<reponame>ytai/ioio<gh_stars>100-1000 /* * Copyright (C) 2009-2012 by <NAME> * * 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 the copyright holders nor the names of * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * 4. Any redistribution, use, or modification is done solely for * personal benefit and not for any commercial purpose or for * monetary gain. * * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD 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 MATTHIAS * RINGWALD 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. * * Please inquire about commercial licensing options at <EMAIL> * */ /* * hci_dump.c * * Dump HCI trace in various formats: * * - BlueZ's hcidump format * - Apple's PacketLogger * - stdout hexdump * * Created by <NAME> on 5/26/09. */ #include "config.h" #include "hci_dump.h" #include "hci.h" #include "hci_transport.h" #include <btstack/hci_cmds.h> #ifndef EMBEDDED #include <fcntl.h> // open #include <arpa/inet.h> // hton.. #include <unistd.h> // write #include <stdio.h> #include <time.h> #include <sys/time.h> // for timestamps #include <sys/stat.h> // for mode flags #include <stdarg.h> // for va_list #endif // BLUEZ hcidump typedef struct { uint16_t len; uint8_t in; uint8_t pad; uint32_t ts_sec; uint32_t ts_usec; uint8_t packet_type; } #ifdef __GNUC__ __attribute__ ((packed)) #endif hcidump_hdr; // APPLE PacketLogger typedef struct { uint32_t len; uint32_t ts_sec; uint32_t ts_usec; uint8_t type; // 0xfc for note } #ifdef __GNUC__ __attribute__ ((packed)) #endif pktlog_hdr; #ifndef EMBEDDED static int dump_file = -1; static int dump_format; static hcidump_hdr header_bluez; static pktlog_hdr header_packetlogger; static char time_string[40]; static int max_nr_packets = -1; static int nr_packets = 0; static char log_message_buffer[256]; #endif void hci_dump_open(char *filename, hci_dump_format_t format){ #ifndef EMBEDDED dump_format = format; if (dump_format == HCI_DUMP_STDOUT) { dump_file = fileno(stdout); } else { dump_file = open(filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); } #endif } #ifndef EMBEDDED void hci_dump_set_max_packets(int packets){ max_nr_packets = packets; } #endif void hci_dump_packet(uint8_t packet_type, uint8_t in, uint8_t *packet, uint16_t len) { #ifndef EMBEDDED if (dump_file < 0) return; // not activated yet // don't grow bigger than max_nr_packets if (dump_format != HCI_DUMP_STDOUT && max_nr_packets > 0){ if (nr_packets >= max_nr_packets){ lseek(dump_file, 0, SEEK_SET); ftruncate(dump_file, 0); nr_packets = 0; } nr_packets++; } // get time struct timeval curr_time; struct tm* ptm; gettimeofday(&curr_time, NULL); switch (dump_format){ case HCI_DUMP_STDOUT: { /* Obtain the time of day, and convert it to a tm struct. */ ptm = localtime (&curr_time.tv_sec); /* Format the date and time, down to a single second. */ strftime (time_string, sizeof (time_string), "[%Y-%m-%d %H:%M:%S", ptm); /* Compute milliseconds from microseconds. */ uint16_t milliseconds = curr_time.tv_usec / 1000; /* Print the formatted time, in seconds, followed by a decimal point and the milliseconds. */ printf ("%s.%03u] ", time_string, milliseconds); switch (packet_type){ case HCI_COMMAND_DATA_PACKET: printf("CMD => "); break; case HCI_EVENT_PACKET: printf("EVT <= "); break; case HCI_ACL_DATA_PACKET: if (in) { printf("ACL <= "); } else { printf("ACL => "); } break; case LOG_MESSAGE_PACKET: // assume buffer is big enough packet[len] = 0; printf("LOG -- %s\n", (char*) packet); return; default: return; } hexdump(packet, len); break; } case HCI_DUMP_BLUEZ: bt_store_16( (uint8_t *) &header_bluez.len, 0, 1 + len); header_bluez.in = in; header_bluez.pad = 0; bt_store_32( (uint8_t *) &header_bluez.ts_sec, 0, curr_time.tv_sec); bt_store_32( (uint8_t *) &header_bluez.ts_usec, 0, curr_time.tv_usec); header_bluez.packet_type = packet_type; write (dump_file, &header_bluez, sizeof(hcidump_hdr) ); write (dump_file, packet, len ); break; case HCI_DUMP_PACKETLOGGER: header_packetlogger.len = htonl( sizeof(pktlog_hdr) - 4 + len); header_packetlogger.ts_sec = htonl(curr_time.tv_sec); header_packetlogger.ts_usec = htonl(curr_time.tv_usec); switch (packet_type){ case HCI_COMMAND_DATA_PACKET: header_packetlogger.type = 0x00; break; case HCI_ACL_DATA_PACKET: if (in) { header_packetlogger.type = 0x03; } else { header_packetlogger.type = 0x02; } break; case HCI_EVENT_PACKET: header_packetlogger.type = 0x01; break; case LOG_MESSAGE_PACKET: header_packetlogger.type = 0xfc; break; default: return; } write (dump_file, &header_packetlogger, sizeof(pktlog_hdr) ); write (dump_file, packet, len ); break; default: break; } #endif } void hci_dump_log(const char * format, ...){ #ifndef EMBEDDED va_list argptr; va_start(argptr, format); int len = vsnprintf(log_message_buffer, sizeof(log_message_buffer), format, argptr); hci_dump_packet(LOG_MESSAGE_PACKET, 0, (uint8_t*) log_message_buffer, len); va_end(argptr); #endif } void hci_dump_close(){ #ifndef EMBEDDED close(dump_file); dump_file = -1; #endif }
3,730
1,569
{ "title": "Report", "navLink": "Report", "meta": "A page example with a report", "loading": "Loading..." }
42
348
<gh_stars>100-1000 {"nom":"Lubilhac","circ":"2ème circonscription","dpt":"Haute-Loire","inscrits":131,"abs":51,"votants":80,"blancs":10,"nuls":5,"exp":65,"res":[{"nuance":"LR","nom":"<NAME>","voix":50},{"nuance":"REM","nom":"<NAME>","voix":15}]}
102
826
/*************************************************************************** * Copyright 1998-2018 by authors (see AUTHORS.txt) * * * * This file is part of LuxCoreRender. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* * See the License for the specific language governing permissions and * * limitations under the License. * ***************************************************************************/ #include <cstdlib> #include <iostream> #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include "luxrays/utils/oclerror.h" #include "luxcoreapp.h" #include "fileext.h" using namespace std; using namespace luxrays; using namespace luxcore; LogWindow *LuxCoreApp::currentLogWindow = NULL; ImVec4 LuxCoreApp::colLabel = ImVec4(1.f, .5f, 0.f, 1.f); //------------------------------------------------------------------------------ // LuxCoreApp //------------------------------------------------------------------------------ LuxCoreApp::LuxCoreApp(luxcore::RenderConfig *renderConfig) : // Note: isOpenCLAvailable and isCUDAAvailable have to be initialized before // ObjectEditorWindow constructors call (it is used by RenderEngineWindow). isOpenCLAvailable(GetPlatformDesc().Get(Property("compile.LUXRAYS_ENABLE_OPENCL")(false)).Get<bool>()), isCUDAAvailable(GetPlatformDesc().Get(Property("compile.LUXRAYS_ENABLE_CUDA")(false)).Get<bool>()), acceleratorWindow(this), epsilonWindow(this), filmChannelsWindow(this), filmOutputsWindow(this), filmRadianceGroupsWindow(this), lightStrategyWindow(this), oclDeviceWindow(this), pixelFilterWindow(this), renderEngineWindow(this), samplerWindow(this), haltConditionsWindow(this), statsWindow(this), logWindow(this), helpWindow(this), userImportancePaintWindow(this) { config = renderConfig; session = NULL; window = NULL; renderImageBuffer = NULL; renderImageWidth = 0xffffffffu; renderImageHeight = 0xffffffffu; currentTool = TOOL_CAMERA_EDIT; menuBarHeight = 0; captionHeight = 0; mouseHoverRenderingWindow = false; optRealTimeMode = false; droppedFramesCount = 0; refreshDecoupling = 1; optMouseGrabMode = false; optMoveScale = 1.f; optMoveStep = .5f; optRotateStep = 4.f; mouseButton0 = false; mouseButton2 = false; mouseGrabLastX = 0.0; mouseGrabLastY = 0.0; lastMouseUpdate = 0.0; optFullScreen = false; currentLogWindow = &logWindow; renderFrameBufferTexMinFilter = GL_LINEAR; renderFrameBufferTexMagFilter = GL_LINEAR; imagePipelineIndex = 0; guiLoopTimeShortAvg = 0.0; guiLoopTimeLongAvg = 0.0; guiSleepTime = 0.0; guiFilmUpdateTime = 0.0; } LuxCoreApp::~LuxCoreApp() { currentLogWindow = NULL; delete[] renderImageBuffer; delete session; delete config; } static int MaximumExtent(const float pMin[3], const float pMax[3]) { const float diagX = pMax[0] - pMin[0]; const float diagY = pMax[1] - pMin[1]; const float diagZ = pMax[2] - pMin[2]; if (diagX > diagY && diagX > diagZ) return 0; else if (diagY > diagZ) return 1; else return 2; } void LuxCoreApp::UpdateMoveStep() { float pMin[3], pMax[3]; config->GetScene().GetBBox(pMin, pMax); const int maxExtent = MaximumExtent(pMin, pMax); const float worldSize = Max(pMax[maxExtent] - pMin[maxExtent], .001f); optMoveStep = optMoveScale * worldSize / 50.f; } void LuxCoreApp::IncScreenRefreshInterval() { const unsigned int screenRefreshInterval = config->ToProperties().Get("screen.refresh.interval").Get<unsigned int>(); if (screenRefreshInterval >= 1000) config->Parse(Properties().Set(Property("screen.refresh.interval")(screenRefreshInterval + 1000))); else if (screenRefreshInterval >= 100) config->Parse(Properties().Set(Property("screen.refresh.interval")(screenRefreshInterval + 50))); else config->Parse(Properties().Set(Property("screen.refresh.interval")(screenRefreshInterval + 5))); } void LuxCoreApp::DecScreenRefreshInterval() { const unsigned int screenRefreshInterval = config->ToProperties().Get("screen.refresh.interval").Get<unsigned int>(); if (screenRefreshInterval > 1000) config->Parse(Properties().Set(Property("screen.refresh.interval")(Max(1000u, screenRefreshInterval - 1000)))); else if (screenRefreshInterval > 100) config->Parse(Properties().Set(Property("screen.refresh.interval")(Max(50u, screenRefreshInterval - 50)))); else config->Parse(Properties().Set(Property("screen.refresh.interval")(Max(10u, screenRefreshInterval - 5)))); } void LuxCoreApp::CloseAllRenderConfigEditors() { acceleratorWindow.Close(); epsilonWindow.Close(); filmChannelsWindow.Close(); filmOutputsWindow.Close(); filmRadianceGroupsWindow.Close(); lightStrategyWindow.Close(); oclDeviceWindow.Close(); pixelFilterWindow.Close(); renderEngineWindow.Close(); samplerWindow.Close(); haltConditionsWindow.Close(); statsWindow.Close(); } void LuxCoreApp::SetRenderingEngineType(const string &engineType) { if (engineType != config->ToProperties().Get("renderengine.type").Get<string>()) { Properties props; if (engineType == "RTPATHCPU") { props << Property("renderengine.type")("RTPATHCPU") << Property("sampler.type")("RTPATHCPUSAMPLER"); } else if (engineType == "RTPATHOCL") { props << Property("renderengine.type")("RTPATHOCL") << Property("sampler.type")("TILEPATHSAMPLER"); } else if (engineType == "TILEPATHCPU") { props << Property("renderengine.type")("TILEPATHCPU") << Property("sampler.type")("TILEPATHSAMPLER"); } else if (engineType == "TILEPATHOCL") { props << Property("renderengine.type")("TILEPATHOCL") << Property("sampler.type")("TILEPATHSAMPLER"); } else { props << Property("renderengine.type")(engineType) << Property("sampler.type")("SOBOL"); } RenderConfigParse(props); } } void LuxCoreApp::RenderConfigParse(const Properties &props) { if (session) { // Delete the session delete session; session = NULL; } // Change the configuration try { config->Parse(props); } catch(exception &ex) { LA_LOG("RenderConfig fatal parse error: " << endl << ex.what()); // I can not recover from a RenderConfig parse error: I would have to create // a new RenderConfig exit(EXIT_FAILURE); } StartRendering(); } void LuxCoreApp::RenderSessionParse(const Properties &props) { try { session->Parse(props); } catch(exception &ex) { LA_LOG("RenderSession parse error: " << endl << ex.what()); delete session; session = NULL; } } void LuxCoreApp::AdjustFilmResolutionToWindowSize(unsigned int *filmWidth, unsigned int *filmHeight) { int currentFrameBufferWidth, currentFrameBufferHeight; glfwGetFramebufferSize(window, &currentFrameBufferWidth, &currentFrameBufferHeight); const float newRatio = currentFrameBufferWidth / (float) currentFrameBufferHeight; if (newRatio >= 1.f) *filmHeight = (unsigned int) (*filmWidth * (1.f / newRatio)); else *filmWidth = (unsigned int) (*filmHeight * newRatio); LA_LOG("Film size adjusted: " << *filmWidth << "x" << *filmHeight << " (Frame buffer size: " << currentFrameBufferWidth << "x" << currentFrameBufferHeight << ")"); } void LuxCoreApp::SetFilmResolution(const unsigned int width, const unsigned int height) { // Close film related editors filmChannelsWindow.Close(); filmOutputsWindow.Close(); filmRadianceGroupsWindow.Close(); targetFilmWidth = width; targetFilmHeight = height; StartRendering(); } void LuxCoreApp::LoadRenderConfig(const std::string &fileName) { DeleteRendering(); // Set the current directory to place where the configuration file is boost::filesystem::current_path(boost::filesystem::path(fileName).parent_path()); // Clear the file name resolver list luxcore::ClearFileNameResolverPaths(); // Add the current directory to the list of place where to look for files luxcore::AddFileNameResolverPath("."); // Add the .cfg directory to the list of place where to look for files boost::filesystem::path path(fileName); luxcore::AddFileNameResolverPath(path.parent_path().generic_string()); try { const string ext = GetFileNameExt(fileName); if (ext == ".lxs") { // It is a LuxRender SDL file LA_LOG("Parsing LuxRender SDL file..."); Properties renderConfigProps, sceneProps; luxcore::ParseLXS(fileName, renderConfigProps, sceneProps); // For debugging //LA_LOG("RenderConfig: \n" << renderConfigProps); //LA_LOG("Scene: \n" << sceneProps); Scene *scene = Scene::Create(); scene->Parse(sceneProps); config = RenderConfig::Create(renderConfigProps, scene); config->DeleteSceneOnExit(); StartRendering(); } else if (ext == ".cfg") { // It is a LuxCore SDL file config = RenderConfig::Create(Properties(fileName)); StartRendering(); } else if (ext == ".bcf") { // It is a LuxCore RenderConfig binary archive config = RenderConfig::Create(fileName); StartRendering(); } else if (ext == ".rsm") { // It is a LuxCore resume file RenderState *startState; Film *startFilm; config = RenderConfig::Create(fileName, &startState, &startFilm); StartRendering(startState, startFilm); } else throw runtime_error("Unknown file extension: " + fileName); } catch(exception &ex) { LA_LOG("RenderConfig loading error: " << endl << ex.what()); delete session; session = NULL; delete config; config = NULL; } popupMenuBar = true; } void LuxCoreApp::StartRendering(RenderState *startState, Film *startFilm) { CloseAllRenderConfigEditors(); if (session) delete session; session = NULL; const string engineType = config->ToProperties().Get("renderengine.type").Get<string>(); if (boost::starts_with(engineType, "RT")) { if (config->ToProperties().Get("screen.refresh.interval").Get<unsigned int>() > 25) config->Parse(Properties().Set(Property("screen.refresh.interval")(25))); optRealTimeMode = true; // Reset the dropped frames counter droppedFramesCount = 0; refreshDecoupling = 1; } else optRealTimeMode = false; const string toolTypeStr = config->ToProperties().Get("screen.tool.type").Get<string>(); if (toolTypeStr == "OBJECT_SELECTION") currentTool = TOOL_OBJECT_SELECTION; else if (toolTypeStr == "IMAGE_VIEW") currentTool = TOOL_IMAGE_VIEW; else if (toolTypeStr == "USER_IMPORTANCE_PAINT") currentTool = TOOL_USER_IMPORTANCE_PAINT; else currentTool = TOOL_CAMERA_EDIT; unsigned int filmWidth = targetFilmWidth; unsigned int filmHeight = targetFilmHeight; if (currentTool != TOOL_IMAGE_VIEW) { // Delete scene.camera.screenwindow so frame buffer resize will // automatically adjust the ratio Properties cameraProps = config->GetScene().ToProperties().GetAllProperties("scene.camera"); cameraProps.DeleteAll(cameraProps.GetAllNames("scene.camera.screenwindow")); config->GetScene().Parse(cameraProps); // Adjust the width and height to match the window width and height ratio AdjustFilmResolutionToWindowSize(&filmWidth, &filmHeight); } Properties cfgProps; cfgProps << Property("film.width")(filmWidth) << Property("film.height")(filmHeight); config->Parse(cfgProps); LA_LOG("RenderConfig has cached kernels: " << (config->HasCachedKernels() ? "True" : "False")); try { session = RenderSession::Create(config, startState, startFilm); // Re-start the rendering session->Start(); UpdateMoveStep(); if (currentTool == TOOL_USER_IMPORTANCE_PAINT) userImportancePaintWindow.Init(); } catch(exception &ex) { LA_LOG("RenderSession starting error: " << endl << ex.what()); delete session; session = NULL; } } void LuxCoreApp::DeleteRendering() { CloseAllRenderConfigEditors(); delete session; session = NULL; delete config; config = NULL; } //------------------------------------------------------------------------------ // Console log //------------------------------------------------------------------------------ void LuxCoreApp::LogHandler(const char *msg) { cout << msg << endl; if (currentLogWindow) currentLogWindow->AddMsg(msg); } //------------------------------------------------------------------------------ // GUI related methods //------------------------------------------------------------------------------ void LuxCoreApp::ColoredLabelText(const ImVec4 &col, const char *label, const char *fmt, ...) { ImGui::TextColored(col, "%s", label); ImGui::SameLine(); va_list args; va_start(args, fmt); ImGui::TextV(fmt, args); va_end(args); } void LuxCoreApp::ColoredLabelText(const char *label, const char *fmt, ...) { ImGui::TextColored(colLabel, "%s", label); ImGui::SameLine(); va_list args; va_start(args, fmt); ImGui::TextV(fmt, args); va_end(args); } void LuxCoreApp::HelpMarker(const char *desc) { ImGui::SameLine(); ImGui::TextDisabled("(?)"); if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", desc); }
4,929
3,084
/*++ Copyright (C) Microsoft Corporation, All Rights Reserved. Module Name: Driver.cpp Abstract: This module contains the implementation of the UMDF Socketecho Sample's core driver callback object. Environment: Windows User-Mode Driver Framework (WUDF) --*/ #include "internal.h" #include "driver.tmh" STDMETHODIMP CMyDriver::OnInitialize( _In_ IWDFDriver* pWdfDriver ) /*++ Routine Description: This routine is invoked by the framework at driver load . This method will invoke the Winsock Library for using Winsock API in this driver. Arguments: pWdfDriver - Framework driver object Return Value: S_OK if successful, or error otherwise. --*/ { Trace( TRACE_LEVEL_INFORMATION, "%!FUNC!" ); UNREFERENCED_PARAMETER(pWdfDriver); WORD sockVersion; WSADATA wsaData; sockVersion = MAKEWORD(2, 0); int result = WSAStartup(sockVersion, &wsaData); if (result != 0) { DWORD err = WSAGetLastError(); Trace( TRACE_LEVEL_ERROR, L"ERROR: Failed to initialize Winsock 2.0 %!winerr!", err ); return HRESULT_FROM_WIN32(err); } return S_OK; } STDMETHODIMP_(void) CMyDriver::OnDeinitialize( _In_ IWDFDriver* pWdfDriver ) /*++ Routine Description: The FX invokes this method when it unloads the driver. This routine will Cleanup Winsock library Arguments: pWdfDriver - the Fx driver object. Return Value: None --*/ { Trace( TRACE_LEVEL_INFORMATION, "%!FUNC!" ); UNREFERENCED_PARAMETER(pWdfDriver); WSACleanup(); } STDMETHODIMP CMyDriver::OnDeviceAdd( _In_ IWDFDriver *FxWdfDriver, _In_ IWDFDeviceInitialize *FxDeviceInit ) /*++ Routine Description: The FX invokes this method when it wants to install our driver on a device stack. This method creates a device callback object, then calls the Fx to create an Fx device object and associate the new callback object with it. Arguments: FxWdfDriver - the Fx driver object. FxDeviceInit - the initialization information for the device. Return Value: status --*/ { Trace( TRACE_LEVEL_INFORMATION, "%!FUNC!" ); HRESULT hr; CComObject<CMyDevice> * device = NULL; // // Create a new instance of our device callback object // hr = CComObject<CMyDevice>::CreateInstance(&device); if (SUCCEEDED(hr)) { device->AddRef(); hr = device->Initialize(FxWdfDriver, FxDeviceInit); } // // If that succeeded then call the device's configure method. This // allows the device to create any queues or other structures that it // needs now that the corresponding fx device object has been created. // if (SUCCEEDED(hr)) { hr = device->Configure(); } // // Release the reference we took on the device callback object. // The framework took its own references on the object's callback interfaces // when we called FxWdfDriver->CreateDevice, and will manage the object's lifetime. // SAFE_RELEASE(device); return hr; }
1,494
778
/* * Copyright (C) 2018-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #pragma once #include "shared/source/built_ins/built_ins.h" #include <string> #include <unordered_map> namespace NEO { struct RegisterEmbeddedResource { RegisterEmbeddedResource(const char *name, const char *resource, size_t resourceLength) { auto &storageRegistry = EmbeddedStorageRegistry::getInstance(); storageRegistry.store(name, createBuiltinResource(resource, resourceLength)); } RegisterEmbeddedResource(const char *name, std::string &&resource) : RegisterEmbeddedResource(name, resource.data(), resource.size() + 1) { } }; } // namespace NEO
228
363
/* Copyright 2009, 2011 predic8 GmbH, www.predic8.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. */ package com.predic8.membrane.core.util; import static com.predic8.membrane.core.util.URLParamUtil.*; import static com.predic8.membrane.core.util.URLUtil.getHost; import static org.junit.Assert.assertEquals; import java.io.IOException; import org.junit.Test; public class URLUtilTest { @Test public void testHost() { assertEquals(getHost("service:a"), "a"); assertEquals(getHost("service://a"), "a"); assertEquals(getHost("a"), "a"); assertEquals(getHost("a/b"), "a"); assertEquals(getHost("service:a/b"), "a"); assertEquals(getHost("service://a/b"), "a"); } @Test public void testCreateQueryString() throws IOException { assertEquals("endpoint=http%3A%2F%2Fnode1.clustera&cluster=c1", createQueryString("endpoint", "http://node1.clustera", "cluster","c1")); } @Test public void testParseQueryString() throws IOException { assertEquals("http://node1.clustera", parseQueryString("endpoint=http%3A%2F%2Fnode1.clustera&cluster=c1").get("endpoint")); assertEquals("c1", parseQueryString("endpoint=http%3A%2F%2Fnode1.clustera&cluster=c1").get("cluster")); } @Test public void testParamsWithoutValueString() throws IOException { assertEquals("jim", parseQueryString("name=jim&male").get("name")); assertEquals("", parseQueryString("name=jim&male").get("male")); assertEquals("", parseQueryString("name=anna&age=").get("age")); } @Test public void testDecodePath() throws Exception{ URI u = new URI(true,"/path/to%20my/resource"); assertEquals("/path/to my/resource", u.getPath()); assertEquals("/path/to%20my/resource",u.getRawPath()); } }
779
335
<filename>R/Rheumatology_noun.json { "word": "Rheumatology", "definitions": [ "The study of rheumatism, arthritis, and other disorders of the joints, muscles, and ligaments." ], "parts-of-speech": "Noun" }
92
1,444
<reponame>GabrielSturtevant/mage<gh_stars>1000+ package mage.cards.h; import java.util.UUID; import mage.abilities.common.EntersBattlefieldTappedAbility; import mage.abilities.mana.BlueManaAbility; import mage.abilities.mana.RedManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; /** * * @author fireshoes */ public final class HighlandLake extends CardImpl { public HighlandLake(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.LAND},""); // Highland Lake enters the battlefield tapped. this.addAbility(new EntersBattlefieldTappedAbility()); // {T}: Add {U} or {R}. this.addAbility(new BlueManaAbility()); this.addAbility(new RedManaAbility()); } private HighlandLake(final HighlandLake card) { super(card); } @Override public HighlandLake copy() { return new HighlandLake(this); } }
354