max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
11,868
<reponame>MalcolmScoffable/openapi-generator<gh_stars>1000+ #ifndef _keyValuePair_H_ #define _keyValuePair_H_ #include<string.h> typedef struct keyValuePair_t { char* key; void* value; } keyValuePair_t; keyValuePair_t *keyValuePair_create(char *key, void *value); keyValuePair_t* keyValuePair_create_allocate(char* key, double value); void keyValuePair_free(keyValuePair_t *keyValuePair); #endif /* _keyValuePair_H_ */
181
310
{ "name": "S24B300HL", "description": "A 23.6 inch LED screen.", "url": "http://www.samsung.com/uk/support/model/LS24B300HL/EN" }
58
372
<reponame>sordina/morpheus-graphql<gh_stars>100-1000 { "errors": [ { "message": "Argument \"monster\" got invalid value. Expected type \"Monster!\" found {}. Exclusive input objects must provide a value for at least one field.", "locations": [{ "line": 2, "column": 22 }] }, { "message": "Argument \"monster\" got invalid value. Expected type \"Monster!\" found { Hydra: { name: \"someName\", age: 12 }, UnidentifiedMonster: Unit }. Exclusive input objects are not allowed to provide values for multiple fields.", "locations": [{ "line": 4, "column": 5 }] } ] }
205
713
package org.infinispan.distribution.rehash; import org.infinispan.test.TestingUtil; public abstract class RehashLeaveTestBase extends RehashTestBase { void waitForRehashCompletion() { TestingUtil.blockUntilViewsReceived(60000, false, caches); TestingUtil.waitForNoRebalance(caches); } }
107
1,338
<reponame>Kirishikesan/haiku<filename>src/libs/glut/glutEvent.cpp<gh_stars>1000+ /*********************************************************** * Copyright (C) 1997, Be Inc. Copyright (C) 1999, <NAME>. * * This program is freely distributable without licensing fees * and is provided without guarantee or warrantee expressed or * implied. This program is -not- in the public domain. * * * FILE: glutEvent.cpp * * DESCRIPTION: here it is, the BeOS GLUT event loop ***********************************************************/ /*********************************************************** * Headers ***********************************************************/ #include <GL/glut.h> #include "glutint.h" #include "glutState.h" #include "glutBlocker.h" #include <stdio.h> #include <stdlib.h> #define MOUSE_WHEEL_UP 3 #define MOUSE_WHEEL_DOWN 4 /*********************************************************** * CLASS: GLUTtimer * * DESCRIPTION: list of timer callbacks ***********************************************************/ struct GLUTtimer { GLUTtimer *next; // list of timers bigtime_t timeout; // time to be called GLUTtimerCB func; // function to call int value; // value }; /*********************************************************** * Private variables ***********************************************************/ static GLUTtimer *__glutTimerList = 0; // list of timer callbacks static GLUTtimer *freeTimerList = 0; /*********************************************************** * FUNCTION: glutTimerFunc (7.19) * * DESCRIPTION: register a new timer callback ***********************************************************/ void APIENTRY glutTimerFunc(unsigned int interval, GLUTtimerCB timerFunc, int value) { GLUTtimer *timer, *other; GLUTtimer **prevptr; if (!timerFunc) return; if (freeTimerList) { timer = freeTimerList; freeTimerList = timer->next; } else { timer = new GLUTtimer(); if (!timer) __glutFatalError("out of memory."); } timer->func = timerFunc; timer->value = value; timer->next = NULL; timer->timeout = system_time() + (interval*1000); // 1000 ticks in a millisecond prevptr = &__glutTimerList; other = *prevptr; while (other && (other->timeout < timer->timeout)) { prevptr = &other->next; other = *prevptr; } timer->next = other; *prevptr = timer; } /*********************************************************** * FUNCTION: handleTimeouts * * DESCRIPTION: private function to handle outstanding timeouts ***********************************************************/ static void handleTimeouts(void) { bigtime_t now; GLUTtimer *timer; /* Assumption is that __glutTimerList is already determined to be non-NULL. */ now = system_time(); while (__glutTimerList->timeout <= now) { timer = __glutTimerList; if(gState.currentWindow) gState.currentWindow->LockGL(); timer->func(timer->value); if(gState.currentWindow) gState.currentWindow->UnlockGL(); __glutTimerList = timer->next; timer->next = freeTimerList; freeTimerList = timer; if (!__glutTimerList) break; } } /*********************************************************** * FUNCTION: processEventsAndTimeouts * * DESCRIPTION: clear gBlock, then check all windows for events ***********************************************************/ static void processEventsAndTimeouts(void) { gBlock.WaitEvent(); // if there is already an event, returns // immediately, otherwise wait forever gBlock.ClearEvents(); if(gState.quitAll) exit(0); // exit handler cleans up windows and quits nicely if (gState.currentWindow) gState.currentWindow->LockGL(); for(int i=0; i<gState.windowListSize; i++) { if (gState.windowList[i]) { GlutWindow *win = gState.windowList[i]; // NOTE: we can use win as a shortcut for gState.windowList[i] // in callbacks, EXCEPT we need to check the original variable // after each callback to make sure the window hasn't been destroyed if (win->anyevents) { win->anyevents = false; if (win->reshapeEvent) { win->reshapeEvent = false; __glutSetWindow(win); win->reshape(win->m_width, win->m_height); } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->displayEvent) { win->displayEvent = false; __glutSetWindow(win); win->display(); } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->mouseEvent) { win->mouseEvent = false; __glutSetWindow(win); if (win->mouse) { gState.modifierKeys = win->modifierKeys; win->mouse(win->button, win->mouseState, win->mouseX, win->mouseY); gState.modifierKeys = ~0; } } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->menuEvent) { win->menuEvent = false; __glutSetWindow(win); GlutMenu *menu = __glutGetMenuByNum(win->menuNumber); if (menu) { gState.currentMenu = menu; menu->select(win->menuValue); } } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->statusEvent) { win->statusEvent = false; __glutSetWindow(win); if (gState.menuStatus) { gState.currentMenu = __glutGetMenuByNum(win->menuNumber); gState.menuStatus(win->menuStatus, win->statusX, win->statusY); } } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->motionEvent) { win->motionEvent = false; __glutSetWindow(win); if (win->motion) win->motion(win->motionX, win->motionY); } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->passiveEvent) { win->passiveEvent = false; __glutSetWindow(win); if (win->passive) win->passive(win->passiveX, win->passiveY); } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->keybEvent) { win->keybEvent = false; __glutSetWindow(win); if (win->keyboard) { gState.modifierKeys = win->modifierKeys; win->keyboard(win->key, win->keyX, win->keyY); gState.modifierKeys = ~0; } } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->specialEvent) { win->specialEvent = false; __glutSetWindow(win); if (win->special) { gState.modifierKeys = win->modifierKeys; win->special(win->specialKey, win->specialX, win->specialY); gState.modifierKeys = ~0; } } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->keybUpEvent) { win->keybUpEvent = false; __glutSetWindow(win); if (win->keyboardUp) { gState.modifierKeys = win->modifierKeys; win->keyboardUp(win->key, win->keyX, win->keyY); gState.modifierKeys = ~0; } } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->specialUpEvent) { win->specialUpEvent = false; __glutSetWindow(win); if (win->specialUp) { gState.modifierKeys = win->modifierKeys; win->specialUp(win->specialKey, win->specialX, win->specialY); gState.modifierKeys = ~0; } } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->entryEvent) { win->entryEvent = false; __glutSetWindow(win); if (win->entry) win->entry(win->entryState); } if (!gState.windowList[i]) continue; // window was destroyed by callback! if (win->windowStatusEvent) { win->windowStatusEvent = false; __glutSetWindow(win); if (win->windowStatus) win->windowStatus(win->visState); } if (!gState.windowList[i]) continue; // window was destroyed by callback! } } } if (gState.currentWindow) gState.currentWindow->UnlockGL(); // This code isn't necessary since BGLView automatically traps errors #if 0 if(gState.debug) { for(int i=0; i<gState.windowListSize; i++) { if (gState.windowList[i]) { gState.windowList[i]->LockGL(); glutReportErrors(); gState.windowList[i]->UnlockGL(); } } } #endif if (__glutTimerList) { handleTimeouts(); } } /*********************************************************** * FUNCTION: waitForSomething * * DESCRIPTION: use gBlock to wait for a new event or timeout ***********************************************************/ static void waitForSomething(void) { bigtime_t timeout = __glutTimerList->timeout; bigtime_t now = system_time(); if (gBlock.PendingEvent()) goto immediatelyHandleEvent; if(timeout>now) gBlock.WaitEvent(timeout-now); if (gBlock.PendingEvent()) { immediatelyHandleEvent: processEventsAndTimeouts(); } else { if (__glutTimerList) handleTimeouts(); } } /*********************************************************** * FUNCTION: idleWait * * DESCRIPTION: check for events, then call idle function ***********************************************************/ static void idleWait(void) { if (gBlock.PendingEvent()) { processEventsAndTimeouts(); } else { if (__glutTimerList) handleTimeouts(); } /* Make sure idle func still exists! */ if(gState.currentWindow) gState.currentWindow->LockGL(); if (gState.idle) { gState.idle(); } if(gState.currentWindow) gState.currentWindow->UnlockGL(); } /*********************************************************** * FUNCTION: glutMainLoop (3.1) * * DESCRIPTION: enter the event processing loop ***********************************************************/ void glutMainLoop() { if (!gState.windowListSize) __glutFatalUsage("main loop entered with no windows created."); if(gState.currentWindow) gState.currentWindow->UnlockGL(); for (;;) { if (gState.idle) { idleWait(); } else { if (__glutTimerList) { waitForSomething(); } else { processEventsAndTimeouts(); } } } } void glutSetKeyRepeat(int repeatMode) { switch(repeatMode) { case GLUT_KEY_REPEAT_DEFAULT: gState.keyRepeatMode = GLUT_KEY_REPEAT_ON; break; case GLUT_KEY_REPEAT_ON: case GLUT_KEY_REPEAT_OFF: gState.keyRepeatMode = repeatMode; break; default: __glutWarning("invalid glutSetKeyRepeat mode: %d", repeatMode); } } void glutIgnoreKeyRepeat(int ignore) { if (gState.currentWindow) gState.currentWindow->ignoreKeyRepeat = (ignore != 0); } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: KeyDown * * DESCRIPTION: handles keyboard and special events ***********************************************************/ void GlutWindow::KeyDown(const char *s, int32 slen) { ulong aChar = s[0]; BGLView::KeyDown(s,slen); BPoint p; if (ignoreKeyRepeat && Window()->CurrentMessage()->FindInt32("be:key_repeat") > 0) return; switch (aChar) { case B_FUNCTION_KEY: switch(Window()->CurrentMessage()->FindInt32("key")) { case B_F1_KEY: aChar = GLUT_KEY_F1; goto specialLabel; case B_F2_KEY: aChar = GLUT_KEY_F2; goto specialLabel; case B_F3_KEY: aChar = GLUT_KEY_F3; goto specialLabel; case B_F4_KEY: aChar = GLUT_KEY_F4; goto specialLabel; case B_F5_KEY: aChar = GLUT_KEY_F5; goto specialLabel; case B_F6_KEY: aChar = GLUT_KEY_F6; goto specialLabel; case B_F7_KEY: aChar = GLUT_KEY_F7; goto specialLabel; case B_F8_KEY: aChar = GLUT_KEY_F8; goto specialLabel; case B_F9_KEY: aChar = GLUT_KEY_F9; goto specialLabel; case B_F10_KEY: aChar = GLUT_KEY_F10; goto specialLabel; case B_F11_KEY: aChar = GLUT_KEY_F11; goto specialLabel; case B_F12_KEY: aChar = GLUT_KEY_F12; goto specialLabel; default: return; } case B_LEFT_ARROW: aChar = GLUT_KEY_LEFT; goto specialLabel; case B_UP_ARROW: aChar = GLUT_KEY_UP; goto specialLabel; case B_RIGHT_ARROW: aChar = GLUT_KEY_RIGHT; goto specialLabel; case B_DOWN_ARROW: aChar = GLUT_KEY_DOWN; goto specialLabel; case B_PAGE_UP: aChar = GLUT_KEY_PAGE_UP; goto specialLabel; case B_PAGE_DOWN: aChar = GLUT_KEY_PAGE_DOWN; goto specialLabel; case B_HOME: aChar = GLUT_KEY_HOME; goto specialLabel; case B_END: aChar = GLUT_KEY_END; goto specialLabel; case B_INSERT: aChar = GLUT_KEY_INSERT; specialLabel: if (special) { anyevents = specialEvent = true; GetMouse(&p,&m_buttons); specialKey = aChar; specialX = (int)p.x; specialY = (int)p.y; goto setModifiers; // set the modifier variable } return; default: break; } if (keyboard) { anyevents = keybEvent = true; GetMouse(&p,&m_buttons); key = aChar; keyX = (int)p.x; keyY = (int)p.y; setModifiers: modifierKeys = 0; uint32 beMod = Window()->CurrentMessage()->FindInt32("modifiers"); if(beMod & B_SHIFT_KEY) modifierKeys |= GLUT_ACTIVE_SHIFT; if(beMod & B_CONTROL_KEY) modifierKeys |= GLUT_ACTIVE_CTRL; if(beMod & B_OPTION_KEY) { // since the window traps B_COMMAND_KEY, we'll have to settle // for the option key.. but we need to get the raw character, // not the Unicode-enhanced version key = Window()->CurrentMessage()->FindInt32("raw_char"); modifierKeys |= GLUT_ACTIVE_ALT; } gBlock.NewEvent(); } } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: KeyUp * * DESCRIPTION: handles keyboard and special events ***********************************************************/ void GlutWindow::KeyUp(const char *s, int32 slen) { ulong aChar = s[0]; BGLView::KeyUp(s,slen); BPoint p; switch (aChar) { case B_FUNCTION_KEY: switch(Window()->CurrentMessage()->FindInt32("key")) { case B_F1_KEY: aChar = GLUT_KEY_F1; goto specialLabel; case B_F2_KEY: aChar = GLUT_KEY_F2; goto specialLabel; case B_F3_KEY: aChar = GLUT_KEY_F3; goto specialLabel; case B_F4_KEY: aChar = GLUT_KEY_F4; goto specialLabel; case B_F5_KEY: aChar = GLUT_KEY_F5; goto specialLabel; case B_F6_KEY: aChar = GLUT_KEY_F6; goto specialLabel; case B_F7_KEY: aChar = GLUT_KEY_F7; goto specialLabel; case B_F8_KEY: aChar = GLUT_KEY_F8; goto specialLabel; case B_F9_KEY: aChar = GLUT_KEY_F9; goto specialLabel; case B_F10_KEY: aChar = GLUT_KEY_F10; goto specialLabel; case B_F11_KEY: aChar = GLUT_KEY_F11; goto specialLabel; case B_F12_KEY: aChar = GLUT_KEY_F12; goto specialLabel; default: return; } case B_LEFT_ARROW: aChar = GLUT_KEY_LEFT; goto specialLabel; case B_UP_ARROW: aChar = GLUT_KEY_UP; goto specialLabel; case B_RIGHT_ARROW: aChar = GLUT_KEY_RIGHT; goto specialLabel; case B_DOWN_ARROW: aChar = GLUT_KEY_DOWN; goto specialLabel; case B_PAGE_UP: aChar = GLUT_KEY_PAGE_UP; goto specialLabel; case B_PAGE_DOWN: aChar = GLUT_KEY_PAGE_DOWN; goto specialLabel; case B_HOME: aChar = GLUT_KEY_HOME; goto specialLabel; case B_END: aChar = GLUT_KEY_END; goto specialLabel; case B_INSERT: aChar = GLUT_KEY_INSERT; specialLabel: if (specialUp!=0) { anyevents = specialUpEvent = true; GetMouse(&p,&m_buttons); specialKey = aChar; specialX = (int)p.x; specialY = (int)p.y; goto setModifiers; // set the modifier variable } return; default: break; } if (keyboardUp!=0) { anyevents = keybUpEvent = true; GetMouse(&p,&m_buttons); key = aChar; keyX = (int)p.x; keyY = (int)p.y; setModifiers: modifierKeys = 0; uint32 beMod = Window()->CurrentMessage()->FindInt32("modifiers"); if(beMod & B_SHIFT_KEY) modifierKeys |= GLUT_ACTIVE_SHIFT; if(beMod & B_CONTROL_KEY) modifierKeys |= GLUT_ACTIVE_CTRL; if(beMod & B_OPTION_KEY) { // since the window traps B_COMMAND_KEY, we'll have to settle // for the option key.. but we need to get the raw character, // not the Unicode-enhanced version key = Window()->CurrentMessage()->FindInt32("raw_char"); modifierKeys |= GLUT_ACTIVE_ALT; } gBlock.NewEvent(); } } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: MouseDown * * DESCRIPTION: handles mouse and menustatus events ***********************************************************/ void GlutWindow::MouseDown(BPoint point) { BGLView::MouseDown(point); MouseCheck(); } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: MouseCheck * * DESCRIPTION: checks for button state changes ***********************************************************/ void GlutWindow::MouseCheck() { if (mouseEvent) return; // we already have an outstanding mouse event BPoint point; uint32 newButtons; GetMouse(&point, &newButtons); if (m_buttons != newButtons) { if (newButtons&B_PRIMARY_MOUSE_BUTTON && !(m_buttons&B_PRIMARY_MOUSE_BUTTON)) { button = GLUT_LEFT_BUTTON; mouseState = GLUT_DOWN; } else if (m_buttons&B_PRIMARY_MOUSE_BUTTON && !(newButtons&B_PRIMARY_MOUSE_BUTTON)) { button = GLUT_LEFT_BUTTON; mouseState = GLUT_UP; } else if (newButtons&B_SECONDARY_MOUSE_BUTTON && !(m_buttons&B_SECONDARY_MOUSE_BUTTON)) { button = GLUT_RIGHT_BUTTON; mouseState = GLUT_DOWN; } else if (m_buttons&B_SECONDARY_MOUSE_BUTTON && !(newButtons&B_SECONDARY_MOUSE_BUTTON)) { button = GLUT_RIGHT_BUTTON; mouseState = GLUT_UP; } else if (newButtons&B_TERTIARY_MOUSE_BUTTON && !(m_buttons&B_TERTIARY_MOUSE_BUTTON)) { button = GLUT_MIDDLE_BUTTON; mouseState = GLUT_DOWN; } else if (m_buttons&B_TERTIARY_MOUSE_BUTTON && !(newButtons&B_TERTIARY_MOUSE_BUTTON)) { button = GLUT_MIDDLE_BUTTON; mouseState = GLUT_UP; } } else { return; // no change, return } m_buttons = newButtons; if (mouseState == GLUT_DOWN) { BWindow *w = Window(); GlutMenu *m = __glutGetMenuByNum(menu[button]); if (m) { if (gState.menuStatus) { anyevents = statusEvent = true; menuNumber = menu[button]; menuStatus = GLUT_MENU_IN_USE; statusX = (int)point.x; statusY = (int)point.y; gBlock.NewEvent(); } BRect bounds = w->Frame(); point.x += bounds.left; point.y += bounds.top; GlutPopUp *bmenu = static_cast<GlutPopUp*>(m->CreateBMenu()); // start menu bmenu->point = point; bmenu->win = this; thread_id menu_thread = spawn_thread(MenuThread, "menu thread", B_NORMAL_PRIORITY, bmenu); resume_thread(menu_thread); return; } } if (mouse) { anyevents = mouseEvent = true; mouseX = (int)point.x; mouseY = (int)point.y; modifierKeys = 0; uint32 beMod = modifiers(); if(beMod & B_SHIFT_KEY) modifierKeys |= GLUT_ACTIVE_SHIFT; if(beMod & B_CONTROL_KEY) modifierKeys |= GLUT_ACTIVE_CTRL; if(beMod & B_OPTION_KEY) { modifierKeys |= GLUT_ACTIVE_ALT; } gBlock.NewEvent(); } } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: MouseMoved * * DESCRIPTION: handles entry, motion, and passive events ***********************************************************/ void GlutWindow::MouseMoved(BPoint point, uint32 transit, const BMessage *msg) { BGLView::MouseMoved(point,transit,msg); if(transit != B_INSIDE_VIEW) { if (entry) { anyevents = entryEvent = true; gBlock.NewEvent(); } if (transit == B_ENTERED_VIEW) { entryState = GLUT_ENTERED; MakeFocus(); // make me the current focus __glutSetCursor(cursor); } else entryState = GLUT_LEFT; } MouseCheck(); if(m_buttons) { if(motion) { anyevents = motionEvent = true; motionX = (int)point.x; motionY = (int)point.y; gBlock.NewEvent(); } } else { if(passive) { anyevents = passiveEvent = true; passiveX = (int)point.x; passiveY = (int)point.y; gBlock.NewEvent(); } } } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: MessageReceived * * DESCRIPTION: handles mouse wheel events ***********************************************************/ void GlutWindow::MessageReceived(BMessage *message) { switch(message->what){ case B_MOUSE_WHEEL_CHANGED: { float shift=0; if(message->FindFloat("be:wheel_delta_y",&shift)==B_OK) { if(shift>0)button = MOUSE_WHEEL_UP; if(shift<0)button = MOUSE_WHEEL_DOWN; if(shift!=0) { anyevents = mouseEvent = true; gBlock.NewEvent(); } } break; } default: BGLView::MessageReceived(message); break; } } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: FrameResized * * DESCRIPTION: handles reshape event ***********************************************************/ void GlutWindow::FrameResized(float width, float height) { BGLView::FrameResized(width, height); if (visible) { anyevents = reshapeEvent = true; m_width = (int)(width)+1; m_height = (int)(height)+1; gBlock.NewEvent(); } } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: Draw * * DESCRIPTION: handles reshape and display events ***********************************************************/ void GlutWindow::Draw(BRect updateRect) { BGLView::Draw(updateRect); BRect frame = Frame(); if (m_width != (frame.Width()+1) || m_height != (frame.Height()+1)) { FrameResized(frame.Width(), frame.Height()); } Window()->Lock(); if (visible) { anyevents = displayEvent = true; gBlock.NewEvent(); } Window()->Unlock(); } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: Pulse * * DESCRIPTION: handles mouse up event (MouseUp is broken) ***********************************************************/ void GlutWindow::Pulse() { BGLView::Pulse(); if (m_buttons) { // if there are buttons pressed MouseCheck(); } } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: ErrorCallback * * DESCRIPTION: handles GL error messages ***********************************************************/ void GlutWindow::ErrorCallback(unsigned long errorCode) { __glutWarning("GL error: %s", gluErrorString(errorCode)); } /*********************************************************** * CLASS: GlutWindow * * FUNCTION: MenuThread * * DESCRIPTION: a new thread to launch popup menu, wait * wait for response, then clean up afterwards and * send appropriate messages ***********************************************************/ status_t GlutWindow::MenuThread(void *m) { GlutPopUp *bmenu = static_cast<GlutPopUp*>(m); GlutWindow *win = bmenu->win; // my window GlutBMenuItem *result = (GlutBMenuItem*)bmenu->Go(bmenu->point); win->Window()->Lock(); win->anyevents = win->statusEvent = true; win->menuStatus = GLUT_MENU_NOT_IN_USE; win->menuNumber = bmenu->menu; BPoint cursor; uint32 buttons; win->GetMouse(&cursor, &buttons); win->statusX = (int)cursor.x; win->statusY = (int)cursor.y; if(result && result->menu) { win->menuEvent = true; win->menuNumber = result->menu; // in case it was a submenu win->menuValue = result->value; } win->Window()->Unlock(); gBlock.NewEvent(); delete bmenu; return B_OK; }
9,368
806
package com.evenwell.powersaving.g3.powersaver.function; import android.content.Context; import android.database.ContentObserver; import android.provider.Settings.System; import android.text.TextUtils; import android.util.Log; import com.evenwell.powersaving.g3.lpm.LpmUtils; import com.evenwell.powersaving.g3.utils.PSConst.LPM.LPMSPREF; import com.evenwell.powersaving.g3.utils.PSConst.SETTINGDB.LPMDB; import com.evenwell.powersaving.g3.utils.PSConst.SWITCHER; public class ScreenTimeout extends Function { private String DEFAULT_TIMEOUT; private ContentObserver mScreenTimeoutSettingObserver; private class Listener implements eventListener { private Listener() { } public void onClose() { ScreenTimeout.this.setEnable(ScreenTimeout.this.getValueFromDB()); Log.i("Function", "ScreenTimeout registerContentObserver"); ScreenTimeout.this.mContext.getContentResolver().registerContentObserver(System.getUriFor("screen_off_timeout"), true, ScreenTimeout.this.mScreenTimeoutSettingObserver); } public void onRestore() { ScreenTimeout.this.mContext.getContentResolver().unregisterContentObserver(ScreenTimeout.this.mScreenTimeoutSettingObserver); String value = ScreenTimeout.this.readFromBackFile(); if (!TextUtils.isEmpty(value)) { ScreenTimeout.this.setEnable(value); } Log.i("Function", "ScreenTimeout unregisterContentObserver"); } } private class ScreenTimeoutSettingObserver extends ContentObserver { public ScreenTimeoutSettingObserver() { super(null); } public void onChange(boolean selfChange) { String screenTimeout = LpmUtils.GetScreenTimeout(ScreenTimeout.this.mContext); Log.i("Function", "savePreference : " + ScreenTimeout.this.getRefBackUpFileKey() + " = " + screenTimeout); ScreenTimeout.this.savePreference(ScreenTimeout.this.getRefBackUpFileKey(), screenTimeout); Log.i("Function", "Screen timeout on change screenTimeout:" + screenTimeout); } } public ScreenTimeout(Context context) { super(context); this.mScreenTimeoutSettingObserver = null; this.DEFAULT_TIMEOUT = "15000"; this.mScreenTimeoutSettingObserver = new ScreenTimeoutSettingObserver(); setListener(new Listener()); } protected String getRefBackUpFileKey() { return LPMSPREF.SCREEN_TIMEOUT; } protected String getDBKey() { return LPMDB.SCREEN_TIMEOUT; } public boolean getEnabled() { return !this.isClose; } protected void setEnable(String value) { if (!value.equals(SWITCHER.KEEP)) { if (value.equals(SWITCHER.ON) || value.equals(SWITCHER.OFF)) { Log.i("Function", "skip PSConst.SWITCHER.ON and PSConst.SWITCHER.OFF"); value = this.DEFAULT_TIMEOUT; } Log.i("Function", "Timeout = " + value); try { LpmUtils.SetScreenTimeout(this.mContext, value); } catch (Exception ex) { ex.printStackTrace(); } } } public void saveCurrentStateToBackUpFile() { String key = getRefBackUpFileKey(); String value = ""; if (SWITCHER.KEEP.equals(getValueFromDB())) { value = SWITCHER.KEEP; } else { value = LpmUtils.GetScreenTimeout(this.mContext); } Log.i("Function", "savePreference : " + key + " = " + value); savePreference(key, value); } public void bootHandling(int mode) { Log.i("Function", "[ScreenTimeout]: bootHandling() mode = " + mode); if (mode != -1) { this.mContext.getContentResolver().registerContentObserver(System.getUriFor("screen_off_timeout"), true, this.mScreenTimeoutSettingObserver); } } }
1,613
6,224
<reponame>olavst-nordic/sdk-zephyr /* * Copyright (c) 2017 Intel Corporation. * Copytight (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #include <zephyr.h> #include <pm/pm.h> #include <hal/nrf_regulators.h> #include <logging/log.h> LOG_MODULE_DECLARE(soc, CONFIG_SOC_LOG_LEVEL); /* Invoke Low Power/System Off specific Tasks */ __weak void pm_power_state_set(struct pm_state_info info) { switch (info.state) { case PM_STATE_SOFT_OFF: nrf_regulators_system_off(NRF_REGULATORS); break; default: LOG_DBG("Unsupported power state %u", info.state); break; } } /* Handle SOC specific activity after Low Power Mode Exit */ __weak void pm_power_state_exit_post_ops(struct pm_state_info info) { switch (info.state) { case PM_STATE_SOFT_OFF: /* Nothing to do. */ break; default: LOG_DBG("Unsupported power state %u", info.state); break; } /* * System is now in active mode. Reenable interrupts which were disabled * when OS started idling code. */ irq_unlock(0); }
397
1,172
<gh_stars>1000+ { "latencyActive": false, "exceptionsActive": false, "killApplicationActive": false, "memoryActive": false }
54
1,272
<gh_stars>1000+ /* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <CertifiedSender/SQLiteMessageStorage.h> #include <SQLiteStorage/SQLiteStatement.h> #include <AVSCommon/Utils/File/FileUtils.h> #include <fstream> #include <queue> #include <memory> using namespace ::testing; namespace alexaClientSDK { namespace certifiedSender { namespace test { using namespace avsCommon::utils::file; /// The filename we will use for the test database file. static const std::string TEST_DATABASE_FILE_PATH = "messageStorageTestDatabase.db"; /// The path delimiter used by the OS to identify file locations. static const std::string PATH_DELIMITER = "/"; /// The full filepath to the database file we will create and delete during tests. static std::string g_dbTestFilePath; /// A test message text. static const std::string TEST_MESSAGE_ONE = "test_message_one"; /// A test message text. static const std::string TEST_MESSAGE_TWO = "test_message_two"; /// A test message text. static const std::string TEST_MESSAGE_THREE = "test_message_three"; /// A test message uri. static const std::string TEST_MESSAGE_URI = "/v20160207/events/SpeechRecognizer/Recognize"; /// The name of the alerts table. static const std::string MESSAGES_TABLE_NAME = "messages_with_uri"; /// The name of the 'id' field we will use as the primary key in our tables. static const std::string DATABASE_COLUMN_ID_NAME = "id"; /// The name of the 'message_text' field we will use as the primary key in our tables. static const std::string DATABASE_COLUMN_MESSAGE_TEXT_NAME = "message_text"; /// The name of the 'uriPathExtension' field corresponding to the uri path extension of the message. static const std::string DATABASE_COLUMN_URI = "uri"; /// The name of the 'timestamp' field is the creation time of the message. static const std::string DATABASE_COLUMN_TIMESTAMP = "timestamp"; /// The SQL string to create the alerts table. static const std::string CREATE_LEGACY_MESSAGES_TABLE_SQL_STRING = std::string("CREATE TABLE ") + MESSAGES_TABLE_NAME + " (" + DATABASE_COLUMN_ID_NAME + " INT PRIMARY KEY NOT NULL," + DATABASE_COLUMN_URI + " TEXT NOT NULL," + DATABASE_COLUMN_MESSAGE_TEXT_NAME + " TEXT NOT NULL);"; /** * A class which helps drive this unit test suite. */ class MessageStorageTest : public ::testing::Test { public: /** * Constructor. */ MessageStorageTest(); /** * Destructor. */ ~MessageStorageTest(); /** * Utility function to create the database, using the global filename. */ void createDatabase(); /** * Utility function to create legacy database that does not have timestamp column */ bool createLegacyDatabase(); /** * Utility function to cleanup the test database file, if it exists. */ void cleanupLocalDbFile(); /** * Utility function to check if the current table is legacy or not * EXPECT: 1 = DB is legacy, 0 = DB is not legacy, -1 = errors */ int isDatabaseLegacy(); /** * Utility function to insert old messages in the storage */ bool insertOldMessagesToDatabase(int id, const std::string& record_age); /** * Utility function to create old messages in the storage */ bool createOldMessages(); protected: /// The message database object we will test. std::shared_ptr<MessageStorageInterface> m_storage; std::unique_ptr<alexaClientSDK::storage::sqliteStorage::SQLiteDatabase> m_legacyDB; }; /** * Utility function to determine if the storage component is opened. * * @param storage The storage component to check. * @return True if the storage component's underlying database is opened, false otherwise. */ static bool isOpen(const std::shared_ptr<MessageStorageInterface>& storage) { std::queue<MessageStorageInterface::StoredMessage> dummyMessages; return storage->load(&dummyMessages); } MessageStorageTest::MessageStorageTest() : m_storage{std::make_shared<SQLiteMessageStorage>(g_dbTestFilePath)} { cleanupLocalDbFile(); } MessageStorageTest::~MessageStorageTest() { m_storage->close(); if (m_legacyDB) { m_legacyDB->close(); } cleanupLocalDbFile(); } void MessageStorageTest::createDatabase() { m_storage->createDatabase(); } bool MessageStorageTest::createLegacyDatabase() { m_legacyDB = std::unique_ptr<alexaClientSDK::storage::sqliteStorage::SQLiteDatabase>( new alexaClientSDK::storage::sqliteStorage::SQLiteDatabase(g_dbTestFilePath)); if (!m_legacyDB || !m_legacyDB->initialize()) { return false; } if (!m_legacyDB->performQuery(CREATE_LEGACY_MESSAGES_TABLE_SQL_STRING)) { m_legacyDB->close(); return false; } return true; } void MessageStorageTest::cleanupLocalDbFile() { if (g_dbTestFilePath.empty()) { return; } if (fileExists(g_dbTestFilePath)) { removeFile(g_dbTestFilePath.c_str()); } } int MessageStorageTest::isDatabaseLegacy() { auto sqlStatement = m_legacyDB->createStatement("PRAGMA table_info(" + MESSAGES_TABLE_NAME + ");"); if ((!sqlStatement) || (!sqlStatement->step())) { return -1; } const std::string tableInfoColumnName = "name"; std::string columnName; while (SQLITE_ROW == sqlStatement->getStepResult()) { int columnCount = sqlStatement->getColumnCount(); for (int i = 0; i < columnCount; i++) { std::string tableColumnName = sqlStatement->getColumnName(i); if (tableInfoColumnName == tableColumnName) { columnName = sqlStatement->getColumnText(i); if (DATABASE_COLUMN_TIMESTAMP == columnName) { return 0; } } } if (!sqlStatement->step()) { return -1; } } return 1; } bool MessageStorageTest::insertOldMessagesToDatabase(int id, const std::string& record_age) { if (!m_legacyDB) { return false; } std::string sqlString = std::string("INSERT INTO " + MESSAGES_TABLE_NAME + " (") + DATABASE_COLUMN_ID_NAME + ", " + DATABASE_COLUMN_URI + ", " + DATABASE_COLUMN_MESSAGE_TEXT_NAME + ", " + DATABASE_COLUMN_TIMESTAMP + ") VALUES (?, ?, ?, datetime('now', ?));"; auto statement = m_legacyDB->createStatement(sqlString); int boundParam = 1; std::string uriPathExtension = "testURI"; std::string message = "testURI"; if (!statement->bindIntParameter(boundParam++, id) || !statement->bindStringParameter(boundParam++, uriPathExtension) || !statement->bindStringParameter(boundParam++, message) || !statement->bindStringParameter(boundParam, record_age)) { return false; } if (!statement->step()) { return false; } return true; } bool MessageStorageTest::createOldMessages() { m_legacyDB = std::unique_ptr<alexaClientSDK::storage::sqliteStorage::SQLiteDatabase>( new alexaClientSDK::storage::sqliteStorage::SQLiteDatabase(g_dbTestFilePath)); m_legacyDB->open(); // Insert 60 records 1 month ago for (int id = 1; id <= 60; ++id) { if (!insertOldMessagesToDatabase(id, "-1 months")) { return false; } } // Insert 60 record at this moment for (int id = 61; id <= 120; ++id) { if (!insertOldMessagesToDatabase(id, "-0 seconds")) { return false; } } return true; } /** * Test basic construction. Database should not be open. */ TEST_F(MessageStorageTest, test_constructionAndDestruction) { EXPECT_FALSE(isOpen(m_storage)); } /** * Test database creation. */ TEST_F(MessageStorageTest, test_databaseCreation) { EXPECT_FALSE(isOpen(m_storage)); createDatabase(); EXPECT_TRUE(isOpen(m_storage)); } /** * Test opening and closing a database. */ TEST_F(MessageStorageTest, test_openAndCloseDatabase) { EXPECT_FALSE(isOpen(m_storage)); createDatabase(); EXPECT_TRUE(isOpen(m_storage)); m_storage->close(); EXPECT_FALSE(isOpen(m_storage)); EXPECT_TRUE(m_storage->open()); EXPECT_TRUE(isOpen(m_storage)); m_storage->close(); EXPECT_FALSE(isOpen(m_storage)); } /** * Test storing records in the database. */ TEST_F(MessageStorageTest, test_databaseStoreAndLoad) { createDatabase(); EXPECT_TRUE(isOpen(m_storage)); std::queue<MessageStorageInterface::StoredMessage> dbMessages; EXPECT_TRUE(m_storage->load(&dbMessages)); EXPECT_EQ(static_cast<int>(dbMessages.size()), 0); // test storing a single message first int dbId = 0; EXPECT_TRUE(m_storage->store(TEST_MESSAGE_ONE, &dbId)); EXPECT_EQ(dbId, 1); EXPECT_TRUE(m_storage->load(&dbMessages)); EXPECT_EQ(static_cast<int>(dbMessages.size()), 1); EXPECT_EQ(dbMessages.front().message, TEST_MESSAGE_ONE); dbMessages.pop(); // now store two more, and verify EXPECT_TRUE(m_storage->store(TEST_MESSAGE_TWO, &dbId)); EXPECT_EQ(dbId, 2); EXPECT_TRUE(m_storage->store(TEST_MESSAGE_THREE, &dbId)); EXPECT_EQ(dbId, 3); EXPECT_TRUE(m_storage->load(&dbMessages)); EXPECT_EQ(static_cast<int>(dbMessages.size()), 3); EXPECT_EQ(dbMessages.front().message, TEST_MESSAGE_ONE); dbMessages.pop(); EXPECT_EQ(dbMessages.front().message, TEST_MESSAGE_TWO); dbMessages.pop(); EXPECT_EQ(dbMessages.front().message, TEST_MESSAGE_THREE); } /** * Test erasing a record from the database. */ TEST_F(MessageStorageTest, test_databaseErase) { createDatabase(); EXPECT_TRUE(isOpen(m_storage)); // add three messages, and verify int dbId = 0; EXPECT_TRUE(m_storage->store(TEST_MESSAGE_ONE, &dbId)); EXPECT_TRUE(m_storage->store(TEST_MESSAGE_TWO, &dbId)); EXPECT_TRUE(m_storage->store(TEST_MESSAGE_THREE, &dbId)); std::queue<MessageStorageInterface::StoredMessage> dbMessages; EXPECT_TRUE(m_storage->load(&dbMessages)); EXPECT_EQ(static_cast<int>(dbMessages.size()), 3); EXPECT_EQ(dbMessages.front().message, TEST_MESSAGE_ONE); // erase the first one, then verify it's gone from db EXPECT_TRUE(m_storage->erase(dbMessages.front().id)); while (!dbMessages.empty()) { dbMessages.pop(); } EXPECT_TRUE(m_storage->load(&dbMessages)); EXPECT_EQ(static_cast<int>(dbMessages.size()), 2); EXPECT_EQ(dbMessages.front().message, TEST_MESSAGE_TWO); dbMessages.pop(); EXPECT_EQ(dbMessages.front().message, TEST_MESSAGE_THREE); } /** * Test clearing the database. */ TEST_F(MessageStorageTest, test_databaseClear) { createDatabase(); EXPECT_TRUE(isOpen(m_storage)); int dbId = 0; EXPECT_TRUE(m_storage->store(TEST_MESSAGE_ONE, &dbId)); EXPECT_TRUE(m_storage->store(TEST_MESSAGE_TWO, &dbId)); EXPECT_TRUE(m_storage->store(TEST_MESSAGE_THREE, &dbId)); std::queue<MessageStorageInterface::StoredMessage> dbMessages; EXPECT_TRUE(m_storage->load(&dbMessages)); EXPECT_EQ(static_cast<int>(dbMessages.size()), 3); while (!dbMessages.empty()) { dbMessages.pop(); } EXPECT_TRUE(m_storage->clearDatabase()); EXPECT_TRUE(m_storage->load(&dbMessages)); EXPECT_EQ(static_cast<int>(dbMessages.size()), 0); } /** * Test storing records with URI in the database. */ TEST_F(MessageStorageTest, test_DatabaseStoreAndLoadWithURI) { createDatabase(); EXPECT_TRUE(isOpen(m_storage)); std::queue<MessageStorageInterface::StoredMessage> dbMessages; EXPECT_TRUE(m_storage->load(&dbMessages)); EXPECT_EQ(static_cast<int>(dbMessages.size()), 0); int dbId = 0; EXPECT_TRUE(m_storage->store(TEST_MESSAGE_ONE, TEST_MESSAGE_URI, &dbId)); EXPECT_EQ(dbId, 1); EXPECT_TRUE(m_storage->load(&dbMessages)); EXPECT_EQ(dbMessages.front().message, TEST_MESSAGE_ONE); EXPECT_EQ(dbMessages.front().uriPathExtension, TEST_MESSAGE_URI); } /** * Test legacy database */ TEST_F(MessageStorageTest, test_LegacyDatabase) { EXPECT_TRUE(createLegacyDatabase()); EXPECT_EQ(isDatabaseLegacy(), 1); // Perform opening it to change it to new database // and check if it is legacy and it works EXPECT_TRUE(m_storage->open()); EXPECT_TRUE(isOpen(m_storage)); EXPECT_EQ(isDatabaseLegacy(), 0); // Close it and check the file m_storage->close(); EXPECT_FALSE(isOpen(m_storage)); } /** * Test erase legacy message */ TEST_F(MessageStorageTest, test_EraseMessageOverAgeAndSizeLimit) { createDatabase(); // Create old messages over age and database size limit EXPECT_TRUE(createOldMessages()); std::queue<MessageStorageInterface::StoredMessage> dbMessagesBefore; EXPECT_TRUE(m_storage->load(&dbMessagesBefore)); EXPECT_EQ(static_cast<int>(dbMessagesBefore.size()), 120); // The mocking database opens and deletes over age and size limit m_storage->close(); EXPECT_TRUE(m_storage->open()); EXPECT_TRUE(isOpen(m_storage)); std::queue<MessageStorageInterface::StoredMessage> dbMessagesAfter; EXPECT_TRUE(m_storage->load(&dbMessagesAfter)); // eraseMessageOverAgeLimit() takes out the first 60 inserted 1 month ago // eraseMessageOverSizeLimit() takes out the next 35 messages EXPECT_EQ(static_cast<int>(dbMessagesAfter.size()), 25); for (int id = 96; id <= 120; ++id) { EXPECT_EQ(static_cast<int>(dbMessagesAfter.front().id), id); dbMessagesAfter.pop(); } EXPECT_EQ(static_cast<int>(dbMessagesAfter.size()), 0); } } // namespace test } // namespace certifiedSender } // namespace alexaClientSDK int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); if (argc < 2) { std::cerr << "USAGE: " << std::string(argv[0]) << " <path_to_test_directory_location>" << std::endl; return 1; } else { alexaClientSDK::certifiedSender::test::g_dbTestFilePath = std::string(argv[1]) + alexaClientSDK::certifiedSender::test::PATH_DELIMITER + alexaClientSDK::certifiedSender::test::TEST_DATABASE_FILE_PATH; return RUN_ALL_TESTS(); } }
5,614
376
package ru.atom.exception; public class BaseException extends Exception { public BaseException(String message) { super("BaseException: " + message); } }
53
6,238
from vibora import Vibora, TestSuite from vibora.blueprints import Blueprint from vibora.responses import JsonResponse class RouterPrefixesTestCase(TestSuite): async def test_root_route_expect_registered(self): data = {'hello': 'world'} app = Vibora() @app.route('/test', methods=['GET']) async def home(): return JsonResponse(data) response = await app.test_client().request('/test/') self.assertEqual(response.json(), data) async def test_root_route_expect_not_found(self): app = Vibora() response = await app.test_client().request('/test') self.assertEqual(response.status_code, 404) async def test_add_blueprint_with_one_prefix(self): data, app = {'hello': 'world'}, Vibora() bp = Blueprint() @bp.route('/') async def home(): return JsonResponse(data) app.add_blueprint(bp, prefixes={'test': '/test'}) response = await app.test_client().request('/test') self.assertEqual(response.json(), data)
445
348
{"nom":"Saint-Denis-les-Ponts","circ":"4ème circonscription","dpt":"Eure-et-Loir","inscrits":1341,"abs":631,"votants":710,"blancs":42,"nuls":17,"exp":651,"res":[{"nuance":"UDI","nom":"<NAME>","voix":444},{"nuance":"REM","nom":"<NAME>","voix":207}]}
102
3,579
package com.querydsl.apt.domain; import org.junit.Test; import com.querydsl.core.annotations.QueryEntity; import com.querydsl.core.annotations.QuerySupertype; public class RawTest { @QuerySupertype public static class SuperClass<T extends Comparable<T>> { public String property; } @SuppressWarnings("rawtypes") @QueryEntity public static class Entity extends SuperClass { public String property2; } @Test public void test() { } }
180
332
<filename>src/frontends/lean/decl_cmds.h /* Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: <NAME> */ #pragma once #include "util/buffer.h" #include "kernel/expr.h" #include "frontends/lean/cmd_table.h" namespace lean { class parser; /** \brief Parse (optional) universe parameters <tt>'.{' l_1 ... l_k '}'</tt> Store the result in \c ps. Return true when levels were provided. */ ast_id parse_univ_params(parser & p, buffer<name> & ps); /** \brief Add universe levels from \c found_ls to \c ls_buffer (only the levels that do not already occur in \c ls_buffer are added). Then sort \c ls_buffer (using the order in which the universe levels were declared). */ void update_univ_parameters(buffer<name> & ls_buffer, name_set const & found_ls, parser const & p); /** \brief Parse a local attribute command */ environment local_attribute_cmd(parser & p, ast_id & cmd_id, cmd_meta const & meta); void register_decl_cmds(cmd_table & r); void initialize_decl_cmds(); void finalize_decl_cmds(); }
361
2,539
// Windows/MemoryLock.cpp #include "StdAfx.h" #include "../../C/CpuArch.h" #include "MemoryLock.h" namespace NWindows { namespace NSecurity { #ifndef UNDER_CE #ifdef _UNICODE #define MY_FUNC_SELECT(f) :: f #else #define MY_FUNC_SELECT(f) my_ ## f extern "C" { typedef BOOL (WINAPI * Func_OpenProcessToken)(HANDLE ProcessHandle, DWORD DesiredAccess, PHANDLE TokenHandle); typedef BOOL (WINAPI * Func_LookupPrivilegeValue)(LPCTSTR lpSystemName, LPCTSTR lpName, PLUID lpLuid); typedef BOOL (WINAPI * Func_AdjustTokenPrivileges)(HANDLE TokenHandle, BOOL DisableAllPrivileges, PTOKEN_PRIVILEGES NewState, DWORD BufferLength, PTOKEN_PRIVILEGES PreviousState, PDWORD ReturnLength); } #define GET_PROC_ADDR(fff, name) Func_ ## fff my_ ## fff = (Func_ ## fff)GetProcAddress(hModule, name) #endif bool EnablePrivilege(LPCTSTR privilegeName, bool enable) { bool res = false; #ifndef _UNICODE HMODULE hModule = ::LoadLibrary(TEXT("Advapi32.dll")); if (hModule == NULL) return false; GET_PROC_ADDR(OpenProcessToken, "OpenProcessToken"); GET_PROC_ADDR(LookupPrivilegeValue, "LookupPrivilegeValueA"); GET_PROC_ADDR(AdjustTokenPrivileges, "AdjustTokenPrivileges"); if (my_OpenProcessToken && my_AdjustTokenPrivileges && my_LookupPrivilegeValue) #endif { HANDLE token; if (MY_FUNC_SELECT(OpenProcessToken)(::GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token)) { TOKEN_PRIVILEGES tp; if (MY_FUNC_SELECT(LookupPrivilegeValue)(NULL, privilegeName, &(tp.Privileges[0].Luid))) { tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = (enable ? SE_PRIVILEGE_ENABLED : 0); if (MY_FUNC_SELECT(AdjustTokenPrivileges)(token, FALSE, &tp, 0, NULL, NULL)) res = (GetLastError() == ERROR_SUCCESS); } ::CloseHandle(token); } } #ifndef _UNICODE ::FreeLibrary(hModule); #endif return res; } typedef void (WINAPI * Func_RtlGetVersion) (OSVERSIONINFOEXW *); /* We suppose that Window 10 works incorrectly with "Large Pages" at: - Windows 10 1703 (15063) : incorrect allocating after VirtualFree() - Windows 10 1709 (16299) : incorrect allocating after VirtualFree() - Windows 10 1809 (17763) : the failures for blocks of 1 GiB and larger, if CPU doesn't support 1 GB pages. Windows 10 1903 (18362) probably works correctly. */ unsigned Get_LargePages_RiskLevel() { OSVERSIONINFOEXW vi; HMODULE ntdll = ::GetModuleHandleW(L"ntdll.dll"); if (!ntdll) return 0; Func_RtlGetVersion func = (Func_RtlGetVersion)(void *)GetProcAddress(ntdll, "RtlGetVersion"); if (!func) return 0; func(&vi); if (vi.dwPlatformId != VER_PLATFORM_WIN32_NT) return 0; if (vi.dwMajorVersion + vi.dwMinorVersion != 10) return 0; if (vi.dwBuildNumber <= 16299) return 1; #ifdef MY_CPU_X86_OR_AMD64 if (vi.dwBuildNumber < 18362 && !CPU_IsSupported_PageGB()) return 1; #endif return 0; } #endif }}
1,219
14,668
// 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. package org.chromium.chrome.browser.settings; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.test.InstrumentationRegistry; import android.support.test.runner.lifecycle.Stage; import androidx.fragment.app.Fragment; import org.junit.Assert; import org.chromium.base.test.BaseActivityTestRule; import org.chromium.base.test.util.ApplicationTestUtils; import org.chromium.components.browser_ui.settings.SettingsLauncher; /** * Activity test rule that launch {@link SettingsActivity} in tests. * * Noting that the activity is not starting after the test rule created. The user have to call * {@link #startSettingsActivity()} explicitly to launch the settings activity. * * @param <T> Fragment that will be attached to the SettingsActivity. */ public class SettingsActivityTestRule<T extends Fragment> extends BaseActivityTestRule<SettingsActivity> { private final Class<T> mFragmentClass; /** * Create the settings activity test rule with an specific fragment class. * @param fragmentClass Fragment that will be attached after the activity starts. */ public SettingsActivityTestRule(Class<T> fragmentClass) { super(SettingsActivity.class); mFragmentClass = fragmentClass; } /** * Launches the settings activity with the specified fragment. * @return The activity that just started. */ public SettingsActivity startSettingsActivity() { return startSettingsActivity(null); } /** * Launches the settings activity with the specified fragment and arguments. * @param fragmentArgs A bundle of additional fragment arguments. * @return The activity that just started. */ public SettingsActivity startSettingsActivity(Bundle fragmentArgs) { Context context = InstrumentationRegistry.getTargetContext(); SettingsLauncher settingsLauncher = new SettingsLauncherImpl(); Intent intent = settingsLauncher.createSettingsActivityIntent( context, mFragmentClass.getName(), fragmentArgs); launchActivity(intent); ApplicationTestUtils.waitForActivityState(getActivity(), Stage.RESUMED); return getActivity(); } /** * @return The fragment attached to the SettingsActivity. */ public T getFragment() { Assert.assertNotNull("#getFragment is called before activity launch.", getActivity()); Fragment fragment = getActivity().getMainFragment(); Assert.assertNotNull(fragment); return (T) fragment; } }
848
3,973
<filename>felix/bpf-gpl/policy.h // Project Calico BPF dataplane programs. // Copyright (c) 2020-2021 Tigera, Inc. All rights reserved. // SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later #ifndef __CALI_POLICY_H__ #define __CALI_POLICY_H__ enum calico_policy_result { CALI_POL_NO_MATCH, CALI_POL_ALLOW, CALI_POL_DENY, }; struct port_range { __u64 ip_set_id; __u16 min, max; }; struct cidr { __be32 mask, addr; }; // IP sets, all stored in one big map with a prefix to identify the set. // WARNING: must be kept in sync with the definitions in bpf/polprog/pol_prog_builder.go. // WARNING: must be kept in sync with the definitions in bpf/ipsets/map.go. struct ip4_set_key { __u32 mask; __be64 set_id; __be32 addr; __u16 port; __u8 protocol; __u8 pad; } __attribute__((packed)); union ip4_set_lpm_key { struct bpf_lpm_trie_key lpm; struct ip4_set_key ip; }; struct bpf_map_def_extended __attribute__((section("maps"))) cali_v4_ip_sets = { .type = BPF_MAP_TYPE_LPM_TRIE, .key_size = sizeof(union ip4_set_lpm_key), .value_size = sizeof(__u32), .max_entries = 1024*1024, .map_flags = BPF_F_NO_PREALLOC, #if !defined(__BPFTOOL_LOADER__) && defined(__IPTOOL_LOADER__) .pinning_strategy = MAP_PIN_GLOBAL, #endif }; #define RULE_START(id) \ CALI_DEBUG("Rule " #id " \n"); #define RULE_END(id, action) \ CALI_DEBUG(" MATCH -> " #action "\n"); \ goto action; /* Reach here if the rule matched. */ \ rule_no_match_ ## id: do {;} while (false) #endif /* __CALI_POLICY_H__ */
702
348
<reponame>chamberone/Leaflet.PixiOverlay {"nom":"<NAME>","circ":"6ème circonscription","dpt":"Seine-Maritime","inscrits":3864,"abs":1986,"votants":1878,"blancs":37,"nuls":9,"exp":1832,"res":[{"nuance":"COM","nom":"<NAME>","voix":834},{"nuance":"FN","nom":"M. <NAME>","voix":417},{"nuance":"REM","nom":"<NAME>","voix":320},{"nuance":"SOC","nom":"Mme <NAME>","voix":128},{"nuance":"UDI","nom":"Mme <NAME>","voix":80},{"nuance":"EXG","nom":"M. <NAME>","voix":29},{"nuance":"DIV","nom":"<NAME>","voix":15},{"nuance":"DVG","nom":"M. <NAME>","voix":9}]}
224
384
<reponame>WanEnNg/mmcv import os.path as osp import tempfile import warnings def test_save_checkpoint(): try: import torch import torch.nn as nn except ImportError: warnings.warn('Skipping test_save_checkpoint in the absense of torch') return import mmcv.runner model = nn.Linear(1, 1) runner = mmcv.runner.Runner(model=model, batch_processor=lambda x: x) with tempfile.TemporaryDirectory() as root: runner.save_checkpoint(root) latest_path = osp.join(root, 'latest.pth') epoch1_path = osp.join(root, 'epoch_1.pth') assert osp.exists(latest_path) assert osp.exists(epoch1_path) assert osp.realpath(latest_path) == epoch1_path torch.load(latest_path)
331
441
package org.basex.query.func.java; import static org.basex.query.value.type.AtomType.*; import static org.basex.query.value.type.NodeType.*; import java.math.*; import java.net.*; import java.util.*; import javax.xml.namespace.*; import org.basex.query.value.array.*; import org.basex.query.value.item.*; import org.basex.query.value.map.*; import org.basex.query.value.node.*; import org.basex.query.value.type.*; import org.basex.util.*; import org.w3c.dom.*; /** * Pre-defined Java/XQuery type mappings. * * @author BaseX Team 2005-21, BSD License * @author <NAME> */ @SuppressWarnings({ "rawtypes", "unchecked" }) final class JavaMapping { /** Private constructor. */ private JavaMapping() { } /** Atomic mappings. */ private static final HashMap<Class<?>, Type> ATOMIC_MAP = new HashMap<>(); /** XQuery mappings. */ private static final HashMap<Class<?>, Type> XQUERY_MAP = new HashMap<>(); /** Pairs with simple type conversions. */ private static final Pair[] ATOMIC = { new Pair(BigDecimal.class, DECIMAL), new Pair(BigInteger.class, UNSIGNED_LONG), new Pair(boolean.class, BOOLEAN), new Pair(Boolean.class, BOOLEAN), new Pair(byte.class, BYTE), new Pair(Byte.class, BYTE), new Pair(char.class, UNSIGNED_SHORT), new Pair(Character.class, UNSIGNED_SHORT), new Pair(double.class, DOUBLE), new Pair(Double.class, DOUBLE), new Pair(float.class, FLOAT), new Pair(Float.class, FLOAT), new Pair(int.class, INT), new Pair(Integer.class, INT), new Pair(long.class, INTEGER), new Pair(Long.class, INTEGER), new Pair(QName.class, QNAME), new Pair(short.class, SHORT), new Pair(Short.class, SHORT), new Pair(String.class, STRING), new Pair(URI.class, ANY_URI), new Pair(URL.class, ANY_URI), }; /** Node pairs. */ private static final Pair[] NODES = { new Pair(Attr.class, ATTRIBUTE), new Pair(Comment.class, COMMENT), new Pair(Document.class, DOCUMENT_NODE), new Pair(DocumentFragment.class, DOCUMENT_NODE), new Pair(Element.class, ELEMENT), new Pair(Node.class, NODE), new Pair(ProcessingInstruction.class, PROCESSING_INSTRUCTION), new Pair(Text.class, TEXT), }; /** XQuery pairs (no conversion required). */ private static final Pair[] XQUERY = { // atomic types new Pair(ANum.class, NUMERIC), new Pair(Atm.class, UNTYPED_ATOMIC), new Pair(B64.class, BASE64_BINARY), new Pair(Bln.class, BOOLEAN), new Pair(Dat.class, DATE), new Pair(Dbl.class, DOUBLE), new Pair(Dec.class, DECIMAL), new Pair(DTDur.class, DAY_TIME_DURATION), new Pair(Dtm.class, DATE_TIME), new Pair(Dur.class, DURATION), new Pair(Flt.class, FLOAT), new Pair(Hex.class, HEX_BINARY), new Pair(Int.class, INTEGER), new Pair(Item.class, ITEM), new Pair(QNm.class, QNAME), new Pair(Str.class, STRING), new Pair(Tim.class, TIME), new Pair(Uri.class, ANY_URI), new Pair(YMDur.class, YEAR_MONTH_DURATION), // node types new Pair(ANode.class, NODE), new Pair(DBNode.class, NODE), new Pair(FAttr.class, ATTRIBUTE), new Pair(FComm.class, COMMENT), new Pair(FDoc.class, DOCUMENT_NODE), new Pair(FElem.class, ELEMENT), new Pair(FNode.class, NODE), new Pair(FNSpace.class, NAMESPACE_NODE), new Pair(FPI.class, PROCESSING_INSTRUCTION), new Pair(FTxt.class, TEXT), // function types new Pair(XQArray.class, SeqType.ARRAY), new Pair(XQMap.class, SeqType.MAP), }; static { for(final Pair<Class<?>, Type> pair : ATOMIC) ATOMIC_MAP.put(pair.name(), pair.value()); for(final Pair<Class<?>, Type> pair : XQUERY) XQUERY_MAP.put(pair.name(), pair.value()); } /** * Returns an appropriate XQuery type for the specified Java class. * @param clazz Java class * @param atomic only check atomic mappings * @return type or {@code null} */ static Type type(final Class<?> clazz, final boolean atomic) { Type type = ATOMIC_MAP.get(clazz); if(type == null && !atomic) { type = XQUERY_MAP.get(clazz); if(type == null) type = nodeType(clazz); } return type; } /** * Returns an appropriate XQuery node type for the specified Java class. * @param clazz Java class * @return type or {@code null} */ private static Type nodeType(final Class<?> clazz) { for(final Pair<Class<?>, Type> pair : NODES) { if(pair.name().isInstance(clazz)) return pair.value(); } return null; } }
1,778
852
<reponame>ckamtsikis/cmssw<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) ) readFiles = cms.untracked.vstring() secFiles = cms.untracked.vstring() source = cms.Source ("PoolSource",fileNames = readFiles, secondaryFileNames = secFiles) readFiles.extend( [ '/store/caf/user/cschomak/wlnu/wlnu1.root', '/store/caf/user/cschomak/wlnu/wlnu2.root', '/store/caf/user/cschomak/wlnu/wlnu3.root', '/store/caf/user/cschomak/wlnu/wlnu4.root', '/store/caf/user/cschomak/wlnu/wlnu5.root', '/store/caf/user/cschomak/wlnu/wlnu6.root', '/store/caf/user/cschomak/wlnu/wlnu7.root', '/store/caf/user/cschomak/wlnu/wlnu8.root', '/store/caf/user/cschomak/wlnu/wlnu9.root', ]); secFiles.extend( [ ] )
440
1,682
<gh_stars>1000+ /* Copyright (c) 2018 LinkedIn Corp. 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.linkedin.entitystream; /** * A Connector reads data from one {@link EntityStream}, process it, and writes it to another {@link EntityStream}. * * @param <T> The type of the data that is read. * @param <R> The type of the data that is written. */ public interface Connector<T, R> extends Reader<T>, Writer<R> { }
270
2,206
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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 * ***************************************************************************** */ package org.datavec.api.records.reader.impl; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class TestDb { public static void dropTables(Connection conn) { try { Statement stmt = conn.createStatement(); try { stmt.execute("DROP TABLE Coffee"); stmt.execute("DROP TABLE AllTypes"); } catch (SQLException ex) { } } catch (SQLException ex) { System.out.println("ERROR: " + ex.getMessage()); ex.printStackTrace(); } } /** * The buildCoffeeTable method creates the Coffee table and adds some rows to it. */ public static void buildCoffeeTable(Connection conn) { try { // Get a Statement object. Statement stmt = conn.createStatement(); // Create the table. stmt.execute("CREATE TABLE Coffee (" + "Description CHAR(25), " + "ProdNum CHAR(10) NOT NULL PRIMARY KEY, " + "Price DOUBLE " + ")"); // Insert row #1. stmt.execute("INSERT INTO Coffee VALUES ( " + "'Bolivian Dark', " + "'14-001', " + "8.95 )"); // Insert row #1. stmt.execute("INSERT INTO Coffee VALUES ( " + "'Bolivian Medium', " + "'14-002', " + "8.95 )"); } catch (SQLException ex) { System.out.println("ERROR: " + ex.getMessage()); ex.printStackTrace(); } } public static void buildAllTypesTable(Connection conn) { try { Statement stmt = conn.createStatement(); stmt.execute("CREATE TABLE AllTypes " + "(" + " boolCol BOOLEAN," + " dateCol DATE," + " timeCol TIME," + " timeStampCol TIMESTAMP," + " charCol CHAR," + " longVarCharCol LONG VARCHAR," + " varCharCol VARCHAR(50)," + " floatCol FLOAT," + " realCol REAL," + " decimalCol DECIMAL," + " numericCol NUMERIC," + " doubleCol DOUBLE," + " integerCol INTEGER," + " smallIntCol SMALLINT," + " bitIntCol BIGINT" + ")"); stmt.execute( "INSERT INTO AllTypes (" + "BOOLCOL, DATECOL, TIMECOL, TIMESTAMPCOL, " + "CHARCOL, LONGVARCHARCOL, VARCHARCOL, " + "FLOATCOL, REALCOL, DECIMALCOL, NUMERICCOL, DOUBLECOL, " + "INTEGERCOL, SMALLINTCOL, BITINTCOL) " + "VALUES (TRUE, '2017-08-08', '12:21:05', '2017-08-08 14:24:22.899000000', " + "'A', 'TEST LONGVARCHAR', 'TEST VARCHAR', " + "0.55, 0.5555556, 0, 0, 0.5555555555555556, " + "555555555, 5, 555555555555555555)"); } catch (SQLException ex) { System.out.println("ERROR: " + ex.getMessage()); } } }
1,865
14,668
<reponame>zealoussnow/chromium // Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_GFX_MOJOM_HDR_METADATA_MOJOM_TRAITS_H_ #define UI_GFX_MOJOM_HDR_METADATA_MOJOM_TRAITS_H_ #include "ui/gfx/hdr_metadata.h" #include "ui/gfx/mojom/hdr_metadata.mojom.h" namespace mojo { template <> struct StructTraits<gfx::mojom::ColorVolumeMetadataDataView, gfx::ColorVolumeMetadata> { static const gfx::PointF& primary_r(const gfx::ColorVolumeMetadata& input) { return input.primary_r; } static const gfx::PointF& primary_g(const gfx::ColorVolumeMetadata& input) { return input.primary_g; } static const gfx::PointF& primary_b(const gfx::ColorVolumeMetadata& input) { return input.primary_b; } static const gfx::PointF& white_point(const gfx::ColorVolumeMetadata& input) { return input.white_point; } static float luminance_max(const gfx::ColorVolumeMetadata& input) { return input.luminance_max; } static float luminance_min(const gfx::ColorVolumeMetadata& input) { return input.luminance_min; } static bool Read(gfx::mojom::ColorVolumeMetadataDataView data, gfx::ColorVolumeMetadata* output); }; template <> struct StructTraits<gfx::mojom::HDRMetadataDataView, gfx::HDRMetadata> { static unsigned max_content_light_level(const gfx::HDRMetadata& input) { return input.max_content_light_level; } static unsigned max_frame_average_light_level(const gfx::HDRMetadata& input) { return input.max_frame_average_light_level; } static const gfx::ColorVolumeMetadata& color_volume_metadata( const gfx::HDRMetadata& input) { return input.color_volume_metadata; } static bool Read(gfx::mojom::HDRMetadataDataView data, gfx::HDRMetadata* output); }; } // namespace mojo #endif // UI_GFX_MOJOM_HDR_METADATA_MOJOM_TRAITS_H_
769
776
<reponame>Diffblue-benchmarks/actframework<filename>legacy-testapp/src/test/java/testapp/endpoint/SimpleEventListenerMarkerTest.java package testapp.endpoint; import org.junit.Test; import java.io.IOException; public class SimpleEventListenerMarkerTest extends EndpointTester { @Test public void test() throws IOException { url("/event/custom_marker").get(); checkRespCode(); } }
146
1,664
<reponame>samyzh/ambari /* * 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.ambari.server.security.authentication.jwt; import static org.apache.ambari.server.configuration.AmbariServerConfigurationCategory.SSO_CONFIGURATION; import java.util.Collection; import org.apache.ambari.server.configuration.AmbariServerConfigurationProvider; import org.apache.ambari.server.events.publishers.AmbariEventPublisher; import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.persist.jpa.AmbariJpaPersistService; /** * JwtAuthenticationPropertiesProvider manages a {@link JwtAuthenticationProperties} instance by * lazily loading the properties if needed and refreshing the properties if updates are made to the * sso-configuration category of the Ambari configuration data. * <p> * The {@link JwtAuthenticationProperties} are updated upon events received from the {@link AmbariEventPublisher}. */ @Singleton public class JwtAuthenticationPropertiesProvider extends AmbariServerConfigurationProvider<JwtAuthenticationProperties> { @Inject public JwtAuthenticationPropertiesProvider(AmbariEventPublisher ambariEventPublisher, AmbariJpaPersistService ambariJpaPersistService) { super(SSO_CONFIGURATION, ambariEventPublisher, ambariJpaPersistService); } /** * Creates a JwtAuthenticationProperties from a list of {@link AmbariConfigurationEntity}s. * * @param configurationEntities a list of {@link AmbariConfigurationEntity}s * @return a filled in {@link JwtAuthenticationProperties} */ @Override protected JwtAuthenticationProperties loadInstance(Collection<AmbariConfigurationEntity> configurationEntities) { return new JwtAuthenticationProperties(toProperties(configurationEntities)); } }
706
14,668
<filename>chromeos/network/onc/onc_normalizer_fuzzer.cc // Copyright 2021 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 <stddef.h> #include <stdint.h> #include "base/json/json_reader.h" #include "base/strings/string_piece.h" #include "base/values.h" #include "chromeos/components/onc/onc_signature.h" #include "chromeos/network/onc/onc_normalizer.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace chromeos { namespace onc { // Fuzzer for methods of the `Normalizer` class. extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { absl::optional<base::Value> parsed_json = base::JSONReader::Read( base::StringPiece(reinterpret_cast<const char*>(data), size)); if (!parsed_json || !parsed_json->is_dict()) return 0; for (bool remove_recommended_fields : {false, true}) { Normalizer normalizer(remove_recommended_fields); normalizer.NormalizeObject(&kNetworkConfigurationSignature, *parsed_json); } return 0; } } // namespace onc } // namespace chromeos
404
14,668
<reponame>zealoussnow/chromium // 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. #ifndef IOS_CHROME_BROWSER_UI_AUTHENTICATION_CELLS_TABLE_VIEW_ACCOUNT_ITEM_H_ #define IOS_CHROME_BROWSER_UI_AUTHENTICATION_CELLS_TABLE_VIEW_ACCOUNT_ITEM_H_ #import <UIKit/UIKit.h> #import "ios/chrome/browser/ui/table_view/cells/table_view_item.h" @class ChromeIdentity; typedef NS_ENUM(NSInteger, TableViewAccountMode) { // The cell can be tappable, and the colors are not dimmed. TableViewAccountModeEnabled, // The cell is not tappable, and the colors are not dimmed. TableViewAccountModeNonTappable, // The cell is not tappable, and the colors are dimmed. TableViewAccountModeDisabled, }; // Item for account avatar, used everywhere an account cell is shown. @interface TableViewAccountItem : TableViewItem @property(nonatomic, strong) UIImage* image; @property(nonatomic, copy) NSString* text; @property(nonatomic, copy) NSString* detailText; @property(nonatomic, assign) BOOL shouldDisplayError; @property(nonatomic, strong) ChromeIdentity* chromeIdentity; // The default value is TableViewAccountModeEnabled. @property(nonatomic, assign) TableViewAccountMode mode; @end // Cell for account avatar with a leading avatar imageView, title text label, // and detail text label. This looks very similar to the // TableViewDetailCell, except that it applies a circular mask to the // imageView. The imageView is vertical-centered and leading aligned. // If item/cell is disabled the image and text alpha will be set to 0.5 and // user interaction will be disabled. @interface TableViewAccountCell : TableViewCell // Rounded image used for the account user picture. @property(nonatomic, readonly, strong) UIImageView* imageView; // Cell title. @property(nonatomic, readonly, strong) UILabel* textLabel; // Cell subtitle. @property(nonatomic, readonly, strong) UILabel* detailTextLabel; // Error icon that will be displayed on the left side of the cell. @property(nonatomic, readonly, strong) UIImageView* errorIcon; @end #endif // IOS_CHROME_BROWSER_UI_AUTHENTICATION_CELLS_TABLE_VIEW_ACCOUNT_ITEM_H_
682
306
<filename>warp/tests/test_mesh_query_ray.py # Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved. # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # include parent path import numpy as np import math import warp as wp from warp.tests.test_base import * np.random.seed(42) wp.init() # triangulate a list of polygon face indices def triangulate(face_counts, face_indices): num_tris = np.sum(np.subtract(face_counts, 2)) num_tri_vtx = num_tris * 3 tri_indices = np.zeros(num_tri_vtx, dtype=int) ctr = 0 wedgeIdx = 0 for nb in face_counts: for i in range(nb-2): tri_indices[ctr] = face_indices[wedgeIdx] tri_indices[ctr + 1] = face_indices[wedgeIdx + i + 1] tri_indices[ctr + 2] = face_indices[wedgeIdx + i + 2] ctr+=3 wedgeIdx+=nb return tri_indices @wp.kernel def mesh_query_ray_loss(mesh: wp.uint64, query_points: wp.array(dtype=wp.vec3), query_dirs: wp.array(dtype=wp.vec3), intersection_points: wp.array(dtype=wp.vec3), loss: wp.array(dtype=float)): tid = wp.tid() p = query_points[tid] D = query_dirs[tid] max_t = 10012.0 t = float(0.0) bary_u = float(0.0) bary_v = float(0.0) sign = float(0.0) normal = wp.vec3() face_index = int(0) q = wp.vec3() if wp.mesh_query_ray(mesh, p, D, max_t, t, bary_u, bary_v, sign, normal, face_index): q = wp.mesh_eval_position(mesh, face_index, bary_u, bary_v) intersection_points[tid] = q l = q[0] loss[tid] = l def test_adj_mesh_query_ray(test, device): from pxr import Usd, UsdGeom, Gf, Sdf # test tri # print("Testing Single Triangle") # mesh_points = wp.array(np.array([[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [0.0, 2.0, 0.0]]), dtype=wp.vec3, device=device) # mesh_indices = wp.array(np.array([0,1,2]), dtype=int, device=device) mesh = Usd.Stage.Open(os.path.abspath(os.path.join(os.path.dirname(__file__), "assets/torus.usda"))) mesh_geom = UsdGeom.Mesh(mesh.GetPrimAtPath("/World/Torus")) mesh_counts = mesh_geom.GetFaceVertexCountsAttr().Get() mesh_indices = mesh_geom.GetFaceVertexIndicesAttr().Get() tri_indices = triangulate(mesh_counts, mesh_indices) mesh_points = wp.array(np.array(mesh_geom.GetPointsAttr().Get()), dtype=wp.vec3, device=device) mesh_indices = wp.array(np.array(tri_indices), dtype=int, device=device) p = wp.vec3(50.0, 50.0, 0.0) D = wp.vec3(0.0, -1.0, 0.0) # create mesh mesh = wp.Mesh( points=mesh_points, velocities=None, indices=mesh_indices) tape = wp.Tape() # analytic gradients with tape: query_points = wp.array(p, dtype=wp.vec3, device=device, requires_grad=True) query_dirs = wp.array(D, dtype=wp.vec3, device=device, requires_grad=True) intersection_points = wp.zeros(n=1, dtype=wp.vec3, device=device) loss = wp.zeros(n=1, dtype=float, device=device, requires_grad=True) wp.launch(kernel=mesh_query_ray_loss, dim=1, inputs=[mesh.id, query_points, query_dirs, intersection_points, loss], device=device) tape.backward(loss=loss) q = intersection_points.numpy().flatten() analytic_p = tape.gradients[query_points].numpy().flatten() analytic_D = tape.gradients[query_dirs].numpy().flatten() # numeric gradients # ray origin eps = 1.e-3 loss_values_p = [] numeric_p = np.zeros(3) offset_query_points = [ wp.vec3(p[0] - eps, p[1], p[2]), wp.vec3(p[0] + eps, p[1], p[2]), wp.vec3(p[0], p[1] - eps, p[2]), wp.vec3(p[0], p[1] + eps, p[2]), wp.vec3(p[0], p[1], p[2] - eps), wp.vec3(p[0], p[1], p[2] + eps)] for i in range(6): q = offset_query_points[i] query_points = wp.array(q, dtype=wp.vec3, device=device) query_dirs = wp.array(D, dtype=wp.vec3, device=device) intersection_points = wp.zeros(n=1, dtype=wp.vec3, device=device) loss = wp.zeros(n=1, dtype=float, device=device) wp.launch(kernel=mesh_query_ray_loss, dim=1, inputs=[mesh.id, query_points, query_dirs, intersection_points, loss], device=device) loss_values_p.append(loss.numpy()[0]) for i in range(3): l_0 = loss_values_p[i*2] l_1 = loss_values_p[i*2+1] gradient = (l_1 - l_0) / (2.0*eps) numeric_p[i] = gradient # ray dir loss_values_D = [] numeric_D = np.zeros(3) offset_query_dirs = [ wp.vec3(D[0] - eps, D[1], D[2]), wp.vec3(D[0] + eps, D[1], D[2]), wp.vec3(D[0], D[1] - eps, D[2]), wp.vec3(D[0], D[1] + eps, D[2]), wp.vec3(D[0], D[1], D[2] - eps), wp.vec3(D[0], D[1], D[2] + eps)] for i in range(6): q = offset_query_dirs[i] query_points = wp.array(p, dtype=wp.vec3, device=device) query_dirs = wp.array(q, dtype=wp.vec3, device=device) intersection_points = wp.zeros(n=1, dtype=wp.vec3, device=device) loss = wp.zeros(n=1, dtype=float, device=device) wp.launch(kernel=mesh_query_ray_loss, dim=1, inputs=[mesh.id, query_points, query_dirs, intersection_points, loss], device=device) loss_values_D.append(loss.numpy()[0]) for i in range(3): l_0 = loss_values_D[i*2] l_1 = loss_values_D[i*2+1] gradient = (l_1 - l_0) / (2.0*eps) numeric_D[i] = gradient error_p = ((analytic_p - numeric_p) * (analytic_p - numeric_p)).sum(axis=0) error_D = ((analytic_D - numeric_D) * (analytic_D - numeric_D)).sum(axis=0) tolerance = 1.e-3 test.assertTrue(error_p < tolerance, f"error is {error_p} which is >= {tolerance}") test.assertTrue(error_D < tolerance, f"error is {error_D} which is >= {tolerance}") def register(parent): devices = wp.get_devices() class TestMeshQueryRay(parent): pass add_function_test(TestMeshQueryRay, "test_adj_mesh_query_ray", test_adj_mesh_query_ray, devices=devices) return TestMeshQueryRay if __name__ == '__main__': c = register(unittest.TestCase) unittest.main(verbosity=2)
3,024
395
// For Capstone Engine. AUTO-GENERATED FILE, DO NOT EDIT package capstone; public class Sparc_const { // Enums corresponding to Sparc condition codes, both icc's and fcc's. public static final int SPARC_CC_INVALID = 0; // Integer condition codes public static final int SPARC_CC_ICC_A = 8 + 256; public static final int SPARC_CC_ICC_N = 0 + 256; public static final int SPARC_CC_ICC_NE = 9 + 256; public static final int SPARC_CC_ICC_E = 1 + 256; public static final int SPARC_CC_ICC_G = 10 + 256; public static final int SPARC_CC_ICC_LE = 2 + 256; public static final int SPARC_CC_ICC_GE = 11 + 256; public static final int SPARC_CC_ICC_L = 3 + 256; public static final int SPARC_CC_ICC_GU = 12 + 256; public static final int SPARC_CC_ICC_LEU = 4 + 256; public static final int SPARC_CC_ICC_CC = 13 + 256; public static final int SPARC_CC_ICC_CS = 5 + 256; public static final int SPARC_CC_ICC_POS = 14 + 256; public static final int SPARC_CC_ICC_NEG = 6 + 256; public static final int SPARC_CC_ICC_VC = 15 + 256; public static final int SPARC_CC_ICC_VS = 7 + 256; // Floating condition codes public static final int SPARC_CC_FCC_A = 8 + 16 + 256; public static final int SPARC_CC_FCC_N = 0 + 16 + 256; public static final int SPARC_CC_FCC_U = 7 + 16 + 256; public static final int SPARC_CC_FCC_G = 6 + 16 + 256; public static final int SPARC_CC_FCC_UG = 5 + 16 + 256; public static final int SPARC_CC_FCC_L = 4 + 16 + 256; public static final int SPARC_CC_FCC_UL = 3 + 16 + 256; public static final int SPARC_CC_FCC_LG = 2 + 16 + 256; public static final int SPARC_CC_FCC_NE = 1 + 16 + 256; public static final int SPARC_CC_FCC_E = 9 + 16 + 256; public static final int SPARC_CC_FCC_UE = 10 + 16 + 256; public static final int SPARC_CC_FCC_GE = 11 + 16 + 256; public static final int SPARC_CC_FCC_UGE = 12 + 16 + 256; public static final int SPARC_CC_FCC_LE = 13 + 16 + 256; public static final int SPARC_CC_FCC_ULE = 14 + 16 + 256; public static final int SPARC_CC_FCC_O = 15 + 16 + 256; // Branch hint public static final int SPARC_HINT_INVALID = 0; public static final int SPARC_HINT_A = 1 << 0; public static final int SPARC_HINT_PT = 1 << 1; public static final int SPARC_HINT_PN = 1 << 2; // Operand type for instruction's operands public static final int SPARC_OP_INVALID = 0; public static final int SPARC_OP_REG = 1; public static final int SPARC_OP_IMM = 2; public static final int SPARC_OP_MEM = 3; // SPARC registers public static final int SPARC_REG_INVALID = 0; public static final int SPARC_REG_F0 = 1; public static final int SPARC_REG_F1 = 2; public static final int SPARC_REG_F2 = 3; public static final int SPARC_REG_F3 = 4; public static final int SPARC_REG_F4 = 5; public static final int SPARC_REG_F5 = 6; public static final int SPARC_REG_F6 = 7; public static final int SPARC_REG_F7 = 8; public static final int SPARC_REG_F8 = 9; public static final int SPARC_REG_F9 = 10; public static final int SPARC_REG_F10 = 11; public static final int SPARC_REG_F11 = 12; public static final int SPARC_REG_F12 = 13; public static final int SPARC_REG_F13 = 14; public static final int SPARC_REG_F14 = 15; public static final int SPARC_REG_F15 = 16; public static final int SPARC_REG_F16 = 17; public static final int SPARC_REG_F17 = 18; public static final int SPARC_REG_F18 = 19; public static final int SPARC_REG_F19 = 20; public static final int SPARC_REG_F20 = 21; public static final int SPARC_REG_F21 = 22; public static final int SPARC_REG_F22 = 23; public static final int SPARC_REG_F23 = 24; public static final int SPARC_REG_F24 = 25; public static final int SPARC_REG_F25 = 26; public static final int SPARC_REG_F26 = 27; public static final int SPARC_REG_F27 = 28; public static final int SPARC_REG_F28 = 29; public static final int SPARC_REG_F29 = 30; public static final int SPARC_REG_F30 = 31; public static final int SPARC_REG_F31 = 32; public static final int SPARC_REG_F32 = 33; public static final int SPARC_REG_F34 = 34; public static final int SPARC_REG_F36 = 35; public static final int SPARC_REG_F38 = 36; public static final int SPARC_REG_F40 = 37; public static final int SPARC_REG_F42 = 38; public static final int SPARC_REG_F44 = 39; public static final int SPARC_REG_F46 = 40; public static final int SPARC_REG_F48 = 41; public static final int SPARC_REG_F50 = 42; public static final int SPARC_REG_F52 = 43; public static final int SPARC_REG_F54 = 44; public static final int SPARC_REG_F56 = 45; public static final int SPARC_REG_F58 = 46; public static final int SPARC_REG_F60 = 47; public static final int SPARC_REG_F62 = 48; public static final int SPARC_REG_FCC0 = 49; public static final int SPARC_REG_FCC1 = 50; public static final int SPARC_REG_FCC2 = 51; public static final int SPARC_REG_FCC3 = 52; public static final int SPARC_REG_FP = 53; public static final int SPARC_REG_G0 = 54; public static final int SPARC_REG_G1 = 55; public static final int SPARC_REG_G2 = 56; public static final int SPARC_REG_G3 = 57; public static final int SPARC_REG_G4 = 58; public static final int SPARC_REG_G5 = 59; public static final int SPARC_REG_G6 = 60; public static final int SPARC_REG_G7 = 61; public static final int SPARC_REG_I0 = 62; public static final int SPARC_REG_I1 = 63; public static final int SPARC_REG_I2 = 64; public static final int SPARC_REG_I3 = 65; public static final int SPARC_REG_I4 = 66; public static final int SPARC_REG_I5 = 67; public static final int SPARC_REG_I7 = 68; public static final int SPARC_REG_ICC = 69; public static final int SPARC_REG_L0 = 70; public static final int SPARC_REG_L1 = 71; public static final int SPARC_REG_L2 = 72; public static final int SPARC_REG_L3 = 73; public static final int SPARC_REG_L4 = 74; public static final int SPARC_REG_L5 = 75; public static final int SPARC_REG_L6 = 76; public static final int SPARC_REG_L7 = 77; public static final int SPARC_REG_O0 = 78; public static final int SPARC_REG_O1 = 79; public static final int SPARC_REG_O2 = 80; public static final int SPARC_REG_O3 = 81; public static final int SPARC_REG_O4 = 82; public static final int SPARC_REG_O5 = 83; public static final int SPARC_REG_O7 = 84; public static final int SPARC_REG_SP = 85; public static final int SPARC_REG_Y = 86; public static final int SPARC_REG_XCC = 87; public static final int SPARC_REG_ENDING = 88; public static final int SPARC_REG_O6 = SPARC_REG_SP; public static final int SPARC_REG_I6 = SPARC_REG_FP; // SPARC instruction public static final int SPARC_INS_INVALID = 0; public static final int SPARC_INS_ADDCC = 1; public static final int SPARC_INS_ADDX = 2; public static final int SPARC_INS_ADDXCC = 3; public static final int SPARC_INS_ADDXC = 4; public static final int SPARC_INS_ADDXCCC = 5; public static final int SPARC_INS_ADD = 6; public static final int SPARC_INS_ALIGNADDR = 7; public static final int SPARC_INS_ALIGNADDRL = 8; public static final int SPARC_INS_ANDCC = 9; public static final int SPARC_INS_ANDNCC = 10; public static final int SPARC_INS_ANDN = 11; public static final int SPARC_INS_AND = 12; public static final int SPARC_INS_ARRAY16 = 13; public static final int SPARC_INS_ARRAY32 = 14; public static final int SPARC_INS_ARRAY8 = 15; public static final int SPARC_INS_B = 16; public static final int SPARC_INS_JMP = 17; public static final int SPARC_INS_BMASK = 18; public static final int SPARC_INS_FB = 19; public static final int SPARC_INS_BRGEZ = 20; public static final int SPARC_INS_BRGZ = 21; public static final int SPARC_INS_BRLEZ = 22; public static final int SPARC_INS_BRLZ = 23; public static final int SPARC_INS_BRNZ = 24; public static final int SPARC_INS_BRZ = 25; public static final int SPARC_INS_BSHUFFLE = 26; public static final int SPARC_INS_CALL = 27; public static final int SPARC_INS_CASX = 28; public static final int SPARC_INS_CAS = 29; public static final int SPARC_INS_CMASK16 = 30; public static final int SPARC_INS_CMASK32 = 31; public static final int SPARC_INS_CMASK8 = 32; public static final int SPARC_INS_CMP = 33; public static final int SPARC_INS_EDGE16 = 34; public static final int SPARC_INS_EDGE16L = 35; public static final int SPARC_INS_EDGE16LN = 36; public static final int SPARC_INS_EDGE16N = 37; public static final int SPARC_INS_EDGE32 = 38; public static final int SPARC_INS_EDGE32L = 39; public static final int SPARC_INS_EDGE32LN = 40; public static final int SPARC_INS_EDGE32N = 41; public static final int SPARC_INS_EDGE8 = 42; public static final int SPARC_INS_EDGE8L = 43; public static final int SPARC_INS_EDGE8LN = 44; public static final int SPARC_INS_EDGE8N = 45; public static final int SPARC_INS_FABSD = 46; public static final int SPARC_INS_FABSQ = 47; public static final int SPARC_INS_FABSS = 48; public static final int SPARC_INS_FADDD = 49; public static final int SPARC_INS_FADDQ = 50; public static final int SPARC_INS_FADDS = 51; public static final int SPARC_INS_FALIGNDATA = 52; public static final int SPARC_INS_FAND = 53; public static final int SPARC_INS_FANDNOT1 = 54; public static final int SPARC_INS_FANDNOT1S = 55; public static final int SPARC_INS_FANDNOT2 = 56; public static final int SPARC_INS_FANDNOT2S = 57; public static final int SPARC_INS_FANDS = 58; public static final int SPARC_INS_FCHKSM16 = 59; public static final int SPARC_INS_FCMPD = 60; public static final int SPARC_INS_FCMPEQ16 = 61; public static final int SPARC_INS_FCMPEQ32 = 62; public static final int SPARC_INS_FCMPGT16 = 63; public static final int SPARC_INS_FCMPGT32 = 64; public static final int SPARC_INS_FCMPLE16 = 65; public static final int SPARC_INS_FCMPLE32 = 66; public static final int SPARC_INS_FCMPNE16 = 67; public static final int SPARC_INS_FCMPNE32 = 68; public static final int SPARC_INS_FCMPQ = 69; public static final int SPARC_INS_FCMPS = 70; public static final int SPARC_INS_FDIVD = 71; public static final int SPARC_INS_FDIVQ = 72; public static final int SPARC_INS_FDIVS = 73; public static final int SPARC_INS_FDMULQ = 74; public static final int SPARC_INS_FDTOI = 75; public static final int SPARC_INS_FDTOQ = 76; public static final int SPARC_INS_FDTOS = 77; public static final int SPARC_INS_FDTOX = 78; public static final int SPARC_INS_FEXPAND = 79; public static final int SPARC_INS_FHADDD = 80; public static final int SPARC_INS_FHADDS = 81; public static final int SPARC_INS_FHSUBD = 82; public static final int SPARC_INS_FHSUBS = 83; public static final int SPARC_INS_FITOD = 84; public static final int SPARC_INS_FITOQ = 85; public static final int SPARC_INS_FITOS = 86; public static final int SPARC_INS_FLCMPD = 87; public static final int SPARC_INS_FLCMPS = 88; public static final int SPARC_INS_FLUSHW = 89; public static final int SPARC_INS_FMEAN16 = 90; public static final int SPARC_INS_FMOVD = 91; public static final int SPARC_INS_FMOVQ = 92; public static final int SPARC_INS_FMOVRDGEZ = 93; public static final int SPARC_INS_FMOVRQGEZ = 94; public static final int SPARC_INS_FMOVRSGEZ = 95; public static final int SPARC_INS_FMOVRDGZ = 96; public static final int SPARC_INS_FMOVRQGZ = 97; public static final int SPARC_INS_FMOVRSGZ = 98; public static final int SPARC_INS_FMOVRDLEZ = 99; public static final int SPARC_INS_FMOVRQLEZ = 100; public static final int SPARC_INS_FMOVRSLEZ = 101; public static final int SPARC_INS_FMOVRDLZ = 102; public static final int SPARC_INS_FMOVRQLZ = 103; public static final int SPARC_INS_FMOVRSLZ = 104; public static final int SPARC_INS_FMOVRDNZ = 105; public static final int SPARC_INS_FMOVRQNZ = 106; public static final int SPARC_INS_FMOVRSNZ = 107; public static final int SPARC_INS_FMOVRDZ = 108; public static final int SPARC_INS_FMOVRQZ = 109; public static final int SPARC_INS_FMOVRSZ = 110; public static final int SPARC_INS_FMOVS = 111; public static final int SPARC_INS_FMUL8SUX16 = 112; public static final int SPARC_INS_FMUL8ULX16 = 113; public static final int SPARC_INS_FMUL8X16 = 114; public static final int SPARC_INS_FMUL8X16AL = 115; public static final int SPARC_INS_FMUL8X16AU = 116; public static final int SPARC_INS_FMULD = 117; public static final int SPARC_INS_FMULD8SUX16 = 118; public static final int SPARC_INS_FMULD8ULX16 = 119; public static final int SPARC_INS_FMULQ = 120; public static final int SPARC_INS_FMULS = 121; public static final int SPARC_INS_FNADDD = 122; public static final int SPARC_INS_FNADDS = 123; public static final int SPARC_INS_FNAND = 124; public static final int SPARC_INS_FNANDS = 125; public static final int SPARC_INS_FNEGD = 126; public static final int SPARC_INS_FNEGQ = 127; public static final int SPARC_INS_FNEGS = 128; public static final int SPARC_INS_FNHADDD = 129; public static final int SPARC_INS_FNHADDS = 130; public static final int SPARC_INS_FNOR = 131; public static final int SPARC_INS_FNORS = 132; public static final int SPARC_INS_FNOT1 = 133; public static final int SPARC_INS_FNOT1S = 134; public static final int SPARC_INS_FNOT2 = 135; public static final int SPARC_INS_FNOT2S = 136; public static final int SPARC_INS_FONE = 137; public static final int SPARC_INS_FONES = 138; public static final int SPARC_INS_FOR = 139; public static final int SPARC_INS_FORNOT1 = 140; public static final int SPARC_INS_FORNOT1S = 141; public static final int SPARC_INS_FORNOT2 = 142; public static final int SPARC_INS_FORNOT2S = 143; public static final int SPARC_INS_FORS = 144; public static final int SPARC_INS_FPACK16 = 145; public static final int SPARC_INS_FPACK32 = 146; public static final int SPARC_INS_FPACKFIX = 147; public static final int SPARC_INS_FPADD16 = 148; public static final int SPARC_INS_FPADD16S = 149; public static final int SPARC_INS_FPADD32 = 150; public static final int SPARC_INS_FPADD32S = 151; public static final int SPARC_INS_FPADD64 = 152; public static final int SPARC_INS_FPMERGE = 153; public static final int SPARC_INS_FPSUB16 = 154; public static final int SPARC_INS_FPSUB16S = 155; public static final int SPARC_INS_FPSUB32 = 156; public static final int SPARC_INS_FPSUB32S = 157; public static final int SPARC_INS_FQTOD = 158; public static final int SPARC_INS_FQTOI = 159; public static final int SPARC_INS_FQTOS = 160; public static final int SPARC_INS_FQTOX = 161; public static final int SPARC_INS_FSLAS16 = 162; public static final int SPARC_INS_FSLAS32 = 163; public static final int SPARC_INS_FSLL16 = 164; public static final int SPARC_INS_FSLL32 = 165; public static final int SPARC_INS_FSMULD = 166; public static final int SPARC_INS_FSQRTD = 167; public static final int SPARC_INS_FSQRTQ = 168; public static final int SPARC_INS_FSQRTS = 169; public static final int SPARC_INS_FSRA16 = 170; public static final int SPARC_INS_FSRA32 = 171; public static final int SPARC_INS_FSRC1 = 172; public static final int SPARC_INS_FSRC1S = 173; public static final int SPARC_INS_FSRC2 = 174; public static final int SPARC_INS_FSRC2S = 175; public static final int SPARC_INS_FSRL16 = 176; public static final int SPARC_INS_FSRL32 = 177; public static final int SPARC_INS_FSTOD = 178; public static final int SPARC_INS_FSTOI = 179; public static final int SPARC_INS_FSTOQ = 180; public static final int SPARC_INS_FSTOX = 181; public static final int SPARC_INS_FSUBD = 182; public static final int SPARC_INS_FSUBQ = 183; public static final int SPARC_INS_FSUBS = 184; public static final int SPARC_INS_FXNOR = 185; public static final int SPARC_INS_FXNORS = 186; public static final int SPARC_INS_FXOR = 187; public static final int SPARC_INS_FXORS = 188; public static final int SPARC_INS_FXTOD = 189; public static final int SPARC_INS_FXTOQ = 190; public static final int SPARC_INS_FXTOS = 191; public static final int SPARC_INS_FZERO = 192; public static final int SPARC_INS_FZEROS = 193; public static final int SPARC_INS_JMPL = 194; public static final int SPARC_INS_LDD = 195; public static final int SPARC_INS_LD = 196; public static final int SPARC_INS_LDQ = 197; public static final int SPARC_INS_LDSB = 198; public static final int SPARC_INS_LDSH = 199; public static final int SPARC_INS_LDSW = 200; public static final int SPARC_INS_LDUB = 201; public static final int SPARC_INS_LDUH = 202; public static final int SPARC_INS_LDX = 203; public static final int SPARC_INS_LZCNT = 204; public static final int SPARC_INS_MEMBAR = 205; public static final int SPARC_INS_MOVDTOX = 206; public static final int SPARC_INS_MOV = 207; public static final int SPARC_INS_MOVRGEZ = 208; public static final int SPARC_INS_MOVRGZ = 209; public static final int SPARC_INS_MOVRLEZ = 210; public static final int SPARC_INS_MOVRLZ = 211; public static final int SPARC_INS_MOVRNZ = 212; public static final int SPARC_INS_MOVRZ = 213; public static final int SPARC_INS_MOVSTOSW = 214; public static final int SPARC_INS_MOVSTOUW = 215; public static final int SPARC_INS_MULX = 216; public static final int SPARC_INS_NOP = 217; public static final int SPARC_INS_ORCC = 218; public static final int SPARC_INS_ORNCC = 219; public static final int SPARC_INS_ORN = 220; public static final int SPARC_INS_OR = 221; public static final int SPARC_INS_PDIST = 222; public static final int SPARC_INS_PDISTN = 223; public static final int SPARC_INS_POPC = 224; public static final int SPARC_INS_RD = 225; public static final int SPARC_INS_RESTORE = 226; public static final int SPARC_INS_RETT = 227; public static final int SPARC_INS_SAVE = 228; public static final int SPARC_INS_SDIVCC = 229; public static final int SPARC_INS_SDIVX = 230; public static final int SPARC_INS_SDIV = 231; public static final int SPARC_INS_SETHI = 232; public static final int SPARC_INS_SHUTDOWN = 233; public static final int SPARC_INS_SIAM = 234; public static final int SPARC_INS_SLLX = 235; public static final int SPARC_INS_SLL = 236; public static final int SPARC_INS_SMULCC = 237; public static final int SPARC_INS_SMUL = 238; public static final int SPARC_INS_SRAX = 239; public static final int SPARC_INS_SRA = 240; public static final int SPARC_INS_SRLX = 241; public static final int SPARC_INS_SRL = 242; public static final int SPARC_INS_STBAR = 243; public static final int SPARC_INS_STB = 244; public static final int SPARC_INS_STD = 245; public static final int SPARC_INS_ST = 246; public static final int SPARC_INS_STH = 247; public static final int SPARC_INS_STQ = 248; public static final int SPARC_INS_STX = 249; public static final int SPARC_INS_SUBCC = 250; public static final int SPARC_INS_SUBX = 251; public static final int SPARC_INS_SUBXCC = 252; public static final int SPARC_INS_SUB = 253; public static final int SPARC_INS_SWAP = 254; public static final int SPARC_INS_TADDCCTV = 255; public static final int SPARC_INS_TADDCC = 256; public static final int SPARC_INS_T = 257; public static final int SPARC_INS_TSUBCCTV = 258; public static final int SPARC_INS_TSUBCC = 259; public static final int SPARC_INS_UDIVCC = 260; public static final int SPARC_INS_UDIVX = 261; public static final int SPARC_INS_UDIV = 262; public static final int SPARC_INS_UMULCC = 263; public static final int SPARC_INS_UMULXHI = 264; public static final int SPARC_INS_UMUL = 265; public static final int SPARC_INS_UNIMP = 266; public static final int SPARC_INS_FCMPED = 267; public static final int SPARC_INS_FCMPEQ = 268; public static final int SPARC_INS_FCMPES = 269; public static final int SPARC_INS_WR = 270; public static final int SPARC_INS_XMULX = 271; public static final int SPARC_INS_XMULXHI = 272; public static final int SPARC_INS_XNORCC = 273; public static final int SPARC_INS_XNOR = 274; public static final int SPARC_INS_XORCC = 275; public static final int SPARC_INS_XOR = 276; public static final int SPARC_INS_RET = 277; public static final int SPARC_INS_RETL = 278; public static final int SPARC_INS_ENDING = 279; // Group of SPARC instructions public static final int SPARC_GRP_INVALID = 0; // Generic groups public static final int SPARC_GRP_JUMP = 1; // Architecture-specific groups public static final int SPARC_GRP_HARDQUAD = 128; public static final int SPARC_GRP_V9 = 129; public static final int SPARC_GRP_VIS = 130; public static final int SPARC_GRP_VIS2 = 131; public static final int SPARC_GRP_VIS3 = 132; public static final int SPARC_GRP_32BIT = 133; public static final int SPARC_GRP_64BIT = 134; public static final int SPARC_GRP_ENDING = 135; }
8,281
550
<gh_stars>100-1000 from glue.core.fitters import BaseFitter1D from glue.core.simpleforms import IntOption from glue.config import fit_plugin import numpy as np @fit_plugin class PolynomialFitter(BaseFitter1D): label = "Polynomial" degree = IntOption(min=0, max=5, default=3, label="Polynomial Degree") def fit(self, x, y, dy, constraints, degree=2): return np.polyfit(x, y, degree) def predict(self, fit_result, x): return np.polyval(fit_result, x) def summarize(self, fit_result, x, y, dy=None): return "Coefficients:\n" + "\n".join("%e" % coeff for coeff in fit_result.tolist())
291
537
<reponame>wangxuan-cn/SMSGate<filename>src/test/java/es/rickyepoderi/wbxml/bind/wvcsp/ListManageResponse.java<gh_stars>100-1000 // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.08.25 at 05:48:09 PM CEST // package es.rickyepoderi.wbxml.bind.wvcsp; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "result", "nickList", "contactListProperties" }) @XmlRootElement(name = "ListManage-Response") public class ListManageResponse { @XmlElement(name = "Result", required = true) protected Result result; @XmlElement(name = "NickList") protected NickList nickList; @XmlElement(name = "ContactListProperties") protected ContactListProperties contactListProperties; /** * Gets the value of the result property. * * @return * possible object is * {@link Result } * */ public Result getResult() { return result; } /** * Sets the value of the result property. * * @param value * allowed object is * {@link Result } * */ public void setResult(Result value) { this.result = value; } /** * Gets the value of the nickList property. * * @return * possible object is * {@link NickList } * */ public NickList getNickList() { return nickList; } /** * Sets the value of the nickList property. * * @param value * allowed object is * {@link NickList } * */ public void setNickList(NickList value) { this.nickList = value; } /** * Gets the value of the contactListProperties property. * * @return * possible object is * {@link ContactListProperties } * */ public ContactListProperties getContactListProperties() { return contactListProperties; } /** * Sets the value of the contactListProperties property. * * @param value * allowed object is * {@link ContactListProperties } * */ public void setContactListProperties(ContactListProperties value) { this.contactListProperties = value; } }
1,143
66,985
/* * Copyright 2012-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.health; import org.springframework.util.Assert; /** * A single named health endpoint contributors (either {@link HealthContributor} or * {@link ReactiveHealthContributor}). * * @param <C> the contributor type * @author <NAME> * @since 2.0.0 * @see NamedContributors */ public interface NamedContributor<C> { /** * Returns the name of the contributor. * @return the contributor name */ String getName(); /** * Returns the contributor instance. * @return the contributor instance */ C getContributor(); static <C> NamedContributor<C> of(String name, C contributor) { Assert.notNull(name, "Name must not be null"); Assert.notNull(contributor, "Contributor must not be null"); return new NamedContributor<C>() { @Override public String getName() { return name; } @Override public C getContributor() { return contributor; } }; } }
468
1,110
<filename>Classes/GSStartup.h // // GSStartup.h // gfxCardStatus // // Created by <NAME> on 6/12/12. // Copyright (c) 2012 <NAME>. All rights reserved. // @interface GSStartup : NSObject // Whether or not the app exists in the current user's Login Items list. + (BOOL)existsInStartupItems; // Put the app in the current user's Login Items list. + (void)loadAtStartup:(BOOL)value; @end
137
743
{"actions":[{"fallback":"drop","title":"This is a bug!","type":"SomeCustomAction"}],"body":[{"fallback":"drop","type":"SomeCustomElement"}],"type":"AdaptiveCard","version":"1.2"}
47
32,544
package com.baeldung.hibernate.manytomany.util; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import com.baeldung.hibernate.manytomany.model.Employee; import com.baeldung.hibernate.manytomany.model.Project; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HibernateUtil { private static final Logger LOGGER = LoggerFactory.getLogger(HibernateUtil.class); private static SessionFactory sessionFactory; private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate-annotation.cfg.xml Configuration configuration = new Configuration(); configuration.addAnnotatedClass(Employee.class); configuration.addAnnotatedClass(Project.class); configuration.configure("manytomany.cfg.xml"); LOGGER.debug("Hibernate Annotation Configuration loaded"); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) .build(); LOGGER.debug("Hibernate Annotation serviceRegistry created"); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); return sessionFactory; } catch (Throwable ex) { LOGGER.error("Initial SessionFactory creation failed.", ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { if (sessionFactory == null) { sessionFactory = buildSessionFactory(); } return sessionFactory; } }
709
3,755
<reponame>alijasim/frappe<filename>frappe/utils/lazy_loader.py import importlib.util import sys def lazy_import(name, package=None): """Import a module lazily. The module is loaded when modules's attribute is accessed for the first time. This works with both absolute and relative imports. $ cat mod.py print("Loading mod.py") $ python -i lazy_loader.py >>> mod = lazy_import("mod") # Module is not loaded >>> mod.__str__() # module is loaded on accessing attribute Loading mod.py "<module 'mod' from '.../frappe/utils/mod.py'>" >>> Code based on https://github.com/python/cpython/blob/master/Doc/library/importlib.rst#implementing-lazy-imports. """ # Return if the module already loaded if name in sys.modules: return sys.modules[name] # Find the spec if not loaded spec = importlib.util.find_spec(name, package) if not spec: raise ImportError(f'Module {name} Not found.') loader = importlib.util.LazyLoader(spec.loader) spec.loader = loader module = importlib.util.module_from_spec(spec) sys.modules[name] = module loader.exec_module(module) return module
365
322
<filename>spring-social-core/src/main/java/org/springframework/social/oauth2/OAuth2ServiceProvider.java /* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.social.oauth2; import org.springframework.social.ServiceProvider; /** * A ServiceProvider that uses the OAuth 2.0 protocol. * @author <NAME> * @param <A> The service provider's API type */ public interface OAuth2ServiceProvider<A> extends ServiceProvider<A> { /** * Get the service interface for carrying out the "OAuth dance" with this provider. * The result of the OAuth dance is an access token that can be used to obtain a {@link #getApi(String) API binding}. * @return an {@link OAuth2Operations} for carrying out the "OAuth dance" with this provider. */ OAuth2Operations getOAuthOperations(); /** * Returns an API interface allowing the client application to access protected resources on behalf of a user. * @param accessToken the API access token * @return a binding to the service provider's API */ A getApi(String accessToken); }
441
2,360
<filename>var/spack/repos/builtin/packages/py-extension-helpers/package.py # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyExtensionHelpers(PythonPackage): """The extension-helpers package includes convenience helpers to assist with building Python packages with compiled C/Cython extensions. It is developed by the Astropy project but is intended to be general and usable by any Python package.""" homepage = 'https://github.com/astropy/astropy-helpers' pypi = 'extension-helpers/extension-helpers-0.1.tar.gz' version('0.1', sha256='ac8a6fe91c6d98986a51a9f08ca0c7945f8fd70d95b662ced4040ae5eb973882') depends_on('[email protected]:', type=('build', 'run')) depends_on('[email protected]:', type='build')
311
335
{ "word": "Bladder", "definitions": [ "A muscular membranous sac in the abdomen which receives urine from the kidneys and stores it for excretion.", "An inflated or hollow flexible bag or chamber." ], "parts-of-speech": "Noun" }
92
2,023
<reponame>tdiprima/code #!/usr/bin/env python import os import subprocess import sys import StringIO def cmdtolist(str): cmdlist=[] current=[] gc='' last='' for c in str: if (c == '\\'): pass elif (last == '\\'): current.append(c) elif (gc != ''): if (c != gc): current.append(c) else: gc='' else: if (c.isspace()): cmdlist.append(''.join(current)) current = [] elif (c == '"'): gc = c elif (c == "'"): gc = c else: current.append(c) last = c if (len(current) != 0): cmdlist.append(''.join(current)) return cmdlist def pipe(*cmds): def func(): pass def norm(cmd): if (isinstance(cmd, str)): return cmdtolist(cmd) return cmd def pipeobj(cmd, stdin=None): if (callable(cmd)): fp = Fpipe(cmd, stdin) fp.call() fp.stdout.seek(0) return fp if (stdin is None): return subprocess.Popen(norm(cmd), stdout=subprocess.PIPE) else: return subprocess.Popen(norm(cmd), stdin=stdin, stdout=subprocess.PIPE) if (len(cmds) == 0): return prev = None for cmd in cmds: if (prev is None): prev = pipeobj(cmd) else: prev = pipeobj(cmd, stdin=prev.stdout) return prev.stdout class Fpipe: def __init__(self, fn, stdin=None): self.fn = fn self.stdin = stdin self.stdout = StringIO.StringIO() def call(self): self.fn(self.stdin, self.stdout)
986
2,151
// Copyright 2017 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 "chrome/browser/ui/desktop_ios_promotion/desktop_ios_promotion_util.h" #include <memory> #include "base/i18n/rtl.h" #include "base/metrics/field_trial.h" #include "base/metrics/field_trial_params.h" #include "base/test/scoped_feature_list.h" #include "chrome/browser/prefs/browser_prefs.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/profile_sync_test_util.h" #include "chrome/common/chrome_features.h" #include "chrome/test/base/scoped_testing_local_state.h" #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "components/browser_sync/profile_sync_service.h" #include "components/browser_sync/test_profile_sync_service.h" #include "components/prefs/pref_service.h" #include "components/signin/core/browser/profile_oauth2_token_service.h" #include "components/signin/core/browser/signin_manager.h" #include "components/sync/driver/fake_sync_service.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/test/test_browser_thread_bundle.h" #include "google_apis/gaia/oauth2_token_service_delegate.h" namespace { class TestSyncService : public browser_sync::TestProfileSyncService { public: explicit TestSyncService(Profile* profile) : browser_sync::TestProfileSyncService( CreateProfileSyncServiceParamsForTest(profile)) {} bool IsSyncAllowed() const override { return is_sync_allowed_; } void set_sync_allowed(bool sync_allowed) { is_sync_allowed_ = sync_allowed; } private: bool is_sync_allowed_ = true; DISALLOW_COPY_AND_ASSIGN(TestSyncService); }; std::unique_ptr<KeyedService> BuildFakeSyncService( content::BrowserContext* context) { return std::make_unique<TestSyncService>( static_cast<TestingProfile*>(context)); } constexpr int kSMSEntrypointSavePasswordBubble = 1 << static_cast<int>(desktop_ios_promotion::PromotionEntryPoint::SAVE_PASSWORD_BUBBLE); constexpr int kSMSEntrypointBookmarksBubble = 1 << static_cast<int>(desktop_ios_promotion::PromotionEntryPoint::BOOKMARKS_BUBBLE); } // namespace class DesktopIOSPromotionUtilTest : public testing::Test { public: DesktopIOSPromotionUtilTest() : local_state_(TestingBrowserProcess::GetGlobal()) {} ~DesktopIOSPromotionUtilTest() override {} void SetUp() override { auto pref_service = std::make_unique<sync_preferences::TestingPrefServiceSyncable>(); RegisterUserProfilePrefs(pref_service->registry()); TestingProfile::Builder profile_builder; profile_builder.SetPrefService(std::move(pref_service)); profile_builder.AddTestingFactory(ProfileSyncServiceFactory::GetInstance(), &BuildFakeSyncService); profile_ = profile_builder.Build(); sync_service_ = static_cast<TestSyncService*>( ProfileSyncServiceFactory::GetForProfile(profile_.get())); mock_signin_ = SigninManagerFactory::GetForProfile(profile_.get()); mock_signin_->SetAuthenticatedAccountInfo("test", "test"); } void TearDown() override { profile_.reset(); } PrefService* local_state() { return local_state_.Get(); } TestSyncService* sync_service() { return sync_service_; } PrefService* prefs() { return profile_->GetPrefs(); } Profile* profile() { return profile_.get(); } double GetDoubleNDayOldDate(int days) { base::Time time_result = base::Time::NowFromSystemTime() - base::TimeDelta::FromDays(days); return time_result.ToDoubleT(); } private: TestSyncService* sync_service_ = nullptr; content::TestBrowserThreadBundle thread_bundle_; ScopedTestingLocalState local_state_; SigninManagerBase* mock_signin_ = nullptr; std::unique_ptr<TestingProfile> profile_; DISALLOW_COPY_AND_ASSIGN(DesktopIOSPromotionUtilTest); }; TEST_F(DesktopIOSPromotionUtilTest, IsEligibleForIOSPromotionForSavePassword) { desktop_ios_promotion::PromotionEntryPoint entry_point = desktop_ios_promotion::PromotionEntryPoint::SAVE_PASSWORD_BUBBLE; // By default the promo is off. EXPECT_FALSE( desktop_ios_promotion::IsEligibleForIOSPromotion(profile(), entry_point)); // Enable the promotion and assign the entry_point finch parameter. base::FieldTrialList field_trial_list(nullptr); base::test::ScopedFeatureList scoped_feature_list; std::map<std::string, std::string> params; params["entry_point"] = "SavePasswordsBubblePromotion"; base::AssociateFieldTrialParams("DesktopIOSPromotion", "SavePasswordBubblePromotion", params); scoped_refptr<base::FieldTrial> trial( base::FieldTrialList::FactoryGetFieldTrial( "DesktopIOSPromotion", 100, "SavePasswordBubblePromotion", base::FieldTrialList::kNoExpirationYear, 1, 1, base::FieldTrial::SESSION_RANDOMIZED, nullptr)); std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList); feature_list->RegisterFieldTrialOverride( features::kDesktopIOSPromotion.name, base::FeatureList::OVERRIDE_ENABLE_FEATURE, trial.get()); scoped_feature_list.InitWithFeatureList(std::move(feature_list)); std::string locales[] = {"en-US", "en-CA", "en-AU", "es-US"}; constexpr struct { bool is_sync_allowed; bool signin_error; int locale_index; bool is_dismissed; int show_count; int last_impression_days; int sms_entrypoint; bool is_user_eligible; bool promo_done; bool result; } kTestData[] = { // {sync allowed, signin error exist, locale, dismissed before, impression // count, seen days // ago, bitmask with entry points seen, is user eligible, flow was // completed before, expected result } {false, false, 0, false, 0, 1, 0, false, false, false}, {false, false, 1, false, 0, 3, 0, true, false, false}, {true, false, 3, false, 0, 4, 0, true, false, false}, {true, false, 2, false, 0, 10, 0, true, false, false}, {true, false, 0, true, 1, 3, 0, true, false, false}, {true, false, 0, false, 3, 1, 0, true, false, false}, {true, false, 0, false, 1, 3, kSMSEntrypointSavePasswordBubble, true, false, false}, {true, false, 0, false, 0, 4, kSMSEntrypointBookmarksBubble, true, false, false}, {true, false, 0, false, 1, 10, 0, false, false, false}, {true, false, 0, false, 0, 1, 0, true, true, false}, {true, true, 1, false, 1, 1, 0, true, false, false}, {true, false, 1, false, 1, 1, 0, true, false, true}, {true, false, 1, false, 0, 2, 0, true, false, true}, {true, true, 0, false, 0, 8, kSMSEntrypointSavePasswordBubble, true, false, false}, {true, false, 0, false, 0, 8, kSMSEntrypointSavePasswordBubble, true, false, true}, }; std::string locale = base::i18n::GetConfiguredLocale(); for (const auto& test_case : kTestData) { SCOPED_TRACE(testing::Message("#test_case = ") << (&test_case - kTestData)); sync_service()->set_sync_allowed(test_case.is_sync_allowed); const GoogleServiceAuthError error( test_case.signin_error ? GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS : GoogleServiceAuthError::NONE); ProfileOAuth2TokenService* token_service = ProfileOAuth2TokenServiceFactory::GetForProfile(profile()); token_service->UpdateCredentials("test", "refresh_token"); // TODO(https://crbug.com/836212): Do not use the delegate directly, because // it is internal API. token_service->GetDelegate()->UpdateAuthError("test", error); local_state()->SetBoolean(prefs::kSavePasswordsBubbleIOSPromoDismissed, test_case.is_dismissed); local_state()->SetInteger(prefs::kNumberSavePasswordsBubbleIOSPromoShown, test_case.show_count); base::i18n::SetICUDefaultLocale(locales[test_case.locale_index]); prefs()->SetDouble(prefs::kIOSPromotionLastImpression, GetDoubleNDayOldDate(test_case.last_impression_days)); prefs()->SetInteger(prefs::kIOSPromotionSMSEntryPoint, test_case.sms_entrypoint); prefs()->SetBoolean(prefs::kIOSPromotionEligible, test_case.is_user_eligible); prefs()->SetBoolean(prefs::kIOSPromotionDone, test_case.promo_done); EXPECT_EQ(test_case.result, IsEligibleForIOSPromotion(profile(), entry_point)); } base::i18n::SetICUDefaultLocale(locale); }
3,340
573
<reponame>EdwardBetts/UniversalSplitScreen #include "stdafx.h" #include "InstallHooks.h" #include "Hooking.h" #include <vector> #include <winternl.h> #include <random> #include <map> #include <iostream> std::mt19937 randomGenerator; //Key: search term. Value: the assigned name that is replaced for every name that matched the search term. (value is empty if needs generating) std::map <std::wstring, std::wstring> searchTermsToAssignedNames; typedef enum _EVENT_TYPE { NotificationEvent, SynchronizationEvent } EVENT_TYPE, *PEVENT_TYPE; typedef NTSTATUS(NTAPI* t_NtCreateMutant)(PHANDLE MutantHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, BOOLEAN InitialOwner); typedef NTSTATUS(NTAPI* t_NtOpenMutant)(PHANDLE MutantHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes); typedef NTSTATUS(NTAPI* t_NtCreateEvent)(PHANDLE EventHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, EVENT_TYPE EventType, BOOLEAN InitialState); typedef NTSTATUS(NTAPI* t_NtOpenEvent)(PHANDLE EventHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes); typedef NTSTATUS(NTAPI* t_NtCreateSemaphore)(PHANDLE SemaphoreHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, ULONG InitialCount, ULONG MaximumCount); typedef NTSTATUS(NTAPI* t_NtOpenSemaphore)(PHANDLE SemaphoreHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes); static t_NtCreateMutant NtCreateMutant; static t_NtOpenMutant NtOpenMutant; static t_NtCreateEvent NtCreateEvent; static t_NtOpenEvent NtOpenEvent; static t_NtCreateSemaphore NtCreateSemaphore; static t_NtOpenSemaphore NtOpenSemaphore; inline UNICODE_STRING stdWStringToUnicodeString(const std::wstring& str) { UNICODE_STRING unicodeString; DWORD len = 0; len = str.length(); LPWSTR cstr = new WCHAR[len + 1]; memcpy(cstr, str.c_str(), (len + 1) * sizeof(WCHAR)); unicodeString.Buffer = cstr; unicodeString.Length = (USHORT)(len * sizeof(WCHAR)); unicodeString.MaximumLength = (USHORT)((len + 1) * sizeof(WCHAR)); return unicodeString; } void updateName(PUNICODE_STRING inputName) { if (!(inputName->Length > 0 && inputName->Length <= inputName->MaximumLength)) return; for (std::map<std::wstring, std::wstring>::value_type& pair : searchTermsToAssignedNames) { if (wcsstr(inputName->Buffer, pair.first.c_str()) != nullptr) { if (pair.second.empty()) { const auto rand = std::to_wstring(randomGenerator()); const std::wstring oldName = inputName->Buffer; const auto newName = oldName + rand; pair.second = newName; } *inputName = stdWStringToUnicodeString(pair.second); } } } inline void updateNameObject(POBJECT_ATTRIBUTES ObjectAttributes) { if (ObjectAttributes != NULL && ObjectAttributes->ObjectName != NULL) { updateName(ObjectAttributes->ObjectName); } } NTSTATUS NTAPI NtCreateMutant_Hook(OUT PHANDLE MutantHandle, IN ULONG DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN BOOLEAN InitialOwner) { updateNameObject(ObjectAttributes); return NtCreateMutant(MutantHandle, DesiredAccess, ObjectAttributes, InitialOwner); } NTSTATUS NTAPI NtOpenMutant_Hook(PHANDLE MutantHandle, ULONG DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes) { updateNameObject(ObjectAttributes); return NtOpenMutant(MutantHandle, DesiredAccess, ObjectAttributes); } NTSTATUS NTAPI NtCreateEvent_Hook(PHANDLE EventHandle, DWORD DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, EVENT_TYPE EventType, BOOLEAN InitialState) { updateNameObject(ObjectAttributes); return NtCreateEvent(EventHandle, DesiredAccess, ObjectAttributes, EventType, InitialState); } NTSTATUS NTAPI NtOpenEvent_Hook(PHANDLE EventHandle, DWORD DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes) { updateNameObject(ObjectAttributes); return NtOpenEvent(EventHandle, DesiredAccess, ObjectAttributes); } NTSTATUS NTAPI NtCreateSemaphore_Hook(PHANDLE SemaphoreHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, ULONG InitialCount, ULONG MaximumCounts) { updateNameObject(ObjectAttributes); return NtCreateSemaphore(SemaphoreHandle, DesiredAccess, ObjectAttributes, InitialCount, MaximumCounts); } NTSTATUS NTAPI NtOpenSemaphore_Hook(PHANDLE SemaphoreHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes) { updateNameObject(ObjectAttributes); return NtOpenSemaphore(SemaphoreHandle, DesiredAccess, ObjectAttributes); } void installFindMutexHooks(LPCWSTR targets) { //Random std::random_device rd; randomGenerator = static_cast<std::mt19937>(rd()); //Search terms #define ADD_SEARCH_TERM(term) searchTermsToAssignedNames.insert(std::make_pair((term), L"")); std::wcout << L"Added search term: " << sub << std::endl; { std::wstring target_s(targets); std::wstring splitter = L"&&&&&"; unsigned int startIndex = 0; unsigned int endIndex = 0; while ((endIndex = target_s.find(splitter, startIndex)) < target_s.size()) { std::wstring sub = target_s.substr(startIndex, endIndex - startIndex); ADD_SEARCH_TERM(sub); startIndex = endIndex + splitter.size(); } if (startIndex < target_s.size()) { //No splitters in string std::wstring sub = target_s.substr(startIndex); ADD_SEARCH_TERM(sub); } } #undef ADD_SEARCH_TERM //Ntdll functions #define GET_NT_PROC(name, type) (type)GetProcAddress(GetModuleHandle("ntdll.dll"), name) NtCreateMutant = GET_NT_PROC("NtCreateMutant", t_NtCreateMutant); NtOpenMutant = GET_NT_PROC("NtOpenMutant", t_NtOpenMutant); NtCreateEvent = GET_NT_PROC("NtCreateEvent", t_NtCreateEvent); NtOpenEvent = GET_NT_PROC("NtOpenEvent", t_NtOpenEvent); NtCreateSemaphore = GET_NT_PROC("NtCreateSemaphore", t_NtCreateSemaphore); NtOpenSemaphore = GET_NT_PROC("NtOpenSemaphore", t_NtOpenSemaphore); #undef GET_NT_PROC //Hooks installHook("ntdll.dll", "NtCreateMutant", NtCreateMutant_Hook); installHook("ntdll.dll", "NtOpenMutant", NtOpenMutant_Hook); installHook("ntdll.dll", "NtCreateEvent", NtCreateEvent_Hook); installHook("ntdll.dll", "NtOpenEvent", NtOpenEvent_Hook); installHook("ntdll.dll", "NtCreateSemaphore", NtCreateSemaphore_Hook); installHook("ntdll.dll", "NtOpenSemaphore", NtOpenSemaphore_Hook); }
2,268
583
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2017-2020 The Project X-Ray Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC from prjxray.segmaker import Segmaker from prjxray import verilog import json # Set to true to enable additional tags useful for tracing bit toggles. DEBUG_FUZZER = False def bitfilter(frame, word): if frame < 25 or frame > 31: return False return True def handle_data_width(segmk, d): if 'DATA_WIDTH' not in d: return site = d['ilogic_loc'] # It appears several widths end up with the same bitstream pattern. # This groups those widths together for documentation. widths = [ [2], [3], [4, 6], [5, 7], [8], [10], [14], ] width_map = {} for ws in widths: for w in ws: width_map[w] = 'W{}'.format('_'.join(map(str, ws))) zero_opt = 2 W_OPT_ZERO = width_map[zero_opt] if d['DATA_WIDTH'] == zero_opt: segmk.add_site_tag(site, 'ISERDES.DATA_WIDTH.{}'.format(W_OPT_ZERO), 1) for opt in width_map.values(): if opt == W_OPT_ZERO: continue segmk.add_site_tag(site, 'ISERDES.DATA_WIDTH.{}'.format(opt), 0) else: w_opt = width_map[d['DATA_WIDTH']] if w_opt != W_OPT_ZERO: segmk.add_site_tag( site, 'ISERDES.DATA_WIDTH.{}'.format(W_OPT_ZERO), 0) segmk.add_site_tag(site, 'ISERDES.DATA_WIDTH.{}'.format(w_opt), 1) def handle_data_rate(segmk, d): if 'DATA_WIDTH' not in d: return site = d['ilogic_loc'] for opt in ['SDR', 'DDR']: segmk.add_site_tag( site, 'ISERDES.DATA_RATE.{}'.format(opt), verilog.unquote(d['DATA_RATE']) == opt) def main(): print("Loading tags") segmk = Segmaker("design.bits") with open('params.jl', 'r') as f: design = json.load(f) for d in design: site = d['ilogic_loc'] handle_data_width(segmk, d) handle_data_rate(segmk, d) segmk.add_site_tag(site, 'ISERDES.IN_USE', d['use_iserdese2']) if 'NUM_CE' in d: segmk.add_site_tag(site, 'ISERDES.NUM_CE.N2', d['NUM_CE'] == 2) segmk.add_site_tag( site, 'IDDR_OR_ISERDES.IN_USE', d['use_iserdese2'] or d['iddr_mux_config'] != 'none') if 'INTERFACE_TYPE' in d: for opt in ( 'MEMORY', 'MEMORY_DDR3', 'MEMORY_QDR', 'NETWORKING', 'OVERSAMPLE', ): segmk.add_site_tag( site, 'ISERDES.INTERFACE_TYPE.{}'.format(opt), opt == verilog.unquote(d['INTERFACE_TYPE'])) segmk.add_site_tag( site, 'ISERDES.INTERFACE_TYPE.Z_{}'.format(opt), opt != verilog.unquote(d['INTERFACE_TYPE'])) segmk.add_site_tag( site, 'ISERDES.INTERFACE_TYPE.NOT_MEMORY', 'MEMORY' not in verilog.unquote(d['INTERFACE_TYPE'])) if d['iddr_mux_config'] != 'none': segmk.add_site_tag(site, 'IFF.ZINIT_Q1', not d['INIT_Q1']) segmk.add_site_tag(site, 'IFF.ZINIT_Q2', not d['INIT_Q2']) if 'DYN_CLKDIV_INV_EN' in d: segmk.add_site_tag( site, 'DYN_CLKDIV_INV_EN', verilog.unquote(d['DYN_CLKDIV_INV_EN']) == 'TRUE') if 'DYN_CLK_INV_EN' in d: segmk.add_site_tag( site, 'DYN_CLK_INV_EN', verilog.unquote(d['DYN_CLK_INV_EN']) == 'TRUE') if 'INIT_Q3' in d: segmk.add_site_tag(site, 'IFF.ZINIT_Q3', not d['INIT_Q3']) segmk.add_site_tag(site, 'IFF.ZINIT_Q4', not d['INIT_Q4']) segmk.add_site_tag( site, 'IFF.ZSRVAL_Q1', not d['SRVAL_Q1']) segmk.add_site_tag( site, 'IFF.ZSRVAL_Q2', not d['SRVAL_Q2']) segmk.add_site_tag( site, 'IFF.ZSRVAL_Q3', not d['SRVAL_Q3']) segmk.add_site_tag( site, 'IFF.ZSRVAL_Q4', not d['SRVAL_Q4']) if 'IS_CLK_INVERTED' in d and not d['DISABLE_CLOCKS']: if verilog.unquote(d['INTERFACE_TYPE']) == 'MEMORY_DDR3': segmk.add_site_tag( site, 'IFF.INV_CLK', d['IS_CLK_INVERTED']) segmk.add_site_tag( site, 'IFF.INV_CLKB', d['IS_CLKB_INVERTED']) segmk.add_site_tag( site, 'IFF.ZINV_CLK', not d['IS_CLK_INVERTED']) segmk.add_site_tag( site, 'IFF.ZINV_CLKB', not d['IS_CLKB_INVERTED']) segmk.add_site_tag( site, 'IFF.ZINV_CLK_XOR', d['IS_CLK_INVERTED'] ^ d['IS_CLKB_INVERTED']) segmk.add_site_tag( site, 'IFF.ZINV_CLK_NXOR', not (d['IS_CLK_INVERTED'] ^ d['IS_CLKB_INVERTED'])) segmk.add_site_tag( site, 'IFF.ZINV_CLK_OR', d['IS_CLK_INVERTED'] or d['IS_CLKB_INVERTED']) segmk.add_site_tag( site, 'IFF.ZINV_CLK_NOR', not ( d['IS_CLK_INVERTED'] or d['IS_CLKB_INVERTED'])) segmk.add_site_tag( site, 'IFF.ZINV_CLK_AND', d['IS_CLK_INVERTED'] and d['IS_CLKB_INVERTED']) segmk.add_site_tag( site, 'IFF.ZINV_CLK_NAND', not ( d['IS_CLK_INVERTED'] and d['IS_CLKB_INVERTED'])) if 'IS_OCLK_INVERTED' in d and not d['DISABLE_CLOCKS']: segmk.add_site_tag( site, 'IFF.INV_OCLK', d['IS_OCLK_INVERTED']) segmk.add_site_tag( site, 'IFF.ZINV_OCLK', not d['IS_OCLK_INVERTED']) segmk.add_site_tag( site, 'IFF.INV_OCLKB', d['IS_OCLKB_INVERTED']) segmk.add_site_tag( site, 'IFF.ZINV_OCLKB', not d['IS_OCLKB_INVERTED']) if 'IS_CLKDIV_INVERTED' in d and not d['DISABLE_CLOCKS'] and \ verilog.unquote(d['INTERFACE_TYPE']) == 'MEMORY': segmk.add_site_tag( site, 'IFF.INV_CLKDIV', d['IS_CLKDIV_INVERTED']) segmk.add_site_tag( site, 'IFF.ZINV_CLKDIV', not d['IS_CLKDIV_INVERTED']) if 'IS_C_INVERTED' in d: segmk.add_site_tag( site, 'IFF.ZINV_C', not d['IS_C_INVERTED']) segmk.add_site_tag(site, 'ZINV_D', not d['IS_D_INVERTED']) if 'SRTYPE' in d: for opt in ['ASYNC', 'SYNC']: segmk.add_site_tag( site, 'IFF.SRTYPE.{}'.format(opt), verilog.unquote(d['SRTYPE']) == opt) if 'DDR_CLK_EDGE' in d: for opt in ['OPPOSITE_EDGE', 'SAME_EDGE', 'SAME_EDGE_PIPELINED']: segmk.add_site_tag( site, 'IFF.DDR_CLK_EDGE.{}'.format(opt), verilog.unquote(d['DDR_CLK_EDGE']) == opt) if d['iddr_mux_config'] == 'direct': segmk.add_site_tag(site, 'IFFDELMUXE3.P0', 0) segmk.add_site_tag(site, 'IFFDELMUXE3.P1', 1) segmk.add_site_tag(site, 'IFFDELMUXE3.P2', 0) elif d['iddr_mux_config'] == 'idelay': segmk.add_site_tag(site, 'IFFDELMUXE3.P0', 1) segmk.add_site_tag(site, 'IFFDELMUXE3.P1', 0) segmk.add_site_tag(site, 'IFFDELMUXE3.P2', 0) elif d['iddr_mux_config'] == 'none': segmk.add_site_tag(site, 'IFFDELMUXE3.P0', 0) segmk.add_site_tag(site, 'IFFDELMUXE3.P1', 0) segmk.add_site_tag(site, 'IFFDELMUXE3.P2', 0) else: assert False, d['mux_config'] if d['mux_config'] == 'direct': segmk.add_site_tag(site, 'IDELMUXE3.P0', 0) segmk.add_site_tag(site, 'IDELMUXE3.P1', 1) segmk.add_site_tag(site, 'IDELMUXE3.P2', 0) elif d['mux_config'] == 'idelay': segmk.add_site_tag(site, 'IDELMUXE3.P0', 1) segmk.add_site_tag(site, 'IDELMUXE3.P1', 0) segmk.add_site_tag(site, 'IDELMUXE3.P2', 0) elif d['mux_config'] == 'none': segmk.add_site_tag(site, 'IDELMUXE3.P0', 0) segmk.add_site_tag(site, 'IDELMUXE3.P1', 0) segmk.add_site_tag(site, 'IDELMUXE3.P2', 0) else: assert False, d['mux_config'] if DEBUG_FUZZER: for k in d: segmk.add_site_tag( site, 'param_' + k + '_' + str(d[k]).replace( ' ', '').replace('\n', ''), 1) segmk.compile(bitfilter=bitfilter) segmk.write(allow_empty=True) if __name__ == "__main__": main()
6,336
2,072
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 from amundsen_application.base.base_bigquery_preview_client import BaseBigqueryPreviewClient from amundsen_application.models.preview_data import ( PreviewData, ) from google.cloud import bigquery from flatten_dict import flatten class BigqueryPreviewClient(BaseBigqueryPreviewClient): """ Returns a Response object, where the response data represents a json object with the preview data accessible on 'preview_data' key. The preview data should match amundsen_application.models.preview_data.PreviewDataSchema """ def __init__(self) -> None: # Requires access to a service account eg. # GOOGLE_APPLICATION_CREDENTIALS=path/serviceaccount.json or a mounted service kubernetes service account. super().__init__(bq_client=bigquery.Client("your project here")) def _bq_list_rows( self, gcp_project_id: str, table_project_name: str, table_name: str ) -> PreviewData: """ Returns PreviewData from bigquery list rows api. """ table_id = f"{gcp_project_id}.{table_project_name}.{table_name}" rows = self.bq_client.list_rows(table_id, max_results=self.preview_limit) # Make flat key ColumnItems from table schema. columns = [] for field in rows.schema: extend_with = self._column_item_from_bq_schema(field) columns.extend(extend_with) # Flatten rows and set missing empty keys to None, to avoid errors with undefined values # in frontend column_data = [] for row in rows: flat_row = flatten(dict(row), reducer="dot") for key in columns: if key.column_name not in flat_row: flat_row[key.column_name] = None column_data.append(flat_row) return PreviewData(columns, column_data)
749
1,240
<filename>SubEthaEdit-Mac/Source/SEEApplication.h // SEEApplication.h // SubEthaEdit // // Created by <NAME> on 06.08.14. #import <Cocoa/Cocoa.h> @interface SEEApplication : NSApplication @end
77
1,975
// Copyright 2006-2009 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== // // Iterator over persisted metrics #ifndef OMAHA_STATSREPORT_PERSISTENT_ITERATOR_WIN32_H__ #define OMAHA_STATSREPORT_PERSISTENT_ITERATOR_WIN32_H__ #include <atlbase.h> #include <atlstr.h> #include <iterator> #include "omaha/base/safe_format.h" #include "omaha/statsreport/metrics.h" #include "omaha/statsreport/const-win32.h" namespace stats_report { /// Forward iterator for persisted metrics class PersistentMetricsIteratorWin32 : public std::iterator<std::forward_iterator_tag, const MetricBase *> { public: /// @param app_name see MetricsAggregatorWin32 explicit PersistentMetricsIteratorWin32(const wchar_t *app_name) : state_(kUninitialized), is_machine_(false) { omaha::SafeCStringFormat(&key_name_, kStatsKeyFormatString, app_name); Next(); } /// @param app_name see MetricsAggregatorWin32 /// @param is_machine specifies the registry hive PersistentMetricsIteratorWin32(const wchar_t *app_name, bool is_machine) : state_(kUninitialized), is_machine_(is_machine) { omaha::SafeCStringFormat(&key_name_, kStatsKeyFormatString, app_name); Next(); } /// Constructs the at-end iterator PersistentMetricsIteratorWin32() : state_(kUninitialized) { } MetricBase *operator* () { return Current(); } MetricBase *operator-> () { return Current(); } /// Preincrement, we don't implement postincrement because we don't /// want to deal with making iterators copyable, comparable etc. PersistentMetricsIteratorWin32 &operator++() { Next(); return (*this); } /// Compare for equality with o. bool equals(const PersistentMetricsIteratorWin32 &o) const { // compare equal to self, and end iterators compare equal if ((this == &o) || (NULL == current_value_.get() && NULL == o.current_value_.get())) return true; return false; } private: MetricBase *Current() { DCHECK(current_value_.get()); return current_value_.get(); } enum IterationState { kUninitialized, kCounts, kTimings, kIntegers, kBooleans, kFinished, }; /// Walk to the next key/value under iteration void Next(); /// Keeps track of which subkey we're iterating over IterationState state_; /// The full path from HKCU to the key we iterate over CString key_name_; /// The top-level key we're iterating over, valid only /// after first call to Next(). CRegKey key_; /// The subkey we're currently enumerating over CRegKey sub_key_; /// Current value we're indexing over DWORD value_index_; /// Name of the value under the iterator CStringA current_value_name_; /// The metric under the iterator std::unique_ptr<MetricBase> current_value_; /// Specifies HKLM or HKCU, respectively. bool is_machine_; }; inline bool operator == (const PersistentMetricsIteratorWin32 &a, const PersistentMetricsIteratorWin32 &b) { return a.equals(b); } inline bool operator != (const PersistentMetricsIteratorWin32 &a, const PersistentMetricsIteratorWin32 &b) { return !a.equals(b); } } // namespace stats_report #endif // OMAHA_STATSREPORT_PERSISTENT_ITERATOR_WIN32_H__
1,300
856
// // Copyright © 2020 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #include "SampleMemoryManager.hpp" #include <algorithm> namespace sdb // sample dynamic backend { SampleMemoryManager::SampleMemoryManager() {} SampleMemoryManager::~SampleMemoryManager() {} SampleMemoryManager::Pool* SampleMemoryManager::Manage(unsigned int numBytes) { if (!m_FreePools.empty()) { Pool* res = m_FreePools.back(); m_FreePools.pop_back(); res->Reserve(numBytes); return res; } else { m_Pools.push_front(Pool(numBytes)); return &m_Pools.front(); } } void SampleMemoryManager::Allocate(SampleMemoryManager::Pool* pool) { m_FreePools.push_back(pool); } void* SampleMemoryManager::GetPointer(SampleMemoryManager::Pool* pool) { return pool->GetPointer(); } void SampleMemoryManager::Acquire() { for (Pool &pool: m_Pools) { pool.Acquire(); } } void SampleMemoryManager::Release() { for (Pool &pool: m_Pools) { pool.Release(); } } SampleMemoryManager::Pool::Pool(unsigned int numBytes) : m_Size(numBytes), m_Pointer(nullptr) {} SampleMemoryManager::Pool::~Pool() { if (m_Pointer) { Release(); } } void* SampleMemoryManager::Pool::GetPointer() { return m_Pointer; } void SampleMemoryManager::Pool::Reserve(unsigned int numBytes) { m_Size = std::max(m_Size, numBytes); } void SampleMemoryManager::Pool::Acquire() { m_Pointer = ::operator new(size_t(m_Size)); } void SampleMemoryManager::Pool::Release() { ::operator delete(m_Pointer); m_Pointer = nullptr; } } // namespace sdb
672
1,198
<reponame>dherbst/lullaby /* Copyright 2017-2019 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. */ #ifndef LULLABY_TOOLS_COMPILE_BLUEPRINT_FROM_JSON_BLUEPRINT_FROM_JSON_COMPILER_H_ #define LULLABY_TOOLS_COMPILE_BLUEPRINT_FROM_JSON_BLUEPRINT_FROM_JSON_COMPILER_H_ #include <memory> #include <string> #include <vector> #include "flatbuffers/idl.h" #include "lullaby/modules/ecs/blueprint_builder.h" #include "lullaby/util/span.h" #include "lullaby/util/string_view.h" #include "rapidjson/document.h" namespace lull { namespace tool { // Compiles JSON representations of BlueprintDefs into flatbuffer binaries. class BlueprintFromJsonCompiler { public: BlueprintFromJsonCompiler(); // Parses the contents of |fbs_contents| to adds to the available schema. // |include_paths| is a null-terminated list of cstrings used to resolve any // include statements. // |fbs_filename| is the filename of the fbs. bool ParseFbs(string_view fbs_contents, const char** include_paths, string_view fbs_filename); // Compiles the contents of |json_contents| into a flatbuffer binary and // returns it, or an empty buffer if failed. flatbuffers::DetachedBuffer ParseJson(string_view json_contents); private: bool ParseJsonEntity(const rapidjson::Value& json_entity); std::string GetDefTypeName(string_view def_type); std::unique_ptr<flatbuffers::Parser> fb_parser_; detail::BlueprintBuilder blueprint_builder_; }; } // namespace tool } // namespace lull #endif // LULLABY_TOOLS_COMPILE_BLUEPRINT_FROM_JSON_BLUEPRINT_FROM_JSON_COMPILER_H_
700
4,335
/* ---------------------------------------------------------------------------- * Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved. * Description: Stack Info Implementation * Author: Huawei LiteOS Team * Create: 2019-09-01 * 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 holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written * permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * --------------------------------------------------------------------------- */ #include "securec.h" #include "los_stackinfo_pri.h" #ifdef LOSCFG_SHELL #include "shcmd.h" #include "shell.h" #endif const StackInfo *g_stackInfo = NULL; UINT32 g_stackNum; UINT32 OsStackWaterLineGet(const UINTPTR *stackBottom, const UINTPTR *stackTop, UINT32 *peakUsed) { UINT32 size; const UINTPTR *tmp = NULL; if (*stackTop == OS_STACK_MAGIC_WORD) { tmp = stackTop + 1; while ((tmp < stackBottom) && (*tmp == OS_STACK_INIT)) { tmp++; } size = (UINT32)((UINTPTR)stackBottom - (UINTPTR)tmp); *peakUsed = (size == 0) ? size : (size + sizeof(CHAR *)); return LOS_OK; } else { *peakUsed = OS_INVALID_WATERLINE; return LOS_NOK; } } VOID OsExcStackInfoReg(const StackInfo *stackInfo, UINT32 stackNum) { g_stackInfo = stackInfo; g_stackNum = stackNum; } VOID OsStackInit(VOID *stacktop, UINT32 stacksize) { /* initialize the task stack, write magic num to stack top */ (VOID)memset_s(stacktop, stacksize, (INT32)OS_STACK_INIT, stacksize); *((UINTPTR *)stacktop) = OS_STACK_MAGIC_WORD; } VOID OsGetStackInfo(const StackInfo **stackInfo, UINT32 *stackNum) { *stackInfo = g_stackInfo; *stackNum = g_stackNum; }
999
371
/*************************************************************** //工程名称 : ClassPropertyTest //文件名称 : MyObject.h //创建时间 : 2017/3/14 //创建作者 : JXT //版权归属 : 霖溦 //文件描述 : ***************************************************************/ #import <Foundation/Foundation.h> @interface MyObject : NSObject //实例属性 @property (nonatomic, strong) NSObject * instanceProperty; //类属性1(不加'class'修饰,点方法会报错) @property (nonatomic, strong, class) NSObject * classProperty; //类属性2 @property (nonatomic, strong, class) NSObject * classProperty2; @end
244
19,628
// // UIImageView+DoraemonSDImage.h // DoraemonKit // // Created by yixiang on 2019/6/19. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UIImageView (DoraemonSDImage) @end NS_ASSUME_NONNULL_END
98
575
<gh_stars>100-1000 // Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/launch/file_handling_expiry_impl.h" #include <memory> #include "third_party/blink/public/mojom/file_system_access/file_system_access_directory_handle.mojom-blink.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/origin_trials/origin_trial_context.h" #include "third_party/blink/renderer/core/script/script.h" #include "third_party/blink/renderer/modules/launch/dom_window_launch_queue.h" #include "third_party/blink/renderer/platform/heap/heap_allocator.h" #include "third_party/blink/renderer/platform/wtf/text/string_utf8_adaptor.h" namespace blink { // static const char FileHandlingExpiryImpl::kSupplementName[] = "FileHandlingExpiryImpl"; // static FileHandlingExpiryImpl* FileHandlingExpiryImpl::From(LocalDOMWindow& window) { return Supplement<LocalDOMWindow>::From<FileHandlingExpiryImpl>(window); } // static void FileHandlingExpiryImpl::BindReceiver( LocalFrame* frame, mojo::PendingAssociatedReceiver<mojom::blink::FileHandlingExpiry> receiver) { DCHECK(frame && frame->DomWindow()); auto* expiry_service = FileHandlingExpiryImpl::From(*frame->DomWindow()); if (!expiry_service) { expiry_service = MakeGarbageCollected<FileHandlingExpiryImpl>( base::PassKey<FileHandlingExpiryImpl>(), frame->DomWindow()); Supplement<LocalDOMWindow>::ProvideTo(*frame->DomWindow(), expiry_service); } expiry_service->Bind(std::move(receiver)); } FileHandlingExpiryImpl::FileHandlingExpiryImpl( base::PassKey<FileHandlingExpiryImpl>, LocalDOMWindow* window) : Supplement<LocalDOMWindow>(*window), receivers_(this, window) {} void FileHandlingExpiryImpl::Bind( mojo::PendingAssociatedReceiver<mojom::blink::FileHandlingExpiry> receiver) { receivers_.Add(std::move(receiver), GetSupplementable()->GetFrame()->GetTaskRunner( TaskType::kMiscPlatformAPI)); } void FileHandlingExpiryImpl::Trace(Visitor* visitor) const { visitor->Trace(receivers_); Supplement<LocalDOMWindow>::Trace(visitor); } FileHandlingExpiryImpl::~FileHandlingExpiryImpl() = default; void FileHandlingExpiryImpl::RequestOriginTrialExpiryTime( RequestOriginTrialExpiryTimeCallback callback) { auto* origin_trials = GetSupplementable()->GetExecutionContext()->GetOriginTrialContext(); base::Time expiry_time = origin_trials->GetFeatureExpiry(OriginTrialFeature::kFileHandling); std::move(callback).Run(expiry_time); } } // namespace blink
1,010
3,513
<filename>src/SHADERed/Objects/Debug/DebuggerSuggestion.h #pragma once #include <SHADERed/Objects/PipelineItem.h> #include <glm/glm.hpp> namespace ed { class DebuggerSuggestion { public: enum class SuggestionType { ComputeShader }; DebuggerSuggestion() { Thread = WorkgroupSize = glm::ivec3(0); Type = SuggestionType::ComputeShader; Item = nullptr; } SuggestionType Type; PipelineItem* Item; glm::ivec3 Thread; glm::ivec3 WorkgroupSize; }; }
204
30,023
<gh_stars>1000+ """Support for IBM Watson TTS integration."""
19
12,278
<filename>libs/geometry/index/test/rtree/generated/s2d/rtree_drst_que_s2d.cpp<gh_stars>1000+ // Boost.Geometry Index // Unit Test // Copyright (c) 2011-2014 <NAME>, <NAME>. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <rtree/test_rtree.hpp> int test_main(int, char* []) { typedef bg::model::segment< bg::model::point<double, 2, bg::cs::cartesian> > Indexable; testset::queries<Indexable>(bgi::dynamic_rstar(5, 2), std::allocator<int>()); return 0; }
239
369
<reponame>Shiva-D/rtos-course /* sys/ports_def.h -- Definition of system ports Copyright 2000 Free Software Foundation, Inc. Written by <NAME> (<EMAIL>) This file is part of GEL. GEL is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License** as published by the Free Software Foundation; either version 2, or (at your option) any later version. GEL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GEL; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifndef _SYS_PORTS_DEF_H #define _SYS_PORTS_DEF_H #ifdef mc6811 //# include <asm-m68hc11/ports_def.h> #endif #ifdef mc68hcs12 # include <asm-m68hcs12/ports_def.h> #elif defined(mc6812) //# include <asm-m68hc12/ports_def.h> #endif #endif /* _SYS_PORTS_DEF_H */
367
988
//------------------------------------------------------------------------------ // GB_AxB_saxpy_template: C=A*B, C<M>=A*B, or C<!M>=A*B via saxpy method //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // All 4 matrices have any format: hypersparse, sparse, bitmap, or full. { switch (saxpy_method) { case GB_SAXPY_METHOD_3 : { // C is sparse or hypersparse, using minimal workspace. ASSERT (GB_IS_SPARSE (C) || GB_IS_HYPERSPARSE (C)) ; if (M == NULL) { // C = A*B, no mask #define GB_NO_MASK 1 #define GB_MASK_COMP 0 #include "GB_AxB_saxpy3_template.c" } else if (!Mask_comp) { // C<M> = A*B #define GB_NO_MASK 0 #define GB_MASK_COMP 0 #include "GB_AxB_saxpy3_template.c" } else { // C<!M> = A*B #define GB_NO_MASK 0 #define GB_MASK_COMP 1 #include "GB_AxB_saxpy3_template.c" } } break ; case GB_SAXPY_METHOD_BITMAP : { // C is bitmap or full #include "GB_bitmap_AxB_saxpy_template.c" } default:; } }
814
575
<gh_stars>100-1000 // Copyright 2016-2019 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /** * @file LivelinessManager.h */ #ifndef _FASTDDS_RTPS_LIVELINESS_MANAGER_H_ #define _FASTDDS_RTPS_LIVELINESS_MANAGER_H_ #include <fastdds/rtps/resources/TimedEvent.h> #include <fastdds/rtps/writer/LivelinessData.h> #include <fastrtps/utils/collections/ResourceLimitedVector.hpp> #include <fastrtps/utils/shared_mutex.hpp> #include <mutex> namespace eprosima { namespace fastrtps { namespace rtps { using LivelinessCallback = std::function<void ( const GUID_t&, const LivelinessQosPolicyKind&, const Duration_t&, int32_t alive_change, int32_t not_alive_change)>; /** * @brief A class managing the liveliness of a set of writers. Writers are represented by their LivelinessData * @details Uses a shared timed event and informs outside classes on liveliness changes * @ingroup WRITER_MODULE */ class LivelinessManager { public: /** * @brief Constructor * @param callback A callback that will be invoked when a writer changes its liveliness status * @param service ResourceEvent object that will operate with the events. * @param manage_automatic True to manage writers with automatic liveliness, false otherwise */ LivelinessManager( const LivelinessCallback& callback, ResourceEvent& service, bool manage_automatic = true); /** * @brief Constructor */ ~LivelinessManager(); /** * @brief LivelinessManager * @param other */ LivelinessManager( const LivelinessManager& other) = delete; /** * @brief Adds a writer to the set * @param guid GUID of the writer * @param kind Liveliness kind * @param lease_duration Liveliness lease duration * @return True if the writer was successfully added */ bool add_writer( GUID_t guid, LivelinessQosPolicyKind kind, Duration_t lease_duration); /** * @brief Removes a writer * @param guid GUID of the writer * @param kind Liveliness kind * @param lease_duration Liveliness lease duration * @return True if the writer was successfully removed */ bool remove_writer( GUID_t guid, LivelinessQosPolicyKind kind, Duration_t lease_duration); /** * @brief Asserts liveliness of a writer in the set * @param guid The writer to assert liveliness of * @param kind The kind of the writer * @param lease_duration The lease duration * @return True if liveliness was successfully asserted */ bool assert_liveliness( GUID_t guid, LivelinessQosPolicyKind kind, Duration_t lease_duration); /** * @brief Asserts liveliness of writers with given liveliness kind * @param kind Liveliness kind * @return True if liveliness was successfully asserted */ bool assert_liveliness( LivelinessQosPolicyKind kind); /** * @brief A method to check any writer of the given kind is alive * @param kind The liveliness kind to check for * @return True if at least one writer of this kind is alive. False otherwise */ bool is_any_alive( LivelinessQosPolicyKind kind); /** * @brief A method to return liveliness data * @details Should only be used for testing purposes * @return Vector of liveliness data */ const ResourceLimitedVector<LivelinessData>& get_liveliness_data() const; private: /** * @brief A method responsible for invoking the callback when liveliness is asserted * @param writer The liveliness data of the writer asserting liveliness * @pre The collection shared_mutex must be taken for reading */ void assert_writer_liveliness( LivelinessData& writer); /** * @brief A method to calculate the time when the next writer is going to lose liveliness * @details This method is public for testing purposes but it should not be used from outside this class * @pre std::mutex_ should not be taken on calling this method to avoid deadlock. * @return True if at least one writer is alive */ bool calculate_next(); //! @brief A method called if the timer expires //! @return True if the timer should be restarted bool timer_expired(); //! A callback to inform outside classes that a writer changed its liveliness status const LivelinessCallback callback_; //! A boolean indicating whether we are managing writers with automatic liveliness const bool manage_automatic_; //! A vector of liveliness data ResourceLimitedVector<LivelinessData> writers_; //! A mutex to protect the liveliness data included LivelinessData objects std::mutex mutex_; //! A mutex devoted to protect the writers_ collection eprosima::shared_mutex col_mutex_; //! The timer owner, i.e. the writer which is next due to lose its liveliness LivelinessData* timer_owner_; //! A timed callback expiring when a writer (the timer owner) loses its liveliness TimedEvent timer_; }; } /* namespace rtps */ } /* namespace fastrtps */ } /* namespace eprosima */ #endif /* _FASTDDS_RTPS_LIVELINESS_MANAGER_H_ */
2,069
2,023
<reponame>tdiprima/code #!/usr/bin/python2.6 # -*- coding: utf-8 -*- """ Read page indices to build book index. """ # index should be between 3 and 9 pages #1. fix tricky names (e.g., <NAME>, <NAME>) import codecs import getopt from optparse import OptionParser import os import re import sys ABBRV = ( ('NPOV', 'Neutral Point of View (NPOV)'), ('IETF', 'Internet Engineering Task Force (IETF)'), ('ODF', 'Open Document Format (ODF)'), ('W3C', 'World Wide Web Consortium (W3C)'), ('OASIS', 'Organization for the Advancement of Structured Information Standards'), ) BORING_WORDS = ('', 'a', 'also', 'of', 'if', 'in', 'an', 'to', 'for', 'the', 'and', 're') NAMES = set() # from http://names.mongabay.com/ for line in open('/home/reagle/joseph/2010/03/names-male.csv'): NAMES.add(line.split(' ')[0]) for line in open('/home/reagle/joseph/2010/03/names-female.csv'): NAMES.add(line.split(' ')[0]) NAMES_EXCEPTIONS = set(['LONG']) NAMES.difference_update(NAMES_EXCEPTIONS) # exceptions to the lists KEEP_LOWER = ('danah', 'boyd') def a_name(text): """Test if a common first name. >>> a_name("John") True """ text = text.upper() if text[1] == '.': # e.g., <NAME> return True if text in NAMES: return True return False def strip_var(v): """Strip a bit of text >>> strip_var(' foo bar ') 'foo bar' """ if v: return v.strip() else: return None def build_index(text): index = {} pattern_re = re.compile( r'(?P<topic>\D.+?) (?:see (?P<see_ref>.*)|(?P<pages>[0-9,\-n]+(?!\.)) ?(?P<subtopic>.*))') for line in text: if line == '': continue if opts.debug: print 'line =', line topic, see_ref, pages, subtopic = pattern_re.match(line).groupdict().values() topic, see_ref, pages, subtopic = map(strip_var, (topic, see_ref, pages, subtopic)) chunks = topic.split(' ') if len(chunks) > 1: if a_name(chunks[0]): pre, last = topic.split(' ', 1) topic = chunks[-1] + ', ' + ' '.join(chunks[0:-1]) if topic not in index: index[topic] = {} if see_ref: if see_ref.startswith('also '): index[topic].setdefault('also', []).append(see_ref[5:]) else: index[topic].setdefault('see', []).append(see_ref) elif subtopic: index[topic].setdefault('subtopics', {}).setdefault(subtopic, []).append(pages) else: index[topic].setdefault('pages', []).append(pages) return index def entitle(s): '''title case first word of refs >>> entitle('also monographic principle') 'also monographic principle' >>> entitle('monographic principle') 'Monographic principle' ''' new_refs = [] if s.startswith('\tsee also '): # remove 'see' prefix text s = s[10:] prefix = '. *See also* ' elif s.startswith('\tsee '): s = s[5:] prefix = '. *See* ' else: prefix = '' refs = s.split('; ') for ref in refs: # check refs words = ref.split() if words[0] not in BORING_WORDS and words[0][0].islower(): words[0] = words[0].title() words = ' '.join(words) new_refs.append(words) return prefix + '; '.join(sorted(new_refs)) range_re = re.compile(u'\d+[-–n]\d+') def sort_range(text): """Sort index page refs such that: >>> sort_range('12-13') 12 >>> sort_range('5n3') 5 >>> sort_range('see also Smith') 'see also Smith' """ if range_re.match(text): if 'n' in text: text = text.split('n')[0] if '-' in text: text = text.split('-')[0] if u'–' in text: # ndash text = text.split(u'–')[0] if text.isdigit(): text = int(text) return text def sort_topic(topic): topic = topic.replace('"', '').replace('*', '') words = topic.split(' ') if words[0] in ('and', 'on', 'see', 'also'): words.pop(0) words[0] = words[0].upper() return words emphasis_re = re.compile(r'\*(.*)\*') def fixup(s): """Make some final formatting tweaks >>> fixup('on "zeal in research", 156') 'on "zeal in research," 156' """ s = emphasis_re.sub(r'<em>\1</em>', s) # replace asterisks with balanced <em> return s.replace('",', ',"') # move comma inside quotes def print_index(index): """Print the index""" fdo.write('<html>' '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>' '<body><pre>') for topic in sorted(index, key=sort_topic): topic_txt = topic pages_txt = see_txt = also_txt = '' # uppercase first letter of entries, and replace abbreviations if topic.split(', ')[0] not in KEEP_LOWER: topic_txt = topic[0].upper() + topic[1:] for abbrv, expansion in ABBRV: topic_txt = topic_txt.replace(abbrv, expansion) if 'pages' in index[topic]: pages_txt = ', ' + ', '.join(index[topic]['pages'])\ .replace('-', u'–') # ndash # cross references if 'see' in index[topic] and index[topic]['see'] != [None]: see_refs = index[topic]['see'] see_refs = [entitle(ref) for ref in see_refs] see_txt = '. *See* ' + '; '.join(sorted(see_refs)) if 'also' in index[topic] and index[topic]['also'] != [None]: also_refs = index[topic]['also'] also_refs = [entitle(ref) for ref in also_refs] also_txt = '. *See also* ' + '; '.join(sorted(also_refs)) if 'subtopics' not in index[topic]: fdo.write(fixup(topic_txt + pages_txt + see_txt + also_txt + '\n')) else: subtopics = index[topic]['subtopics'] # a dict sub_txt = sub_pages_txt = '' sub_pages = [] # join if topic has no pages itself and only one subtopic if 'pages' not in index[topic] and len(subtopics) == 1: sub_txt, sub_pages = subtopics.items()[0] sub_pages_txt = ', ' + ', '.join(sub_pages)\ .replace('-', u'–') # ndash fdo.write(fixup(topic_txt + ', ' + sub_txt + sub_pages_txt + '\n')) continue # collapse if number of subentries below threshold elif 0 < len(subtopics) <= opts.collapse: for subtopic in subtopics: sub_pages.extend(subtopics[subtopic]) sub_pages_txt += ', ' + ', '.join(sorted(sub_pages, key=sort_range))\ .replace('-', u'–') # ndash fdo.write(fixup(topic_txt + sub_pages_txt + '\n')) continue # write out subtopics normally else: fdo.write(fixup(topic_txt + pages_txt + see_txt + also_txt + '\n')) for subtopic in subtopics: fdo.write(fixup('\t' + subtopic + ', ' + ', '.join(subtopics[subtopic]).replace('-', u'–') +'\n')) fdo.write('</pre></body></html>') if __name__ == "__main__": sys.stdout = codecs.getwriter('UTF-8')(sys.__stdout__, errors='replace') parser = OptionParser(usage="usage: %prog [options] [FILE]") parser.add_option("-d", "--debug", default=False, action="store_true", help="print lines as processed") parser.add_option("-c", "--collapse", default=0, type="int", help="collapse if <= THRESHOLD subentries (default: %default)", metavar="THRESHOLD") parser.add_option("-t", "--tests", action="store_true", default=False, help="run tests") opts, files = parser.parse_args() if opts.tests: print "Running doctests" import doctest doctest.testmod() fn = files[0] fdi = codecs.open(fn, "rb", 'utf-8') text = [line.strip() for line in fdi.readlines()] text[0] = text[0].lstrip(unicode(codecs.BOM_UTF8, "utf8")) fileOut = os.path.splitext(fn)[0] + '-formatted.html' fdo = codecs.open(fileOut, "wb", "utf-8") index = build_index(text) print_index(index)
3,014
379
package com.oim.fx.view.node; import com.oim.core.business.sender.UserCategoryMemberSender; import com.oim.core.business.service.UserService; import com.oim.core.business.view.UserDataView; import com.oim.core.common.app.view.UserHeadMenuView; import com.only.common.result.Info; import com.only.fx.common.component.OnlyMenuItem; import com.only.net.action.Back; import com.only.net.data.action.DataBackActionAdapter; import com.onlyxiahui.app.base.AppContext; import com.onlyxiahui.app.base.view.AbstractView; import com.onlyxiahui.im.bean.UserData; import javafx.application.Platform; import javafx.geometry.Side; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.ContextMenu; import javafx.scene.control.TextInputDialog; import javafx.scene.control.Alert.AlertType; import javafx.stage.Modality; import javafx.stage.Window; /** * @author XiaHui * @date 2017年9月4日 下午5:22:57 */ public class UserHeadMenuViewImpl extends AbstractView implements UserHeadMenuView { Alert information = new Alert(AlertType.INFORMATION); TextInputDialog textInput = new TextInputDialog(""); private ContextMenu menu = new ContextMenu(); private OnlyMenuItem showMenuItem = new OnlyMenuItem(); private OnlyMenuItem updateRemarkMenuItem = new OnlyMenuItem(); private OnlyMenuItem deleteMenuItem = new OnlyMenuItem(); UserData userData; public UserHeadMenuViewImpl(AppContext appContext) { super(appContext); initMenu(); initEvent(); } private void initMenu() { information.initModality(Modality.APPLICATION_MODAL); information.initOwner(menu); information.getDialogPane().setHeaderText(null); textInput.setTitle("输入备注"); textInput.setContentText("备注:"); textInput.getEditor().setText(""); showMenuItem.setText("查看信息"); updateRemarkMenuItem.setText("修改备注"); deleteMenuItem.setText("删除好友"); menu.getItems().add(showMenuItem); menu.getItems().add(updateRemarkMenuItem); menu.getItems().add(deleteMenuItem); } private void initEvent() { showMenuItem.setOnAction(a -> { UserDataView v = appContext.getSingleView(UserDataView.class); v.showUserData(userData); v.setVisible(true); }); updateRemarkMenuItem.setOnAction(a -> { textInput.getEditor().setText(null==userData?"":userData.getRemarkName()); textInput.showAndWait().ifPresent(response -> { if (null == response || response.isEmpty()) { } else { updateUserRemark(response); } }); }); deleteMenuItem.setOnAction(a -> { deleteUser(); }); } @Override public void setUserData(UserData userData) { this.userData = userData; } @Override public void show(Window ownerWindow, double anchorX, double anchorY) { menu.show(ownerWindow, anchorX, anchorY); } public void showPrompt(String text) { information.getDialogPane().setContentText(text); information.showAndWait(); } public void clearData() { textInput.getEditor().setText(""); } public void updateUserRemark(String remark) { if (null!=userData&&null != remark && !"".equals(remark)) { String userId=userData.getId(); DataBackActionAdapter action = new DataBackActionAdapter() { @Override public void lost() { Platform.runLater(new Runnable() { @Override public void run() { showPrompt("修改失败!"); } }); } @Override public void timeOut() { Platform.runLater(new Runnable() { @Override public void run() { showPrompt("修改失败!"); } }); } @Back public void back(Info info) { if (info.isSuccess()) { UserService userService = appContext.getService(UserService.class); userService.updateRemarkName(userId, remark); } else { Platform.runLater(new Runnable() { @Override public void run() { showPrompt("修改失败!"); } }); } } }; UserCategoryMemberSender ucms = this.appContext.getSender(UserCategoryMemberSender.class); ucms.updateUserCategoryMemberRemark(userId, remark, action); } } public void deleteUser() { if (null!=userData) { String userId=userData.getId(); DataBackActionAdapter action = new DataBackActionAdapter() { @Override public void lost() { Platform.runLater(new Runnable() { @Override public void run() { showPrompt("删除失败!"); } }); } @Override public void timeOut() { Platform.runLater(new Runnable() { @Override public void run() { showPrompt("删除失败!"); } }); } @Back public void back(Info info) { if (info.isSuccess()) { UserService userService = appContext.getService(UserService.class); userService.deleteUser(userId); } else { Platform.runLater(new Runnable() { @Override public void run() { showPrompt("删除失败!"); } }); } } }; UserCategoryMemberSender ucms = this.appContext.getSender(UserCategoryMemberSender.class); ucms.deleteUserCategoryMember(userId, action); } } @Override public void show(Node anchor, double screenX, double screenY) { menu.show(anchor, screenX, screenY); } @Override public void show(Node anchor, Side side, double dx, double dy) { menu.show(anchor, side, dx, dy); } }
2,177
316
<reponame>pcrane70/Argus /* * Copyright (c) 2016, Salesforce.com, Inc. * 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. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.dva.argus.entity; import com.google.inject.persist.Transactional; import com.salesforce.dva.argus.system.SystemAssert; import java.util.Objects; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.NoResultException; import javax.persistence.Table; import javax.persistence.TypedQuery; import javax.persistence.UniqueConstraint; import static com.salesforce.dva.argus.system.SystemAssert.requireArgument; /** * The entity encapsulates information about whether a particular Argus sub-system has been enabled or disabled. * * <p>Fields that determine uniqueness are:</p> * * <ul> * <li>SERVICE</li> * </ul> * * <p>Fields that cannot be null are:</p> * * <ul> * <li>SERVICE</li> * <li>ENABLED</li> * </ul> * * @author <NAME> (<EMAIL>) */ @SuppressWarnings("serial") @Entity @Table(name = "SERVICE_MANAGEMENT_RECORD", uniqueConstraints = @UniqueConstraint(columnNames = { "service" })) @NamedQueries( { @NamedQuery(name = "ServiceManagementRecord.findByService", query = "SELECT r FROM ServiceManagementRecord r WHERE r.service = :service") } ) public class ServiceManagementRecord extends JPAEntity { //~ Instance fields ****************************************************************************************************************************** @Enumerated(EnumType.STRING) @Column(nullable = false) private Service service; @Basic(optional = false) @Column(name = "enabled", nullable = false) boolean enabled; //~ Constructors ********************************************************************************************************************************* /** * Creates a ServiceManagementRecord object. * * @param creator The creator of this record. * @param service The service to manage. Cannot be null. * @param enabled Whether the service is enabled or disabled. */ public ServiceManagementRecord(PrincipalUser creator, Service service, boolean enabled) { super(creator); setService(service); setEnabled(enabled); } /** Creates a ServiceManagementRecord object. */ protected ServiceManagementRecord() { super(null); } //~ Methods ************************************************************************************************************************************** /** * Returns a record for the specified service. * * @param em The entity manager to use. Cannot be null. * @param service The service for which to obtain the record. Cannot be null. * * @return The management record for the specified service or null if no record exists. */ public static ServiceManagementRecord findServiceManagementRecord(EntityManager em, Service service) { requireArgument(em != null, "Entity manager can not be null."); requireArgument(service != null, "Service cannot be null."); TypedQuery<ServiceManagementRecord> query = em.createNamedQuery("ServiceManagementRecord.findByService", ServiceManagementRecord.class); try { query.setParameter("service", service); return query.getSingleResult(); } catch (NoResultException ex) { return null; } } /** * Determine a given service's enability. * * @param em The EntityManager to use. * @param service The service for which to determine enability. * * @return True or false depending on whether the service is enabled or disabled. */ public static boolean isServiceEnabled(EntityManager em, Service service) { ServiceManagementRecord record = findServiceManagementRecord(em, service); return record == null ? true : record.isEnabled(); } /** * Updates the ServiceManagementRecord entity. * * @param em Entity manager. Cannot be null. * @param record serviceManagementRecord object. Cannot be null. * * @return updated ServiceManagementRecord entity. */ @Transactional public static ServiceManagementRecord updateServiceManagementRecord(EntityManager em, ServiceManagementRecord record) { SystemAssert.requireArgument(em != null, "Entity manager can not be null."); SystemAssert.requireArgument(record != null, "ServiceManagementRecord cannot be null."); TypedQuery<ServiceManagementRecord> query = em.createNamedQuery("ServiceManagementRecord.findByService", ServiceManagementRecord.class); query.setParameter("service", record.getService()); try { ServiceManagementRecord oldRecord = query.getSingleResult(); oldRecord.setEnabled(record.isEnabled()); return em.merge(oldRecord); } catch (NoResultException ex) { return em.merge(record); } } //~ Methods ************************************************************************************************************************************** /** * Returns the service associated with the record. * * @return The service associated with the record. */ public Service getService() { return service; } /** * Sets the service associated with the record. * * @param service The service associated with the record. Cannot be null. */ public void setService(Service service) { SystemAssert.requireArgument(service != null, "Service cannot be null."); this.service = service; } /** * Indicates whether the service is enabled. * * @return True if enabled or false if it is disabled. */ public boolean isEnabled() { return enabled; } /** * Enables or disables the associated service. * * @param enabled True if enabled or false if it is disabled. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public int hashCode() { int hash = 7; hash = 67 * hash + Objects.hashCode(this.service); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ServiceManagementRecord other = (ServiceManagementRecord) obj; if (this.service != other.service) { return false; } return true; } @Override public String toString() { return "ServiceManagementRecord{" + "service=" + service + ", enabled=" + enabled + '}'; } //~ Enums **************************************************************************************************************************************** /** * The list of interfaces that are supported by the management service. * * @author <NAME> (<EMAIL>) */ public enum Service { MONITORING("Monitoring"), WARDEN("Warden"), SCHEDULING("Scheduling"); private String _name; /** * Creates a new Service object. * * @param name The name of the object. */ Service(String name) { _name = name; } /** * Returns the name of the object. * * @return Returns the name of the service. */ public String getName() { return _name; } /** * Sets the name of the object. * * @param name The name of the associated service. */ public void setName(String name) { _name = name; } } } /* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
3,235
348
{"nom":"Veslud","circ":"1ère circonscription","dpt":"Aisne","inscrits":179,"abs":77,"votants":102,"blancs":4,"nuls":8,"exp":90,"res":[{"nuance":"REM","nom":"<NAME>","voix":54},{"nuance":"FN","nom":"<NAME>","voix":36}]}
89
421
<gh_stars>100-1000  // The following code example shows how to create a CultureInfo for S"Spanish - Spain" // with the international sort and another with the traditional sort. // <snippet1> using namespace System; using namespace System::Collections; using namespace System::Globalization; int main() { // Creates and initializes the CultureInfo which uses the international sort. CultureInfo^ myCIintl = gcnew CultureInfo( "es-ES",false ); // Creates and initializes the CultureInfo which uses the traditional sort. CultureInfo^ myCItrad = gcnew CultureInfo( 0x040A,false ); // Displays the properties of each culture. Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "PROPERTY", "INTERNATIONAL", "TRADITIONAL" ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "CompareInfo", myCIintl->CompareInfo, myCItrad->CompareInfo ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "DisplayName", myCIintl->DisplayName, myCItrad->DisplayName ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "EnglishName", myCIintl->EnglishName, myCItrad->EnglishName ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "IsNeutralCulture", myCIintl->IsNeutralCulture, myCItrad->IsNeutralCulture ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "IsReadOnly", myCIintl->IsReadOnly, myCItrad->IsReadOnly ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "LCID", myCIintl->LCID, myCItrad->LCID ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "Name", myCIintl->Name, myCItrad->Name ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "NativeName", myCIintl->NativeName, myCItrad->NativeName ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "Parent", myCIintl->Parent, myCItrad->Parent ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "TextInfo", myCIintl->TextInfo, myCItrad->TextInfo ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "ThreeLetterISOLanguageName", myCIintl->ThreeLetterISOLanguageName, myCItrad->ThreeLetterISOLanguageName ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "ThreeLetterWindowsLanguageName", myCIintl->ThreeLetterWindowsLanguageName, myCItrad->ThreeLetterWindowsLanguageName ); Console::WriteLine( "{0,-31}{1,-47}{2,-25}", "TwoLetterISOLanguageName", myCIintl->TwoLetterISOLanguageName, myCItrad->TwoLetterISOLanguageName ); Console::WriteLine(); // Compare two strings using myCIintl -> Console::WriteLine( "Comparing \"llegar\" and \"lugar\"" ); Console::WriteLine( " With myCIintl -> CompareInfo -> Compare: {0}", myCIintl->CompareInfo->Compare( "llegar", "lugar" ) ); Console::WriteLine( " With myCItrad -> CompareInfo -> Compare: {0}", myCItrad->CompareInfo->Compare( "llegar", "lugar" ) ); } /* This code produces the following output. PROPERTY INTERNATIONAL TRADITIONAL CompareInfo CompareInfo - es-ES CompareInfo - es-ES_tradnl DisplayName Spanish (Spain) Spanish (Spain) EnglishName Spanish (Spain, International Sort) Spanish (Spain, Traditional Sort) IsNeutralCulture False False IsReadOnly False False LCID 3082 1034 Name es-ES es-ES NativeName Español (España, alfabetización internacional) Español (España, alfabetización tradicional) Parent es es TextInfo TextInfo - es-ES TextInfo - es-ES_tradnl ThreeLetterISOLanguageName spa spa ThreeLetterWindowsLanguageName ESN ESP TwoLetterISOLanguageName es es Comparing "llegar" and "lugar" With myCIintl -> CompareInfo -> Compare: -1 With myCItrad -> CompareInfo -> Compare: 1 */ // </snippet1>
2,179
453
/* * Promise API implemented by cpp as Javascript promise style * * Copyright (c) 2016, xhawk18 * at gmail.com * * The MIT License (MIT) * * 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. */ #include <stdio.h> #include <string> #include <vector> #include "promise-cpp/promise.hpp" using namespace promise; #define output_func_name() do{ printf("in function %s, line %d\n", __func__, __LINE__); } while(0) void test1() { output_func_name(); } int test2() { output_func_name(); return 5; } void test3(int n) { output_func_name(); printf("n = %d\n", n); } Promise run(Promise &next){ return newPromise([](Defer d) { output_func_name(); d.resolve(3, 5, 6); }).then([](pm_any &any){ output_func_name(); return resolve(3, 5, 16); }).then([](const int &a, int b, int c) { printf("%d %d %d\n", a, b, c); output_func_name(); }).then([](){ output_func_name(); }).then([&next](){ output_func_name(); next = newPromise([](Defer d) { output_func_name(); }); //Will call next.resole() or next.reject() later //throw 33; //next.reject(55, 66); return next; }).finally([](int n) { printf("finally n == %d\n", n); }).then([](int n, char c) { output_func_name(); printf("n = %d, c = %c\n", (int)n, c); }).then([](char n) { output_func_name(); printf("n = %d\n", (int)n); }).fail([](char n) { output_func_name(); printf("n = %d\n", (int)n); }).fail([](short n) { output_func_name(); printf("n = %d\n", (int)n); }).fail([](int &n) { output_func_name(); printf("n = %d\n", (int)n); }).fail([](const std::string &str) { output_func_name(); printf("str = %s\n", str.c_str()); }).fail([](uint64_t n) { output_func_name(); printf("n = %d\n", (int)n); }).then(test1) .then(test2) .then(&test3); //.always([]() { // output_func_name(); //}); } void test_promise_all() { std::vector<Promise> ds = { newPromise([](Defer d) { output_func_name(); d.resolve(1); //d.reject(1); }), newPromise([](Defer d) { output_func_name(); d.resolve(2); }) }; all(ds).then([]() { output_func_name(); }, []() { output_func_name(); }); } int main(int argc, char **argv) { handleUncaughtException([](Promise &d) { d.fail([](long n, int m) { printf("UncaughtException parameters = %d %d\n", (int)n, m); }).fail([]() { printf("UncaughtException\n"); }); }); test_promise_all(); Promise next; run(next); printf("====== after call run ======\n"); //next.reject(123, 'a'); if(next) { next.reject((long)123, (int)345); //it will go to handleUncaughtException(...) } //next.resolve('b'); //next.reject(std::string("xhchen")); //next.reject(45); return 0; }
1,965
575
<filename>tools/mb/mb_config_expectations/client.v8.fyi.json { "Android V8 FYI Release (Nexus 5X)": { "gn_args": { "dcheck_always_on": true, "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "symbol_level": 1, "target_cpu": "arm64", "target_os": "android", "use_goma": true, "use_static_angle": true } }, "Linux ASAN Builder": { "gn_args": { "dcheck_always_on": true, "is_asan": true, "is_component_build": false, "is_debug": false, "is_lsan": true, "symbol_level": 1, "use_goma": true } }, "Linux Debug Builder": { "gn_args": { "ffmpeg_branding": "Chrome", "is_component_build": true, "is_debug": true, "proprietary_codecs": true, "symbol_level": 1, "use_goma": true } }, "Linux V8 FYI Release (NVIDIA)": { "gn_args": { "dcheck_always_on": true, "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "symbol_level": 1, "use_goma": true } }, "Linux V8 FYI Release - pointer compression (NVIDIA)": { "gn_args": { "dcheck_always_on": true, "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "symbol_level": 1, "use_goma": true, "v8_enable_pointer_compression": false } }, "Mac V8 FYI Release (Intel)": { "gn_args": { "dcheck_always_on": true, "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "symbol_level": 1, "use_goma": true } }, "V8 Android GN (dbg)": { "gn_args": { "ffmpeg_branding": "Chrome", "is_component_build": true, "is_debug": true, "proprietary_codecs": true, "symbol_level": 1, "target_os": "android", "use_goma": true } }, "V8 Blink Linux": { "gn_args": { "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "use_goma": true } }, "V8 Blink Linux Debug": { "gn_args": { "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "use_goma": true, "v8_enable_debugging_features": true } }, "V8 Blink Linux Future": { "gn_args": { "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "use_goma": true } }, "V8 Blink Linux Layout NG": { "gn_args": { "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "use_goma": true } }, "V8 Blink Mac": { "gn_args": { "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "use_goma": true } }, "V8 Blink Win": { "gn_args": { "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "use_goma": true } }, "V8 Linux GN": { "gn_args": { "is_component_build": false, "is_debug": false, "use_goma": true } }, "Win V8 FYI Release (NVIDIA)": { "gn_args": { "dcheck_always_on": true, "enable_resource_allowlist_generation": true, "ffmpeg_branding": "Chrome", "is_component_build": false, "is_debug": false, "proprietary_codecs": true, "symbol_level": 1, "target_cpu": "x86", "use_goma": true } } }
1,894
460
<gh_stars>100-1000 // Boost.Bimap // // Copyright (c) 2006-2007 <NAME> // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) /// \file detail/concept_tags.hpp /// \brief Bimap tags and concepts #ifndef BOOST_BIMAP_DETAIL_CONCEPT_TAGS_HPP #define BOOST_BIMAP_DETAIL_CONCEPT_TAGS_HPP #if defined(_MSC_VER) && (_MSC_VER>=1200) #pragma once #endif #include <boost/config.hpp> #include <boost/mpl/identity.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/bool.hpp> namespace boost { namespace bimaps { namespace detail { /// \brief Tag of {SetType}_of definition classes /** The {SetType}_of classes are derived from this class so it is easy to construct metafunctions. For example now is easy to create a is_set_type_of metafunction. **/ struct set_type_of_tag {}; /// \brief Tag of {SetType}_of_relation defition classes struct set_type_of_relation_tag {}; /// \brief Tag of {Side}_based identifiers struct side_based_tag : set_type_of_relation_tag {}; } // namespace detail /** \struct boost::bimaps::left_based \brief Tag to indicate that the main view will be based on the left side. This is convenient because the multi-index core will be more efficient. If possible use this options or the right based one. See also right_based. **/ /** \struct boost::bimaps::right_based \brief Tag to indicate that the main view will be based on the right side. This is convenient because the multi-index core will be more efficient. If possible use this options or the right based one. See also left_based. **/ #ifndef BOOST_BIMAP_DOXYGEN_WILL_NOT_PROCESS_THE_FOLLOWING_LINES struct left_based : ::boost::bimaps::detail::side_based_tag { // I run into troubles if I do not define bind for side based tags. // Maybe a more coherent way of binding the relation can be developped. template< class Relation > struct bind_to { typedef void type; }; typedef mpl::bool_<true> left_mutable_key; typedef mpl::bool_<true> right_mutable_key; }; struct right_based : ::boost::bimaps::detail::side_based_tag { // I run into troubles if I do not define bind for side based tags. // Maybe a more coherent way of binding the relation can be developped. template< class Relation > struct bind_to { typedef void type; }; typedef mpl::bool_<true> left_mutable_key; typedef mpl::bool_<true> right_mutable_key; }; #endif // BOOST_BIMAP_DOXYGEN_WILL_NOT_PROCESS_THE_FOLLOWING_LINES typedef mpl::_ _relation; } // namespace bimaps } // namespace boost #endif // BOOST_BIMAP_DETAIL_CONCEPT_TAGS_HPP
1,274
588
package com.flycms.web.tags; import com.flycms.constant.Const; import com.flycms.core.base.AbstractTagPlugin; import com.flycms.module.user.model.User; import freemarker.core.Environment; import freemarker.template.*; import org.springframework.stereotype.Service; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.util.Map; /** * Open source house, All rights reserved * 开发公司:28844.com<br/> * 版权:开源中国<br/> * * 网站样式等静态资源路径查询标签 * * @author sunkaifei * */ @Service public class Login extends AbstractTagPlugin { @Override @SuppressWarnings("rawtypes") public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); try { //获取HttpSession User loginMember = (User) request.getSession().getAttribute(Const.SESSION_USER); env.setVariable("status", builder.build().wrap(loginMember)); body.render(env.getOut()); } catch (Exception e) { e.printStackTrace(); } } }
462
522
/** * @file dot_medianSort.c Generate MedianSort DOT graph * @brief * Implementation that uses dot.h interface to produce on stdout the * DOT commands for a MedianSort execution. * * This code is not intended to be used for sorting. Rather, it * generates DOTTY output that shows the behavior of Median Sort. You * have been warned. Specifically, to compute the median, this code * calls qsort. Ridiculous? You bet! But it simplifies the creation * of the Dotty output. * * @author <NAME> * @date 6/15/08 */ #include <stdio.h> #include <stdlib.h> #include "dot.h" /** * Sort using mediansort method, generating Dotty output to generate a * visualization of the sort algorithm. * * @param id identifier of the graph node generated for this recursive invocation * @param ar array of values * @param cmp comparison function to use * @param left The left-bounds within which to sort (0 <= left < ar.length) * @param right The right-bounds within which to sort (0 <= right < ar.length) */ int mediansort (int id, long *ar, int(*cmp)(const long *,const long *), int left, int right) { DOT_FORMAT_PTR fmt = 0; int sameL, sameR; int i, ct, mid, me = -1; long *copy, med; if (right <= left) { return 0; } /* go backwards to avoid null cases. avoid trivial first case */ if (id/2 > 0) { dot_add_undir_edge (2000+id/2, id); } /* get midpoint and median element position (note 1<=k<=right-left-1). */ /* compute in copy so we don't alter the elements. Note the allocation. */ mid = ((right + left)/2)-left; copy = malloc ((right-left+1)*sizeof (long)); for (i = left; i <= right; i++) { copy [i-left] = ar[i]; } /* return position */ qsort (copy, right-left+1, sizeof (long), (int(*)())cmp); med = copy[mid]; free (copy); /* find where 'med' is within 'ar' */ for (i = left; i <= right; i++) { if (ar[i] == med) { me = i; break; } } /* output line with BLACK median */ fmt = dot_format_list(); dot_add_format (fmt, dot_format_type (left+mid, BLACK));/* ADD BLACK first */ dot_add_format (fmt, dot_format_type (me, GRAY)); /* gray comes next */ dot_node (ar, id, left, right, fmt); dot_release (fmt); fmt = 0; /* swap median/me */ if (me != left+mid) { long tmp = ar[me]; ar[me] = ar[left+mid]; ar[left+mid] = tmp; } /* now identify all higher-out-of-place (BUT DON'T SWAP) */ fmt = dot_format_list(); dot_add_format (fmt, dot_format_type (left+mid, BLACK)); ct = 0; for (i = left; i < left+mid ; i++) { int j; int dct = ct; /* count-down since not swapping */ /* an element left of median greater than it? Find one to swap */ if (ar[i] > ar[left+mid]) { dot_add_format (fmt, dot_format_type (i, GRAY)); for (j = left+mid+1; j <= right; j++) { if (ar[j] <= ar[left+mid] && --dct<0) { dot_add_format (fmt, dot_format_type (j, GRAY)); ct++; break; } } } } /* intermediate nodes are 1000+ */ dot_node (ar, 1000+id, left, right, fmt); dot_release (fmt); /* tie together. */ dot_add_undir_edge (id, 1000+id); /* now swap all higher-out-of-place */ fmt = dot_format_list(); dot_add_format (fmt, dot_format_type (left+mid, BLACK)); for (i = left; i < left+mid ; i++) { int j; /* an element left of median greater than it? Find one to swap */ if (ar[i] > ar[left+mid]) { for (j = left+mid+1; j <= right; j++) { if (ar[j] <= ar[left+mid]) { long tmp = ar[i]; ar[i] = ar[j]; ar[j] = tmp; break; } } } } /* secondary intermediate nodes are 2000+ */ dot_node (ar, 2000+id, left, right, fmt); dot_release (fmt); /* tie together. */ dot_add_undir_edge (1000+id, 2000+id); sameL = mediansort (id*2, ar, cmp, left, left+mid-1); sameR = mediansort (id*2+1, ar, cmp, left+mid+1, right); if (sameL && sameR) { printf ("{rank=same; "); dot_nodeid(id*2); printf (" "); dot_nodeid(id*2+1); printf ("}\n"); } return 1; }
1,603
28,056
package com.alibaba.json.bvtVO.alipay; import com.alibaba.fastjson.annotation.JSONField; import java.util.ArrayList; import java.util.List; public class PlatformDepartmentVO { @JSONField(ordinal=1) private String id ; @JSONField(ordinal=2) private String label ; @JSONField(ordinal=3) private String value; @JSONField(ordinal=4) private String parentId; @JSONField(ordinal=5) private String parentLabel; @JSONField(ordinal=6) private String companyId; @JSONField(ordinal=7) private String departCode; @JSONField(ordinal=8) private String memo; @JSONField(ordinal=9) private String departOrgCode; @JSONField(ordinal=10) private String contact; @JSONField(ordinal=11) private String mobile; @JSONField(ordinal=12) private String departType; @JSONField(serialize=false) private String ipId; @JSONField(serialize=false) private String ipRoleId; @JSONField(serialize=false) private PlatformDepartmentVO parent; @JSONField(ordinal=6,name="ChildNodes") private List<PlatformDepartmentVO> childNodes =new ArrayList<PlatformDepartmentVO>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public String getDepartCode() { return departCode; } public void setDepartCode(String departCode) { this.departCode = departCode; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public PlatformDepartmentVO getParent() { return parent; } public void setParent(PlatformDepartmentVO parent) { this.parent = parent; } public List<PlatformDepartmentVO> getChildNodes() { return childNodes; } public void setChildNodes(List<PlatformDepartmentVO> childNodes) { this.childNodes = childNodes; } /** * Getter method for property <tt>departType</tt>. * * @return property value of departType */ public String getDepartType() { return departType; } /** * Setter method for property <tt>departType</tt>. * * @param departType value to be assigned to property departType */ public void setDepartType(String departType) { this.departType = departType; } /** * Getter method for property <tt>parentLabel</tt>. * * @return property value of parentLabel */ public String getParentLabel() { return parentLabel; } /** * Setter method for property <tt>parentLabel</tt>. * * @param parentLabel value to be assigned to property parentLabel */ public void setParentLabel(String parentLabel) { this.parentLabel = parentLabel; } /** * Getter method for property <tt>departOrgCode</tt>. * * @return property value of departOrgCode */ public String getDepartOrgCode() { return departOrgCode; } /** * Setter method for property <tt>departOrgCode</tt>. * * @param departOrgCode value to be assigned to property departOrgCode */ public void setDepartOrgCode(String departOrgCode) { this.departOrgCode = departOrgCode; } /** * Getter method for property <tt>contact</tt>. * * @return property value of contact */ public String getContact() { return contact; } /** * Setter method for property <tt>contact</tt>. * * @param contact value to be assigned to property contact */ public void setContact(String contact) { this.contact = contact; } /** * Getter method for property <tt>mobile</tt>. * * @return property value of mobile */ public String getMobile() { return mobile; } /** * Setter method for property <tt>mobile</tt>. * * @param mobile value to be assigned to property mobile */ public void setMobile(String mobile) { this.mobile = mobile; } /** * Getter method for property <tt>ipRoleId</tt>. * * @return property value of ipRoleId */ public String getIpRoleId() { return ipRoleId; } /** * Setter method for property <tt>ipRoleId</tt>. * * @param ipRoleId value to be assigned to property ipRoleId */ public void setIpRoleId(String ipRoleId) { this.ipRoleId = ipRoleId; } /** * Getter method for property <tt>ipId</tt>. * * @return property value of ipId */ public String getIpId() { return ipId; } /** * Setter method for property <tt>ipId</tt>. * * @param ipId value to be assigned to property ipId */ public void setIpId(String ipId) { this.ipId = ipId; } public PlatformDepartmentVO() { } // public PlatformDepartmentVO(String id, String label, String value, String parentId, // String companyId) { // this.id = id; // this.label = label; // this.value = value; // this.parentId = parentId; // this.companyId = companyId; // } public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } if(null==this.getId()){ return false; } final PlatformDepartmentVO other = (PlatformDepartmentVO) obj; if(!this.getId().equals(other.getId())) { return false; } return true; } }
2,621
679
<filename>main/bridges/source/cpp_uno/shared/types.cxx /************************************************************** * * 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #include "bridges/cpp_uno/shared/types.hxx" #define INCLUDED_BRIDGES_CPP_UNO_SHARED_VTABLES_HXX #include "typelib/typeclass.h" #include "typelib/typedescription.h" namespace bridges { namespace cpp_uno { namespace shared { bool isSimpleType(typelib_TypeClass typeClass) { return typeClass <= typelib_TypeClass_DOUBLE || typeClass == typelib_TypeClass_ENUM; } bool isSimpleType(typelib_TypeDescriptionReference const * type) { return isSimpleType(type->eTypeClass); } bool isSimpleType(typelib_TypeDescription const * type) { return isSimpleType(type->eTypeClass); } bool relatesToInterfaceType(typelib_TypeDescription const * type) { switch (type->eTypeClass) { case typelib_TypeClass_ANY: case typelib_TypeClass_INTERFACE: return true; case typelib_TypeClass_STRUCT: case typelib_TypeClass_EXCEPTION: { typelib_CompoundTypeDescription const * p = reinterpret_cast< typelib_CompoundTypeDescription const * >( type); for (sal_Int32 i = 0; i < p->nMembers; ++i) { switch (p->ppTypeRefs[i]->eTypeClass) { case typelib_TypeClass_ANY: case typelib_TypeClass_INTERFACE: return true; case typelib_TypeClass_STRUCT: case typelib_TypeClass_EXCEPTION: case typelib_TypeClass_SEQUENCE: { typelib_TypeDescription * t = 0; TYPELIB_DANGER_GET(&t, p->ppTypeRefs[i]); bool b = relatesToInterfaceType(t); TYPELIB_DANGER_RELEASE(t); if (b) { return true; } } break; default: break; } } if (p->pBaseTypeDescription != 0) { return relatesToInterfaceType(&p->pBaseTypeDescription->aBase); } } break; case typelib_TypeClass_SEQUENCE: switch (reinterpret_cast< typelib_IndirectTypeDescription const * >( type)->pType->eTypeClass) { case typelib_TypeClass_ANY: case typelib_TypeClass_INTERFACE: return true; case typelib_TypeClass_STRUCT: case typelib_TypeClass_EXCEPTION: case typelib_TypeClass_SEQUENCE: { typelib_TypeDescription * t = 0; TYPELIB_DANGER_GET( &t, reinterpret_cast< typelib_IndirectTypeDescription const * >( type)->pType); bool b = relatesToInterfaceType(t); TYPELIB_DANGER_RELEASE(t); return b; } default: break; } break; default: break; } return false; } } } }
1,868
331
<filename>unit-tests/apiversions-should-be-recent/Pass/ProviderResource.json { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "resources": [ { "apiVersion": "2018-09-01-preview", "name": "[concat(parameters('mapsAccountName'), '/Microsoft.Authorization/', parameters('guid'))]", "type": "Microsoft.Maps/accounts/providers/roleAssignments", "dependsOn": [ "[parameters('mapsAccountName')]", "[parameters('userAssignedIdentityName')]" ], "properties": { "roleDefinitionId": "[variables('Azure Maps Data Reader')]", "principalId": "[reference(parameters('userAssignedIdentityName')).principalId]", "principalType": "ServicePrincipal" } } ] }
429
302
#include "resourcehandlersfactory.h" #include "resourcehandlers.h" #include "every_cpp.h" namespace BrowserAutomationStudioFramework { ResourceHandlersFactory::ResourceHandlersFactory(QObject *parent) : IResourceHandlersFactory(parent) { } IResourceHandlers * ResourceHandlersFactory::CreateResourceHandlers() { return new ResourceHandlers(); } }
135
10,980
<gh_stars>1000+ import os import sys from optparse import OptionParser import ParseLogs # # Logalyzer. Original: https://github.com/hatRiot/logalyzer # Converted to python3.6 by @programmerchad # # callback for the user flag def user_call(option, opt_str, value, parser): if len(parser.rargs) != 0: value = parser.rargs[0] else: value = None setattr(parser.values, option.dest, value) if __name__ == "__main__": # default location log = '/var/log/auth.log' # parsing options parser = OptionParser(epilog= "Combine flags to view user-specific information. \'-u test -i\' lists IP addresses " "associated with user test") parser.add_option("-u", help="Specify user. Blank lists all users.", action="callback", callback=user_call, default=None, dest="user") parser.add_option("--full", help="Full log dump for specified user", action="store_true", default=False, dest="fullu") parser.add_option("-l", help="Specify log file. Default is auth.log", default=None, dest="log") parser.add_option("-f", help="List failures", action="store_true", default=False, dest="fail") parser.add_option("-s", help="List success logs", action="store_true", default=False, dest="success") parser.add_option("-c", help="List commands by user", action="store_true", default=False, dest="commands") parser.add_option("-i", help="List IP Addresses", action="store_true", default=False, dest="ip") # get arguments (options, args) = parser.parse_args() # if they're trying to access /var/log/auth.log without proper privs, bail if not os.getuid() == 0 and options.log is None: print("[-] Please run with SUDO") sys.exit(1) # check if they specified another file if options.log is not None: log = options.log # parse logs LOGS = ParseLogs.ParseLogs(log) if LOGS is None: sys.exit(1) # validate the user if options.user: if not options.user in LOGS: print(f"[-] User \'{options.user}\' is not present in the logs.") sys.exit(1) # tag log location first print('[!] Log file: ', log) # output all commands if options.commands and not options.user: for i in LOGS: for comms in LOGS[i].commands: print(f"{i}:\t{comms}") sys.exit(1) # output all failures elif options.fail and not options.user: for i in LOGS: for fail in LOGS[i].fail_logs: print(f"{i}:\t{fail}") sys.exit(1) # output all logged IP addresses elif options.ip and not options.user: for i in LOGS: for ip in LOGS[i].ips: print(f"{i}:\t{ip}") sys.exit(1) # output user-specific commands if options.commands and options.user: print(f"[+] Commands for user \'{options.user}\'") for com in LOGS[options.user].commands: print("\t", com) # output user-specific success logs elif options.success and options.user: print(f"[+] Successes logs for user \'{options.user}\'") for log in LOGS[options.user].succ_logs: print("\t", log) # output user-specific failures elif options.fail and options.user: print(f"[+] Failures for user \'{options.user}\'") for fail in LOGS[options.user].fail_logs: print("\t", fail) # output user-specific ip addresses elif options.ip and options.user: print(f"[+] Logged IPs for user \'{options.user}\'") for i in LOGS[options.user].ips: print("\t", i) # print out all information regarding specified user elif options.user is not None: print(f"[!] Logs associated with user \'{options.user}\'") print('[+] First log: ', LOGS[options.user].first_date()) print('[+] Last log: ', LOGS[options.user].last_date()) print("[!] Failure Logs") for fail in LOGS[options.user].fail_logs: print("\t", fail) print("[!] Success Logs") for succ in LOGS[options.user].succ_logs: print("\t", succ) print("[!] Associated IPs") for ip in LOGS[options.user].ips: print("\t", ip) print("[!] Commands") for comm in LOGS[options.user].commands: print("\t", comm) # dump the full log for the user if specified if options.fullu and options.user: print("[!] Full Log") for log in LOGS[options.user].logs: print(log) # if they supplied us with an empty user, dump all of the logged users elif options.user is None: if len(LOGS) > 0: for i in LOGS: print(i)
2,056
1,452
<reponame>CrazyLeoJay/Apktool /* * Copyright (C) 2010 <NAME> <<EMAIL>> * Copyright (C) 2010 <NAME> <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.aapt1; import brut.androlib.*; import brut.directory.ExtFile; import brut.common.BrutException; import brut.util.OS; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static org.junit.Assert.assertTrue; public class SharedLibraryTest extends BaseTest { @BeforeClass public static void beforeClass() throws BrutException { TestUtils.cleanFrameworkFile(); sTmpDir = new ExtFile(OS.createTempDirectory()); TestUtils.copyResourceDir(SharedLibraryTest.class, "aapt1/shared_libraries/", sTmpDir); } @AfterClass public static void afterClass() throws BrutException { OS.rmdir(sTmpDir); } @Test public void isFrameworkTaggingWorking() throws AndrolibException { String apkName = "library.apk"; ApkOptions apkOptions = new ApkOptions(); apkOptions.frameworkFolderLocation = sTmpDir.getAbsolutePath(); apkOptions.frameworkTag = "building"; new Androlib(apkOptions).installFramework(new File(sTmpDir + File.separator + apkName)); assertTrue(fileExists("2-building.apk")); } @Test public void isFrameworkInstallingWorking() throws AndrolibException { String apkName = "library.apk"; ApkOptions apkOptions = new ApkOptions(); apkOptions.frameworkFolderLocation = sTmpDir.getAbsolutePath(); new Androlib(apkOptions).installFramework(new File(sTmpDir + File.separator + apkName)); assertTrue(fileExists("2.apk")); } @Test public void isSharedResourceDecodingAndRebuildingWorking() throws IOException, BrutException { String library = "library.apk"; String client = "client.apk"; // setup apkOptions ApkOptions apkOptions = new ApkOptions(); apkOptions.frameworkFolderLocation = sTmpDir.getAbsolutePath(); apkOptions.frameworkTag = "shared"; // install library/framework new Androlib(apkOptions).installFramework(new File(sTmpDir + File.separator + library)); assertTrue(fileExists("2-shared.apk")); // decode client.apk ApkDecoder apkDecoder = new ApkDecoder(new File(sTmpDir + File.separator + client)); apkDecoder.setOutDir(new File(sTmpDir + File.separator + client + ".out")); apkDecoder.setFrameworkDir(apkOptions.frameworkFolderLocation); apkDecoder.setFrameworkTag(apkOptions.frameworkTag); apkDecoder.decode(); // decode library.apk ApkDecoder libraryDecoder = new ApkDecoder(new File(sTmpDir + File.separator + library)); libraryDecoder.setOutDir(new File(sTmpDir + File.separator + library + ".out")); libraryDecoder.setFrameworkDir(apkOptions.frameworkFolderLocation); libraryDecoder.setFrameworkTag(apkOptions.frameworkTag); libraryDecoder.decode(); // build client.apk ExtFile clientApk = new ExtFile(sTmpDir, client + ".out"); new Androlib(apkOptions).build(clientApk, null); assertTrue(fileExists(client + ".out" + File.separator + "dist" + File.separator + client)); // build library.apk (shared library) ExtFile libraryApk = new ExtFile(sTmpDir, library + ".out"); new Androlib(apkOptions).build(libraryApk, null); assertTrue(fileExists(library + ".out" + File.separator + "dist" + File.separator + library)); } private boolean fileExists(String filepath) { return Files.exists(Paths.get(sTmpDir.getAbsolutePath() + File.separator + filepath)); } }
1,619
7,158
<filename>modules/quality/src/qualitybrisque.cpp // This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. /* Copyright (c) 2011 The University of Texas at Austin All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this code (the source files) and its documentation for any purpose, provided that the copyright notice in its entirety appear in all copies of this code, and the original source of this code, Laboratory for Image and Video Engineering (LIVE, http://live.ece.utexas.edu) and Center for Perceptual Systems (CPS, http://www.cps.utexas.edu) at the University of Texas at Austin (UT Austin, http://www.utexas.edu), is acknowledged in any publication that reports research using this code. The research is to be cited in the bibliography as: 1) <NAME>, <NAME> and <NAME>, "BRISQUE Software Release", URL: http://live.ece.utexas.edu/research/quality/BRISQUE_release.zip, 2011 2) <NAME>, <NAME> and <NAME>, "No Reference Image Quality Assessment in the Spatial Domain" submitted IN NO EVENT SHALL THE UNIVERSITY OF TEXAS AT AUSTIN BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS DATABASE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF TEXAS AT AUSTIN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF TEXAS AT AUSTIN SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE DATABASE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF TEXAS AT AUSTIN HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ /* Original Paper: @cite Mittal2 and Original Implementation: @cite Mittal2_software */ #include "precomp.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/quality/qualitybrisque.hpp" #include "opencv2/quality/quality_utils.hpp" namespace { using namespace cv; using namespace cv::quality; // type of mat we're working with internally // Win32+UMat: performance is 15-20X worse than Mat // Win32+UMat+OCL: performance is 200-300X worse than Mat, plus accuracy errors // Linux+UMat: 15X worse performance than Linux+Mat using brisque_mat_type = cv::Mat; // brisque intermediate calculation type // Linux+Mat: CV_64F is 3X slower than CV_32F // Win32+Mat: CV_64F is 2X slower than CV_32F static constexpr const int BRISQUE_CALC_MAT_TYPE = CV_32F; // brisque intermediate matrix element type. float if BRISQUE_CALC_MAT_TYPE == CV_32F, double if BRISQUE_CALC_MAT_TYPE == CV_64F using brisque_calc_element_type = float; // convert mat to grayscale, range [0-1] brisque_mat_type mat_convert( const brisque_mat_type& mat ) { brisque_mat_type result = mat; switch (mat.channels()) { case 1: break; case 3: cv::cvtColor(result, result, cv::COLOR_BGR2GRAY, 1); break; case 4: cv::cvtColor(result, result, cv::COLOR_BGRA2GRAY, 1); break; default: CV_Error(cv::Error::StsNotImplemented, "Unknown/unsupported channel count"); };//switch // scale to 0-1 range result.convertTo(result, BRISQUE_CALC_MAT_TYPE, 1. / 255.); return result; } // function to compute best fit parameters from AGGDfit void AGGDfit(const brisque_mat_type& structdis, double& lsigma_best, double& rsigma_best, double& gamma_best) { long int poscount = 0, negcount = 0; double possqsum = 0, negsqsum = 0, abssum = 0; for (int i = 0; i < structdis.rows; i++) { for (int j = 0; j < structdis.cols; j++) { double pt = structdis.at<brisque_calc_element_type>(i, j); if (pt > 0) { poscount++; possqsum += pt * pt; abssum += pt; } else if (pt < 0) { negcount++; negsqsum += pt * pt; abssum -= pt; } } } lsigma_best = cv::pow(negsqsum / negcount, 0.5); rsigma_best = cv::pow(possqsum / poscount, 0.5); double gammahat = lsigma_best / rsigma_best; long int totalcount = (structdis.cols)*(structdis.rows); double rhat = cv::pow(abssum / totalcount, static_cast<double>(2)) / ((negsqsum + possqsum) / totalcount); double rhatnorm = rhat * (cv::pow(gammahat, 3) + 1)*(gammahat + 1) / pow(pow(gammahat, 2) + 1, 2); double prevgamma = 0; double prevdiff = 1e10; double sampling = 0.001; for (double gam = 0.2; gam < 10; gam += sampling) //possible to coarsen sampling to quicken the code, with some loss of accuracy { double r_gam = tgamma(2 / gam)*tgamma(2 / gam) / (tgamma(1 / gam)*tgamma(3 / gam)); double diff = abs(r_gam - rhatnorm); if (diff > prevdiff) break; prevdiff = diff; prevgamma = gam; } gamma_best = prevgamma; // return structdis.clone(); } std::vector<brisque_calc_element_type> ComputeBrisqueFeature( const brisque_mat_type& orig ) { CV_DbgAssert(orig.channels() == 1); std::vector<brisque_calc_element_type> featurevector; auto orig_bw = orig; // orig_bw now contains the grayscale image normalized to the range 0,1 int scalenum = 2; // number of times to scale the image for (int itr_scale = 1; itr_scale <= scalenum; itr_scale++) { // resize image cv::Size dst_size( int( orig_bw.cols / cv::pow((double)2, itr_scale - 1) ), int( orig_bw.rows / pow((double)2, itr_scale - 1))); brisque_mat_type imdist_scaled; cv::resize(orig_bw, imdist_scaled, dst_size, 0, 0, cv::INTER_CUBIC); // INTER_CUBIC // calculating MSCN coefficients // compute mu (local mean) brisque_mat_type mu;// (imdist_scaled.size(), CV_64FC1, 1); cv::GaussianBlur(imdist_scaled, mu, cv::Size(7, 7), 7. / 6., 0., cv::BORDER_REPLICATE ); brisque_mat_type mu_sq; cv::pow(mu, double(2.0), mu_sq); //compute sigma (local sigma) brisque_mat_type sigma;// (imdist_scaled.size(), CV_64FC1, 1); cv::multiply(imdist_scaled, imdist_scaled, sigma); cv::GaussianBlur(sigma, sigma, cv::Size(7, 7), 7./6., 0., cv::BORDER_REPLICATE ); cv::subtract(sigma, mu_sq, sigma); cv::pow(sigma, double(0.5), sigma); cv::add(sigma, Scalar(1.0 / 255), sigma); // to avoid DivideByZero Error brisque_mat_type structdis;// (imdist_scaled.size(), CV_64FC1, 1); cv::subtract(imdist_scaled, mu, structdis); cv::divide(structdis, sigma, structdis); // structdis is MSCN image // Compute AGGD fit to MSCN image double lsigma_best, rsigma_best, gamma_best; //structdis = AGGDfit(structdis, lsigma_best, rsigma_best, gamma_best); AGGDfit(structdis, lsigma_best, rsigma_best, gamma_best); featurevector.push_back( (brisque_calc_element_type) gamma_best); featurevector.push_back(( (brisque_calc_element_type)( lsigma_best*lsigma_best + rsigma_best * rsigma_best) / 2 )); // Compute paired product images // indices for orientations (H, V, D1, D2) int shifts[4][2] = { {0,1},{1,0},{1,1},{-1,1} }; for (int itr_shift = 1; itr_shift <= 4; itr_shift++) { // select the shifting index from the 2D array int* reqshift = shifts[itr_shift - 1]; // declare, create shifted_structdis as pairwise image brisque_mat_type shifted_structdis(imdist_scaled.size(), BRISQUE_CALC_MAT_TYPE); //(imdist_scaled.size(), CV_64FC1, 1); // create pair-wise product for the given orientation (reqshift) for (int i = 0; i < structdis.rows; i++) { for (int j = 0; j < structdis.cols; j++) { if (i + reqshift[0] >= 0 && i + reqshift[0] < structdis.rows && j + reqshift[1] >= 0 && j + reqshift[1] < structdis.cols) { shifted_structdis.at<brisque_calc_element_type>(i,j) = structdis.at<brisque_calc_element_type>(i + reqshift[0], j + reqshift[1]); } else { shifted_structdis.at<brisque_calc_element_type>(i, j) = (brisque_calc_element_type) 0; } } } // calculate the products of the pairs cv::multiply(structdis, shifted_structdis, shifted_structdis); // fit the pairwise product to AGGD // shifted_structdis = AGGDfit(shifted_structdis, lsigma_best, rsigma_best, gamma_best); AGGDfit(shifted_structdis, lsigma_best, rsigma_best, gamma_best); double constant = sqrt(tgamma(1 / gamma_best)) / sqrt(tgamma(3 / gamma_best)); double meanparam = (rsigma_best - lsigma_best)*(tgamma(2 / gamma_best) / tgamma(1 / gamma_best))*constant; // push the calculated parameters from AGGD fit to pair-wise products featurevector.push_back((brisque_calc_element_type)gamma_best); featurevector.push_back((brisque_calc_element_type)meanparam); featurevector.push_back( (brisque_calc_element_type) cv::pow(lsigma_best, 2)); featurevector.push_back( (brisque_calc_element_type) cv::pow(rsigma_best, 2)); } } return featurevector; } brisque_calc_element_type computescore(const cv::Ptr<cv::ml::SVM>& model, const cv::Mat& range, const brisque_mat_type& img ) { const auto brisqueFeatures = ComputeBrisqueFeature( img ); // compute brisque features cv::Mat feat_mat( 1,(int)brisqueFeatures.size(), CV_32FC1, (void*)brisqueFeatures.data() ); // load to mat quality_utils::scale(feat_mat, range, -1.f, 1.f);// scale to range [-1,1] cv::Mat result; model->predict(feat_mat, result); return std::min( std::max( result.at<float>(0), 0.f ), 100.f ); // clamp to [0-100] } // computes score for a single frame cv::Scalar compute(const cv::Ptr<cv::ml::SVM>& model, const cv::Mat& range, const brisque_mat_type& img) { auto result = cv::Scalar{ 0. }; result[0] = computescore(model, range, img); return result; } } // static cv::Ptr<QualityBRISQUE> QualityBRISQUE::create(const cv::String& model_file_path, const cv::String& range_file_path) { return cv::Ptr<QualityBRISQUE>(new QualityBRISQUE(model_file_path, range_file_path)); } // static cv::Ptr<QualityBRISQUE> QualityBRISQUE::create(const cv::Ptr<cv::ml::SVM>& model, const cv::Mat& range) { return cv::Ptr<QualityBRISQUE>(new QualityBRISQUE(model, range)); } // static cv::Scalar QualityBRISQUE::compute( InputArray img, const cv::String& model_file_path, const cv::String& range_file_path) { return QualityBRISQUE(model_file_path, range_file_path).compute(img); } // QualityBRISQUE() constructor QualityBRISQUE::QualityBRISQUE(const cv::String& model_file_path, const cv::String& range_file_path) : QualityBRISQUE( cv::ml::SVM::load(model_file_path) , cv::FileStorage(range_file_path, cv::FileStorage::READ)["range"].mat() ) {} cv::Scalar QualityBRISQUE::compute( InputArray img ) { auto mat = quality_utils::extract_mat<brisque_mat_type>(img); // extract input mats mat = mat_convert(mat);// convert to gs, scale to [0,1] return ::compute(this->_model, this->_range, mat ); } //static void QualityBRISQUE::computeFeatures(InputArray img, OutputArray features) { CV_Assert(features.needed()); CV_Assert(img.isMat()); CV_Assert(!img.getMat().empty()); auto mat = mat_convert(img.getMat()); const auto vals = ComputeBrisqueFeature(mat); cv::Mat valmat( cv::Size( (int)vals.size(), 1 ), CV_32FC1, (void*)vals.data()); // create row vector, type depends on brisque_calc_element_type if (features.isUMat()) valmat.copyTo(features.getUMatRef()); else if (features.isMat()) // how to move data instead? // if calling this: // features.getMatRef() = valmat; // then shared data is erased when valmat is released, corrupting the data in the outputarray for the caller valmat.copyTo(features.getMatRef()); else CV_Error(cv::Error::StsNotImplemented, "Unsupported output type"); }
5,891
447
""" The `pip_audit` APIs. """ from pip_audit._version import __version__ __all__ = ["__version__"]
39
1,156
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import copy import unittest import numpy as np import numpy.testing as npt import torch from reagent.core.types import CBInput from reagent.gym.policies.policy import Policy from reagent.gym.policies.samplers.discrete_sampler import GreedyActionSampler from reagent.models.linear_regression import LinearRegressionUCB from reagent.training.cb.linucb_trainer import ( LinUCBTrainer, _get_chosen_action_features, ) from reagent.training.parameters import LinUCBTrainerParameters class TestLinUCButils(unittest.TestCase): def test_get_chosen_action_features(self): all_actions_features = torch.tensor( [[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]] ) actions = torch.tensor([[1], [0]], dtype=torch.long) chosen_action_features = _get_chosen_action_features( all_actions_features, actions ) npt.assert_equal( chosen_action_features.numpy(), np.array([[3.0, 4.0], [5.0, 6.0]]) ) class TestLinUCB(unittest.TestCase): def setUp(self): self.batch_size = 2 self.state_dim = 2 self.action_dim = 2 self.num_actions = 2 self.params = LinUCBTrainerParameters(num_actions=-1) self.x_dim = ( 1 + self.state_dim * self.num_actions + self.state_dim + self.num_actions ) policy_network = LinearRegressionUCB(self.x_dim) self.policy = Policy(scorer=policy_network, sampler=GreedyActionSampler()) self.trainer = LinUCBTrainer(self.policy, **self.params.asdict()) self.batch = CBInput( context_action_features=torch.tensor( [ [ [1, 2, 3, 6, 7, 2 * 6, 2 * 7, 3 * 6, 3 * 7], [1, 2, 3, 10, 11, 2 * 10, 2 * 11, 3 * 10, 3 * 11], ], [ [1, 4, 5, 8, 9, 4 * 8, 4 * 9, 5 * 8, 5 * 9], [1, 4, 5, 12, 13, 4 * 12, 4 * 13, 5 * 12, 5 * 13], ], ], dtype=torch.float, ), action=torch.tensor([[0], [1]], dtype=torch.long), reward=torch.tensor([[1.5], [2.3]]), ) def test_linucb_training_step(self): self.trainer.training_step(self.batch, 0) def test_linucb_training_batch_vs_online(self): # make sure that feeding in a batch gives same result as feeding in examples one-by-one obss = [] for i in range(self.batch_size): obss.append( CBInput( context_action_features=self.batch.context_action_features[ i : i + 1, :, : ], action=self.batch.action[[i]], reward=self.batch.reward[[i]], ) ) scorer_1 = LinearRegressionUCB(self.x_dim) scorer_2 = LinearRegressionUCB(self.x_dim) policy_1 = Policy(scorer=scorer_1, sampler=GreedyActionSampler()) policy_2 = Policy(scorer=scorer_2, sampler=GreedyActionSampler()) trainer_1 = LinUCBTrainer(policy_1, num_actions=-1) trainer_2 = LinUCBTrainer(policy_2, num_actions=-1) trainer_1.training_step(obss[0], 0) trainer_1.training_step(obss[1], 1) trainer_2.training_step(self.batch, 0) npt.assert_array_less( np.zeros(scorer_1.A.shape), scorer_1.A.numpy() ) # make sure A got updated npt.assert_allclose(scorer_1.A.numpy(), scorer_2.A.numpy(), rtol=1e-4) npt.assert_allclose(scorer_1.b.numpy(), scorer_2.b.numpy(), rtol=1e-4) def test_linucb_model_update_equations(self): # make sure that the model parameters match hand-computed values scorer = LinearRegressionUCB(self.x_dim) policy = Policy(scorer=scorer, sampler=GreedyActionSampler()) trainer = LinUCBTrainer(policy, num_actions=-1) trainer.training_step(self.batch, 0) # the feature matrix (computed by hand) x = _get_chosen_action_features( self.batch.context_action_features, self.batch.action ).numpy() npt.assert_allclose(scorer.A.numpy(), np.eye(self.x_dim) + x.T @ x, rtol=1e-5) npt.assert_allclose( scorer.b.numpy(), x.T @ self.batch.reward.squeeze().numpy(), rtol=1e-5 ) scorer._estimate_coefs() npt.assert_equal(scorer.A.numpy(), scorer.coefs_valid_for_A.numpy()) npt.assert_allclose( scorer.A.numpy() @ scorer.inv_A.numpy(), np.eye(self.x_dim), atol=1e-3 ) def test_linucb_weights(self): # make sure that using a weight is same as processing an example several times batch_with_weight = copy.deepcopy(self.batch) batch_with_weight.weight = 3 * torch.ones((self.batch_size, 1)) scorer_1 = LinearRegressionUCB(self.x_dim) scorer_2 = LinearRegressionUCB(self.x_dim) policy_1 = Policy(scorer=scorer_1, sampler=GreedyActionSampler()) policy_2 = Policy(scorer=scorer_2, sampler=GreedyActionSampler()) trainer_1 = LinUCBTrainer(policy_1, num_actions=-1) trainer_2 = LinUCBTrainer(policy_2, num_actions=-1) trainer_1.training_step(batch_with_weight, 0) for i in range(3): trainer_2.training_step(self.batch, i) npt.assert_array_less( np.zeros(scorer_1.A.shape), scorer_1.A.numpy() ) # make sure A got updated npt.assert_allclose(scorer_1.A.numpy(), scorer_2.A.numpy(), rtol=1e-6) npt.assert_allclose(scorer_1.b.numpy(), scorer_2.b.numpy(), rtol=1e-6)
2,841
2,389
/* Copyright 2021 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.kubernetes.client.openapi.models; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Objects; /** * StatefulSetPersistentVolumeClaimRetentionPolicy describes the policy used for PVCs created from * the StatefulSet VolumeClaimTemplates. */ @ApiModel( description = "StatefulSetPersistentVolumeClaimRetentionPolicy describes the policy used for PVCs created from the StatefulSet VolumeClaimTemplates.") @javax.annotation.Generated( value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2021-12-10T19:11:23.904Z[Etc/UTC]") public class V1StatefulSetPersistentVolumeClaimRetentionPolicy { public static final String SERIALIZED_NAME_WHEN_DELETED = "whenDeleted"; @SerializedName(SERIALIZED_NAME_WHEN_DELETED) private String whenDeleted; public static final String SERIALIZED_NAME_WHEN_SCALED = "whenScaled"; @SerializedName(SERIALIZED_NAME_WHEN_SCALED) private String whenScaled; public V1StatefulSetPersistentVolumeClaimRetentionPolicy whenDeleted(String whenDeleted) { this.whenDeleted = whenDeleted; return this; } /** * WhenDeleted specifies what happens to PVCs created from StatefulSet VolumeClaimTemplates when * the StatefulSet is deleted. The default policy of &#x60;Retain&#x60; causes PVCs to not be * affected by StatefulSet deletion. The &#x60;Delete&#x60; policy causes those PVCs to be * deleted. * * @return whenDeleted */ @javax.annotation.Nullable @ApiModelProperty( value = "WhenDeleted specifies what happens to PVCs created from StatefulSet VolumeClaimTemplates when the StatefulSet is deleted. The default policy of `Retain` causes PVCs to not be affected by StatefulSet deletion. The `Delete` policy causes those PVCs to be deleted.") public String getWhenDeleted() { return whenDeleted; } public void setWhenDeleted(String whenDeleted) { this.whenDeleted = whenDeleted; } public V1StatefulSetPersistentVolumeClaimRetentionPolicy whenScaled(String whenScaled) { this.whenScaled = whenScaled; return this; } /** * WhenScaled specifies what happens to PVCs created from StatefulSet VolumeClaimTemplates when * the StatefulSet is scaled down. The default policy of &#x60;Retain&#x60; causes PVCs to not be * affected by a scaledown. The &#x60;Delete&#x60; policy causes the associated PVCs for any * excess pods above the replica count to be deleted. * * @return whenScaled */ @javax.annotation.Nullable @ApiModelProperty( value = "WhenScaled specifies what happens to PVCs created from StatefulSet VolumeClaimTemplates when the StatefulSet is scaled down. The default policy of `Retain` causes PVCs to not be affected by a scaledown. The `Delete` policy causes the associated PVCs for any excess pods above the replica count to be deleted.") public String getWhenScaled() { return whenScaled; } public void setWhenScaled(String whenScaled) { this.whenScaled = whenScaled; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } V1StatefulSetPersistentVolumeClaimRetentionPolicy v1StatefulSetPersistentVolumeClaimRetentionPolicy = (V1StatefulSetPersistentVolumeClaimRetentionPolicy) o; return Objects.equals( this.whenDeleted, v1StatefulSetPersistentVolumeClaimRetentionPolicy.whenDeleted) && Objects.equals( this.whenScaled, v1StatefulSetPersistentVolumeClaimRetentionPolicy.whenScaled); } @Override public int hashCode() { return Objects.hash(whenDeleted, whenScaled); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class V1StatefulSetPersistentVolumeClaimRetentionPolicy {\n"); sb.append(" whenDeleted: ").append(toIndentedString(whenDeleted)).append("\n"); sb.append(" whenScaled: ").append(toIndentedString(whenScaled)).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,651
431
package com.jpay.entity; public class Order { private String appId; private String body; private String subject; private String deviceInfo;//可选 设备ID private String nofityUrl; private String paraTradeNo; private String paraId; private int totalFee;//单位 元 private String attach; private String channelId; public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getDeviceInfo() { return deviceInfo; } public void setDeviceInfo(String deviceInfo) { this.deviceInfo = deviceInfo; } public String getNofityUrl() { return nofityUrl; } public void setNofityUrl(String nofityUrl) { this.nofityUrl = nofityUrl; } public String getParaTradeNo() { return paraTradeNo; } public void setParaTradeNo(String paraTradeNo) { this.paraTradeNo = paraTradeNo; } public String getParaId() { return paraId; } public void setParaId(String paraId) { this.paraId = paraId; } public int getTotalFee() { return totalFee; } public void setTotalFee(int totalFee) { this.totalFee = totalFee; } public String getAttach() { return attach; } public void setAttach(String attach) { this.attach = attach; } public String getChannelId() { return channelId; } public void setChannelId(String channelId) { this.channelId = channelId; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } }
582
2,881
package com.example.zhpan.banner.recyclerview.ui; import android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import com.example.zhpan.banner.R; import com.example.zhpan.banner.recyclerview.listener.ICustomClickListener; import com.example.zhpan.banner.recyclerview.module.RecyclerViewConfig; import java.util.ArrayList; import static com.example.zhpan.banner.recyclerview.module.RecyclerViewConfig.FOOTVIEW_TYPE; import static com.example.zhpan.banner.recyclerview.module.RecyclerViewConfig.HEADVIEW_TYPE; /** * 自定义RecyclerView,主要用于添加不同类型的Head和Foot */ public class CustomRecyclerView extends RecyclerView { //保存头部的view private ArrayList<RecyclerViewConfig> mHeaderCouListInfo; //保存尾部的view private ArrayList<RecyclerViewConfig> mFooterCouListInfo; //记录head的个数 private int headerCount; //记录foot的个数 private int footerCount; //adapter,可能是CustomAdapter, 可能是自定义adapter private Adapter mAdapter; private Context mContext; //private ICustomClickListener customClickListener; public CustomRecyclerView(@NonNull Context context) { this(context, null); } public CustomRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public CustomRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { mHeaderCouListInfo = new ArrayList<>(); mFooterCouListInfo = new ArrayList<>(); mContext = context; } public ArrayList<RecyclerViewConfig> getHeadCouListInfo() { return mHeaderCouListInfo; } public ArrayList<RecyclerViewConfig> getFootCouListInfo() { return mFooterCouListInfo; } /** * 添加HeadView的方法 */ public void addHeaderView(View view) { addHeaderView(view, false); } public void addHeaderView(View view, boolean isCache) { setHeadViewConfig(view, RecyclerViewConfig.HEADVIEW, headerCount, HEADVIEW_TYPE, isCache); headerCount = mHeaderCouListInfo.size(); if (mAdapter != null) { if (!(mAdapter instanceof CustomAdapter)) { wrapHeadAdapter(); } } } public void addFootView(View view) { setFootViewConfig(view, RecyclerViewConfig.FOOTVIEW, footerCount, FOOTVIEW_TYPE); footerCount = mFooterCouListInfo.size(); if (mAdapter != null) { if (!(mAdapter instanceof CustomAdapter)) { wrapHeadAdapter(); } } } /** * 将adapter构建为customadapter用来填充头部尾部布局 */ private void wrapHeadAdapter() { mAdapter = new CustomAdapter(mHeaderCouListInfo, mFooterCouListInfo, mAdapter, mContext, this); } @Override public void setAdapter(@Nullable Adapter adapter) { //if (mHeaderCouListInfo.size() > 0 || mFooterCouListInfo.size() > 0) { mAdapter = new CustomAdapter(mHeaderCouListInfo, mFooterCouListInfo, adapter, mContext, this); //} else { // mAdapter = adapter; //} // 设置头尾的两个缓存为size 变相解决复用问题 getRecycledViewPool().setMaxRecycledViews(FOOTVIEW_TYPE, mFooterCouListInfo.size() + 1); getRecycledViewPool().setMaxRecycledViews(HEADVIEW_TYPE, mHeaderCouListInfo.size() + 1); super.setAdapter(mAdapter); } /** * 配置头部view的信息 */ private void setHeadViewConfig(View view, String type, int count, int headCount, boolean isCache) { RecyclerViewConfig viewConfig = new RecyclerViewConfig(); viewConfig.setTag(view.getClass() + type + count); viewConfig.setType(headCount); viewConfig.setView(R.layout.item_head_foot_parent); viewConfig.setCache(isCache); ViewGroup mHeadParent = (ViewGroup) view.getParent(); if (mHeadParent != null) { mHeadParent.removeView(view); } viewConfig.setContentView(view); mHeaderCouListInfo.add(viewConfig); } /** * 配置尾部view的信息 */ private void setFootViewConfig(View view, String type, int count, int headCount) { RecyclerViewConfig viewConfig = new RecyclerViewConfig(); viewConfig.setTag(view.getClass() + type + count); viewConfig.setType(headCount); viewConfig.setView(R.layout.item_head_foot_parent); ViewGroup mFootParent = (ViewGroup) view.getParent(); if (mFootParent != null) { mFootParent.removeView(view); } viewConfig.setContentView(view); mFooterCouListInfo.add(viewConfig); } public CustomAdapter getHeadAndFootAdapter() { return (CustomAdapter) mAdapter; } public void setCustomClickListener(ICustomClickListener customClickListener) { //this.customClickListener = customClickListener; getHeadAndFootAdapter().setCustomClickListener(customClickListener); } /** * 移除最后一个View, 就是加载更多的哪一个 */ public void removeFooterView(int footerIndex) { if (footerIndex < mFooterCouListInfo.size()) { this.mFooterCouListInfo.remove(footerIndex); footerCount = mFooterCouListInfo.size(); mAdapter.notifyDataSetChanged(); } } public void removeFirstHeaderView() { if (mHeaderCouListInfo.size() > 0) { this.mHeaderCouListInfo.remove(0); headerCount = mHeaderCouListInfo.size(); mAdapter.notifyDataSetChanged(); } } }
2,125
1,875
<gh_stars>1000+ /* * Copyright 2018 <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.teavm.incremental.data.meta; import static org.teavm.metaprogramming.Metaprogramming.exit; import static org.teavm.metaprogramming.Metaprogramming.proxy; import org.teavm.metaprogramming.CompileTime; import org.teavm.metaprogramming.Meta; import org.teavm.metaprogramming.Value; @CompileTime public class Main { private Main() { } public static String run() { return meta("ok").get(); } @Meta private static native StringSupplier meta(String s); private static void meta(Value<String> s) { Value<StringSupplier> result = proxy(StringSupplier.class, (instance, method, args) -> { exit(() -> "meta: " + s.get()); }); exit(() -> result.get()); } interface StringSupplier { String get(); } }
483
602
<gh_stars>100-1000 package org.corfudb.utils.lock.states; import lombok.extern.slf4j.Slf4j; import org.corfudb.utils.lock.Lock; import java.util.Optional; /** * Stopped State. Lock transitions to stopped state only if there is * an unrecoverable error. * * @author mdhawan * @since 04/17/2020 */ @Slf4j public class StoppedState extends LockState { public StoppedState(Lock lock) { super(lock); } /** * Processes events in this state. * * @param event * @return * @throws IllegalTransitionException */ @Override public Optional<LockState> processEvent(LockEvent event) throws IllegalTransitionException { switch (event) { case LEASE_ACQUIRED: case LEASE_RENEWED: case LEASE_REVOKED: case LEASE_EXPIRED: case UNRECOVERABLE_ERROR: return Optional.empty(); default: log.warn("Unexpected lock event {} when in state {}.", event, getType()); throw new IllegalTransitionException(event, getType()); } } @Override public void onEntry(LockState from) { } @Override public void onExit(LockState to) { } @Override public LockStateType getType() { return LockStateType.STOPPED; } }
572
372
// // Notice Regarding Standards. AMD does not provide a license or sublicense to // any Intellectual Property Rights relating to any standards, including but not // limited to any audio and/or video codec technologies such as MPEG-2, MPEG-4; // AVC/H.264; HEVC/H.265; AAC decode/FFMPEG; AAC encode/FFMPEG; VC-1; and MP3 // (collectively, the "Media Technologies"). For clarity, you will pay any // royalties due for such third party technologies, which may include the Media // Technologies that are owed as a result of AMD providing the Software to you. // // MIT license // // // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // 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. // #include <stdio.h> #include <fstream> #include <iosfwd> #include "VideoCaptureImpl.h" #include "public/include/core/Context.h" #include "public/include/core/Trace.h" #include "public/common/TraceAdapter.h" #include "public/common/AMFFactory.h" #include "public/common/DataStream.h" #include "public/include/components/VideoCapture.h" #define AMF_FACILITY L"AMFVideoCaptureImpl" using namespace amf; extern "C" { AMF_RESULT AMFCreateComponentVideoCapture(amf::AMFContext* pContext, amf::AMFComponentEx** ppComponent) { *ppComponent = new amf::AMFInterfaceMultiImpl< amf::AMFVideoCaptureImpl, amf::AMFComponentEx, amf::AMFContext*>(pContext); (*ppComponent)->Acquire(); return AMF_OK; } } //------------------------------------------------------------------------------------------------- AMFVideoCaptureImpl::AMFOutputVideoCaptureImpl::AMFOutputVideoCaptureImpl(AMFVideoCaptureImpl* pHost) : m_pHost(pHost), m_frameCount(0), m_iQueueSize(30) { m_VideoDataQueue.SetQueueSize(m_iQueueSize); } //------------------------------------------------------------------------------------------------- AMFVideoCaptureImpl::AMFOutputVideoCaptureImpl::~AMFOutputVideoCaptureImpl() { } //------------------------------------------------------------------------------------------------- // NOTE: this call will return one compressed frame for each QueryOutput call AMF_RESULT AMF_STD_CALL AMFVideoCaptureImpl::AMFOutputVideoCaptureImpl::QueryOutput(AMFData** ppData) { AMF_RETURN_IF_FALSE(m_pHost != NULL, AMF_UNEXPECTED, L"QueryOutput() - Host not Initialized"); AMF_RESULT err = AMF_REPEAT; AMFDataPtr pFrame; amf_ulong ulID = 0; if (m_VideoDataQueue.Get(ulID, pFrame, 0)) { *ppData = pFrame.Detach(); err = AMF_OK; } return err; } //------------------------------------------------------------------------------------------------- AMF_RESULT AMFVideoCaptureImpl::AMFOutputVideoCaptureImpl::SubmitFrame(AMFData* pData) { AMF_RETURN_IF_FALSE(m_pHost != NULL, AMF_UNEXPECTED, L"QueryOutput() - Host not Initialized"); AMF_RESULT err = AMF_INPUT_FULL; if (m_VideoDataQueue.Add(0, pData, 0, 0)) { err = AMF_OK; } return err; } // AMFVideoCaptureImpl //------------------------------------------------------------------------------------------------- AMFVideoCaptureImpl::AMFVideoCaptureImpl(AMFContext* pContext) : m_pContext(pContext), m_frameCount(0), m_bTerminated(true), m_videoPollingThread(this), m_lenData(0) { AMFPrimitivePropertyInfoMapBegin AMFPropertyInfoInt64(VIDEOCAP_DEVICE_COUNT, VIDEOCAP_DEVICE_COUNT, 2, 0, 8, false), AMFPropertyInfoWString(VIDEOCAP_DEVICE_NAME, VIDEOCAP_DEVICE_NAME, L"", false), AMFPropertyInfoWString(VIDEOCAP_DEVICE_ACTIVE, VIDEOCAP_DEVICE_ACTIVE, L"", false), AMFPropertyInfoWString(VIDEOCAP_CODEC, VIDEOCAP_CODEC, L"", false), AMFPropertyInfoSize(VIDEOCAP_FRAMESIZE, VIDEOCAP_FRAMESIZE, AMFConstructSize(1920, 1080), AMFConstructSize(720, 480), AMFConstructSize(7680, 7680), false), AMFPrimitivePropertyInfoMapEnd } //------------------------------------------------------------------------------------------------- AMFVideoCaptureImpl::~AMFVideoCaptureImpl() { Terminate(); } //------------------------------------------------------------------------------------------------- AMF_RESULT AMF_STD_CALL AMFVideoCaptureImpl::Init(AMF_SURFACE_FORMAT /*format*/, amf_int32 /*width*/, amf_int32 /*height*/) { AMFLock lock(&m_sync); AMF_RESULT res = AMF_OK; if (!m_bTerminated) { Terminate(); } std::wstring deviceNameActive; GetPropertyWString(VIDEOCAP_DEVICE_ACTIVE, &deviceNameActive); //create output m_OutputStream = new AMFOutputVideoCaptureImpl(this); if (!m_OutputStream) { res = AMF_OUT_OF_MEMORY; } //init device if (AMF_OK == res) { res = m_videoSource.Init(deviceNameActive); if (res != AMF_OK) { AMFTraceError(L"Videostitch", L"AMFVideoCaptureImpl, AMFMFSourceImpl::Init() failed!"); } SetProperty(VIDEOCAP_FRAMESIZE, AMFConstructSize(m_videoSource.GetFrameWidth(), m_videoSource.GetFrameHeight())); GUID guidSubType = m_videoSource.GetCodec(); if (MFVideoFormat_H264 == guidSubType) { SetProperty(VIDEOCAP_CODEC, L"AMFVideoDecoderUVD_H264_AVC"); } else if (MFVideoFormat_HEVC == guidSubType) { SetProperty(VIDEOCAP_CODEC, L"AMFVideoEncoder_HEVC"); } else if (MFVideoFormat_MJPG == guidSubType)//mjpeg { SetProperty(VIDEOCAP_CODEC, L"AMFVideoDecoderUVD_MJPEG"); } else if (MFVideoFormat_NV12 == guidSubType)//nv12 raw { SetProperty(VIDEOCAP_CODEC, L"AMFVideoDecoderUVD_H264_AVC"); } } if (AMF_OK == res) { if (deviceNameActive.length() <= 0) //query device list { UINT deviceCount = m_videoSource.GetDeviceCount(); std::string nameList(""); for (UINT idx = 0; idx < deviceCount; idx++) { std::string deviceName = m_videoSource.GetDeviceName(idx); nameList += (idx == 0) ? deviceName : "\t" + deviceName; } SetProperty(VIDEOCAP_DEVICE_NAME, nameList.c_str()); SetProperty(VIDEOCAP_DEVICE_COUNT, deviceCount); } else { m_videoPollingThread.Start(); } } m_bTerminated = false; return res; } //------------------------------------------------------------------------------------------------- AMF_RESULT AMF_STD_CALL AMFVideoCaptureImpl::ReInit(amf_int32 width, amf_int32 height) { Terminate(); return Init(AMF_SURFACE_UNKNOWN, width, height); } //------------------------------------------------------------------------------------------------- AMF_RESULT AMF_STD_CALL AMFVideoCaptureImpl::Terminate() { m_videoPollingThread.RequestStop(); m_videoPollingThread.WaitForStop(); AMFLock lock(&m_sync); m_OutputStream = NULL; m_frameCount = 0; m_videoSource.Close(); m_bTerminated = true; return AMF_OK; } //------------------------------------------------------------------------------------------------- AMF_RESULT AMF_STD_CALL AMFVideoCaptureImpl::Drain() { AMFLock lock(&m_sync); return AMF_OK; } //------------------------------------------------------------------------------------------------- AMF_RESULT AMF_STD_CALL AMFVideoCaptureImpl::Flush() { AMFLock lock(&m_sync); return AMF_OK; } //------------------------------------------------------------------------------------------------- AMF_RESULT AMF_STD_CALL AMFVideoCaptureImpl::GetOutput(amf_int32 index, AMFOutput** ppOutput) { AMF_RETURN_IF_FALSE(ppOutput != NULL, AMF_INVALID_ARG, L"ppOutput = NULL"); *ppOutput = m_OutputStream; (*ppOutput)->Acquire(); return AMF_OK; } //------------------------------------------------------------------------------------------------- void AMF_STD_CALL AMFVideoCaptureImpl::OnPropertyChanged(const wchar_t* pName) { AMFLock lock(&m_sync); amf_wstring name(pName); } //------------------------------------------------------------------------------------------------- AMF_RESULT AMFVideoCaptureImpl::PollStream() { AMF_RESULT res = AMF_OK; // error checking can be added later char* pData(NULL); UINT lenData(0); amf_pts timestampCapStart = amf_high_precision_clock(); int err = m_videoSource.CaptureOnePacket(&pData, lenData); amf_pts timestampCapEnd = amf_high_precision_clock(); if ((err != AMF_OK) || (lenData <= 0)) { AMFTraceWarning(L"Videostitch", L"Video Data len- lenData <= 0!!"); res = AMF_FAIL; } else { AMFBufferPtr pVideoBuffer; err = m_pContext->AllocBuffer(AMF_MEMORY_HOST, lenData, &pVideoBuffer); if (AMF_OK == err && pVideoBuffer) { amf_pts duration = m_videoSource.GetFrameDuration(); amf_pts timestamp = amf_high_precision_clock(); pVideoBuffer->SetPts(timestamp); pVideoBuffer->SetDuration(duration); if (pData) { void* pDst = pVideoBuffer->GetNative(); memcpy(pDst, pData, lenData); } AMF_RESULT err = AMF_INPUT_FULL; while (!m_videoPollingThread.StopRequested()) { err = m_OutputStream->SubmitFrame(pVideoBuffer); if (AMF_INPUT_FULL != err) { break; } amf_sleep(1); // milliseconds } } } m_videoSource.CaptureOnePacketDone(); m_frameCount++; return res; } //------------------------------------------------------------------------------------------------- void AMFVideoCaptureImpl::VideoCapturePollingThread::Run() { AMF_RESULT res = AMF_OK; // error checking can be added later while (AMF_OK == res) { res = m_pHost->PollStream(); if (res == AMF_EOF) { break; // Drain complete } if (StopRequested()) { break; } } } //------------------------------------------------------------------------------------------------- AMFVideoCaptureImpl::VideoCapturePollingThread::VideoCapturePollingThread(AMFVideoCaptureImpl *pHost) : m_pHost(pHost) { } //------------------------------------------------------------------------------------------------- AMFVideoCaptureImpl::VideoCapturePollingThread::~VideoCapturePollingThread() { }
4,278
460
///////////////////////////////////////////////////////////////////////////// // Name: wx/motif/icon.h // Purpose: wxIcon class // Author: <NAME> // Modified by: // Created: 17/09/98 // RCS-ID: $Id: icon.h 42752 2006-10-30 19:26:48Z VZ $ // Copyright: (c) <NAME> // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_ICON_H_ #define _WX_ICON_H_ #include "wx/bitmap.h" // Icon class WXDLLEXPORT wxIcon : public wxBitmap { public: wxIcon(); // Initialize with XBM data wxIcon(const char bits[], int width, int height); // Initialize with XPM data wxIcon(const char **data); wxIcon(char **data); wxIcon(const wxString& name, wxBitmapType type = wxBITMAP_TYPE_XPM, int desiredWidth = -1, int desiredHeight = -1) { LoadFile(name, type, desiredWidth, desiredHeight); } wxIcon(const wxIconLocation& loc) { LoadFile(loc.GetFileName(), wxBITMAP_TYPE_ANY); } virtual ~wxIcon(); bool LoadFile(const wxString& name, wxBitmapType type, int desiredWidth, int desiredHeight = -1); // unhide base class LoadFile() virtual bool LoadFile(const wxString& name, wxBitmapType type = wxBITMAP_TYPE_XPM) { return LoadFile(name, type, -1, -1); } // create from bitmap (which should have a mask unless it's monochrome): // there shouldn't be any implicit bitmap -> icon conversion (i.e. no // ctors, assignment operators...), but it's ok to have such function void CopyFromBitmap(const wxBitmap& bmp); DECLARE_DYNAMIC_CLASS(wxIcon) }; #endif // _WX_ICON_H_
694
1,970
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hudi.payload; import org.apache.hudi.common.model.OverwriteWithLatestAvroPayload; import org.apache.hudi.common.util.Option; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.IndexedRecord; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; public class TestAWSDmsAvroPayload { private static final String AVRO_SCHEMA_STRING = "{\"type\": \"record\"," + "\"name\": \"events\"," + "\"fields\": [ " + "{\"name\": \"field1\", \"type\" : \"int\"}," + "{\"name\": \"Op\", \"type\": \"string\"}" + "]}"; @Test public void testInsert() { Schema avroSchema = new Schema.Parser().parse(AVRO_SCHEMA_STRING); GenericRecord record = new GenericData.Record(avroSchema); record.put("field1", 0); record.put("Op", "I"); AWSDmsAvroPayload payload = new AWSDmsAvroPayload(Option.of(record)); try { Option<IndexedRecord> outputPayload = payload.getInsertValue(avroSchema); assertTrue((int) outputPayload.get().get(0) == 0); assertTrue(outputPayload.get().get(1).toString().equals("I")); } catch (Exception e) { fail("Unexpected exception"); } } @Test public void testUpdate() { Schema avroSchema = new Schema.Parser().parse(AVRO_SCHEMA_STRING); GenericRecord newRecord = new GenericData.Record(avroSchema); newRecord.put("field1", 1); newRecord.put("Op", "U"); GenericRecord oldRecord = new GenericData.Record(avroSchema); oldRecord.put("field1", 0); oldRecord.put("Op", "I"); AWSDmsAvroPayload payload = new AWSDmsAvroPayload(Option.of(newRecord)); try { Option<IndexedRecord> outputPayload = payload.combineAndGetUpdateValue(oldRecord, avroSchema); assertTrue((int) outputPayload.get().get(0) == 1); assertTrue(outputPayload.get().get(1).toString().equals("U")); } catch (Exception e) { fail("Unexpected exception"); } } @Test public void testDelete() { Schema avroSchema = new Schema.Parser().parse(AVRO_SCHEMA_STRING); GenericRecord deleteRecord = new GenericData.Record(avroSchema); deleteRecord.put("field1", 2); deleteRecord.put("Op", "D"); GenericRecord oldRecord = new GenericData.Record(avroSchema); oldRecord.put("field1", 2); oldRecord.put("Op", "U"); AWSDmsAvroPayload payload = new AWSDmsAvroPayload(Option.of(deleteRecord)); try { Option<IndexedRecord> outputPayload = payload.combineAndGetUpdateValue(oldRecord, avroSchema); // expect nothing to be comitted to table assertFalse(outputPayload.isPresent()); } catch (Exception e) { fail("Unexpected exception"); } } @Test public void testPreCombineWithDelete() { Schema avroSchema = new Schema.Parser().parse(AVRO_SCHEMA_STRING); GenericRecord deleteRecord = new GenericData.Record(avroSchema); deleteRecord.put("field1", 4); deleteRecord.put("Op", "D"); GenericRecord oldRecord = new GenericData.Record(avroSchema); oldRecord.put("field1", 4); oldRecord.put("Op", "I"); AWSDmsAvroPayload payload = new AWSDmsAvroPayload(Option.of(deleteRecord)); AWSDmsAvroPayload insertPayload = new AWSDmsAvroPayload(Option.of(oldRecord)); try { OverwriteWithLatestAvroPayload output = payload.preCombine(insertPayload); Option<IndexedRecord> outputPayload = output.getInsertValue(avroSchema); // expect nothing to be comitted to table assertFalse(outputPayload.isPresent()); } catch (Exception e) { fail("Unexpected exception"); } } }
1,601
581
<reponame>flix-/phasar #include <iostream> using namespace std; int main() { std::string c("test"); std::string d(c); std::cout << c << d << "\n"; std::string e, f; e = c; std::cout << e << "\n"; std::string g(move(e)); std::cout << g << "\n"; f = move(d); std::cout << f << "\n"; return 0; }
147
476
/* * 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.prestosql.operator.aggregation; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import io.airlift.bytecode.DynamicClassLoader; import io.prestosql.metadata.BoundVariables; import io.prestosql.metadata.FunctionAndTypeManager; import io.prestosql.metadata.SqlAggregationFunction; import io.prestosql.operator.ParametricImplementationsGroup; import io.prestosql.operator.aggregation.AggregationMetadata.AccumulatorStateDescriptor; import io.prestosql.operator.aggregation.AggregationMetadata.ParameterMetadata; import io.prestosql.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType; import io.prestosql.operator.aggregation.state.StateCompiler; import io.prestosql.spi.PrestoException; import io.prestosql.spi.function.AccumulatorStateFactory; import io.prestosql.spi.function.AccumulatorStateSerializer; import io.prestosql.spi.function.Signature; import io.prestosql.spi.type.Type; import io.prestosql.spi.type.TypeSignature; import java.lang.invoke.MethodHandle; import java.util.List; import java.util.Optional; import static com.google.common.base.Throwables.throwIfUnchecked; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.prestosql.metadata.SignatureBinder.applyBoundVariables; import static io.prestosql.operator.ParametricFunctionHelpers.bindDependencies; import static io.prestosql.operator.aggregation.AggregationUtils.generateAggregationName; import static io.prestosql.operator.aggregation.state.StateCompiler.generateStateSerializer; import static io.prestosql.spi.StandardErrorCode.AMBIGUOUS_FUNCTION_CALL; import static io.prestosql.spi.StandardErrorCode.FUNCTION_IMPLEMENTATION_MISSING; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class ParametricAggregation extends SqlAggregationFunction { private final AggregationHeader details; private final ParametricImplementationsGroup<AggregationImplementation> implementations; public ParametricAggregation( Signature signature, AggregationHeader details, ParametricImplementationsGroup<AggregationImplementation> implementations) { super(signature, details.isHidden()); this.details = requireNonNull(details, "details is null"); this.implementations = requireNonNull(implementations, "implementations is null"); } @Override public InternalAggregationFunction specialize(BoundVariables variables, int arity, FunctionAndTypeManager functionAndTypeManager) { // Bind variables Signature boundSignature = applyBoundVariables(getSignature(), variables, arity); // Find implementation matching arguments AggregationImplementation concreteImplementation = findMatchingImplementation(boundSignature, variables, functionAndTypeManager); // Build argument and return Types from signatures List<Type> inputTypes = boundSignature.getArgumentTypes().stream().map(functionAndTypeManager::getType).collect(toImmutableList()); Type outputType = functionAndTypeManager.getType(boundSignature.getReturnType()); // Create classloader for additional aggregation dependencies Class<?> definitionClass = concreteImplementation.getDefinitionClass(); DynamicClassLoader classLoader = new DynamicClassLoader(definitionClass.getClassLoader(), getClass().getClassLoader()); // Build state factory and serializer Class<?> stateClass = concreteImplementation.getStateClass(); AccumulatorStateSerializer<?> stateSerializer = getAccumulatorStateSerializer(concreteImplementation, variables, functionAndTypeManager, stateClass, classLoader); AccumulatorStateFactory<?> stateFactory = StateCompiler.generateStateFactory(stateClass, classLoader); // Bind provided dependencies to aggregation method handlers MethodHandle inputHandle = bindDependencies(concreteImplementation.getInputFunction(), concreteImplementation.getInputDependencies(), variables, functionAndTypeManager); MethodHandle combineHandle = bindDependencies(concreteImplementation.getCombineFunction(), concreteImplementation.getCombineDependencies(), variables, functionAndTypeManager); MethodHandle outputHandle = bindDependencies(concreteImplementation.getOutputFunction(), concreteImplementation.getOutputDependencies(), variables, functionAndTypeManager); // Build metadata of input parameters List<ParameterMetadata> parametersMetadata = buildParameterMetadata(concreteImplementation.getInputParameterMetadataTypes(), inputTypes); // Generate Aggregation name String aggregationName = generateAggregationName(getSignature().getNameSuffix(), outputType.getTypeSignature(), signaturesFromTypes(inputTypes)); // Collect all collected data in Metadata AggregationMetadata aggregationMetadata = new AggregationMetadata( aggregationName, parametersMetadata, inputHandle, combineHandle, outputHandle, ImmutableList.of(new AccumulatorStateDescriptor( stateClass, stateSerializer, stateFactory)), outputType); // Create specialized InternalAggregregationFunction for Presto return new InternalAggregationFunction(getSignature().getNameSuffix(), inputTypes, ImmutableList.of(stateSerializer.getSerializedType()), outputType, details.isDecomposable(), details.isOrderSensitive(), new LazyAccumulatorFactoryBinder(aggregationMetadata, classLoader)); } @VisibleForTesting public ParametricImplementationsGroup<AggregationImplementation> getImplementations() { return implementations; } @Override public String getDescription() { return details.getDescription().orElse(""); } private AggregationImplementation findMatchingImplementation(Signature boundSignature, BoundVariables variables, FunctionAndTypeManager functionAndTypeManager) { Optional<AggregationImplementation> foundImplementation = Optional.empty(); if (implementations.getExactImplementations().containsKey(boundSignature)) { foundImplementation = Optional.of(implementations.getExactImplementations().get(boundSignature)); } else { for (AggregationImplementation candidate : implementations.getGenericImplementations()) { if (candidate.areTypesAssignable(boundSignature, variables, functionAndTypeManager)) { if (foundImplementation.isPresent()) { throw new PrestoException(AMBIGUOUS_FUNCTION_CALL, format("Ambiguous function call (%s) for %s", variables, getSignature())); } foundImplementation = Optional.of(candidate); } } } if (!foundImplementation.isPresent()) { throw new PrestoException(FUNCTION_IMPLEMENTATION_MISSING, format("Unsupported type parameters (%s) for %s", variables, getSignature())); } return foundImplementation.get(); } private static AccumulatorStateSerializer<?> getAccumulatorStateSerializer(AggregationImplementation implementation, BoundVariables variables, FunctionAndTypeManager functionAndTypeManager, Class<?> stateClass, DynamicClassLoader classLoader) { AccumulatorStateSerializer<?> stateSerializer; Optional<MethodHandle> stateSerializerFactory = implementation.getStateSerializerFactory(); if (stateSerializerFactory.isPresent()) { try { MethodHandle factoryHandle = bindDependencies(stateSerializerFactory.get(), implementation.getStateSerializerFactoryDependencies(), variables, functionAndTypeManager); stateSerializer = (AccumulatorStateSerializer<?>) factoryHandle.invoke(); } catch (Throwable t) { throwIfUnchecked(t); throw new RuntimeException(t); } } else { stateSerializer = generateStateSerializer(stateClass, classLoader); } return stateSerializer; } private static List<TypeSignature> signaturesFromTypes(List<Type> types) { return types .stream() .map(Type::getTypeSignature) .collect(toImmutableList()); } private static List<ParameterMetadata> buildParameterMetadata(List<ParameterType> parameterMetadataTypes, List<Type> inputTypes) { ImmutableList.Builder<ParameterMetadata> builder = ImmutableList.builder(); int inputId = 0; for (ParameterType parameterMetadataType : parameterMetadataTypes) { switch (parameterMetadataType) { case STATE: case BLOCK_INDEX: builder.add(new ParameterMetadata(parameterMetadataType)); break; case INPUT_CHANNEL: case BLOCK_INPUT_CHANNEL: case NULLABLE_BLOCK_INPUT_CHANNEL: builder.add(new ParameterMetadata(parameterMetadataType, inputTypes.get(inputId++))); break; } } return builder.build(); } }
3,554
424
#include <Fastor/Fastor.h> using namespace Fastor; #define Tol 1e-12 #define BigTol 1e-5 template<typename T> void run() { using std::abs; { Tensor<T,9,10> a1; a1.iota(0); Tensor<int,5,5> it1; for (auto i=0; i<5; ++i) for (auto j=0; j<5; ++j) it1(i,j) = i*9 + j + 11 + i; // Check construction from views Tensor<T,5,5> a2 = a1(it1); FASTOR_EXIT_ASSERT(abs(a2.sum() - 825) < Tol); a2 += a1(it1); FASTOR_EXIT_ASSERT(abs(a2.sum() - 2*825) < Tol); a2 -= a1(it1); FASTOR_EXIT_ASSERT(abs(a2.sum() - 825) < Tol); a2 *= 2. + a1(it1); FASTOR_EXIT_ASSERT(abs(a2.sum() - 33925) < Tol); a2 /= a1(it1) + 5000; FASTOR_EXIT_ASSERT(abs(a2.sum() - 6.72701) < 1e-2); // Assigning to a view from numbers/tensors/views Tensor<T,9,10> a3; a3.iota(10); a3(it1) = 4; FASTOR_EXIT_ASSERT(abs(a3.sum() - 3930) < Tol); a3(it1) += 3; FASTOR_EXIT_ASSERT(abs(a3.sum() - 4005) < Tol); a3(it1) -= 3; FASTOR_EXIT_ASSERT(abs(a3.sum() - 3930) < Tol); a3(it1) *= 3; FASTOR_EXIT_ASSERT(abs(a3.sum() - 4130) < Tol); a3(it1) /= 3; FASTOR_EXIT_ASSERT(abs(a3.sum() - 3930) < Tol); Tensor<T,5,5> a4; a4.iota(1); a3.fill(1); a3(it1) = a4; FASTOR_EXIT_ASSERT(abs(a3.sum() - 390) < Tol); a3(it1) += 2*a4; FASTOR_EXIT_ASSERT(abs(a3.sum() - 1040) < Tol); a3(it1) -= a4+2; FASTOR_EXIT_ASSERT(abs(a3.sum() - 665) < Tol); a3(it1) *= -a4-100; FASTOR_EXIT_ASSERT(abs(a3.sum() + 70335) < Tol); a3(it1) /= 100000.+a4; FASTOR_EXIT_ASSERT(abs(a3.sum() - 64.2961) < 1e-2); a3.iota(10); a3(it1) = a3(it1); FASTOR_EXIT_ASSERT(abs(a3.sum() - 4905) < Tol); a3(it1) += a3(it1); FASTOR_EXIT_ASSERT(abs(a3.sum() - 5980) < Tol); a3(it1) -= a3(it1); FASTOR_EXIT_ASSERT(abs(a3.sum() - 3830) < Tol); a3(it1) = 2; a3(it1) *= a3(it1); FASTOR_EXIT_ASSERT(abs(a3.sum() - 3930) < Tol); a3(it1) /= a3(it1); FASTOR_EXIT_ASSERT(abs(a3.sum() - 3855) < BigTol); // Check overlap a3.iota(10); Tensor<int,5,5> it2; it2.iota(0); it1.iota(2); a3(it1).noalias() = a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 4855) < BigTol); a3(it1).noalias() += a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 5359) < BigTol); a3(it1).noalias() -= a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 4414) < BigTol); a3(it1).noalias() *= a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 4888) < BigTol); a3(it1).noalias() /= a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 4348.14550) < 1e-2); a3.iota(10); a3(it1).noalias() = a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 4855) < BigTol); a3(it1).noalias() += a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 5359) < BigTol); a3(it1).noalias() -= a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 4414) < BigTol); a3(it1).noalias() *= a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 4888) < BigTol); a3(it1).noalias() /= a3(it2); FASTOR_EXIT_ASSERT(abs(a3.sum() - 4348.14550) < 1e-2); print(FGRN(BOLD("All tests passed successfully"))); } } int main() { print(FBLU(BOLD("Testing multi-dimensional random tensor views: single precision"))); run<float>(); print(FBLU(BOLD("Testing multi-dimensional random tensor views: double precision"))); run<double>(); return 0; }
2,179
4,268
import os, sys, json, yaml if __name__ == '__main__': # Use safe_dump() instead of dump() to avoid tags like "!!python/unicode" print(yaml.safe_dump(json.load(sys.stdin), default_flow_style=False))
77
574
# -*- coding: utf-8 -*- from strategyease_sdk.jobs.basic_job import BasicJob class ConvertibleBondsPurchaseJob(BasicJob): def __init__(self, client, client_aliases=None, name=None, **kwargs): super(ConvertibleBondsPurchaseJob, self).__init__(name, kwargs.get('schedule', None), kwargs.get('enabled', False)) self._client = client self._client_aliases = client_aliases def __call__(self): for client_alias in self._client_aliases: try: client = self._client_aliases[client_alias] self._client.purchase_convertible_bonds(client) except: self._logger.exception('客户端[%s]申购转债失败', client_alias)
327
372
#include "TextureManager.h" #include "Bitmap.h" #if IMGUI_USE_GLBINDING #define GLBINDING_AVAILABLE 1 #include <glbinding-aux/ContextInfo.h> #include <glbinding/gl21/gl.h> #include <glbinding/gl21ext/gl.h> #include <glbinding/gl30/gl.h> using namespace gl21; #elif IMGUI_USE_GLAD2 #include <glad/gl.h> #else #include <Windows.h> #include <gl/GL.h> #endif #include <mh/concurrency/thread_sentinel.hpp> #include <mh/memory/unique_object.hpp> #include <array> #include <set> using namespace tf2_bot_detector; namespace { struct TextureHandleTraits final { static void delete_obj(GLuint t) { glDeleteTextures(1, &t); } static GLuint release_obj(GLuint& t) { auto retVal = t; t = {}; return retVal; } static bool is_obj_valid(GLuint t) { return t > 0; } }; using TextureHandle = mh::unique_object<GLuint, TextureHandleTraits>; class TextureManager; class Texture final : public ITexture { public: Texture(const TextureManager& manager, const Bitmap& bitmap, const TextureSettings& settings); handle_type GetHandle() const override { return m_Handle; } const TextureSettings& GetSettings() const override { return m_Settings; } uint16_t GetWidth() const override { return m_Width; } uint16_t GetHeight() const override { return m_Height; } private: TextureHandle m_Handle{}; TextureSettings m_Settings{}; uint16_t m_Width{}; uint16_t m_Height{}; }; class TextureManager final : public ITextureManager { public: TextureManager(); void EndFrame() override; std::shared_ptr<ITexture> CreateTexture(const Bitmap& bitmap, const TextureSettings& settings) override; size_t GetActiveTextureCount() const override { return m_Textures.size(); } #ifdef IMGUI_USE_GLBINDING bool HasExtension(GLextension ext) const { return GetExtensions().contains(ext); } const std::set<GLextension>& GetExtensions() const { return m_Extensions; } const glbinding::Version& GetContextVersion() const { return m_ContextVersion; } #endif private: #ifdef IMGUI_USE_GLBINDING glbinding::Version m_ContextVersion{}; const std::set<GLextension> m_Extensions = glbinding::aux::ContextInfo::extensions(); #endif uint64_t m_FrameCount{}; std::vector<std::shared_ptr<Texture>> m_Textures; mh::thread_sentinel m_Sentinel; }; } std::shared_ptr<ITextureManager> tf2_bot_detector::ITextureManager::Create() { return std::make_unique<TextureManager>(); } TextureManager::TextureManager() { #ifdef IMGUI_USE_GLBINDING m_ContextVersion = glbinding::aux::ContextInfo::version(); #endif } void TextureManager::EndFrame() { m_Sentinel.check(); std::erase_if(m_Textures, [](const std::shared_ptr<Texture>& t) { return t.use_count() == 1; }); } std::shared_ptr<ITexture> TextureManager::CreateTexture(const Bitmap& bitmap, const TextureSettings& settings) { m_Sentinel.check(); return m_Textures.emplace_back(std::make_shared<Texture>(*this, bitmap, settings)); } Texture::Texture(const TextureManager& manager, const Bitmap& bitmap, const TextureSettings& settings) : m_Settings(settings), m_Width(bitmap.GetWidth()), m_Height(bitmap.GetHeight()) { GLenum internalFormat{}; GLenum sourceFormat{}; std::array<GLint, 4> swizzle{}; constexpr GLenum sourceType = GL_UNSIGNED_BYTE; switch (bitmap.GetChannelCount()) { case 1: internalFormat = GL_RED; sourceFormat = GL_RED; swizzle = { GL_RED, GL_RED, GL_RED, GL_ONE }; break; case 2: internalFormat = GL_RGB; sourceFormat = GL_RGB; swizzle = { GL_RED, GL_RED, GL_RED, GL_GREEN }; break; case 3: internalFormat = GL_RGB; sourceFormat = GL_RGB; swizzle = { GL_RED, GL_GREEN, GL_BLUE, GL_ONE }; break; case 4: internalFormat = GL_RGBA; sourceFormat = GL_RGBA; swizzle = { GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA }; break; } glGenTextures(1, &m_Handle.reset_and_get_ref()); assert(m_Handle); glBindTexture(GL_TEXTURE_2D, m_Handle); glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, bitmap.GetWidth(), bitmap.GetHeight(), 0, sourceFormat, sourceType, bitmap.GetData()); if (GLAD_GL_ARB_texture_swizzle) { glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzle.data()); } else if (GLAD_GL_EXT_texture_swizzle) { glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA_EXT, swizzle.data()); } #if 0 if (glGenerateMipmap) { glGenerateMipmap(GL_TEXTURE_2D); } else if (glGenerateMipmapEXT) { glGenerateMipmapEXT(GL_TEXTURE_2D); } else #endif { // just disable mipmaps glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } }
1,746
470
<filename>Sonora/Categories/NSObject+AssociatedObjects.h // // NSObject+AssociatedObjects.h // // Created by <NAME> on 8/27/09. // Public domain because I love you. // #import <Foundation/Foundation.h> @interface NSObject (AMAssociatedObjects) - (void)associateValue:(id)value withKey:(void *)key; // Strong reference - (void)weaklyAssociateValue:(id)value withKey:(void *)key; - (id)associatedValueForKey:(void *)key; @end
145
3,104
{ "compileOnSave": false, "compilerOptions": { "module": "commonjs", "noEmit": true, "noImplicitAny": true, "types": [] }, "include": [ "../index.d.ts", "../moment-timezone-utils.d.ts", "./moment-timezone-tests.ts", "./moment-timezone-utils-tests.ts" ] }
140
451
<reponame>bujiio/buji-pac4j<filename>src/main/java/io/buji/pac4j/filter/CallbackFilter.java /* * Licensed to the bujiio organization of the Shiro project 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 io.buji.pac4j.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.pac4j.core.config.Config; import org.pac4j.core.context.JEEContextFactory; import org.pac4j.core.context.WebContext; import org.pac4j.core.context.session.SessionStore; import org.pac4j.core.engine.CallbackLogic; import org.pac4j.core.engine.DefaultCallbackLogic; import org.pac4j.core.http.adapter.HttpActionAdapter; import org.pac4j.core.http.adapter.JEEHttpActionAdapter; import io.buji.pac4j.context.ShiroSessionStore; import org.pac4j.core.util.FindBest; /** * <p>This filter finishes the login process for an indirect client.</p> * * @author <NAME> * @since 2.0.0 */ public class CallbackFilter implements Filter { private CallbackLogic callbackLogic; private Config config; private String defaultUrl; private String defaultClient; private HttpActionAdapter httpActionAdapter; @Override public void init(final FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException { final SessionStore bestSessionStore = FindBest.sessionStore(null, config, ShiroSessionStore.INSTANCE); final HttpActionAdapter bestAdapter = FindBest.httpActionAdapter(httpActionAdapter, config, JEEHttpActionAdapter.INSTANCE); final CallbackLogic bestLogic = FindBest.callbackLogic(callbackLogic, config, DefaultCallbackLogic.INSTANCE); final WebContext context = FindBest.webContextFactory(null, config, JEEContextFactory.INSTANCE).newContext(servletRequest, servletResponse); bestLogic.perform(context, bestSessionStore, config, bestAdapter, defaultUrl, false, defaultClient); } @Override public void destroy() {} public CallbackLogic getCallbackLogic() { return callbackLogic; } public void setCallbackLogic(final CallbackLogic callbackLogic) { this.callbackLogic = callbackLogic; } public Config getConfig() { return config; } public void setConfig(final Config config) { this.config = config; } public String getDefaultUrl() { return defaultUrl; } public void setDefaultUrl(final String defaultUrl) { this.defaultUrl = defaultUrl; } public String getDefaultClient() { return defaultClient; } public void setDefaultClient(final String defaultClient) { this.defaultClient = defaultClient; } public HttpActionAdapter getHttpActionAdapter() { return httpActionAdapter; } public void setHttpActionAdapter(final HttpActionAdapter httpActionAdapter) { this.httpActionAdapter = httpActionAdapter; } }
1,236
348
{"nom":"Marsac","circ":"2ème circonscription","dpt":"Tarn-et-Garonne","inscrits":105,"abs":39,"votants":66,"blancs":4,"nuls":4,"exp":58,"res":[{"nuance":"RDG","nom":"Mme <NAME>","voix":35},{"nuance":"FN","nom":"M. <NAME>","voix":23}]}
98
10,225
<reponame>PieterjanDeconinck/quarkus<filename>integration-tests/main/src/test/java/io/quarkus/it/main/JaxbTestCase.java package io.quarkus.it.main; import static org.hamcrest.Matchers.contains; import org.junit.jupiter.api.Test; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; @QuarkusTest public class JaxbTestCase { @Test public void testNews() { RestAssured.when().get("/test/jaxb/getnews").then() .body("author", contains("<NAME>")); } }
220
945
<filename>node-commons/src/main/java/org/apache/iotdb/commons/auth/role/LocalFileRoleAccessor.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.commons.auth.role; import org.apache.iotdb.commons.auth.entity.PathPrivilege; import org.apache.iotdb.commons.auth.entity.Role; import org.apache.iotdb.commons.conf.IoTDBConstant; import org.apache.iotdb.commons.file.SystemFileFactory; import org.apache.iotdb.commons.utils.FileUtils; import org.apache.iotdb.commons.utils.IOUtils; import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; /** * This class store each role in a separate sequential file. Role file schema : Int32 role name size * Utf-8 role name bytes Int32 seriesPath privilege number n Int32 seriesPath[1] size Utf-8 * seriesPath[1] bytes Int32 privilege num k1 Int32 privilege[1][1] Int32 privilege[1][2] ... Int32 * privilege[1][k1] Int32 seriesPath[2] size Utf-8 seriesPath[2] bytes Int32 privilege num yk2 Int32 * privilege[2][1] Int32 privilege[2][2] ... Int32 privilege[2][k2] ... Int32 seriesPath[n] size * Utf-8 seriesPath[n] bytes Int32 privilege num kn Int32 privilege[n][1] Int32 privilege[n][2] ... * Int32 privilege[n][kn] */ public class LocalFileRoleAccessor implements IRoleAccessor { private static final Logger logger = LoggerFactory.getLogger(LocalFileRoleAccessor.class); private static final String TEMP_SUFFIX = ".temp"; private static final String STRING_ENCODING = "utf-8"; private static final String roleSnapshotFileName = "system" + File.separator + "roles"; private String roleDirPath; /** * Reused buffer for primitive types encoding/decoding, which aim to reduce memory fragments. Use * ThreadLocal for thread safety. */ private ThreadLocal<ByteBuffer> encodingBufferLocal = new ThreadLocal<>(); private ThreadLocal<byte[]> strBufferLocal = new ThreadLocal<>(); public LocalFileRoleAccessor(String roleDirPath) { this.roleDirPath = roleDirPath; } @Override public Role loadRole(String rolename) throws IOException { File roleProfile = SystemFileFactory.INSTANCE.getFile( roleDirPath + File.separator + rolename + IoTDBConstant.PROFILE_SUFFIX); if (!roleProfile.exists() || !roleProfile.isFile()) { // System may crush before a newer file is written, so search for back-up file. File backProfile = SystemFileFactory.INSTANCE.getFile( roleDirPath + File.separator + rolename + IoTDBConstant.PROFILE_SUFFIX + TEMP_SUFFIX); if (backProfile.exists() && backProfile.isFile()) { roleProfile = backProfile; } else { return null; } } FileInputStream inputStream = new FileInputStream(roleProfile); try (DataInputStream dataInputStream = new DataInputStream(new BufferedInputStream(inputStream))) { Role role = new Role(); role.setName(IOUtils.readString(dataInputStream, STRING_ENCODING, strBufferLocal)); int privilegeNum = dataInputStream.readInt(); List<PathPrivilege> pathPrivilegeList = new ArrayList<>(); for (int i = 0; i < privilegeNum; i++) { pathPrivilegeList.add( IOUtils.readPathPrivilege(dataInputStream, STRING_ENCODING, strBufferLocal)); } role.setPrivilegeList(pathPrivilegeList); return role; } catch (Exception e) { throw new IOException(e); } finally { strBufferLocal.remove(); } } @Override public void saveRole(Role role) throws IOException { File roleProfile = SystemFileFactory.INSTANCE.getFile( roleDirPath + File.separator + role.getName() + IoTDBConstant.PROFILE_SUFFIX + TEMP_SUFFIX); File roleDir = new File(roleDirPath); if (!roleDir.exists()) { roleDir.mkdirs(); } try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(roleProfile))) { try { IOUtils.writeString(outputStream, role.getName(), STRING_ENCODING, encodingBufferLocal); role.getPrivilegeList().sort(PathPrivilege.REFERENCE_DESCENT_SORTER); int privilegeNum = role.getPrivilegeList().size(); IOUtils.writeInt(outputStream, privilegeNum, encodingBufferLocal); for (int i = 0; i < privilegeNum; i++) { PathPrivilege pathPrivilege = role.getPrivilegeList().get(i); IOUtils.writePathPrivilege( outputStream, pathPrivilege, STRING_ENCODING, encodingBufferLocal); } outputStream.flush(); } catch (Exception e) { throw new IOException(e); } } finally { encodingBufferLocal.remove(); } File oldFile = SystemFileFactory.INSTANCE.getFile( roleDirPath + File.separator + role.getName() + IoTDBConstant.PROFILE_SUFFIX); IOUtils.replaceFile(roleProfile, oldFile); } @Override public boolean deleteRole(String rolename) throws IOException { File roleProfile = SystemFileFactory.INSTANCE.getFile( roleDirPath + File.separator + rolename + IoTDBConstant.PROFILE_SUFFIX); File backFile = SystemFileFactory.INSTANCE.getFile( roleDirPath + File.separator + rolename + IoTDBConstant.PROFILE_SUFFIX + TEMP_SUFFIX); if (!roleProfile.exists() && !backFile.exists()) { return false; } if ((roleProfile.exists() && !roleProfile.delete()) || (backFile.exists() && !backFile.delete())) { throw new IOException(String.format("Cannot delete role file of %s", rolename)); } return true; } @Override public List<String> listAllRoles() { File roleDir = SystemFileFactory.INSTANCE.getFile(roleDirPath); String[] names = roleDir.list( (dir, name) -> name.endsWith(IoTDBConstant.PROFILE_SUFFIX) || name.endsWith(TEMP_SUFFIX)); List<String> retList = new ArrayList<>(); if (names != null) { // in very rare situations, normal file and backup file may exist at the same time // so a set is used to deduplicate Set<String> set = new HashSet<>(); for (String fileName : names) { set.add(fileName.replace(IoTDBConstant.PROFILE_SUFFIX, "").replace(TEMP_SUFFIX, "")); } retList.addAll(set); } return retList; } @Override public boolean processTakeSnapshot(File snapshotDir) throws TException, IOException { SystemFileFactory systemFileFactory = SystemFileFactory.INSTANCE; File roleFolder = systemFileFactory.getFile(roleDirPath); File roleSnapshotDir = systemFileFactory.getFile(snapshotDir, roleSnapshotFileName); File roleTmpSnapshotDir = systemFileFactory.getFile(roleSnapshotDir.getAbsolutePath() + "-" + UUID.randomUUID()); boolean result = true; try { result = FileUtils.copyDir(roleFolder, roleTmpSnapshotDir); result &= roleTmpSnapshotDir.renameTo(roleSnapshotDir); } finally { if (roleTmpSnapshotDir.exists() && !roleTmpSnapshotDir.delete()) { FileUtils.deleteDirectory(roleTmpSnapshotDir); } } return result; } @Override public void processLoadSnapshot(File snapshotDir) throws TException, IOException { SystemFileFactory systemFileFactory = SystemFileFactory.INSTANCE; File roleFolder = systemFileFactory.getFile(roleDirPath); File roleTmpFolder = systemFileFactory.getFile(roleFolder.getAbsolutePath() + "-" + UUID.randomUUID()); File roleSnapshotDir = systemFileFactory.getFile(snapshotDir, roleSnapshotFileName); try { org.apache.commons.io.FileUtils.moveDirectory(roleFolder, roleTmpFolder); if (!FileUtils.copyDir(roleSnapshotDir, roleFolder)) { logger.error("Failed to load role folder snapshot and rollback."); // rollback if failed to copy FileUtils.deleteDirectory(roleFolder); org.apache.commons.io.FileUtils.moveDirectory(roleTmpFolder, roleFolder); } } finally { FileUtils.deleteDirectory(roleTmpFolder); } } @Override public void reset() { if (SystemFileFactory.INSTANCE.getFile(roleDirPath).mkdirs()) { logger.info("role info dir {} is created", roleDirPath); } else if (!SystemFileFactory.INSTANCE.getFile(roleDirPath).exists()) { logger.error("role info dir {} can not be created", roleDirPath); } } }
3,453
851
<filename>references/ExoPlayer/library/core/src/main/java/com/google/android/exoplayer2/extractor/mp4/PsshAtomUtil.java /* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2.extractor.mp4; import android.util.Log; import com.google.android.exoplayer2.util.ParsableByteArray; import java.nio.ByteBuffer; import java.util.UUID; /** * Utility methods for handling PSSH atoms. */ public final class PsshAtomUtil { private static final String TAG = "PsshAtomUtil"; private PsshAtomUtil() {} /** * Builds a version 0 PSSH atom for a given system id, containing the given data. * * @param systemId The system id of the scheme. * @param data The scheme specific data. * @return The PSSH atom. */ public static byte[] buildPsshAtom(UUID systemId, byte[] data) { return buildPsshAtom(systemId, null, data); } /** * Builds a PSSH atom for the given system id, containing the given key ids and data. * * @param systemId The system id of the scheme. * @param keyIds The key ids for a version 1 PSSH atom, or null for a version 0 PSSH atom. * @param data The scheme specific data. * @return The PSSH atom. */ public static byte[] buildPsshAtom(UUID systemId, UUID[] keyIds, byte[] data) { boolean buildV1Atom = keyIds != null; int dataLength = data != null ? data.length : 0; int psshBoxLength = Atom.FULL_HEADER_SIZE + 16 /* SystemId */ + 4 /* DataSize */ + dataLength; if (buildV1Atom) { psshBoxLength += 4 /* KID_count */ + (keyIds.length * 16) /* KIDs */; } ByteBuffer psshBox = ByteBuffer.allocate(psshBoxLength); psshBox.putInt(psshBoxLength); psshBox.putInt(Atom.TYPE_pssh); psshBox.putInt(buildV1Atom ? 0x01000000 : 0 /* version=(buildV1Atom ? 1 : 0), flags=0 */); psshBox.putLong(systemId.getMostSignificantBits()); psshBox.putLong(systemId.getLeastSignificantBits()); if (buildV1Atom) { psshBox.putInt(keyIds.length); for (UUID keyId : keyIds) { psshBox.putLong(keyId.getMostSignificantBits()); psshBox.putLong(keyId.getLeastSignificantBits()); } } if (dataLength != 0) { psshBox.putInt(data.length); psshBox.put(data); } // Else the last 4 bytes are a 0 DataSize. return psshBox.array(); } /** * Parses the UUID from a PSSH atom. Version 0 and 1 PSSH atoms are supported. * <p> * The UUID is only parsed if the data is a valid PSSH atom. * * @param atom The atom to parse. * @return The parsed UUID. Null if the input is not a valid PSSH atom, or if the PSSH atom has * an unsupported version. */ public static UUID parseUuid(byte[] atom) { PsshAtom parsedAtom = parsePsshAtom(atom); if (parsedAtom == null) { return null; } return parsedAtom.uuid; } /** * Parses the version from a PSSH atom. Version 0 and 1 PSSH atoms are supported. * <p> * The version is only parsed if the data is a valid PSSH atom. * * @param atom The atom to parse. * @return The parsed version. -1 if the input is not a valid PSSH atom, or if the PSSH atom has * an unsupported version. */ public static int parseVersion(byte[] atom) { PsshAtom parsedAtom = parsePsshAtom(atom); if (parsedAtom == null) { return -1; } return parsedAtom.version; } /** * Parses the scheme specific data from a PSSH atom. Version 0 and 1 PSSH atoms are supported. * <p> * The scheme specific data is only parsed if the data is a valid PSSH atom matching the given * UUID, or if the data is a valid PSSH atom of any type in the case that the passed UUID is null. * * @param atom The atom to parse. * @param uuid The required UUID of the PSSH atom, or null to accept any UUID. * @return The parsed scheme specific data. Null if the input is not a valid PSSH atom, or if the * PSSH atom has an unsupported version, or if the PSSH atom does not match the passed UUID. */ public static byte[] parseSchemeSpecificData(byte[] atom, UUID uuid) { PsshAtom parsedAtom = parsePsshAtom(atom); if (parsedAtom == null) { return null; } if (uuid != null && !uuid.equals(parsedAtom.uuid)) { Log.w(TAG, "UUID mismatch. Expected: " + uuid + ", got: " + parsedAtom.uuid + "."); return null; } return parsedAtom.schemeData; } /** * Parses a PSSH atom. Version 0 and 1 PSSH atoms are supported. * * @param atom The atom to parse. * @return The parsed PSSH atom. Null if the input is not a valid PSSH atom, or if the PSSH atom * has an unsupported version. */ // TODO: Support parsing of the key ids for version 1 PSSH atoms. private static PsshAtom parsePsshAtom(byte[] atom) { ParsableByteArray atomData = new ParsableByteArray(atom); if (atomData.limit() < Atom.FULL_HEADER_SIZE + 16 /* UUID */ + 4 /* DataSize */) { // Data too short. return null; } atomData.setPosition(0); int atomSize = atomData.readInt(); if (atomSize != atomData.bytesLeft() + 4) { // Not an atom, or incorrect atom size. return null; } int atomType = atomData.readInt(); if (atomType != Atom.TYPE_pssh) { // Not an atom, or incorrect atom type. return null; } int atomVersion = Atom.parseFullAtomVersion(atomData.readInt()); if (atomVersion > 1) { Log.w(TAG, "Unsupported pssh version: " + atomVersion); return null; } UUID uuid = new UUID(atomData.readLong(), atomData.readLong()); if (atomVersion == 1) { int keyIdCount = atomData.readUnsignedIntToInt(); atomData.skipBytes(16 * keyIdCount); } int dataSize = atomData.readUnsignedIntToInt(); if (dataSize != atomData.bytesLeft()) { // Incorrect dataSize. return null; } byte[] data = new byte[dataSize]; atomData.readBytes(data, 0, dataSize); return new PsshAtom(uuid, atomVersion, data); } // TODO: Consider exposing this and making parsePsshAtom public. private static class PsshAtom { private final UUID uuid; private final int version; private final byte[] schemeData; public PsshAtom(UUID uuid, int version, byte[] schemeData) { this.uuid = uuid; this.version = version; this.schemeData = schemeData; } } }
2,546
735
package org.mvel2.optimizers.impl.refl.nodes; import org.mvel2.compiler.ExecutableStatement; import org.mvel2.integration.VariableResolverFactory; import java.lang.reflect.Array; import static org.mvel2.DataConversion.convert; public abstract class InvokableAccessor extends BaseAccessor { protected int length; protected ExecutableStatement[] parms; protected Class[] parameterTypes; protected boolean coercionNeeded = false; protected Object[] executeAndCoerce(Class[] target, Object elCtx, VariableResolverFactory vars, boolean isVarargs) { Object[] values = new Object[length]; for (int i = 0; i < length && !(isVarargs && i >= length-1); i++) { //noinspection unchecked values[i] = convert(parms[i].getValue(elCtx, vars), target[i]); } if (isVarargs) { Class<?> componentType = target[length-1].getComponentType(); Object vararg; if (parms == null) { vararg = Array.newInstance( componentType, 0 ); } else { vararg = Array.newInstance(componentType, parms.length - length + 1); for (int i = length-1; i < parms.length; i++) { Array.set(vararg, i - length + 1, convert(parms[i].getValue(elCtx, vars), componentType)); } } values[length-1] = vararg; } return values; } public Class[] getParameterTypes() { return parameterTypes; } }
507