max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
698 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nginx.clojure;
/**
*
* @author <NAME>
*/
public class Merge3Test implements Runnable {
public boolean a;
public boolean b;
public void run() throws SuspendExecution {
if(a) {
Object[] arr = new Object[2];
System.out.println(arr);
} else {
float[] arr = new float[3];
System.out.println(arr);
}
blub();
System.out.println();
}
private void blub() throws SuspendExecution {
}
@org.junit.Test
public void testMerge3() {
Coroutine c = new Coroutine(new Merge3Test());
c.run();
}
}
| 371 |
10,225 |
<filename>extensions/smallrye-metrics/deployment/src/test/java/io/quarkus/smallrye/metrics/jaxrs/MetricsResource.java
package io.quarkus.smallrye.metrics.jaxrs;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
@Path("/")
public class MetricsResource {
@Path("/hello/{name}")
@GET
public String hello(@PathParam("name") String name) {
return "hello " + name;
}
@Path("/error")
@GET
public Response error() {
return Response.serverError().build();
}
@Path("/exception")
@GET
public Long exception() {
throw new RuntimeException("!!!");
}
@GET
@Path("{segment}/{other}/{segment}/list")
public Response list(@PathParam("segment") List<PathSegment> segments) {
return Response.ok().build();
}
@GET
@Path("{segment}/{other}/{segment}/array")
public Response array(@PathParam("segment") PathSegment[] segments) {
return Response.ok().build();
}
@GET
@Path("{segment}/{other}/{segment}/varargs")
public Response varargs(@PathParam("segment") PathSegment... segments) {
return Response.ok().build();
}
@Path("/async")
@GET
public CompletionStage<String> async() {
return CompletableFuture.supplyAsync(() -> "Hello");
}
}
| 613 |
590 |
<gh_stars>100-1000
# coding: utf-8
"""
Heap Sort
https://en.wikipedia.org/wiki/Heapsort
Worst-case performance: O(n * log n)
Best-case performance: O(n * log n)
Average performance: O(n * log n)
"""
import heapq
# Also see: https://github.com/vinta/fuck-coding-interviews/blob/master/data_structures/heaps/array_based_binary_heap.py
class Heap:
def __init__(self):
self._array = []
def _parent(self, index):
return (index - 1) // 2
def _left(self, index):
return (2 * index) + 1
def _right(self, index):
return (2 * index) + 2
def _swap(self, a, b):
self._array[a], self._array[b] = self._array[b], self._array[a]
def _up_heap(self, index):
while index >= 1:
parent_index = self._parent(index)
parent = self._array[parent_index]
current = self._array[index]
if parent > current:
self._swap(parent_index, index)
else:
return
index = parent_index
def push(self, value):
self._array.append(value)
self._up_heap(len(self._array) - 1)
def _min_child_index(self, index):
left_index = self._left(index)
right_index = self._right(index)
left = self._array[left_index] if left_index < len(self._array) else None
right = self._array[right_index] if right_index < len(self._array) else None
if (left is not None) and (right is not None):
if left < right:
return left_index
else:
return right_index
if left is not None:
return left_index
if right is not None:
return right_index
def _down_heap(self, index):
min_child_index = self._min_child_index(index)
if min_child_index:
current = self._array[index]
min_child = self._array[min_child_index]
if current > min_child:
self._swap(index, min_child_index)
self._down_heap(min_child_index)
def pop_min(self):
if not self._array:
raise ValueError('heap is empty')
self._swap(0, len(self._array) - 1)
popped = self._array.pop()
self._down_heap(0)
return popped
def heapsort(arr):
heap = Heap()
for item in arr:
heap.push(item)
return [heap.pop_min() for _ in range(len(arr))]
def heap_sort_heapq(arr):
heapq.heapify(arr)
return [heapq.heappop(arr) for _ in range(len(arr))]
| 1,198 |
1,473 |
/*
* Autopsy
*
* Copyright 2020 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* 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.sleuthkit.autopsy.discovery.ui;
import java.util.ArrayList;
import java.util.Collections;
import org.sleuthkit.autopsy.discovery.search.AbstractFilter;
import java.util.List;
import java.util.logging.Level;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.event.ListSelectionListener;
import org.openide.util.NbBundle;
import org.sleuthkit.autopsy.casemodule.Case;
import org.sleuthkit.autopsy.coreutils.Logger;
import org.sleuthkit.autopsy.coreutils.ThreadConfined;
import org.sleuthkit.autopsy.discovery.search.SearchFiltering;
import org.sleuthkit.datamodel.DataSource;
import org.sleuthkit.datamodel.TskCoreException;
/**
* A panel which displays the controls for the Data Source Filter.
*/
final class DataSourceFilterPanel extends AbstractDiscoveryFilterPanel {
private static final long serialVersionUID = 1L;
private final static Logger logger = Logger.getLogger(DataSourceFilterPanel.class.getName());
/**
* Creates new form DataSourceFilterPanel.
*/
@ThreadConfined(type = ThreadConfined.ThreadType.AWT)
DataSourceFilterPanel() {
initComponents();
setUpDataSourceFilter();
this.add(dataSourceCheckBoxList);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
dataSourceCheckbox = new javax.swing.JCheckBox();
dataSourceCheckBoxList = new org.sleuthkit.autopsy.guiutils.CheckBoxListPanel<>();
org.openide.awt.Mnemonics.setLocalizedText(dataSourceCheckbox, org.openide.util.NbBundle.getMessage(DataSourceFilterPanel.class, "DataSourceFilterPanel.dataSourceCheckbox.text")); // NOI18N
dataSourceCheckbox.setMaximumSize(new java.awt.Dimension(150, 25));
dataSourceCheckbox.setMinimumSize(new java.awt.Dimension(150, 25));
dataSourceCheckbox.setPreferredSize(new java.awt.Dimension(150, 25));
dataSourceCheckbox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dataSourceCheckboxActionPerformed(evt);
}
});
setMinimumSize(new java.awt.Dimension(250, 30));
setPreferredSize(new java.awt.Dimension(250, 50));
setRequestFocusEnabled(false);
setLayout(new java.awt.BorderLayout());
add(dataSourceCheckBoxList, java.awt.BorderLayout.CENTER);
}// </editor-fold>//GEN-END:initComponents
private void dataSourceCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataSourceCheckboxActionPerformed
dataSourceCheckBoxList.setEnabled(dataSourceCheckbox.isSelected());
}//GEN-LAST:event_dataSourceCheckboxActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private org.sleuthkit.autopsy.guiutils.CheckBoxListPanel<DataSource> dataSourceCheckBoxList;
private javax.swing.JCheckBox dataSourceCheckbox;
// End of variables declaration//GEN-END:variables
@ThreadConfined(type = ThreadConfined.ThreadType.AWT)
@Override
void configurePanel(boolean selected, List<?> selectedItems) {
dataSourceCheckbox.setSelected(selected);
if (dataSourceCheckbox.isEnabled() && dataSourceCheckbox.isSelected()) {
dataSourceCheckBoxList.setEnabled(true);
if (selectedItems != null) {
List<DataSource> dsList = new ArrayList<>();
for (Object item : selectedItems) {
if (item instanceof DataSource) {
dsList.add((DataSource) item);
}
}
if (!dsList.isEmpty()) {
dataSourceCheckBoxList.setSelectedElements(dsList);
}
}
} else {
dataSourceCheckBoxList.setEnabled(false);
}
}
@ThreadConfined(type = ThreadConfined.ThreadType.AWT)
@Override
JCheckBox getCheckbox() {
return dataSourceCheckbox;
}
@Override
JLabel getAdditionalLabel() {
return null;
}
/**
* Initialize the data source filter.
*/
@ThreadConfined(type = ThreadConfined.ThreadType.AWT)
private void setUpDataSourceFilter() {
try {
dataSourceCheckBoxList.clearList();
List<DataSource> dataSources = Case.getCurrentCase().getSleuthkitCase().getDataSources();
Collections.sort(dataSources, (DataSource ds1, DataSource ds2) -> ds1.getName().compareToIgnoreCase(ds2.getName()));
for (DataSource ds : dataSources) {
dataSourceCheckBoxList.addElement(ds.getName() + " (ID: " + ds.getId() + ")", null, ds);
}
} catch (TskCoreException ex) {
logger.log(Level.SEVERE, "Error loading data sources", ex);
dataSourceCheckbox.setEnabled(false);
dataSourceCheckBoxList.setEnabled(false);
}
}
@Override
void addListSelectionListener(ListSelectionListener listener) {
dataSourceCheckBoxList.addListSelectionListener(listener);
}
@Override
boolean isFilterSupported() {
return !dataSourceCheckBoxList.isEmpty();
}
@ThreadConfined(type = ThreadConfined.ThreadType.AWT)
@NbBundle.Messages({"DataSourceFilterPanel.error.text=At least one data source must be selected."})
@Override
String checkForError() {
if (dataSourceCheckbox.isSelected() && dataSourceCheckBoxList.getSelectedElements().isEmpty()) {
return Bundle.DataSourceFilterPanel_error_text();
}
return "";
}
@ThreadConfined(type = ThreadConfined.ThreadType.AWT)
@Override
AbstractFilter getFilter() {
if (dataSourceCheckbox.isSelected()) {
List<DataSource> dataSources = dataSourceCheckBoxList.getSelectedElements();
return new SearchFiltering.DataSourceFilter(dataSources);
}
return null;
}
}
| 2,624 |
2,322 |
<gh_stars>1000+
/*
* Setupapi cabinet routines
*
* Copyright 2003 <NAME>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <share.h>
#include "windef.h"
#include "winbase.h"
#include "wingdi.h"
#include "winuser.h"
#include "winnls.h"
#include "winreg.h"
#include "setupapi.h"
#include "setupapi_private.h"
#include "fdi.h"
#include "wine/debug.h"
OSVERSIONINFOW OsVersionInfo;
HINSTANCE SETUPAPI_hInstance = 0;
typedef struct
{
PSP_FILE_CALLBACK_A msghandler;
void *context;
char cab_path[MAX_PATH];
char last_cab[MAX_PATH];
char most_recent_target[MAX_PATH];
} SC_HSC_A, *PSC_HSC_A;
WINE_DEFAULT_DEBUG_CHANNEL(setupapi);
static void * CDECL sc_cb_alloc(ULONG cb)
{
return HeapAlloc(GetProcessHeap(), 0, cb);
}
static void CDECL sc_cb_free(void *pv)
{
HeapFree(GetProcessHeap(), 0, pv);
}
static INT_PTR CDECL sc_cb_open(char *pszFile, int oflag, int pmode)
{
DWORD creation = 0, sharing = 0;
int ioflag = 0;
SECURITY_ATTRIBUTES sa;
switch(oflag & (_O_RDONLY | _O_WRONLY | _O_RDWR)) {
case _O_RDONLY:
ioflag |= GENERIC_READ;
break;
case _O_WRONLY:
ioflag |= GENERIC_WRITE;
break;
case _O_RDWR:
ioflag |= GENERIC_READ | GENERIC_WRITE;
break;
}
if (oflag & _O_CREAT) {
if (oflag & _O_EXCL)
creation = CREATE_NEW;
else if (oflag & _O_TRUNC)
creation = CREATE_ALWAYS;
else
creation = OPEN_ALWAYS;
} else {
if (oflag & _O_TRUNC)
creation = TRUNCATE_EXISTING;
else
creation = OPEN_EXISTING;
}
switch( pmode & 0x70 ) {
case _SH_DENYRW:
sharing = 0L;
break;
case _SH_DENYWR:
sharing = FILE_SHARE_READ;
break;
case _SH_DENYRD:
sharing = FILE_SHARE_WRITE;
break;
case _SH_COMPAT:
case _SH_DENYNO:
sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
break;
}
sa.nLength = sizeof( SECURITY_ATTRIBUTES );
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = !(ioflag & _O_NOINHERIT);
return (INT_PTR) CreateFileA(pszFile, ioflag, sharing, &sa, creation, FILE_ATTRIBUTE_NORMAL, NULL);
}
static UINT CDECL sc_cb_read(INT_PTR hf, void *pv, UINT cb)
{
DWORD num_read;
if (!ReadFile((HANDLE)hf, pv, cb, &num_read, NULL))
return -1;
return num_read;
}
static UINT CDECL sc_cb_write(INT_PTR hf, void *pv, UINT cb)
{
DWORD num_written;
if (!WriteFile((HANDLE)hf, pv, cb, &num_written, NULL))
return -1;
return num_written;
}
static int CDECL sc_cb_close(INT_PTR hf)
{
if (!CloseHandle((HANDLE)hf))
return -1;
return 0;
}
static LONG CDECL sc_cb_lseek(INT_PTR hf, LONG dist, int seektype)
{
DWORD ret;
if (seektype < 0 || seektype > 2)
return -1;
if (((ret = SetFilePointer((HANDLE)hf, dist, NULL, seektype)) == INVALID_SET_FILE_POINTER) && GetLastError())
return -1;
return ret;
}
#define SIZEOF_MYSTERIO (MAX_PATH*3)
static INT_PTR CDECL sc_FNNOTIFY_A(FDINOTIFICATIONTYPE fdint, PFDINOTIFICATION pfdin)
{
FILE_IN_CABINET_INFO_A fici;
PSC_HSC_A phsc = pfdin->pv;
CABINET_INFO_A ci;
FILEPATHS_A fp;
UINT err;
CHAR mysterio[SIZEOF_MYSTERIO]; /* how big? undocumented! probably 256... */
memset(mysterio, 0, SIZEOF_MYSTERIO);
switch (fdint) {
case fdintCABINET_INFO:
TRACE("New cabinet, path %s, set %u, number %u, next disk %s, next cabinet %s.\n",
debugstr_a(pfdin->psz3), pfdin->setID, pfdin->iCabinet, debugstr_a(pfdin->psz2), debugstr_a(pfdin->psz1));
ci.CabinetFile = pfdin->psz1;
ci.CabinetPath = pfdin->psz3;
ci.DiskName = pfdin->psz2;
ci.SetId = pfdin->setID;
ci.CabinetNumber = pfdin->iCabinet;
phsc->msghandler(phsc->context, SPFILENOTIFY_CABINETINFO, (UINT_PTR) &ci, 0);
return 0;
case fdintPARTIAL_FILE:
return 0;
case fdintCOPY_FILE:
TRACE("Copy file %s, length %d, date %#x, time %#x, attributes %#x.\n",
debugstr_a(pfdin->psz1), pfdin->cb, pfdin->date, pfdin->time, pfdin->attribs);
fici.NameInCabinet = pfdin->psz1;
fici.FileSize = pfdin->cb;
fici.Win32Error = 0;
fici.DosDate = pfdin->date;
fici.DosTime = pfdin->time;
fici.DosAttribs = pfdin->attribs;
memset(fici.FullTargetName, 0, MAX_PATH);
err = phsc->msghandler(phsc->context, SPFILENOTIFY_FILEINCABINET,
(UINT_PTR)&fici, (UINT_PTR)phsc->last_cab);
if (err == FILEOP_DOIT) {
TRACE("Callback specified filename: %s\n", debugstr_a(fici.FullTargetName));
if (!fici.FullTargetName[0]) {
WARN("Empty return string causing abort.\n");
SetLastError(ERROR_PATH_NOT_FOUND);
return -1;
}
strcpy( phsc->most_recent_target, fici.FullTargetName );
return sc_cb_open(fici.FullTargetName, _O_BINARY | _O_CREAT | _O_WRONLY, _S_IREAD | _S_IWRITE);
} else {
TRACE("Callback skipped file.\n");
return 0;
}
case fdintCLOSE_FILE_INFO:
TRACE("File extracted.\n");
fp.Source = phsc->last_cab;
fp.Target = phsc->most_recent_target;
fp.Win32Error = 0;
fp.Flags = 0;
/* FIXME: set file time and attributes */
sc_cb_close(pfdin->hf);
err = phsc->msghandler(phsc->context, SPFILENOTIFY_FILEEXTRACTED, (UINT_PTR)&fp, 0);
if (err) {
SetLastError(err);
return FALSE;
} else
return TRUE;
case fdintNEXT_CABINET:
TRACE("Need new cabinet, path %s, file %s, disk %s, set %u, number %u.\n",
debugstr_a(pfdin->psz3), debugstr_a(pfdin->psz1),
debugstr_a(pfdin->psz2), pfdin->setID, pfdin->iCabinet);
ci.CabinetFile = pfdin->psz1;
ci.CabinetPath = pfdin->psz3;
ci.DiskName = pfdin->psz2;
ci.SetId = pfdin->setID;
ci.CabinetNumber = pfdin->iCabinet;
sprintf(phsc->last_cab, "%s%s", phsc->cab_path, ci.CabinetFile);
err = phsc->msghandler(phsc->context, SPFILENOTIFY_NEEDNEWCABINET, (UINT_PTR)&ci, (UINT_PTR)mysterio);
if (err) {
SetLastError(err);
return -1;
} else {
if (mysterio[0]) {
/* some easy paranoia. no such carefulness exists on the wide API IIRC */
lstrcpynA(pfdin->psz3, mysterio, SIZEOF_MYSTERIO);
}
return 0;
}
default:
FIXME("Unknown notification type %d.\n", fdint);
return 0;
}
}
/***********************************************************************
* SetupIterateCabinetA (SETUPAPI.@)
*/
BOOL WINAPI SetupIterateCabinetA(const char *file, DWORD reserved,
PSP_FILE_CALLBACK_A callback, void *context)
{
SC_HSC_A my_hsc;
ERF erf;
CHAR pszCabinet[MAX_PATH], pszCabPath[MAX_PATH], *filepart = NULL;
size_t path_size = 0;
const char *p;
DWORD fpnsize;
HFDI hfdi;
BOOL ret;
TRACE("file %s, reserved %#x, callback %p, context %p.\n",
debugstr_a(file), reserved, callback, context);
if (!file)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if (strlen(file) >= MAX_PATH)
{
SetLastError(ERROR_BAD_PATHNAME);
return FALSE;
}
fpnsize = GetFullPathNameA(file, MAX_PATH, pszCabPath, &filepart);
if (fpnsize > MAX_PATH)
{
SetLastError(ERROR_BAD_PATHNAME);
return FALSE;
}
if (filepart)
{
strcpy(pszCabinet, filepart);
*filepart = '\0';
}
else
{
strcpy(pszCabinet, file);
pszCabPath[0] = '\0';
}
for (p = file; *p; ++p)
{
if (*p == '/' || *p == '\\')
path_size = p - file;
}
memcpy(my_hsc.cab_path, file, path_size);
my_hsc.cab_path[path_size] = 0;
TRACE("path: %s, cabfile: %s\n", debugstr_a(pszCabPath), debugstr_a(pszCabinet));
strcpy(my_hsc.last_cab, file);
my_hsc.msghandler = callback;
my_hsc.context = context;
hfdi = FDICreate(sc_cb_alloc, sc_cb_free, sc_cb_open, sc_cb_read,
sc_cb_write, sc_cb_close, sc_cb_lseek, cpuUNKNOWN, &erf);
if (!hfdi) return FALSE;
ret = FDICopy(hfdi, pszCabinet, pszCabPath, 0, sc_FNNOTIFY_A, NULL, &my_hsc);
FDIDestroy(hfdi);
return ret;
}
struct iterate_wtoa_ctx
{
PSP_FILE_CALLBACK_A orig_cb;
void *orig_ctx;
};
static UINT WINAPI iterate_wtoa_cb(void *pctx, UINT message, UINT_PTR param1, UINT_PTR param2)
{
struct iterate_wtoa_ctx *ctx = pctx;
switch (message)
{
case SPFILENOTIFY_CABINETINFO:
case SPFILENOTIFY_NEEDNEWCABINET:
{
const CABINET_INFO_A *infoA = (const CABINET_INFO_A *)param1;
WCHAR pathW[MAX_PATH], fileW[MAX_PATH], diskW[MAX_PATH];
CABINET_INFO_W infoW =
{
.CabinetPath = pathW,
.CabinetFile = fileW,
.DiskName = diskW,
.SetId = infoA->SetId,
.CabinetNumber = infoA->CabinetNumber,
};
MultiByteToWideChar(CP_ACP, 0, infoA->CabinetPath, -1, pathW, ARRAY_SIZE(pathW));
MultiByteToWideChar(CP_ACP, 0, infoA->CabinetFile, -1, fileW, ARRAY_SIZE(fileW));
MultiByteToWideChar(CP_ACP, 0, infoA->DiskName, -1, diskW, ARRAY_SIZE(diskW));
if (message == SPFILENOTIFY_CABINETINFO)
return ctx->orig_cb(ctx->orig_ctx, message, (UINT_PTR)&infoW, 0);
else
{
char *newpathA = (char *)param2;
WCHAR newpathW[MAX_PATH] = {0};
BOOL ret = ctx->orig_cb(ctx->orig_ctx, message, (UINT_PTR)&infoW, (UINT_PTR)newpathW);
WideCharToMultiByte(CP_ACP, 0, newpathW, -1, newpathA, MAX_PATH, NULL, NULL);
return ret;
}
}
case SPFILENOTIFY_FILEINCABINET:
{
FILE_IN_CABINET_INFO_A *infoA = (FILE_IN_CABINET_INFO_A *)param1;
const char *cabA = (const char *)param2;
WCHAR cabW[MAX_PATH], fileW[MAX_PATH];
FILE_IN_CABINET_INFO_W infoW =
{
.NameInCabinet = fileW,
.FileSize = infoA->FileSize,
.Win32Error = infoA->Win32Error,
.DosDate = infoA->DosDate,
.DosTime = infoA->DosTime,
.DosAttribs = infoA->DosAttribs,
};
BOOL ret;
MultiByteToWideChar(CP_ACP, 0, infoA->NameInCabinet, -1, fileW, ARRAY_SIZE(fileW));
MultiByteToWideChar(CP_ACP, 0, cabA, -1, cabW, ARRAY_SIZE(cabW));
ret = ctx->orig_cb(ctx->orig_ctx, message, (UINT_PTR)&infoW, (UINT_PTR)cabW);
WideCharToMultiByte(CP_ACP, 0, infoW.FullTargetName, -1, infoA->FullTargetName,
ARRAY_SIZE(infoA->FullTargetName), NULL, NULL);
return ret;
}
case SPFILENOTIFY_FILEEXTRACTED:
{
const FILEPATHS_A *pathsA = (const FILEPATHS_A *)param1;
WCHAR targetW[MAX_PATH], sourceW[MAX_PATH];
FILEPATHS_W pathsW =
{
.Target = targetW,
.Source = sourceW,
.Win32Error = pathsA->Win32Error,
.Flags = pathsA->Flags,
};
MultiByteToWideChar(CP_ACP, 0, pathsA->Target, -1, targetW, ARRAY_SIZE(targetW));
MultiByteToWideChar(CP_ACP, 0, pathsA->Source, -1, sourceW, ARRAY_SIZE(sourceW));
return ctx->orig_cb(ctx->orig_ctx, message, (UINT_PTR)&pathsW, 0);
}
default:
FIXME("Unexpected callback %#x.\n", message);
return FALSE;
}
}
/***********************************************************************
* SetupIterateCabinetW (SETUPAPI.@)
*/
BOOL WINAPI SetupIterateCabinetW(const WCHAR *fileW, DWORD reserved,
PSP_FILE_CALLBACK_W handler, void *context)
{
struct iterate_wtoa_ctx ctx = {handler, context};
char fileA[MAX_PATH];
if (!WideCharToMultiByte(CP_ACP, 0, fileW, -1, fileA, ARRAY_SIZE(fileA), NULL, NULL))
return FALSE;
return SetupIterateCabinetA(fileA, reserved, iterate_wtoa_cb, &ctx);
}
/***********************************************************************
* DllMain
*
* PARAMS
* hinstDLL [I] handle to the DLL's instance
* fdwReason [I]
* lpvReserved [I] reserved, must be NULL
*
* RETURNS
* Success: TRUE
* Failure: FALSE
*/
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason) {
case DLL_PROCESS_ATTACH:
DisableThreadLibraryCalls(hinstDLL);
OsVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
if (!GetVersionExW(&OsVersionInfo))
return FALSE;
SETUPAPI_hInstance = hinstDLL;
break;
case DLL_PROCESS_DETACH:
if (lpvReserved) break;
SetupCloseLog();
break;
}
return TRUE;
}
| 6,371 |
10,225 |
<gh_stars>1000+
package io.quarkus.resteasy.reactive.server.test.resource.basic.resource;
import java.net.URI;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
@Path("/")
public class UriInfoRelativizeResource {
@Produces("text/plain")
@GET
@Path("{path : .*}")
public String relativize(@Context UriInfo info, @QueryParam("to") String to) {
return info.relativize(URI.create(to)).toString();
}
}
| 230 |
3,428 |
<reponame>ghalimi/stdlib
{"id":"02419","group":"easy-ham-1","checksum":{"type":"MD5","value":"ade095af23802012668f4ec856bf7e63"},"text":"From <EMAIL> Thu Oct 10 12:32:20 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>int.org\nReceived: from localhost (jalapeno [127.0.0.1])\n\tby jmason.org (Postfix) with ESMTP id 9311E16F16\n\tfor <jm@localhost>; Thu, 10 Oct 2002 12:32:18 +0100 (IST)\nReceived: from jalapeno [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Thu, 10 Oct 2002 12:32:18 +0100 (IST)\nReceived: from dogma.slashnull.org (localhost [127.0.0.1]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g9A848K14131 for\n <<EMAIL>>; Thu, 10 Oct 2002 09:04:08 +0100\nMessage-Id: <<EMAIL>>\nTo: yyyy@<EMAIL>int.org\nFrom: guardian <<EMAIL>>\nSubject: Monkey or man?\nDate: Thu, 10 Oct 2002 08:04:07 -0000\nContent-Type: text/plain; encoding=utf-8\n\nURL: http://www.newsisfree.com/click/-4,8723993,215/\nDate: 2002-10-10T03:26:58+01:00\n\nToumai, hailed as our oldest ancestor, is stirring ancient scientific \nrivalries.�Quizzes[1]�| Crossword[2]�| Interactive guides[3]�| <NAME>[4]�| \nWeblog[5]�*Other news and comment**Blair ready to suspend Stormont*[6]\n\n[1] http://www.newsisfree.com/quiz/0,7476,349695,00.html\n[2] http://www.newsisfree.com/crossword/0,4406,180778,00.html\n[3] http://www.newsisfree.com/interactive/0,2759,192055,00.html\n[4] http://www.newsisfree.com/cartoons/0,7371,337484,00.html\n[5] http://www.newsisfree.com/weblog/0,6798,517233,00.html\n[6] http://www.newsisfree.com/Northern_Ireland/Story/0,2763,808962,00.html\n\n\n"}
| 704 |
1,682 |
<reponame>haroldl/rest.li<gh_stars>1000+
/*
Copyright (c) 2019 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.restli.examples.instrumentation;
import com.linkedin.r2.RemoteInvocationException;
import com.linkedin.r2.filter.FilterChain;
import com.linkedin.r2.filter.FilterChains;
import com.linkedin.r2.filter.NextFilter;
import com.linkedin.r2.filter.message.rest.RestFilter;
import com.linkedin.r2.filter.message.stream.StreamFilter;
import com.linkedin.r2.message.Request;
import com.linkedin.r2.message.RequestContext;
import com.linkedin.r2.message.Response;
import com.linkedin.r2.message.rest.RestRequest;
import com.linkedin.r2.message.rest.RestResponse;
import com.linkedin.r2.message.stream.StreamRequest;
import com.linkedin.r2.message.stream.StreamResponse;
import com.linkedin.r2.message.timing.FrameworkTimingKeys;
import com.linkedin.r2.message.timing.TimingContextUtil;
import com.linkedin.r2.message.timing.TimingImportance;
import com.linkedin.r2.message.timing.TimingKey;
import com.linkedin.r2.util.RequestContextUtil;
import com.linkedin.r2.util.finalizer.RequestFinalizer;
import com.linkedin.r2.util.finalizer.RequestFinalizerManager;
import com.linkedin.restli.client.CreateIdEntityRequest;
import com.linkedin.restli.client.ResponseFuture;
import com.linkedin.restli.client.RestLiResponseException;
import com.linkedin.restli.common.IdEntityResponse;
import com.linkedin.restli.examples.RestLiIntegrationTest;
import com.linkedin.restli.examples.instrumentation.api.InstrumentationControl;
import com.linkedin.restli.examples.instrumentation.client.LatencyInstrumentationBuilders;
import com.linkedin.restli.examples.instrumentation.server.LatencyInstrumentationResource;
import com.linkedin.restli.server.RestLiServiceException;
import com.linkedin.test.util.retry.SingleRetry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Tests to ensure that framework latency information collected using {@link FrameworkTimingKeys} and
* {@link TimingContextUtil} is consistent and as-expected.
*
* These integration tests send requests to {@link LatencyInstrumentationResource}.
*
* TODO: Once instrumentation is supported for scatter-gather, fix the test logic and the assertions here.
* TODO: CLIENT_RESPONSE_RESTLI_ERROR_DESERIALIZATION isn't tested at all due to downstream batching, ideally fix this.
* TODO: Don't re-init on every method invocation, this may require an overall optimization to how our int-tests work.
*
* @author <NAME>
*/
public class TestLatencyInstrumentation extends RestLiIntegrationTest
{
// These timing keys will not be present in the error code path
private static final Set<TimingKey> TIMING_KEYS_MISSING_ON_ERROR =
new HashSet<>(Arrays.asList(FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_PROJECTION_APPLY.key(),
FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_SERIALIZATION.key(),
// The downstream request is a batch request, so its errors are serialized normally
FrameworkTimingKeys.CLIENT_RESPONSE_RESTLI_ERROR_DESERIALIZATION.key()));
// These timing keys will not be present in the success code path
private static final Set<TimingKey> TIMING_KEYS_MISSING_ON_SUCCESS =
new HashSet<>(Arrays.asList(FrameworkTimingKeys.SERVER_RESPONSE_RESTLI_ERROR_SERIALIZATION.key(),
FrameworkTimingKeys.CLIENT_RESPONSE_RESTLI_ERROR_DESERIALIZATION.key()));
// These timing keys are always present because the timing importance threshold is loaded in the custom R2 filter
private static final Set<TimingKey> TIMING_KEYS_ALWAYS_PRESENT =
new HashSet<>(Arrays.asList(FrameworkTimingKeys.SERVER_REQUEST.key(),
FrameworkTimingKeys.SERVER_REQUEST_R2.key(),
FrameworkTimingKeys.SERVER_REQUEST_R2_FILTER_CHAIN.key()));
// These timing keys will not be present when using protocol 2.0.0
private static final Set<TimingKey> TIMING_KEYS_MISSING_ON_PROTOCOL_2_0_0 =
Collections.singleton(FrameworkTimingKeys.SERVER_REQUEST_RESTLI_URI_PARSE_1.key());
private static final double NANOS_TO_MILLIS = .000001;
private Map<TimingKey, TimingContextUtil.TimingContext> _resultMap;
private CountDownLatch _countDownLatch;
private boolean _useStreaming;
private TimingImportance _timingImportanceThreshold;
@Override
public boolean forceUseStreamServer()
{
return _useStreaming;
}
@BeforeMethod
public void beforeMethod(Object[] args) throws Exception
{
_countDownLatch = new CountDownLatch(1);
_useStreaming = (boolean) args[0];
_timingImportanceThreshold = (TimingImportance) args[3];
final InstrumentationTrackingFilter instrumentationTrackingFilter = new InstrumentationTrackingFilter();
final FilterChain filterChain = FilterChains.empty()
.addFirst(instrumentationTrackingFilter)
.addFirstRest(instrumentationTrackingFilter);
// System.setProperty("test.useStreamCodecServer", "true"); // Uncomment this to test with server streaming codec in IDEA
super.init(Collections.emptyList(), filterChain, false);
}
@AfterMethod
public void afterMethod() throws Exception
{
super.shutdown();
}
@DataProvider(name = "latencyInstrumentation")
private Object[][] provideLatencyInstrumentationData()
{
List<Object[]> data = new ArrayList<>();
boolean[] booleanOptions = new boolean[] { true, false };
Collection<TimingImportance> timingImportanceOptions = new ArrayList<>(Arrays.asList(TimingImportance.values()));
timingImportanceOptions.add(null);
for (boolean useStreaming : booleanOptions)
{
for (boolean forceException : booleanOptions)
{
for (boolean useScatterGather : booleanOptions)
{
for (TimingImportance timingImportanceThreshold : timingImportanceOptions)
{
data.add(new Object[] { useStreaming, forceException, useScatterGather, timingImportanceThreshold });
}
}
}
}
return data.toArray(new Object[data.size()][4]);
}
/**
* Ensures that timing data is recorded for all the various timing markers in the framework, and compares them
* to one another to ensure that the timing is logical (e.g. Rest.li filter chain should take less time than the
* Rest.li layer as a whole). Checks this for combinations of rest vs. streaming, success vs. error, and various
* {@link TimingImportance} thresholds.
*
* Note that the "useStreaming" parameter does NOT affect whether the integration test client (this) uses streaming or
* whether the server uses the streaming codec; this is determined by whether the project properties
* "test.useStreamCodecClient" and "test.useStreamCodecServer", respectively, are set to true or false (this is done
* via Gradle, so it cannot be tested in IDEA without manually setting the properties). The integration test client
* using streaming should be inconsequential for this test, but the server using the streaming codec will actually
* affect the outcome.
*
* @param useStreaming whether the server should use an underlying streaming server ("restOverStream") and whether the
* downstream request should use streaming (see the disclaimer above)
* @param forceException whether the upstream and downstream resources should trigger the error response path
* @param timingImportanceThreshold impacts which keys are included in the request context
*/
@Test(dataProvider = "latencyInstrumentation", retryAnalyzer = SingleRetry.class)
public void testLatencyInstrumentation(boolean useStreaming, boolean forceException, boolean useScatterGather,
TimingImportance timingImportanceThreshold) throws RemoteInvocationException, InterruptedException
{
makeUpstreamRequest(useStreaming, forceException, useScatterGather);
checkTimingKeyCompleteness(forceException, timingImportanceThreshold, useScatterGather);
checkTimingKeyConsistency();
checkTimingKeySubsetSums(timingImportanceThreshold, useScatterGather);
}
/**
* Make the "upstream" request (as opposed to the "downstream" request made from the resource method) using a set of
* test parameters. Waits for the timing keys to be recorded by the {@link InstrumentationTrackingFilter} before
* returning.
* @param useStreaming parameter from the test method
* @param forceException parameter from the test method
*/
private void makeUpstreamRequest(boolean useStreaming, boolean forceException, boolean useScatterGather)
throws RemoteInvocationException, InterruptedException
{
InstrumentationControl instrumentationControl = new InstrumentationControl()
.setServiceUriPrefix(FILTERS_URI_PREFIX)
.setUseStreaming(useStreaming)
.setForceException(forceException)
.setUseScatterGather(useScatterGather);
CreateIdEntityRequest<Long, InstrumentationControl> createRequest = new LatencyInstrumentationBuilders()
.createAndGet()
.input(instrumentationControl)
.build();
ResponseFuture<IdEntityResponse<Long, InstrumentationControl>> response = getClient().sendRequest(createRequest);
try
{
response.getResponseEntity();
if (forceException)
{
Assert.fail("Forcing exception, should've failed.");
}
}
catch (RestLiResponseException e)
{
if (e.getStatus() != 400)
{
Assert.fail("Server responded with a non-400 error: " + e.getServiceErrorStackTrace());
}
if (!forceException)
{
Assert.fail("Not forcing exception, didn't expect failure.");
}
}
// Wait for the server to send the response and save the timings
final boolean success = _countDownLatch.await(10, TimeUnit.SECONDS);
if (!success)
{
Assert.fail("Request timed out!");
}
}
/**
* Ensures that the recorded timing keys are "complete", meaning that all keys which are expected to be present
* are present. Also ensures that no unexpected keys are present.
* @param forceException parameter from the test method
* @param timingImportanceThreshold parameter from the test method
*/
private void checkTimingKeyCompleteness(boolean forceException, TimingImportance timingImportanceThreshold,
boolean useScatterGather)
{
// Form the set of expected timing keys using the current test parameters
Set<TimingKey> expectedKeys = Arrays.stream(FrameworkTimingKeys.values())
.map(FrameworkTimingKeys::key)
// For now, expect client keys to be missing if using scatter gather
.filter(timingKey -> !(useScatterGather && timingKey.getName().startsWith(FrameworkTimingKeys.KEY_PREFIX + "client")))
// Expect some keys to be missing depending on if an exception is being forced
.filter(timingKey -> {
if (forceException)
{
return !TIMING_KEYS_MISSING_ON_ERROR.contains(timingKey);
}
else
{
return !TIMING_KEYS_MISSING_ON_SUCCESS.contains(timingKey);
}
})
// Expect some keys to be missing since using protocol 2.0.0
.filter(timingKey -> !TIMING_KEYS_MISSING_ON_PROTOCOL_2_0_0.contains(timingKey))
// Only expect keys that are included by the current timing importance threshold
.filter(timingKey -> timingImportanceThreshold == null ||
TIMING_KEYS_ALWAYS_PRESENT.contains(timingKey) ||
timingKey.getTimingImportance().isAtLeast(timingImportanceThreshold))
.collect(Collectors.toSet());
// Check that all keys have complete timings (not -1) and that there are no unexpected keys
for (TimingKey timingKey : _resultMap.keySet())
{
if (expectedKeys.contains(timingKey))
{
expectedKeys.remove(timingKey);
Assert.assertNotEquals(_resultMap.get(timingKey).getDurationNano(), -1, timingKey.getName() + " is -1");
}
else if (timingKey.getName().contains(FrameworkTimingKeys.KEY_PREFIX))
{
Assert.fail("Encountered unexpected key: " + timingKey);
}
}
// Check that the set of recorded timing keys is "complete"
Assert.assertTrue(expectedKeys.isEmpty(), "Missing keys: " + expectedKeys.stream()
.map(key -> String.format("\"%s\"", key.getName()))
.collect(Collectors.joining(", ")));
}
/**
* Ensures that the set of recorded timing keys is "consistent", meaning that for any code path (denoted by key "A")
* which is a subset of another code path (denoted by key "B"), the duration of key A must be less than that of key B.
*/
private void checkTimingKeyConsistency()
{
ArrayList<Map.Entry<TimingKey, TimingContextUtil.TimingContext>> entrySet = new ArrayList<>(_resultMap.entrySet());
int size = entrySet.size();
// Check that framework key subsets are consistent
// (e.g. duration of "fwk/server/response" > duration of "fwk/server/response/restli")
for (int i = 0; i < size; i++)
{
TimingKey keyA = entrySet.get(i).getKey();
if (!keyA.getName().contains(FrameworkTimingKeys.KEY_PREFIX))
{
continue;
}
for (int j = 0; j < size; j++)
{
TimingKey keyB = entrySet.get(j).getKey();
if (i == j || !keyB.getName().contains(FrameworkTimingKeys.KEY_PREFIX))
{
continue;
}
if (keyA.getName().contains(keyB.getName()))
{
TimingContextUtil.TimingContext contextA = entrySet.get(i).getValue();
TimingContextUtil.TimingContext contextB = entrySet.get(j).getValue();
String message = String.format("Expected %s (%.2fms) < %s (%.2fms)",
keyA, contextA.getDurationNano() * NANOS_TO_MILLIS,
keyB, contextB.getDurationNano() * NANOS_TO_MILLIS);
Assert.assertTrue(contextA.getDurationNano() < contextB.getDurationNano(), message);
}
}
}
}
/**
* Ensures (in specific cases) the sum of two code paths should be less than or equal to a superset code path of both.
* @param timingImportanceThreshold parameter from the test method
*/
private void checkTimingKeySubsetSums(TimingImportance timingImportanceThreshold, boolean useScatterGather)
{
if (timingImportanceThreshold == null || TimingImportance.MEDIUM.isAtLeast(timingImportanceThreshold))
{
assertSubsetSum(FrameworkTimingKeys.SERVER_REQUEST_R2.key(),
FrameworkTimingKeys.SERVER_REQUEST_RESTLI.key(),
FrameworkTimingKeys.SERVER_REQUEST.key());
assertSubsetSum(FrameworkTimingKeys.SERVER_RESPONSE_R2.key(),
FrameworkTimingKeys.SERVER_RESPONSE_RESTLI.key(),
FrameworkTimingKeys.SERVER_RESPONSE.key());
// For now, client timings are disabled for scatter-gather requests
if (!useScatterGather)
{
assertSubsetSum(FrameworkTimingKeys.CLIENT_REQUEST_R2.key(),
FrameworkTimingKeys.CLIENT_REQUEST_RESTLI.key(),
FrameworkTimingKeys.CLIENT_REQUEST.key());
assertSubsetSum(FrameworkTimingKeys.CLIENT_RESPONSE_R2.key(),
FrameworkTimingKeys.CLIENT_RESPONSE_RESTLI.key(),
FrameworkTimingKeys.CLIENT_RESPONSE.key());
}
}
}
/**
* Asserts that the sum of the durations of two timing keys is less than or equal to that of the third.
* @param keyA the first summand key
* @param keyB the second summand key
* @param keyC the summation key
*/
private void assertSubsetSum(TimingKey keyA, TimingKey keyB, TimingKey keyC)
{
long durationA = _resultMap.get(keyA).getDurationNano();
long durationB = _resultMap.get(keyB).getDurationNano();
long durationC = _resultMap.get(keyC).getDurationNano();
String message = String.format("Expected %s (%.2fms) + %s (%.2fms) <= %s (%.2fms)",
keyA, durationA * NANOS_TO_MILLIS,
keyB, durationB * NANOS_TO_MILLIS,
keyC, durationC * NANOS_TO_MILLIS);
Assert.assertTrue(durationA + durationB <= durationC, message);
}
/**
* R2 filter that adds the "timing importance" threshold to the request context, and also registers the request
* finalizer that allows the integration test to gather timing data from the downstream service call.
*/
private class InstrumentationTrackingFilter implements RestFilter, StreamFilter
{
@Override
public void onRestRequest(RestRequest req,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<RestRequest, RestResponse> nextFilter)
{
requestContext.putLocalAttr(TimingContextUtil.TIMING_IMPORTANCE_THRESHOLD_KEY_NAME, _timingImportanceThreshold);
nextFilter.onRequest(req, requestContext, wireAttrs);
}
@Override
public void onStreamRequest(StreamRequest req,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<StreamRequest, StreamResponse> nextFilter)
{
requestContext.putLocalAttr(TimingContextUtil.TIMING_IMPORTANCE_THRESHOLD_KEY_NAME, _timingImportanceThreshold);
nextFilter.onRequest(req, requestContext, wireAttrs);
}
@Override
public void onRestResponse(RestResponse res,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<RestRequest, RestResponse> nextFilter)
{
registerRequestFinalizer(res, requestContext);
nextFilter.onResponse(res, requestContext, wireAttrs);
}
@Override
public void onStreamResponse(StreamResponse res,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<StreamRequest, StreamResponse> nextFilter)
{
registerRequestFinalizer(res, requestContext);
nextFilter.onResponse(res, requestContext, wireAttrs);
}
@Override
public void onRestError(Throwable ex,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<RestRequest, RestResponse> nextFilter)
{
registerRequestFinalizer(ex, requestContext);
nextFilter.onError(ex, requestContext, wireAttrs);
}
@Override
public void onStreamError(Throwable ex,
RequestContext requestContext,
Map<String, String> wireAttrs,
NextFilter<StreamRequest, StreamResponse> nextFilter)
{
registerRequestFinalizer(ex, requestContext);
nextFilter.onError(ex, requestContext, wireAttrs);
}
/**
* Register the request finalizer, but only if it has the correct header.
* This is to avoid tracking data for the protocol version fetch request.
*/
private void registerRequestFinalizer(Response res, RequestContext requestContext)
{
if (Boolean.valueOf(res.getHeader(LatencyInstrumentationResource.HAS_CLIENT_TIMINGS_HEADER)))
{
registerRequestFinalizer(requestContext);
}
}
/**
* Register the request finalizer, but only if it has the correct service error code.
* This is to avoid tracking data prematurely on the downstream call.
*/
private void registerRequestFinalizer(Throwable ex, RequestContext requestContext)
{
final RestLiServiceException cause = (RestLiServiceException) ex.getCause();
if (cause.hasCode() && cause.getCode().equals(LatencyInstrumentationResource.UPSTREAM_ERROR_CODE))
{
registerRequestFinalizer(requestContext);
}
}
/**
* Register the request finalizer which will collect the timing data from the request context.
*/
private void registerRequestFinalizer(RequestContext requestContext)
{
RequestFinalizerManager manager = RequestContextUtil.getServerRequestFinalizerManager(requestContext);
manager.registerRequestFinalizer(new InstrumentationTrackingRequestFinalizer());
}
}
/**
* Request finalizer that's performed at the very end of the "server response" code path, right before the response
* is sent over the wire. This finalizer collects the response's timing data so that the unit test logic can perform
* analysis on it. It also releases a latch so that the unit test analyzes the timing data only once the whole request
* is complete.
*/
private class InstrumentationTrackingRequestFinalizer implements RequestFinalizer
{
@Override
public void finalizeRequest(Request request, Response response, RequestContext requestContext, Throwable error)
{
final Map<TimingKey, TimingContextUtil.TimingContext> timingsMap = TimingContextUtil.getTimingsMap(requestContext);
_resultMap = new HashMap<>(timingsMap);
_countDownLatch.countDown();
}
}
}
| 7,401 |
348 |
{"nom":"Vinzieux","circ":"2ème circonscription","dpt":"Ardèche","inscrits":308,"abs":152,"votants":156,"blancs":9,"nuls":1,"exp":146,"res":[{"nuance":"SOC","nom":"<NAME>","voix":86},{"nuance":"REM","nom":"<NAME>","voix":60}]}
| 92 |
416 |
<gh_stars>100-1000
/*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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.
*/
package com.tencentcloudapi.tbaas.v20180416.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class BcosBlockObj extends AbstractModel{
/**
* 区块哈希
*/
@SerializedName("BlockHash")
@Expose
private String BlockHash;
/**
* 区块高度
*/
@SerializedName("BlockNumber")
@Expose
private Long BlockNumber;
/**
* 区块时间戳
*/
@SerializedName("BlockTimestamp")
@Expose
private String BlockTimestamp;
/**
* 打包节点ID
*/
@SerializedName("Sealer")
@Expose
private String Sealer;
/**
* 打包节点索引
*/
@SerializedName("SealerIndex")
@Expose
private Long SealerIndex;
/**
* 记录保存时间
*/
@SerializedName("CreateTime")
@Expose
private String CreateTime;
/**
* 交易数量
*/
@SerializedName("TransCount")
@Expose
private Long TransCount;
/**
* 记录修改时间
*/
@SerializedName("ModifyTime")
@Expose
private String ModifyTime;
/**
* Get 区块哈希
* @return BlockHash 区块哈希
*/
public String getBlockHash() {
return this.BlockHash;
}
/**
* Set 区块哈希
* @param BlockHash 区块哈希
*/
public void setBlockHash(String BlockHash) {
this.BlockHash = BlockHash;
}
/**
* Get 区块高度
* @return BlockNumber 区块高度
*/
public Long getBlockNumber() {
return this.BlockNumber;
}
/**
* Set 区块高度
* @param BlockNumber 区块高度
*/
public void setBlockNumber(Long BlockNumber) {
this.BlockNumber = BlockNumber;
}
/**
* Get 区块时间戳
* @return BlockTimestamp 区块时间戳
*/
public String getBlockTimestamp() {
return this.BlockTimestamp;
}
/**
* Set 区块时间戳
* @param BlockTimestamp 区块时间戳
*/
public void setBlockTimestamp(String BlockTimestamp) {
this.BlockTimestamp = BlockTimestamp;
}
/**
* Get 打包节点ID
* @return Sealer 打包节点ID
*/
public String getSealer() {
return this.Sealer;
}
/**
* Set 打包节点ID
* @param Sealer 打包节点ID
*/
public void setSealer(String Sealer) {
this.Sealer = Sealer;
}
/**
* Get 打包节点索引
* @return SealerIndex 打包节点索引
*/
public Long getSealerIndex() {
return this.SealerIndex;
}
/**
* Set 打包节点索引
* @param SealerIndex 打包节点索引
*/
public void setSealerIndex(Long SealerIndex) {
this.SealerIndex = SealerIndex;
}
/**
* Get 记录保存时间
* @return CreateTime 记录保存时间
*/
public String getCreateTime() {
return this.CreateTime;
}
/**
* Set 记录保存时间
* @param CreateTime 记录保存时间
*/
public void setCreateTime(String CreateTime) {
this.CreateTime = CreateTime;
}
/**
* Get 交易数量
* @return TransCount 交易数量
*/
public Long getTransCount() {
return this.TransCount;
}
/**
* Set 交易数量
* @param TransCount 交易数量
*/
public void setTransCount(Long TransCount) {
this.TransCount = TransCount;
}
/**
* Get 记录修改时间
* @return ModifyTime 记录修改时间
*/
public String getModifyTime() {
return this.ModifyTime;
}
/**
* Set 记录修改时间
* @param ModifyTime 记录修改时间
*/
public void setModifyTime(String ModifyTime) {
this.ModifyTime = ModifyTime;
}
public BcosBlockObj() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public BcosBlockObj(BcosBlockObj source) {
if (source.BlockHash != null) {
this.BlockHash = new String(source.BlockHash);
}
if (source.BlockNumber != null) {
this.BlockNumber = new Long(source.BlockNumber);
}
if (source.BlockTimestamp != null) {
this.BlockTimestamp = new String(source.BlockTimestamp);
}
if (source.Sealer != null) {
this.Sealer = new String(source.Sealer);
}
if (source.SealerIndex != null) {
this.SealerIndex = new Long(source.SealerIndex);
}
if (source.CreateTime != null) {
this.CreateTime = new String(source.CreateTime);
}
if (source.TransCount != null) {
this.TransCount = new Long(source.TransCount);
}
if (source.ModifyTime != null) {
this.ModifyTime = new String(source.ModifyTime);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "BlockHash", this.BlockHash);
this.setParamSimple(map, prefix + "BlockNumber", this.BlockNumber);
this.setParamSimple(map, prefix + "BlockTimestamp", this.BlockTimestamp);
this.setParamSimple(map, prefix + "Sealer", this.Sealer);
this.setParamSimple(map, prefix + "SealerIndex", this.SealerIndex);
this.setParamSimple(map, prefix + "CreateTime", this.CreateTime);
this.setParamSimple(map, prefix + "TransCount", this.TransCount);
this.setParamSimple(map, prefix + "ModifyTime", this.ModifyTime);
}
}
| 2,946 |
311 |
package org.javacs.lsp;
public class DidCloseTextDocumentParams {
public TextDocumentIdentifier textDocument = new TextDocumentIdentifier();
}
| 42 |
19,824 |
{
"main": "dist/keystone-next-keystone-testing.cjs.js",
"module": "dist/keystone-next-keystone-testing.esm.js"
}
| 49 |
2,151 |
package junit.tests.framework;
/**
* Test class used in SuiteTest
*/
public class InheritedTestCase extends OneTestCase {
public void test2() {
}
}
| 50 |
411 |
<filename>documents4j-util-ws/src/main/java/com/documents4j/ws/ConverterNetworkProtocol.java
package com.documents4j.ws;
import com.documents4j.throwables.ConversionFormatException;
import com.documents4j.throwables.ConversionInputException;
import com.documents4j.util.Reaction;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import javax.ws.rs.core.Response;
/**
* This class is a non-instantiable carrier for values that are used in network communication between a
* conversion server and a remote converter.
*/
public final class ConverterNetworkProtocol {
/**
* The current protocol version.
*/
public static final int CURRENT_PROTOCOL_VERSION = 1;
/**
* The root resource path.
*/
public static final String RESOURCE_PATH = "/";
/**
* A header for indicating a job's priority. (optional)
*/
public static final String HEADER_JOB_PRIORITY = "Converter-Job-Priority";
/**
* GZip compression type names.
*/
public static final String COMPRESSION_TYPE_GZIP = "gzip", COMPRESSION_TYPE_XGZIP = "x-gzip";
private static final int RESPONSE_STATUS_CODE_CANCEL = 530;
private static final int RESPONSE_STATUS_CODE_TIMEOUT = 522;
private static final int RESPONSE_STATUS_CODE_INPUT_ERROR = 422;
private ConverterNetworkProtocol() {
throw new UnsupportedOperationException();
}
/**
* A collection of known status codes used for communication.
*/
public static enum Status {
OK(Response.Status.OK.getStatusCode(),
Reaction.with(true)),
CANCEL(RESPONSE_STATUS_CODE_CANCEL,
Reaction.with(new Reaction.ConverterAccessExceptionBuilder("The conversion attempt was cancelled"))),
TIMEOUT(RESPONSE_STATUS_CODE_TIMEOUT,
Reaction.with(new Reaction.ConverterAccessExceptionBuilder("The conversion attempt timed out"))),
CONVERTER_ERROR(Response.Status.SERVICE_UNAVAILABLE.getStatusCode(),
Reaction.with(new Reaction.ConverterAccessExceptionBuilder("The converter could not process the request"))),
INPUT_ERROR(RESPONSE_STATUS_CODE_INPUT_ERROR,
Reaction.with(new Reaction.ConversionInputExceptionBuilder("The sent input is invalid"))),
FORMAT_ERROR(Response.Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode(),
Reaction.with(new Reaction.ConversionFormatExceptionBuilder("The given input/output format combination is not supported"))),
UNKNOWN(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
Reaction.with(false));
private final Integer statusCode;
private final Reaction reaction;
private Status(Integer statusCode, Reaction reaction) {
this.statusCode = statusCode;
this.reaction = reaction;
}
public static Status from(int statusCode) {
for (Status status : Status.values()) {
if (Objects.equal(statusCode, status.getStatusCode())) {
return status;
}
}
return UNKNOWN;
}
public static Status describe(Exception e) {
if (e instanceof ConversionInputException) {
return INPUT_ERROR;
} else if (e instanceof ConversionFormatException) {
return FORMAT_ERROR;
} else {
return CONVERTER_ERROR;
}
}
public int getStatusCode() {
return statusCode;
}
public boolean resolve() {
return reaction.apply();
}
@Override
public String toString() {
return MoreObjects.toStringHelper(Status.class)
.add("statusCode", statusCode)
.add("reaction", reaction)
.toString();
}
}
}
| 1,586 |
575 |
<reponame>Ron423c/chromium<filename>third_party/blink/renderer/modules/media_controls/elements/media_control_cast_button_element.cc<gh_stars>100-1000
// 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 "third_party/blink/renderer/modules/media_controls/elements/media_control_cast_button_element.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/strings/grit/blink_strings.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/geometry/dom_rect.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/input_type_names.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h"
#include "third_party/blink/renderer/modules/remoteplayback/remote_playback.h"
#include "third_party/blink/renderer/modules/remoteplayback/remote_playback_metrics.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
namespace blink {
namespace {
Element* ElementFromCenter(Element& element) {
DOMRect* client_rect = element.getBoundingClientRect();
int center_x =
static_cast<int>((client_rect->left() + client_rect->right()) / 2);
int center_y =
static_cast<int>((client_rect->top() + client_rect->bottom()) / 2);
return element.GetDocument().ElementFromPoint(center_x, center_y);
}
} // anonymous namespace
MediaControlCastButtonElement::MediaControlCastButtonElement(
MediaControlsImpl& media_controls,
bool is_overlay_button)
: MediaControlInputElement(media_controls),
is_overlay_button_(is_overlay_button) {
SetShadowPseudoId(is_overlay_button
? "-internal-media-controls-overlay-cast-button"
: "-internal-media-controls-cast-button");
setType(input_type_names::kButton);
UpdateDisplayType();
}
void MediaControlCastButtonElement::TryShowOverlay() {
DCHECK(is_overlay_button_);
SetIsWanted(true);
if (ElementFromCenter(*this) != &MediaElement()) {
SetIsWanted(false);
return;
}
}
void MediaControlCastButtonElement::UpdateDisplayType() {
if (IsPlayingRemotely()) {
setAttribute(html_names::kAriaLabelAttr,
WTF::AtomicString(
GetLocale().QueryString(IDS_AX_MEDIA_CAST_ON_BUTTON)));
} else {
setAttribute(html_names::kAriaLabelAttr,
WTF::AtomicString(
GetLocale().QueryString(IDS_AX_MEDIA_CAST_OFF_BUTTON)));
}
UpdateOverflowString();
SetClass("on", IsPlayingRemotely());
MediaControlInputElement::UpdateDisplayType();
}
bool MediaControlCastButtonElement::WillRespondToMouseClickEvents() {
return true;
}
int MediaControlCastButtonElement::GetOverflowStringId() const {
return IDS_MEDIA_OVERFLOW_MENU_CAST;
}
bool MediaControlCastButtonElement::HasOverflowButton() const {
return true;
}
const char* MediaControlCastButtonElement::GetNameForHistograms() const {
return is_overlay_button_
? "CastOverlayButton"
: IsOverflowElement() ? "CastOverflowButton" : "CastButton";
}
void MediaControlCastButtonElement::DefaultEventHandler(Event& event) {
if (event.type() == event_type_names::kClick) {
if (is_overlay_button_) {
Platform::Current()->RecordAction(
UserMetricsAction("Media.Controls.CastOverlay"));
} else {
Platform::Current()->RecordAction(
UserMetricsAction("Media.Controls.Cast"));
}
RemotePlayback::From(MediaElement()).PromptInternal();
RemotePlaybackMetrics::RecordRemotePlaybackLocation(
RemotePlaybackInitiationLocation::HTML_MEDIA_ELEMENT);
}
MediaControlInputElement::DefaultEventHandler(event);
}
bool MediaControlCastButtonElement::KeepEventInNode(const Event& event) const {
return MediaControlElementsHelper::IsUserInteractionEvent(event);
}
bool MediaControlCastButtonElement::IsPlayingRemotely() const {
return RemotePlayback::From(MediaElement()).GetState() !=
mojom::blink::PresentationConnectionState::CLOSED;
}
} // namespace blink
| 1,578 |
367 |
@import UIKit;
@import Metal;
@interface MBETextureLoader : NSObject
+ (id<MTLTexture>)texture2DWithImageNamed:(NSString *)imageName device:(id<MTLDevice>)device;
+ (id<MTLTexture>)textureCubeWithImagesNamed:(NSArray *)imageNameArray
device:(id<MTLDevice>)device
commandQueue:(id<MTLCommandQueue>)commandQueue;
@end
| 177 |
2,542 |
<gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Common
{
class AsyncOperationState
{
public:
AsyncOperationState();
~AsyncOperationState();
__declspec(property(get=get_CompletedSynchronously)) bool CompletedSynchronously;
__declspec(property(get=get_IsCompleted)) bool IsCompleted;
__declspec(property(get=get_InternalIsCompleted)) bool InternalIsCompleted;
__declspec(property(get=get_InternalIsCompletingOrCompleted)) bool InternalIsCompletingOrCompleted;
__declspec(property(get=get_InternalIsCancelRequested)) bool InternalIsCancelRequested;
bool get_IsCompleted() const throw()
{
return (this->ObserveState() & CompletedMask) != 0;
}
bool get_CompletedSynchronously() const throw()
{
return (this->ObserveState() & ObservedBeforeComplete) == 0;
}
bool get_InternalIsCompleted() const throw()
{
return (this->operationState_.load() & CompletedMask) != 0;
}
bool get_InternalIsCancelRequested() const throw()
{
return (this->operationState_.load() & CancelRequested) != 0;
}
bool get_InternalIsCompletingOrCompleted() const throw()
{
return (this->operationState_.load() & CompletingOrCompletedMask) != 0;
}
void TransitionStarted();
bool TryTransitionCompleting();
void TransitionCompleted();
bool TryTransitionEnded();
void TransitionEnded();
bool TryMarkCancelRequested();
private:
LONG ObserveState() const;
mutable Common::atomic_long operationState_;
static const LONG Created = 0x01;
static const LONG Started = 0x02;
static const LONG Completing = 0x04;
static const LONG Completed = 0x08;
static const LONG Ended = 0x10;
static const LONG ObservedBeforeComplete = 0x20;
static const LONG CancelRequested = 0x40;
static const LONG LifecycleMask = Created | Started | Completing | Completed | Ended;
static const LONG CompletedMask = Completed | Ended;
static const LONG CompletingOrCompletedMask = Completing | Completed | Ended;
};
}
| 1,004 |
6,989 |
#ifdef USE_PYTHON3
#include <contrib/python/numpy/py3/numpy/core/src/umath/ufunc_type_resolution.h>
#else
#include <contrib/python/numpy/py2/numpy/core/src/umath/ufunc_type_resolution.h>
#endif
| 85 |
1,338 |
/*
* Copyright 2009, <NAME>, <EMAIL>.
* Distributed under the terms of the MIT License.
*/
#ifndef SUB_WINDOW_H
#define SUB_WINDOW_H
#include <Window.h>
#include <util/OpenHashTable.h>
class SubWindowManager;
class SubWindowKey {
public:
virtual ~SubWindowKey();
virtual bool Equals(const SubWindowKey* other) const = 0;
virtual size_t HashCode() const = 0;
};
class ObjectSubWindowKey : public SubWindowKey {
public:
ObjectSubWindowKey(void* object);
virtual bool Equals(const SubWindowKey* other) const;
virtual size_t HashCode() const;
private:
void* fObject;
};
class SubWindow : public BWindow {
public:
SubWindow(SubWindowManager* manager,
BRect frame, const char* title,
window_type type, uint32 flags,
uint32 workspace = B_CURRENT_WORKSPACE);
virtual ~SubWindow();
inline SubWindowKey* GetSubWindowKey() const;
bool AddToSubWindowManager(SubWindowKey* key);
bool RemoveFromSubWindowManager();
protected:
SubWindowManager* fSubWindowManager;
SubWindowKey* fSubWindowKey;
public:
SubWindow* fNext;
};
SubWindowKey*
SubWindow::GetSubWindowKey() const
{
return fSubWindowKey;
}
#endif // SUB_WINDOW_H
| 484 |
5,964 |
<gh_stars>1000+
/*
* Copyright (C) 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
* Copyright (C) 2012 Google 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 Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h"
#include "core/html/shadow/MediaControlElements.h"
#include "bindings/core/v8/ExceptionStatePlaceholder.h"
#include "core/InputTypeNames.h"
#include "core/dom/DOMTokenList.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/events/MouseEvent.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLVideoElement.h"
#include "core/html/MediaController.h"
#include "core/html/TimeRanges.h"
#include "core/html/shadow/MediaControls.h"
#include "core/input/EventHandler.h"
#include "core/layout/LayoutSlider.h"
#include "core/layout/LayoutTheme.h"
#include "core/layout/LayoutVideo.h"
#include "platform/RuntimeEnabledFeatures.h"
namespace blink {
using namespace HTMLNames;
// This is the duration from mediaControls.css
static const double fadeOutDuration = 0.3;
static bool isUserInteractionEvent(Event* event)
{
const AtomicString& type = event->type();
return type == EventTypeNames::mousedown
|| type == EventTypeNames::mouseup
|| type == EventTypeNames::click
|| type == EventTypeNames::dblclick
|| event->isKeyboardEvent()
|| event->isTouchEvent();
}
// Sliders (the volume control and timeline) need to capture some additional events used when dragging the thumb.
static bool isUserInteractionEventForSlider(Event* event)
{
const AtomicString& type = event->type();
return type == EventTypeNames::mousedown
|| type == EventTypeNames::mouseup
|| type == EventTypeNames::click
|| type == EventTypeNames::dblclick
|| type == EventTypeNames::mouseover
|| type == EventTypeNames::mouseout
|| type == EventTypeNames::mousemove
|| event->isKeyboardEvent()
|| event->isTouchEvent();
}
MediaControlPanelElement::MediaControlPanelElement(MediaControls& mediaControls)
: MediaControlDivElement(mediaControls, MediaControlsPanel)
, m_isDisplayed(false)
, m_opaque(true)
, m_transitionTimer(this, &MediaControlPanelElement::transitionTimerFired)
{
}
PassRefPtrWillBeRawPtr<MediaControlPanelElement> MediaControlPanelElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlPanelElement> panel = adoptRefWillBeNoop(new MediaControlPanelElement(mediaControls));
panel->setShadowPseudoId(AtomicString("-webkit-media-controls-panel", AtomicString::ConstructFromLiteral));
return panel.release();
}
void MediaControlPanelElement::defaultEventHandler(Event* event)
{
// Suppress the media element activation behavior (toggle play/pause) when
// any part of the control panel is clicked.
if (event->type() == EventTypeNames::click) {
event->setDefaultHandled();
return;
}
HTMLDivElement::defaultEventHandler(event);
}
void MediaControlPanelElement::startTimer()
{
stopTimer();
// The timer is required to set the property display:'none' on the panel,
// such that captions are correctly displayed at the bottom of the video
// at the end of the fadeout transition.
// FIXME: Racing a transition with a setTimeout like this is wrong.
m_transitionTimer.startOneShot(fadeOutDuration, FROM_HERE);
}
void MediaControlPanelElement::stopTimer()
{
if (m_transitionTimer.isActive())
m_transitionTimer.stop();
}
void MediaControlPanelElement::transitionTimerFired(Timer<MediaControlPanelElement>*)
{
if (!m_opaque)
hide();
stopTimer();
}
void MediaControlPanelElement::didBecomeVisible()
{
ASSERT(m_isDisplayed && m_opaque);
mediaElement().mediaControlsDidBecomeVisible();
}
void MediaControlPanelElement::makeOpaque()
{
if (m_opaque)
return;
setInlineStyleProperty(CSSPropertyOpacity, 1.0, CSSPrimitiveValue::CSS_NUMBER);
m_opaque = true;
if (m_isDisplayed) {
show();
didBecomeVisible();
}
}
void MediaControlPanelElement::makeTransparent()
{
if (!m_opaque)
return;
setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
m_opaque = false;
startTimer();
}
void MediaControlPanelElement::setIsDisplayed(bool isDisplayed)
{
if (m_isDisplayed == isDisplayed)
return;
m_isDisplayed = isDisplayed;
if (m_isDisplayed && m_opaque)
didBecomeVisible();
}
bool MediaControlPanelElement::keepEventInNode(Event* event)
{
return isUserInteractionEvent(event);
}
// ----------------------------
MediaControlPanelEnclosureElement::MediaControlPanelEnclosureElement(MediaControls& mediaControls)
// Mapping onto same MediaControlElementType as panel element, since it has similar properties.
: MediaControlDivElement(mediaControls, MediaControlsPanel)
{
}
PassRefPtrWillBeRawPtr<MediaControlPanelEnclosureElement> MediaControlPanelEnclosureElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlPanelEnclosureElement> enclosure = adoptRefWillBeNoop(new MediaControlPanelEnclosureElement(mediaControls));
enclosure->setShadowPseudoId(AtomicString("-webkit-media-controls-enclosure", AtomicString::ConstructFromLiteral));
return enclosure.release();
}
// ----------------------------
MediaControlOverlayEnclosureElement::MediaControlOverlayEnclosureElement(MediaControls& mediaControls)
// Mapping onto same MediaControlElementType as panel element, since it has similar properties.
: MediaControlDivElement(mediaControls, MediaControlsPanel)
{
}
PassRefPtrWillBeRawPtr<MediaControlOverlayEnclosureElement> MediaControlOverlayEnclosureElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlOverlayEnclosureElement> enclosure = adoptRefWillBeNoop(new MediaControlOverlayEnclosureElement(mediaControls));
enclosure->setShadowPseudoId(AtomicString("-webkit-media-controls-overlay-enclosure", AtomicString::ConstructFromLiteral));
return enclosure.release();
}
void* MediaControlOverlayEnclosureElement::preDispatchEventHandler(Event* event)
{
// When the media element is clicked or touched we want to make the overlay cast button visible
// (if the other requirements are right) even if JavaScript is doing its own handling of the event.
// Doing it in preDispatchEventHandler prevents any interference from JavaScript.
// Note that we can't simply test for click, since JS handling of touch events can prevent their translation to click events.
if (event && (event->type() == EventTypeNames::click || event->type() == EventTypeNames::touchstart) && mediaElement().hasRemoteRoutes() && !mediaElement().shouldShowControls())
mediaControls().showOverlayCastButton();
return MediaControlDivElement::preDispatchEventHandler(event);
}
// ----------------------------
MediaControlMuteButtonElement::MediaControlMuteButtonElement(MediaControls& mediaControls)
: MediaControlInputElement(mediaControls, MediaMuteButton)
{
}
PassRefPtrWillBeRawPtr<MediaControlMuteButtonElement> MediaControlMuteButtonElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlMuteButtonElement> button = adoptRefWillBeNoop(new MediaControlMuteButtonElement(mediaControls));
button->ensureUserAgentShadowRoot();
button->setType(InputTypeNames::button);
button->setShadowPseudoId(AtomicString("-webkit-media-controls-mute-button", AtomicString::ConstructFromLiteral));
return button.release();
}
void MediaControlMuteButtonElement::defaultEventHandler(Event* event)
{
if (event->type() == EventTypeNames::click) {
mediaElement().setMuted(!mediaElement().muted());
event->setDefaultHandled();
}
HTMLInputElement::defaultEventHandler(event);
}
void MediaControlMuteButtonElement::updateDisplayType()
{
setDisplayType(mediaElement().muted() ? MediaUnMuteButton : MediaMuteButton);
}
// ----------------------------
MediaControlPlayButtonElement::MediaControlPlayButtonElement(MediaControls& mediaControls)
: MediaControlInputElement(mediaControls, MediaPlayButton)
{
}
PassRefPtrWillBeRawPtr<MediaControlPlayButtonElement> MediaControlPlayButtonElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlPlayButtonElement> button = adoptRefWillBeNoop(new MediaControlPlayButtonElement(mediaControls));
button->ensureUserAgentShadowRoot();
button->setType(InputTypeNames::button);
button->setShadowPseudoId(AtomicString("-webkit-media-controls-play-button", AtomicString::ConstructFromLiteral));
return button.release();
}
void MediaControlPlayButtonElement::defaultEventHandler(Event* event)
{
if (event->type() == EventTypeNames::click) {
mediaElement().togglePlayState();
updateDisplayType();
event->setDefaultHandled();
}
HTMLInputElement::defaultEventHandler(event);
}
void MediaControlPlayButtonElement::updateDisplayType()
{
setDisplayType(mediaElement().togglePlayStateWillPlay() ? MediaPlayButton : MediaPauseButton);
}
// ----------------------------
MediaControlOverlayPlayButtonElement::MediaControlOverlayPlayButtonElement(MediaControls& mediaControls)
: MediaControlInputElement(mediaControls, MediaOverlayPlayButton)
{
}
PassRefPtrWillBeRawPtr<MediaControlOverlayPlayButtonElement> MediaControlOverlayPlayButtonElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlOverlayPlayButtonElement> button = adoptRefWillBeNoop(new MediaControlOverlayPlayButtonElement(mediaControls));
button->ensureUserAgentShadowRoot();
button->setType(InputTypeNames::button);
button->setShadowPseudoId(AtomicString("-webkit-media-controls-overlay-play-button", AtomicString::ConstructFromLiteral));
return button.release();
}
void MediaControlOverlayPlayButtonElement::defaultEventHandler(Event* event)
{
if (event->type() == EventTypeNames::click && mediaElement().togglePlayStateWillPlay()) {
mediaElement().togglePlayState();
updateDisplayType();
event->setDefaultHandled();
}
}
void MediaControlOverlayPlayButtonElement::updateDisplayType()
{
if (mediaElement().shouldShowControls() && mediaElement().togglePlayStateWillPlay())
show();
else
hide();
}
bool MediaControlOverlayPlayButtonElement::keepEventInNode(Event* event)
{
return isUserInteractionEvent(event);
}
// ----------------------------
MediaControlToggleClosedCaptionsButtonElement::MediaControlToggleClosedCaptionsButtonElement(MediaControls& mediaControls)
: MediaControlInputElement(mediaControls, MediaShowClosedCaptionsButton)
{
}
PassRefPtrWillBeRawPtr<MediaControlToggleClosedCaptionsButtonElement> MediaControlToggleClosedCaptionsButtonElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlToggleClosedCaptionsButtonElement> button = adoptRefWillBeNoop(new MediaControlToggleClosedCaptionsButtonElement(mediaControls));
button->ensureUserAgentShadowRoot();
button->setType(InputTypeNames::button);
button->setShadowPseudoId(AtomicString("-webkit-media-controls-toggle-closed-captions-button", AtomicString::ConstructFromLiteral));
button->hide();
return button.release();
}
void MediaControlToggleClosedCaptionsButtonElement::updateDisplayType()
{
bool captionsVisible = mediaElement().closedCaptionsVisible();
setDisplayType(captionsVisible ? MediaHideClosedCaptionsButton : MediaShowClosedCaptionsButton);
setChecked(captionsVisible);
}
void MediaControlToggleClosedCaptionsButtonElement::defaultEventHandler(Event* event)
{
if (event->type() == EventTypeNames::click) {
mediaElement().setClosedCaptionsVisible(!mediaElement().closedCaptionsVisible());
setChecked(mediaElement().closedCaptionsVisible());
updateDisplayType();
event->setDefaultHandled();
}
HTMLInputElement::defaultEventHandler(event);
}
// ----------------------------
MediaControlTimelineElement::MediaControlTimelineElement(MediaControls& mediaControls)
: MediaControlInputElement(mediaControls, MediaSlider)
{
}
PassRefPtrWillBeRawPtr<MediaControlTimelineElement> MediaControlTimelineElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlTimelineElement> timeline = adoptRefWillBeNoop(new MediaControlTimelineElement(mediaControls));
timeline->ensureUserAgentShadowRoot();
timeline->setType(InputTypeNames::range);
timeline->setAttribute(stepAttr, "any");
timeline->setShadowPseudoId(AtomicString("-webkit-media-controls-timeline", AtomicString::ConstructFromLiteral));
return timeline.release();
}
void MediaControlTimelineElement::defaultEventHandler(Event* event)
{
if (event->isMouseEvent() && toMouseEvent(event)->button() != LeftButton)
return;
if (!inDocument() || !document().isActive())
return;
if (event->type() == EventTypeNames::mousedown)
mediaControls().beginScrubbing();
if (event->type() == EventTypeNames::mouseup)
mediaControls().endScrubbing();
MediaControlInputElement::defaultEventHandler(event);
if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove)
return;
double time = value().toDouble();
if (event->type() == EventTypeNames::input) {
// FIXME: This will need to take the timeline offset into consideration
// once that concept is supported, see https://crbug.com/312699
if (mediaElement().controller()) {
if (mediaElement().controller()->seekable()->contain(time))
mediaElement().controller()->setCurrentTime(time);
} else if (mediaElement().seekable()->contain(time)) {
mediaElement().setCurrentTime(time, IGNORE_EXCEPTION);
}
}
LayoutSlider* slider = toLayoutSlider(layoutObject());
if (slider && slider->inDragMode())
mediaControls().updateCurrentTimeDisplay();
}
bool MediaControlTimelineElement::willRespondToMouseClickEvents()
{
return inDocument() && document().isActive();
}
void MediaControlTimelineElement::setPosition(double currentTime)
{
setValue(String::number(currentTime));
if (LayoutObject* layoutObject = this->layoutObject())
layoutObject->setShouldDoFullPaintInvalidation();
}
void MediaControlTimelineElement::setDuration(double duration)
{
setFloatingPointAttribute(maxAttr, std::isfinite(duration) ? duration : 0);
if (LayoutObject* layoutObject = this->layoutObject())
layoutObject->setShouldDoFullPaintInvalidation();
}
bool MediaControlTimelineElement::keepEventInNode(Event* event)
{
return isUserInteractionEventForSlider(event);
}
// ----------------------------
MediaControlVolumeSliderElement::MediaControlVolumeSliderElement(MediaControls& mediaControls)
: MediaControlInputElement(mediaControls, MediaVolumeSlider)
{
}
PassRefPtrWillBeRawPtr<MediaControlVolumeSliderElement> MediaControlVolumeSliderElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlVolumeSliderElement> slider = adoptRefWillBeNoop(new MediaControlVolumeSliderElement(mediaControls));
slider->ensureUserAgentShadowRoot();
slider->setType(InputTypeNames::range);
slider->setAttribute(stepAttr, "any");
slider->setAttribute(maxAttr, "1");
slider->setShadowPseudoId(AtomicString("-webkit-media-controls-volume-slider", AtomicString::ConstructFromLiteral));
return slider.release();
}
void MediaControlVolumeSliderElement::defaultEventHandler(Event* event)
{
if (event->isMouseEvent() && toMouseEvent(event)->button() != LeftButton)
return;
if (!inDocument() || !document().isActive())
return;
MediaControlInputElement::defaultEventHandler(event);
if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove)
return;
double volume = value().toDouble();
mediaElement().setVolume(volume, ASSERT_NO_EXCEPTION);
mediaElement().setMuted(false);
}
bool MediaControlVolumeSliderElement::willRespondToMouseMoveEvents()
{
if (!inDocument() || !document().isActive())
return false;
return MediaControlInputElement::willRespondToMouseMoveEvents();
}
bool MediaControlVolumeSliderElement::willRespondToMouseClickEvents()
{
if (!inDocument() || !document().isActive())
return false;
return MediaControlInputElement::willRespondToMouseClickEvents();
}
void MediaControlVolumeSliderElement::setVolume(double volume)
{
if (value().toDouble() != volume)
setValue(String::number(volume));
}
bool MediaControlVolumeSliderElement::keepEventInNode(Event* event)
{
return isUserInteractionEventForSlider(event);
}
// ----------------------------
MediaControlFullscreenButtonElement::MediaControlFullscreenButtonElement(MediaControls& mediaControls)
: MediaControlInputElement(mediaControls, MediaEnterFullscreenButton)
{
}
PassRefPtrWillBeRawPtr<MediaControlFullscreenButtonElement> MediaControlFullscreenButtonElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlFullscreenButtonElement> button = adoptRefWillBeNoop(new MediaControlFullscreenButtonElement(mediaControls));
button->ensureUserAgentShadowRoot();
button->setType(InputTypeNames::button);
button->setShadowPseudoId(AtomicString("-webkit-media-controls-fullscreen-button", AtomicString::ConstructFromLiteral));
button->hide();
return button.release();
}
void MediaControlFullscreenButtonElement::defaultEventHandler(Event* event)
{
if (event->type() == EventTypeNames::click) {
if (mediaElement().isFullscreen())
mediaElement().exitFullscreen();
else
mediaElement().enterFullscreen();
event->setDefaultHandled();
}
HTMLInputElement::defaultEventHandler(event);
}
void MediaControlFullscreenButtonElement::setIsFullscreen(bool isFullscreen)
{
setDisplayType(isFullscreen ? MediaExitFullscreenButton : MediaEnterFullscreenButton);
}
// ----------------------------
MediaControlCastButtonElement::MediaControlCastButtonElement(MediaControls& mediaControls, bool isOverlayButton)
: MediaControlInputElement(mediaControls, MediaCastOnButton), m_isOverlayButton(isOverlayButton)
{
setIsPlayingRemotely(false);
}
PassRefPtrWillBeRawPtr<MediaControlCastButtonElement> MediaControlCastButtonElement::create(MediaControls& mediaControls, bool isOverlayButton)
{
RefPtrWillBeRawPtr<MediaControlCastButtonElement> button = adoptRefWillBeNoop(new MediaControlCastButtonElement(mediaControls, isOverlayButton));
button->ensureUserAgentShadowRoot();
button->setType(InputTypeNames::button);
return button.release();
}
void MediaControlCastButtonElement::defaultEventHandler(Event* event)
{
if (event->type() == EventTypeNames::click) {
if (mediaElement().isPlayingRemotely()) {
mediaElement().requestRemotePlaybackControl();
} else {
mediaElement().requestRemotePlayback();
}
}
HTMLInputElement::defaultEventHandler(event);
}
const AtomicString& MediaControlCastButtonElement::shadowPseudoId() const
{
DEFINE_STATIC_LOCAL(AtomicString, id_nonOverlay, ("-internal-media-controls-cast-button", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, id_overlay, ("-internal-media-controls-overlay-cast-button", AtomicString::ConstructFromLiteral));
return m_isOverlayButton ? id_overlay : id_nonOverlay;
}
void MediaControlCastButtonElement::setIsPlayingRemotely(bool isPlayingRemotely)
{
if (isPlayingRemotely) {
if (m_isOverlayButton) {
setDisplayType(MediaOverlayCastOnButton);
} else {
setDisplayType(MediaCastOnButton);
}
} else {
if (m_isOverlayButton) {
setDisplayType(MediaOverlayCastOffButton);
} else {
setDisplayType(MediaCastOffButton);
}
}
}
bool MediaControlCastButtonElement::keepEventInNode(Event* event)
{
return isUserInteractionEvent(event);
}
// ----------------------------
MediaControlTimeRemainingDisplayElement::MediaControlTimeRemainingDisplayElement(MediaControls& mediaControls)
: MediaControlTimeDisplayElement(mediaControls, MediaTimeRemainingDisplay)
{
}
PassRefPtrWillBeRawPtr<MediaControlTimeRemainingDisplayElement> MediaControlTimeRemainingDisplayElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlTimeRemainingDisplayElement> element = adoptRefWillBeNoop(new MediaControlTimeRemainingDisplayElement(mediaControls));
element->setShadowPseudoId(AtomicString("-webkit-media-controls-time-remaining-display", AtomicString::ConstructFromLiteral));
return element.release();
}
// ----------------------------
MediaControlCurrentTimeDisplayElement::MediaControlCurrentTimeDisplayElement(MediaControls& mediaControls)
: MediaControlTimeDisplayElement(mediaControls, MediaCurrentTimeDisplay)
{
}
PassRefPtrWillBeRawPtr<MediaControlCurrentTimeDisplayElement> MediaControlCurrentTimeDisplayElement::create(MediaControls& mediaControls)
{
RefPtrWillBeRawPtr<MediaControlCurrentTimeDisplayElement> element = adoptRefWillBeNoop(new MediaControlCurrentTimeDisplayElement(mediaControls));
element->setShadowPseudoId(AtomicString("-webkit-media-controls-current-time-display", AtomicString::ConstructFromLiteral));
return element.release();
}
} // namespace blink
| 7,258 |
568 |
package com.jim.framework.activemq.config;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jim.framework.activemq.producer.ConsumerConnctionFactory;
import com.jim.framework.activemq.producer.ProducerConnctionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.springframework.util.CollectionUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by jiangmin on 2018/1/10.
*/
public class ConnectionFactoryContainer {
public static Map<String, PooledConnectionFactory> producerConnectionFactoryMap = new ConcurrentHashMap(2);
public static Map<String, PooledConnectionFactory> consumerConnectionFactoryMap = new ConcurrentHashMap(2);
private static List<PooledConnectionFactory> needToRemoveConnctionFactories=Lists.newArrayList();
public static Map<String,Set<String>> brokerConnections=new ConcurrentHashMap<>();
public static ExecutorService executorService= Executors.newSingleThreadExecutor();
private static final Object lock=new Object();
static {
// executorService.submit(new Runnable() {
// @Override
// public void run() {
// while (true){
// if(!CollectionUtils.isEmpty(needToRemoveConnctionFactories)){
// for(PooledConnectionFactory pooledConnectionFactory:needToRemoveConnctionFactories){
// pooledConnectionFactory.stop();
// needToRemoveConnctionFactories.remove(pooledConnectionFactory);
// }
// }
//
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }
// });
}
public static void stopProducerConnectionFactory(){
for(Map.Entry<String,PooledConnectionFactory> entry: producerConnectionFactoryMap.entrySet()){
PooledConnectionFactory pooledConnectionFactory=entry.getValue();
if(null!=pooledConnectionFactory){
//pooledConnectionFactory.stop();
needToRemoveConnctionFactories.add(pooledConnectionFactory);
producerConnectionFactoryMap.remove(entry.getKey());
}
}
}
public static void producerConnectionFactoryRebalance(){
for(Map.Entry<String,PooledConnectionFactory> entry: producerConnectionFactoryMap.entrySet()){
PooledConnectionFactory pooledConnectionFactory=entry.getValue();
if(null!=pooledConnectionFactory){
pooledConnectionFactory.setExpiryTimeout(30*1*1000);
System.out.println("expirytimeount set to 60*2*1000");
}
}
}
public static void producerConnectionFactoryResetExpiryTimeout(){
for(Map.Entry<String,PooledConnectionFactory> entry: producerConnectionFactoryMap.entrySet()){
PooledConnectionFactory pooledConnectionFactory=entry.getValue();
if(null!=pooledConnectionFactory){
if(pooledConnectionFactory.getExpiryTimeout()!=0) {
pooledConnectionFactory.setExpiryTimeout(0);
System.out.println("expirytimeount set to 0");
}
}
}
}
public static Map<String,PooledConnectionFactory> getAllPooledConnectionFactory(){
return producerConnectionFactoryMap;
}
public static void addBrokerConnection(String brokerUri,String brokerConnetionId){
synchronized (lock){
if(brokerConnections.containsKey(brokerUri)){
Set<String> connetions=brokerConnections.get(brokerUri);
if(!CollectionUtils.isEmpty(connetions)){
connetions.add(brokerConnetionId);
}
else {
connetions= Sets.newConcurrentHashSet(Arrays.asList(brokerConnetionId));
}
brokerConnections.put(brokerUri,connetions);
}
else {
brokerConnections.put(brokerUri,Sets.newConcurrentHashSet(Arrays.asList(brokerConnetionId)));
}
}
StringBuilder stringBuilder=new StringBuilder();
for(Map.Entry<String,Set<String>> entry:brokerConnections.entrySet()){
stringBuilder.append("uri:"+entry.getKey());
stringBuilder.append(Joiner.on(";").join(entry.getValue()));
}
System.out.println(stringBuilder.toString());
}
public static PooledConnectionFactory createPooledConnectionFactory(String brokerUrl) {
final String brokerClusterUrl=brokerUrl.replace(";",",");
PooledConnectionFactory connectionFactory = null;
//((ActiveMQConnectionFactory)connectionFactory.getConnectionFactory()).get;
synchronized(lock) {
if(producerConnectionFactoryMap.containsKey(brokerClusterUrl)) {
connectionFactory = producerConnectionFactoryMap.get(brokerClusterUrl);
needToRemoveConnctionFactories.add(connectionFactory);
producerConnectionFactoryMap.remove(brokerUrl);
}
ProducerConnctionFactory producerConnctionFactory=new ProducerConnctionFactory();
//producerConnctionFactory.init();
connectionFactory=producerConnctionFactory.create(brokerClusterUrl);
producerConnectionFactoryMap.put(brokerClusterUrl, connectionFactory);
return connectionFactory;
}
}
public static PooledConnectionFactory getPooledConnectionFactory(String brokerUrl) {
final String brokerClusterUrl=brokerUrl.replace(";",",");
PooledConnectionFactory connectionFactory = null;
//((ActiveMQConnectionFactory)connectionFactory.getConnectionFactory()).get;
synchronized(lock) {
if(producerConnectionFactoryMap.containsKey(brokerClusterUrl)) {
connectionFactory = producerConnectionFactoryMap.get(brokerClusterUrl);
} else {
ProducerConnctionFactory producerConnctionFactory=new ProducerConnctionFactory();
//producerConnctionFactory.init();
connectionFactory=producerConnctionFactory.create(brokerClusterUrl);
producerConnectionFactoryMap.put(brokerClusterUrl, connectionFactory);
}
return connectionFactory;
}
}
public static PooledConnectionFactory getConsumerConnectionFactory(String brokerUrl) {
PooledConnectionFactory connectionFactory = null;
synchronized(lock) {
if(consumerConnectionFactoryMap.containsKey(brokerUrl)) {
connectionFactory = (PooledConnectionFactory)consumerConnectionFactoryMap.get(brokerUrl);
} else {
ConsumerConnctionFactory consumerConnctionFactory=new ConsumerConnctionFactory();
//producerConnctionFactory.init();
connectionFactory=consumerConnctionFactory.create(brokerUrl);
consumerConnectionFactoryMap.put(brokerUrl, connectionFactory);
}
return connectionFactory;
}
}
public static String buildProducerBrokerClusterUri(String brokerString){
String prefixBrokerString="failover:";
String brokerTempString=brokerString.substring(brokerString.indexOf("(")+1,brokerString.indexOf(")"));
brokerTempString=brokerTempString.replace(";",",");
String brokerParamString=brokerString.substring(brokerString.indexOf(")")+1);
int virtualBrockerTimes=5;
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append(prefixBrokerString+"(");
for(int i=0;i<virtualBrockerTimes;i++) {
stringBuilder.append(brokerTempString);
if(i!=virtualBrockerTimes-1){
stringBuilder.append(",");
}
}
stringBuilder.append(")"+brokerParamString);
System.out.println("brockerClusterUri:"+stringBuilder.toString());
return stringBuilder.toString();
}
public static List<String> buildConsumerBrokerClusterUri(String brokerString){
String prefixBrokerString="failover:";
String brokerTempString=brokerString.substring(brokerString.indexOf("(")+1,brokerString.indexOf(")"));
String brokerParamString=brokerString.substring(brokerString.indexOf(")")+1);
List<String> brokers= Lists.newArrayList(brokerTempString.split(";"));
List<String> brokerUris=Lists.newArrayList();
for(String broker:brokers){
brokerUris.add(prefixBrokerString+"("+broker+")"+brokerParamString);
}
return brokerUris;
}
}
| 3,687 |
488 |
void foobar ( int size, int array[*] );
void foobar ( int sizeXX, int array[sizeXX] )
{
}
void foo ( int sizeYY, int array[sizeYY] )
{
}
| 63 |
1,056 |
<filename>nbi/engine/tests/org/registry/TestCircles.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.registry;
import junit.framework.TestCase;
/**
*
* @author Danila_Dugurov
*/
public class TestCircles extends TestCase {
/*
private List<Product> list;
public void testThingInSelf() {
try {
list = new LinkedList<Product>();
Product component = new Product();
component.addRequirement(component);
list.add(component);
checkCircles();
fail();
} catch (UnresolvedDependencyException ex) {
}
}
public void testMoreSofisticatedRequirements() {
try {
list = new LinkedList<Product>();
Product component = new Product();
Product depp = new Product();
Product jony = new Product();
list.add(component);
list.add(depp);
list.add(jony);
component.addRequirement(depp);
depp.addRequirement(jony);
jony.addRequirement(component);
checkCircles();
fail();
} catch (UnresolvedDependencyException ex) {
}
}
public void testRequirementsAndConflicts() {
try {
list = new LinkedList<Product>();
Product component = new Product();
Product depp = new Product();
Product jonny = new Product();
list.add(component);
list.add(depp);
list.add(jonny);
component.addRequirement(depp);
depp.addRequirement(jonny);
jonny.addConflict(component);
checkCircles();
fail();
} catch (UnresolvedDependencyException ex) {
}
}
public void testSofisticatedRequirementsAndConflicts() {
try {
list = new LinkedList<Product>();
Product root = new Product();
Product depp = new Product();
Product jonny = new Product();
Product independant = new Product();
list.add(root);
list.add(depp);
list.add(jonny);
list.add(independant);
root.addRequirement(depp);
root.addRequirement(jonny);
jonny.addConflict(depp);
jonny.addRequirement(independant);
depp.addRequirement(independant);
checkCircles();
fail();
} catch (UnresolvedDependencyException ex) {
}
}
public void testOkConflicts() {
try {
list = new LinkedList<Product>();
Product root = new Product();
Product depp = new Product();
Product jonny = new Product();
list.add(depp);
list.add(jonny);
list.add(root);
root.addConflict(depp);
root.addConflict(jonny);
jonny.addRequirement(depp);
checkCircles();
} catch (UnresolvedDependencyException ex) {
fail();
}
}
private void checkCircles() throws UnresolvedDependencyException {
for (Product component : list) {
final Stack<Product> visited = new Stack<Product>();
final Set<Product> conflictSet = new HashSet<Product>();
final Set<Product> requirementSet = new HashSet<Product>();
checkCircles(component, visited, conflictSet, requirementSet);
}
}
private void checkCircles(Product component, Stack<Product> visited,
Set<Product> conflictSet, Set<Product> requirementSet)
throws UnresolvedDependencyException {
if (visited.contains(component) || conflictSet.contains(component))
throw new UnresolvedDependencyException("circles found");
visited.push(component);
requirementSet.add(component);
if (!Collections.disjoint(requirementSet, component.getConflicts()))
throw new UnresolvedDependencyException("circles found");
conflictSet.addAll(component.getConflicts());
for (Product comp : component.getRequirements())
checkCircles(comp, visited, conflictSet, requirementSet);
visited.pop();
}*/
public void testNone() {
}
}
| 2,208 |
1,210 |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making GameAISDK available.
This source code file is licensed under the GNU General Public License Version 3.
For full details, please refer to the file "LICENSE.txt" which is provided as part of this source code package.
Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
"""
import logging
import os
import time
import cv2
from .abstract_debug import AbstractDebug
from ..canvas.data_source import DataSource
from ..tree.project_data_manager import ProjectDataManager
from ...project.project_manager import g_project_manager
from ..utils import set_log_text
from ...common.define import DEBUG_UI_CMD, TASK_PATH, REFER_PATH, SDK_BIN_PATH, TBUS_PATH
from ...communicate.agent_api_mgr import AgentAPIMgr
from ...communicate.protocol import common_pb2
from ...context.app_context import AppContext
from ...subprocess_service.subprocess_service_manager import backend_service_manager as bsa
from ..dialog.tip_dialog import show_warning_tips
from ...common.utils import backend_service_monitor
from ..tree.tree_manager import save_current_data
logger = logging.getLogger('sdktool')
class UIDebug(AbstractDebug):
SERVICE_NAME = 'ui_debug'
def __init__(self):
AbstractDebug.__init__(self)
self.program = DEBUG_UI_CMD
self.api = None
self._last_fps = 10
self.data_source = None
def initialize(self):
""" Initialize
重写基类的initialize函数,初始化tbus
:return:
"""
self.data_source = DataSource()
data_mgr = ProjectDataManager()
if not data_mgr.is_ready():
show_warning_tips('please config project first')
return False
project_config_path = self.get_project_path()
task_path = os.path.join(project_config_path, TASK_PATH)
refer_path = os.path.join(project_config_path, REFER_PATH)
if not os.path.exists(refer_path):
refer_path = None
self.api = AgentAPIMgr()
self.api.initialize(task_path, refer_path, self_addr="SDKToolAddr", cfg_path=TBUS_PATH)
self.set_enabled(True)
return True
def send_frame(self, frame=None):
""" SendFrame
重写基类的send_frame函数,输入为图像帧,将其发送给UIRecognize进程
:param frame:
:return:
"""
src_img_dict = self._generate_img_dict(frame)
ret = self.api.send_ui_src_image(src_img_dict)
if ret is False:
logging.error('send frame failed')
return False
return True
def recv_result(self):
""" RecvResult
重写基类的recv_result函数,从UIRecognize进程接收识别结果,并返回对应的结果图像
:return:
"""
ui_result = self.api.recv_ui_result()
if ui_result is None:
logger.debug("get UI result failed")
return None, False
return self._proc_ui_result(ui_result)
def start_test(self):
"""开始测试,与测试按钮绑定,点击测试按钮则执行此函数
"""
# 每次点击测试按钮时,都要执行各个初始化模块的逻辑
if not self.initialize():
logger.error("initialize failed, please check")
return False
try:
if not save_current_data():
show_warning_tips('保存数据失败,无法启动功能')
return
current_path = os.getcwd()
os.chdir(SDK_BIN_PATH)
time.sleep(1)
prj_file_path = g_project_manager.get_project_property_file()
run_program = "%s/%s cfgpath %s" % (SDK_BIN_PATH, self.program, prj_file_path)
is_ok, desc = bsa.start_service(service_name=self.SERVICE_NAME, run_programs=run_program,
process_param_type=bsa.SUBPROCESS_SHELL_TYPE,
callback_func=backend_service_monitor)
if not is_ok:
logger.error(desc)
return False
os.chdir(current_path)
self._last_fps = self.timer.get_fps()
self.timer.set_fps(1)
self.timer.start()
self.set_enabled(True)
app_ctx = AppContext()
app_ctx.set_info("phone", False)
except RuntimeError as err:
logger.error("start test failed:%s", err)
set_log_text("start test failed:{}".format(err))
return False
return True
def stop_test(self):
""" 停止测试
:return:
"""
super(UIDebug, self).stop_test()
self.timer.set_fps(self._last_fps)
logger.info('stop service:%s', self.SERVICE_NAME)
is_ok, desc = bsa.stop_service(service_name=self.SERVICE_NAME)
if is_ok:
logger.info('stop service %s success', self.SERVICE_NAME)
else:
logger.error('stop service %s failed, %s', self.SERVICE_NAME, desc)
@staticmethod
def _proc_ui_result(ui_result):
""" ProcUIResult
将UIRecognize返回的结果画在图像上'''
:param ui_result:
:return:
"""
ret = False
if ui_result is None:
logger.error('ui_result is None')
return None, ret
frame = ui_result['image']
if frame is None:
logger.error('image is None')
return None, ret
# logger.debug("proc ui result #############frame is {}#############".format(frame))
for action in ui_result['actions']:
ui_type = action.get('type')
logger.info('UI type: %s', ui_type)
if ui_type == common_pb2.PB_UI_ACTION_CLICK:
cv2.putText(frame, "click", (action['points'][0]['x'], action['points'][0]['y']),
cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2)
cv2.circle(frame, (action['points'][0]['x'], action['points'][0]['y']), 8, (0, 0, 255), -1)
logger.info('action: click (%s, %s)', action['points'][0]['x'], action['points'][0]['y'])
ret = True
elif ui_type == common_pb2.PB_UI_ACTION_DRAG:
cv2.putText(frame, "drag", (action['points'][0]['x'], action['points'][0]['y']),
cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2)
cv2.line(frame, (action['points'][0]['x'], action['points'][0]['y']),
(action['points'][1]['x'], action['points'][1]['y']), (0, 0, 255), 3)
logger.info('action: drag (%s, %s)-->(%s, %s)', action['points'][0]['x'],
action['points'][0]['y'], action['points'][1]['x'], action['points'][1]['y'])
ret = True
return frame, ret
def _generate_img_dict(self, src_img):
""" GenerateImgDict
返回发送图像的结构体
:param src_img:
:return:
"""
src_img_dict = dict()
src_img_dict['frameSeq'] = self.frame_seq
self.frame_seq += 1
src_img_dict['image'] = src_img
src_img_dict['width'] = src_img.shape[1]
src_img_dict['height'] = src_img.shape[0]
src_img_dict['deviceIndex'] = 1
return src_img_dict
| 3,689 |
456 |
/*
*
* Copyright 2015 gRPC 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.
*
*/
#include <grpc/support/port_platform.h>
#include "src/core/lib/iomgr/port.h"
#ifdef GRPC_WINSOCK_SOCKET
#include <winsock2.h>
// must be included after winsock2.h
#include <mswsock.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/log_windows.h>
#include <grpc/support/string_util.h>
#include "src/core/lib/iomgr/iocp_windows.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/pollset_windows.h"
#include "src/core/lib/iomgr/sockaddr_windows.h"
#include "src/core/lib/iomgr/socket_windows.h"
static DWORD s_wsa_socket_flags;
grpc_winsocket* grpc_winsocket_create(SOCKET socket, const char* name) {
char* final_name;
grpc_winsocket* r = (grpc_winsocket*)gpr_malloc(sizeof(grpc_winsocket));
memset(r, 0, sizeof(grpc_winsocket));
r->socket = socket;
gpr_mu_init(&r->state_mu);
gpr_asprintf(&final_name, "%s:socket=0x%p", name, r);
grpc_iomgr_register_object(&r->iomgr_object, final_name);
gpr_free(final_name);
grpc_iocp_add_socket(r);
return r;
}
SOCKET grpc_winsocket_wrapped_socket(grpc_winsocket* socket) {
return socket->socket;
}
/* Schedule a shutdown of the socket operations. Will call the pending
operations to abort them. We need to do that this way because of the
various callsites of that function, which happens to be in various
mutex hold states, and that'd be unsafe to call them directly. */
void grpc_winsocket_shutdown(grpc_winsocket* winsocket) {
/* Grab the function pointer for DisconnectEx for that specific socket.
It may change depending on the interface. */
int status;
GUID guid = WSAID_DISCONNECTEX;
LPFN_DISCONNECTEX DisconnectEx;
DWORD ioctl_num_bytes;
gpr_mu_lock(&winsocket->state_mu);
if (winsocket->shutdown_called) {
gpr_mu_unlock(&winsocket->state_mu);
return;
}
winsocket->shutdown_called = true;
gpr_mu_unlock(&winsocket->state_mu);
status = WSAIoctl(winsocket->socket, SIO_GET_EXTENSION_FUNCTION_POINTER,
&guid, sizeof(guid), &DisconnectEx, sizeof(DisconnectEx),
&ioctl_num_bytes, NULL, NULL);
if (status == 0) {
DisconnectEx(winsocket->socket, NULL, 0, 0);
} else {
char* utf8_message = gpr_format_message(WSAGetLastError());
gpr_log(GPR_INFO, "Unable to retrieve DisconnectEx pointer : %s",
utf8_message);
gpr_free(utf8_message);
}
closesocket(winsocket->socket);
}
static void destroy(grpc_winsocket* winsocket) {
grpc_iomgr_unregister_object(&winsocket->iomgr_object);
gpr_mu_destroy(&winsocket->state_mu);
gpr_free(winsocket);
}
static bool check_destroyable(grpc_winsocket* winsocket) {
return winsocket->destroy_called == true &&
winsocket->write_info.closure == NULL &&
winsocket->read_info.closure == NULL;
}
void grpc_winsocket_destroy(grpc_winsocket* winsocket) {
gpr_mu_lock(&winsocket->state_mu);
GPR_ASSERT(!winsocket->destroy_called);
winsocket->destroy_called = true;
bool should_destroy = check_destroyable(winsocket);
gpr_mu_unlock(&winsocket->state_mu);
if (should_destroy) destroy(winsocket);
}
/* Calling notify_on_read or write means either of two things:
-) The IOCP already completed in the background, and we need to call
the callback now.
-) The IOCP hasn't completed yet, and we're queuing it for later. */
static void socket_notify_on_iocp(grpc_winsocket* socket, grpc_closure* closure,
grpc_winsocket_callback_info* info) {
GPR_ASSERT(info->closure == NULL);
gpr_mu_lock(&socket->state_mu);
if (info->has_pending_iocp) {
info->has_pending_iocp = 0;
GRPC_CLOSURE_SCHED(closure, GRPC_ERROR_NONE);
} else {
info->closure = closure;
}
gpr_mu_unlock(&socket->state_mu);
}
void grpc_socket_notify_on_write(grpc_winsocket* socket,
grpc_closure* closure) {
socket_notify_on_iocp(socket, closure, &socket->write_info);
}
void grpc_socket_notify_on_read(grpc_winsocket* socket, grpc_closure* closure) {
socket_notify_on_iocp(socket, closure, &socket->read_info);
}
void grpc_socket_become_ready(grpc_winsocket* socket,
grpc_winsocket_callback_info* info) {
GPR_ASSERT(!info->has_pending_iocp);
gpr_mu_lock(&socket->state_mu);
if (info->closure) {
GRPC_CLOSURE_SCHED(info->closure, GRPC_ERROR_NONE);
info->closure = NULL;
} else {
info->has_pending_iocp = 1;
}
bool should_destroy = check_destroyable(socket);
gpr_mu_unlock(&socket->state_mu);
if (should_destroy) destroy(socket);
}
static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT;
static bool g_ipv6_loopback_available = false;
static void probe_ipv6_once(void) {
SOCKET s = socket(AF_INET6, SOCK_STREAM, 0);
g_ipv6_loopback_available = 0;
if (s == INVALID_SOCKET) {
gpr_log(GPR_INFO, "Disabling AF_INET6 sockets because socket() failed.");
} else {
grpc_sockaddr_in6 addr;
memset(&addr, 0, sizeof(addr));
addr.sin6_family = AF_INET6;
addr.sin6_addr.s6_addr[15] = 1; /* [::1]:0 */
if (bind(s, reinterpret_cast<grpc_sockaddr*>(&addr), sizeof(addr)) == 0) {
g_ipv6_loopback_available = 1;
} else {
gpr_log(GPR_INFO,
"Disabling AF_INET6 sockets because ::1 is not available.");
}
closesocket(s);
}
}
int grpc_ipv6_loopback_available(void) {
gpr_once_init(&g_probe_ipv6_once, probe_ipv6_once);
return g_ipv6_loopback_available;
}
DWORD grpc_get_default_wsa_socket_flags() { return s_wsa_socket_flags; }
void grpc_wsa_socket_flags_init() {
s_wsa_socket_flags = WSA_FLAG_OVERLAPPED;
/* WSA_FLAG_NO_HANDLE_INHERIT may be not supported on the older Windows
versions, see
https://msdn.microsoft.com/en-us/library/windows/desktop/ms742212(v=vs.85).aspx
for details. */
SOCKET sock = WSASocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP, NULL, 0,
s_wsa_socket_flags | WSA_FLAG_NO_HANDLE_INHERIT);
if (sock != INVALID_SOCKET) {
/* Windows 7, Windows 2008 R2 with SP1 or later */
s_wsa_socket_flags |= WSA_FLAG_NO_HANDLE_INHERIT;
closesocket(sock);
}
}
#endif /* GRPC_WINSOCK_SOCKET */
| 2,773 |
11,750 |
<filename>env/lib/python3.8/site-packages/plotly/figure_factory/_quiver.py
from __future__ import absolute_import
import math
from plotly import exceptions
from plotly.graph_objs import graph_objs
from plotly.figure_factory import utils
def create_quiver(
x, y, u, v, scale=0.1, arrow_scale=0.3, angle=math.pi / 9, scaleratio=None, **kwargs
):
"""
Returns data for a quiver plot.
:param (list|ndarray) x: x coordinates of the arrow locations
:param (list|ndarray) y: y coordinates of the arrow locations
:param (list|ndarray) u: x components of the arrow vectors
:param (list|ndarray) v: y components of the arrow vectors
:param (float in [0,1]) scale: scales size of the arrows(ideally to
avoid overlap). Default = .1
:param (float in [0,1]) arrow_scale: value multiplied to length of barb
to get length of arrowhead. Default = .3
:param (angle in radians) angle: angle of arrowhead. Default = pi/9
:param (positive float) scaleratio: the ratio between the scale of the y-axis
and the scale of the x-axis (scale_y / scale_x). Default = None, the
scale ratio is not fixed.
:param kwargs: kwargs passed through plotly.graph_objs.Scatter
for more information on valid kwargs call
help(plotly.graph_objs.Scatter)
:rtype (dict): returns a representation of quiver figure.
Example 1: Trivial Quiver
>>> from plotly.figure_factory import create_quiver
>>> import math
>>> # 1 Arrow from (0,0) to (1,1)
>>> fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1)
>>> fig.show()
Example 2: Quiver plot using meshgrid
>>> from plotly.figure_factory import create_quiver
>>> import numpy as np
>>> import math
>>> # Add data
>>> x,y = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))
>>> u = np.cos(x)*y
>>> v = np.sin(x)*y
>>> #Create quiver
>>> fig = create_quiver(x, y, u, v)
>>> fig.show()
Example 3: Styling the quiver plot
>>> from plotly.figure_factory import create_quiver
>>> import numpy as np
>>> import math
>>> # Add data
>>> x, y = np.meshgrid(np.arange(-np.pi, math.pi, .5),
... np.arange(-math.pi, math.pi, .5))
>>> u = np.cos(x)*y
>>> v = np.sin(x)*y
>>> # Create quiver
>>> fig = create_quiver(x, y, u, v, scale=.2, arrow_scale=.3, angle=math.pi/6,
... name='Wind Velocity', line=dict(width=1))
>>> # Add title to layout
>>> fig.update_layout(title='Quiver Plot') # doctest: +SKIP
>>> fig.show()
Example 4: Forcing a fix scale ratio to maintain the arrow length
>>> from plotly.figure_factory import create_quiver
>>> import numpy as np
>>> # Add data
>>> x,y = np.meshgrid(np.arange(0.5, 3.5, .5), np.arange(0.5, 4.5, .5))
>>> u = x
>>> v = y
>>> angle = np.arctan(v / u)
>>> norm = 0.25
>>> u = norm * np.cos(angle)
>>> v = norm * np.sin(angle)
>>> # Create quiver with a fix scale ratio
>>> fig = create_quiver(x, y, u, v, scale = 1, scaleratio = 0.5)
>>> fig.show()
"""
utils.validate_equal_length(x, y, u, v)
utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale)
if scaleratio is None:
quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle)
else:
quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle, scaleratio)
barb_x, barb_y = quiver_obj.get_barbs()
arrow_x, arrow_y = quiver_obj.get_quiver_arrows()
quiver_plot = graph_objs.Scatter(
x=barb_x + arrow_x, y=barb_y + arrow_y, mode="lines", **kwargs
)
data = [quiver_plot]
if scaleratio is None:
layout = graph_objs.Layout(hovermode="closest")
else:
layout = graph_objs.Layout(
hovermode="closest", yaxis=dict(scaleratio=scaleratio, scaleanchor="x")
)
return graph_objs.Figure(data=data, layout=layout)
class _Quiver(object):
"""
Refer to FigureFactory.create_quiver() for docstring
"""
def __init__(self, x, y, u, v, scale, arrow_scale, angle, scaleratio=1, **kwargs):
try:
x = utils.flatten(x)
except exceptions.PlotlyError:
pass
try:
y = utils.flatten(y)
except exceptions.PlotlyError:
pass
try:
u = utils.flatten(u)
except exceptions.PlotlyError:
pass
try:
v = utils.flatten(v)
except exceptions.PlotlyError:
pass
self.x = x
self.y = y
self.u = u
self.v = v
self.scale = scale
self.scaleratio = scaleratio
self.arrow_scale = arrow_scale
self.angle = angle
self.end_x = []
self.end_y = []
self.scale_uv()
barb_x, barb_y = self.get_barbs()
arrow_x, arrow_y = self.get_quiver_arrows()
def scale_uv(self):
"""
Scales u and v to avoid overlap of the arrows.
u and v are added to x and y to get the
endpoints of the arrows so a smaller scale value will
result in less overlap of arrows.
"""
self.u = [i * self.scale * self.scaleratio for i in self.u]
self.v = [i * self.scale for i in self.v]
def get_barbs(self):
"""
Creates x and y startpoint and endpoint pairs
After finding the endpoint of each barb this zips startpoint and
endpoint pairs to create 2 lists: x_values for barbs and y values
for barbs
:rtype: (list, list) barb_x, barb_y: list of startpoint and endpoint
x_value pairs separated by a None to create the barb of the arrow,
and list of startpoint and endpoint y_value pairs separated by a
None to create the barb of the arrow.
"""
self.end_x = [i + j for i, j in zip(self.x, self.u)]
self.end_y = [i + j for i, j in zip(self.y, self.v)]
empty = [None] * len(self.x)
barb_x = utils.flatten(zip(self.x, self.end_x, empty))
barb_y = utils.flatten(zip(self.y, self.end_y, empty))
return barb_x, barb_y
def get_quiver_arrows(self):
"""
Creates lists of x and y values to plot the arrows
Gets length of each barb then calculates the length of each side of
the arrow. Gets angle of barb and applies angle to each side of the
arrowhead. Next uses arrow_scale to scale the length of arrowhead and
creates x and y values for arrowhead point1 and point2. Finally x and y
values for point1, endpoint and point2s for each arrowhead are
separated by a None and zipped to create lists of x and y values for
the arrows.
:rtype: (list, list) arrow_x, arrow_y: list of point1, endpoint, point2
x_values separated by a None to create the arrowhead and list of
point1, endpoint, point2 y_values separated by a None to create
the barb of the arrow.
"""
dif_x = [i - j for i, j in zip(self.end_x, self.x)]
dif_y = [i - j for i, j in zip(self.end_y, self.y)]
# Get barb lengths(default arrow length = 30% barb length)
barb_len = [None] * len(self.x)
for index in range(len(barb_len)):
barb_len[index] = math.hypot(dif_x[index] / self.scaleratio, dif_y[index])
# Make arrow lengths
arrow_len = [None] * len(self.x)
arrow_len = [i * self.arrow_scale for i in barb_len]
# Get barb angles
barb_ang = [None] * len(self.x)
for index in range(len(barb_ang)):
barb_ang[index] = math.atan2(dif_y[index], dif_x[index] / self.scaleratio)
# Set angles to create arrow
ang1 = [i + self.angle for i in barb_ang]
ang2 = [i - self.angle for i in barb_ang]
cos_ang1 = [None] * len(ang1)
for index in range(len(ang1)):
cos_ang1[index] = math.cos(ang1[index])
seg1_x = [i * j for i, j in zip(arrow_len, cos_ang1)]
sin_ang1 = [None] * len(ang1)
for index in range(len(ang1)):
sin_ang1[index] = math.sin(ang1[index])
seg1_y = [i * j for i, j in zip(arrow_len, sin_ang1)]
cos_ang2 = [None] * len(ang2)
for index in range(len(ang2)):
cos_ang2[index] = math.cos(ang2[index])
seg2_x = [i * j for i, j in zip(arrow_len, cos_ang2)]
sin_ang2 = [None] * len(ang2)
for index in range(len(ang2)):
sin_ang2[index] = math.sin(ang2[index])
seg2_y = [i * j for i, j in zip(arrow_len, sin_ang2)]
# Set coordinates to create arrow
for index in range(len(self.end_x)):
point1_x = [i - j * self.scaleratio for i, j in zip(self.end_x, seg1_x)]
point1_y = [i - j for i, j in zip(self.end_y, seg1_y)]
point2_x = [i - j * self.scaleratio for i, j in zip(self.end_x, seg2_x)]
point2_y = [i - j for i, j in zip(self.end_y, seg2_y)]
# Combine lists to create arrow
empty = [None] * len(self.end_x)
arrow_x = utils.flatten(zip(point1_x, self.end_x, point2_x, empty))
arrow_y = utils.flatten(zip(point1_y, self.end_y, point2_y, empty))
return arrow_x, arrow_y
| 4,160 |
669 |
// Copyright 2020 The TensorFlow Runtime Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Thin wrapper around the NCCL API adding llvm::Error.
#include "tfrt/gpu/wrapper/nccl_wrapper.h"
#include <utility>
#include "wrapper_detail.h"
namespace tfrt {
namespace gpu {
namespace wrapper {
llvm::Expected<int> NcclGetVersion() {
int version = 0;
RETURN_IF_ERROR(ncclGetVersion(&version));
return version;
}
llvm::Expected<ncclUniqueId> NcclGetUniqueId() {
ncclUniqueId id;
// Note: calls ncclInit() on the first call, which calls cudaGetDevice() and
// therefore acquires the primary context if none is current.
//
// This is acceptable because ncclCommInitRank() acquires the primary context
// in all cases. It is also safe because there cannot be a CurrentContext
// instance when the kContextTls.cuda_ctx is null.
//
// TODO(csigg): expose ncclInit() and call during context creation.
RETURN_IF_ERROR(ncclGetUniqueId(&id));
return id;
}
llvm::Expected<OwningCclComm> NcclCommInitRank(CurrentContext current,
int nranks, ncclUniqueId commId,
int rank) {
CheckCudaContext(current);
ncclComm_t comm;
// Note: unless the call is surrounded by NcclGroupStart/End(), calls
// cudaSetDevice() in the calling thread, making the primary context current.
RETURN_IF_ERROR(ncclCommInitRank(&comm, nranks, commId, rank));
CheckCudaContext(current); // Check that kContextTls is still correct.
return OwningCclComm({comm, Platform::CUDA});
}
llvm::Error NcclCommDestroy(ncclComm_t comm) {
return TO_ERROR(ncclCommDestroy(comm));
}
llvm::Error NcclCommAbort(ncclComm_t comm) {
return TO_ERROR(ncclCommAbort(comm));
}
llvm::Error NcclCommGetAsyncError(ncclComm_t comm) {
ncclResult_t result;
RETURN_IF_ERROR(ncclCommGetAsyncError(comm, &result));
return TO_ERROR(result);
}
llvm::Expected<int> NcclCommCount(ncclComm_t comm) {
int count = 0;
RETURN_IF_ERROR(ncclCommCount(comm, &count));
return count;
}
llvm::Expected<int> NcclCommUserRank(ncclComm_t comm) {
int rank = 0;
RETURN_IF_ERROR(ncclCommUserRank(comm, &rank));
return rank;
}
llvm::Error NcclReduce(CurrentContext current, Pointer<const void> sendbuff,
Pointer<void> recvbuff, size_t count,
ncclDataType_t datatype, ncclRedOp_t op, int root,
ncclComm_t comm, cudaStream_t stream) {
CheckCudaContext(current);
RETURN_IF_ERROR(ncclReduce(sendbuff.raw(Platform::CUDA),
recvbuff.raw(Platform::CUDA), count, datatype, op,
root, comm, stream));
CheckCudaContext(current);
return llvm::Error::success();
}
llvm::Error NcclBcast(CurrentContext current, Pointer<void> buffer,
size_t count, ncclDataType_t datatype, int root,
ncclComm_t comm, cudaStream_t stream) {
CheckCudaContext(current);
RETURN_IF_ERROR(ncclBcast(buffer.raw(Platform::CUDA), count, datatype, root,
comm, stream));
CheckCudaContext(current);
return llvm::Error::success();
}
llvm::Error NcclBroadcast(CurrentContext current, Pointer<const void> sendbuff,
Pointer<void> recvbuff, size_t count,
ncclDataType_t datatype, int root, ncclComm_t comm,
cudaStream_t stream) {
CheckCudaContext(current);
RETURN_IF_ERROR(ncclBroadcast(sendbuff.raw(Platform::CUDA),
recvbuff.raw(Platform::CUDA), count, datatype,
root, comm, stream));
CheckCudaContext(current);
return llvm::Error::success();
}
llvm::Error NcclAllReduce(CurrentContext current, Pointer<const void> sendbuff,
Pointer<void> recvbuff, size_t count,
ncclDataType_t datatype, ncclRedOp_t op,
ncclComm_t comm, cudaStream_t stream) {
CheckCudaContext(current);
RETURN_IF_ERROR(ncclAllReduce(sendbuff.raw(Platform::CUDA),
recvbuff.raw(Platform::CUDA), count, datatype,
op, comm, stream));
CheckCudaContext(current);
return llvm::Error::success();
}
llvm::Error NcclReduceScatter(CurrentContext current,
Pointer<const void> sendbuff,
Pointer<void> recvbuff, size_t recvcount,
ncclDataType_t datatype, ncclRedOp_t op,
ncclComm_t comm, cudaStream_t stream) {
CheckCudaContext(current);
RETURN_IF_ERROR(ncclReduceScatter(sendbuff.raw(Platform::CUDA),
recvbuff.raw(Platform::CUDA), recvcount,
datatype, op, comm, stream));
CheckCudaContext(current);
return llvm::Error::success();
}
llvm::Error NcclAllGather(CurrentContext current, Pointer<const void> sendbuff,
Pointer<void> recvbuff, size_t sendcount,
ncclDataType_t datatype, ncclComm_t comm,
cudaStream_t stream) {
CheckCudaContext(current);
RETURN_IF_ERROR(ncclAllGather(sendbuff.raw(Platform::CUDA),
recvbuff.raw(Platform::CUDA), sendcount,
datatype, comm, stream));
CheckCudaContext(current);
return llvm::Error::success();
}
llvm::Error NcclSend(CurrentContext current, Pointer<const void> sendbuff,
size_t count, ncclDataType_t datatype, int peer,
ncclComm_t comm, cudaStream_t stream) {
CheckCudaContext(current);
RETURN_IF_ERROR(ncclSend(sendbuff.raw(Platform::CUDA), count, datatype, peer,
comm, stream));
CheckCudaContext(current);
return llvm::Error::success();
}
llvm::Error NcclRecv(CurrentContext current, Pointer<void> recvbuff,
size_t count, ncclDataType_t datatype, int peer,
ncclComm_t comm, cudaStream_t stream) {
CheckCudaContext(current);
RETURN_IF_ERROR(ncclRecv(recvbuff.raw(Platform::CUDA), count, datatype, peer,
comm, stream));
CheckCudaContext(current);
return llvm::Error::success();
}
llvm::Error NcclGroupStart() { return TO_ERROR(ncclGroupStart()); }
llvm::Error NcclGroupEnd() { return TO_ERROR(ncclGroupEnd()); }
} // namespace wrapper
} // namespace gpu
} // namespace tfrt
| 3,147 |
357 |
#ifndef TC_EVENT_H
#define TC_EVENT_H
#include <xcopy.h>
#define TC_EVENT_SELECT_OLD 0
#define TC_EVENT_SELECT 1
#define TC_EVENT_EPOLL 2
#define TC_EVENT_OK 0
#define TC_EVENT_ERROR -1
#define TC_EVENT_AGAIN 1
#define TC_EVENT_NONE 0
#define TC_EVENT_READ 1
#define TC_EVENT_WRITE 2
#define tc_event_push_active_event(head, ev) \
ev->next = head; head = ev;
typedef struct tc_event_loop_s tc_event_loop_t;
typedef struct tc_event_s tc_event_t;
typedef struct tc_event_timer_s tc_event_timer_t;
typedef int (*ev_create_pt) (tc_event_loop_t *loop);
typedef int (*ev_destroy_pt) (tc_event_loop_t *loop);
typedef int (*ev_add_event_pt) (tc_event_loop_t *loop, tc_event_t *ev,
int events);
typedef int (*ev_delete_event_pt) (tc_event_loop_t *loop, tc_event_t *ev,
int events);
typedef int (*ev_event_poll_pt) (tc_event_loop_t *loop, long timeout);
typedef int (*tc_event_handler_pt) (tc_event_t *ev);
typedef void (*tc_event_timer_handler_pt) (tc_event_timer_t *evt);
typedef struct {
ev_create_pt create;
ev_destroy_pt destroy;
ev_add_event_pt add;
ev_delete_event_pt del;
ev_event_poll_pt poll;
} tc_event_actions_t;
struct tc_event_s {
int fd;
int events;
int reg_evs;
int index;
tc_event_loop_t *loop;
tc_event_handler_pt read_handler;
tc_event_handler_pt write_handler;
tc_event_t *next;
};
typedef tc_rbtree_key_t tc_msec_t;
typedef tc_rbtree_key_int_t tc_msec_int_t;
typedef struct tm tc_tm_t;
struct tc_event_timer_s {
unsigned timer_set:1;
void *data;
tc_pool_t *pool;
tc_rbtree_node_t timer;
tc_event_timer_handler_pt handler;
};
struct tc_event_loop_s {
int size;
void *io;
tc_pool_t *pool;
tc_event_t *active_events;
tc_event_actions_t *actions;
};
int tc_event_loop_init(tc_event_loop_t *loop, int size);
int tc_event_loop_finish(tc_event_loop_t *loop);
int tc_event_proc_cycle(tc_event_loop_t *loop);
int tc_event_add(tc_event_loop_t *loop, tc_event_t *ev, int events);
int tc_event_del(tc_event_loop_t *loop, tc_event_t *ev, int events);
tc_event_t *tc_event_create(tc_pool_t *pool, int fd, tc_event_handler_pt reader,
tc_event_handler_pt writer);
void tc_event_destroy(tc_event_t *ev, int delayed);
void finally_release_obsolete_events(void);
extern tc_atomic_t tc_over;
#endif /* TC_EVENT_H */
| 1,314 |
713 |
<reponame>vansh-tiwari/coding-interview-gym
from collections import deque
class Solution(object):
def openLock(self, deadends, target):
"""
:type deadends: List[str]
:type target: str
:rtype: int
"""
level, queue, visited = -1, deque(['0000']), set(deadends)
while queue:
level += 1
currentLevelSize = len(queue)
for _ in range(currentLevelSize):
currentNode = queue.popleft()
if currentNode == target:
return level
if currentNode in visited:
continue
visited.add(currentNode)
currentNodesNeighour = self.nodeNeighbours(currentNode)
queue.extend(currentNodesNeighour)
return -1
def nodeNeighbours(self, sourceNode):
neighbours = []
for i, char in enumerate(sourceNode):
num = int(char)
neighbours.append(sourceNode[:i] + str((num + 1) % 10) + sourceNode[i + 1:])
neighbours.append(sourceNode[:i] + str((num - 1) % 10) + sourceNode[i + 1:])
return neighbours
| 567 |
14,668 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef DEVICE_BLUETOOTH_BLUETOOTH_L2CAP_CHANNEL_MAC_H_
#define DEVICE_BLUETOOTH_BLUETOOTH_L2CAP_CHANNEL_MAC_H_
#import <IOBluetooth/IOBluetooth.h>
#import <IOKit/IOReturn.h>
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/mac/scoped_nsobject.h"
#include "device/bluetooth/bluetooth_channel_mac.h"
@class BluetoothL2capChannelDelegate;
namespace device {
class BluetoothL2capChannelMac : public BluetoothChannelMac {
public:
// Creates a new L2CAP channel wrapper with the given |socket| and native
// |channel|.
// NOTE: The |channel| is expected to already be retained.
BluetoothL2capChannelMac(BluetoothSocketMac* socket,
IOBluetoothL2CAPChannel* channel);
BluetoothL2capChannelMac(const BluetoothL2capChannelMac&) = delete;
BluetoothL2capChannelMac& operator=(const BluetoothL2capChannelMac&) = delete;
~BluetoothL2capChannelMac() override;
// Opens a new L2CAP channel with Channel ID |channel_id| to the target
// |device|. Returns the opened channel and sets |status| to kIOReturnSuccess
// if the open process was successfully started (or if an existing L2CAP
// channel was found). Otherwise, sets |status| to an error status.
static std::unique_ptr<BluetoothL2capChannelMac> OpenAsync(
BluetoothSocketMac* socket,
IOBluetoothDevice* device,
BluetoothL2CAPPSM psm,
IOReturn* status);
// BluetoothChannelMac:
void SetSocket(BluetoothSocketMac* socket) override;
IOBluetoothDevice* GetDevice() override;
uint16_t GetOutgoingMTU() override;
IOReturn WriteAsync(void* data, uint16_t length, void* refcon) override;
void OnChannelOpenComplete(IOBluetoothL2CAPChannel* channel,
IOReturn status);
void OnChannelClosed(IOBluetoothL2CAPChannel* channel);
void OnChannelDataReceived(IOBluetoothL2CAPChannel* channel,
void* data,
size_t length);
void OnChannelWriteComplete(IOBluetoothL2CAPChannel* channel,
void* refcon,
IOReturn status);
private:
// The wrapped native L2CAP channel.
base::scoped_nsobject<IOBluetoothL2CAPChannel> channel_;
// The delegate for the native channel.
base::scoped_nsobject<BluetoothL2capChannelDelegate> delegate_;
};
} // namespace device
#endif // DEVICE_BLUETOOTH_BLUETOOTH_L2CAP_CHANNEL_MAC_H_
| 975 |
435 |
{
"copyright_text": "Standard YouTube License",
"description": "",
"duration": 1028,
"language": "spa",
"recorded": "2017-09-24T10:00:00+02:00",
"related_urls": [
{
"label": "schedule",
"url": "https://2017.es.pycon.org/es/schedule/"
}
],
"speakers": [
"<NAME>"
],
"tags": [],
"thumbnail_url": "https://i.ytimg.com/vi/9jZSSSxSH_E/maxresdefault.jpg",
"title": "Open Sourceando en Orange",
"videos": [
{
"type": "youtube",
"url": "https://www.youtube.com/watch?v=9jZSSSxSH_E"
}
]
}
| 259 |
610 |
<gh_stars>100-1000
/*
* Copyright 2012-2020 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.cloud.context.scope;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* A simple cache implementation backed by a concurrent map.
*
* @author <NAME>
*
*/
public class StandardScopeCache implements ScopeCache {
private final ConcurrentMap<String, Object> cache = new ConcurrentHashMap<String, Object>();
public Object remove(String name) {
return this.cache.remove(name);
}
public Collection<Object> clear() {
Collection<Object> values = new ArrayList<Object>(this.cache.values());
this.cache.clear();
return values;
}
public Object get(String name) {
return this.cache.get(name);
}
public Object put(String name, Object value) {
Object result = this.cache.putIfAbsent(name, value);
if (result != null) {
return result;
}
return value;
}
}
| 454 |
605 |
<filename>libcxx/test/std/algorithms/robust_re_difference_type.compile.pass.cpp
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <algorithm>
// In the description of the algorithms,
// given an iterator a whose difference type is D,
// and an expression n of integer-like type other than cv D,
// the semantics of a + n and a - n are, respectively,
// those of a + D(n) and a - D(n).
#include <algorithm>
#include <cstddef>
#include <functional>
#include <iterator>
#include "test_macros.h"
// This iterator rejects expressions like (a + n) and (a - n)
// whenever n is of any type other than difference_type.
//
template<class It, class DifferenceType>
class PickyIterator {
It it_;
public:
using iterator_category = std::random_access_iterator_tag;
using value_type = typename std::iterator_traits<It>::value_type;
using difference_type = DifferenceType;
using pointer = It;
using reference = typename std::iterator_traits<It>::reference;
TEST_CONSTEXPR_CXX14 PickyIterator() = default;
TEST_CONSTEXPR_CXX14 explicit PickyIterator(It it) : it_(it) {}
TEST_CONSTEXPR_CXX14 reference operator*() const {return *it_;}
TEST_CONSTEXPR_CXX14 pointer operator->() const {return it_;}
TEST_CONSTEXPR_CXX14 reference operator[](difference_type n) const {return it_[n];}
friend TEST_CONSTEXPR_CXX14 bool operator==(PickyIterator a, PickyIterator b) { return a.it_ == b.it_; }
friend TEST_CONSTEXPR_CXX14 bool operator!=(PickyIterator a, PickyIterator b) { return a.it_ != b.it_; }
friend TEST_CONSTEXPR_CXX14 bool operator<(PickyIterator a, PickyIterator b) { return a.it_ < b.it_; }
friend TEST_CONSTEXPR_CXX14 bool operator>(PickyIterator a, PickyIterator b) { return a.it_ > b.it_; }
friend TEST_CONSTEXPR_CXX14 bool operator<=(PickyIterator a, PickyIterator b) { return a.it_ <= b.it_; }
friend TEST_CONSTEXPR_CXX14 bool operator>=(PickyIterator a, PickyIterator b) { return a.it_ >= b.it_; }
TEST_CONSTEXPR_CXX14 PickyIterator& operator++() {++it_; return *this;}
TEST_CONSTEXPR_CXX14 PickyIterator operator++(int) {auto tmp = *this; ++(*this); return tmp;}
TEST_CONSTEXPR_CXX14 PickyIterator& operator--() {--it_; return *this;}
TEST_CONSTEXPR_CXX14 PickyIterator operator--(int) {auto tmp = *this; --(*this); return tmp;}
TEST_CONSTEXPR_CXX14 PickyIterator& operator+=(difference_type n) {it_ += n; return *this;}
TEST_CONSTEXPR_CXX14 PickyIterator& operator-=(difference_type n) {it_ -= n; return *this;}
friend TEST_CONSTEXPR_CXX14 PickyIterator operator+(PickyIterator it, difference_type n) {it += n; return it;}
friend TEST_CONSTEXPR_CXX14 PickyIterator operator+(difference_type n, PickyIterator it) {it += n; return it;}
friend TEST_CONSTEXPR_CXX14 PickyIterator operator-(PickyIterator it, difference_type n) {it -= n; return it;}
friend TEST_CONSTEXPR_CXX14 difference_type operator-(PickyIterator it, PickyIterator jt) {return it.it_ - jt.it_;}
template<class X> void operator+=(X) = delete;
template<class X> void operator-=(X) = delete;
template<class X> friend void operator+(PickyIterator, X) = delete;
template<class X> friend void operator+(X, PickyIterator) = delete;
template<class X> friend void operator-(PickyIterator, X) = delete;
};
struct UnaryVoid { TEST_CONSTEXPR_CXX14 void operator()(void*) const {} };
struct UnaryTrue { TEST_CONSTEXPR bool operator()(void*) const { return true; } };
struct NullaryValue { TEST_CONSTEXPR std::nullptr_t operator()() const { return nullptr; } };
struct UnaryTransform { TEST_CONSTEXPR std::nullptr_t operator()(void*) const { return nullptr; } };
struct BinaryTransform { TEST_CONSTEXPR std::nullptr_t operator()(void*, void*) const { return nullptr; } };
TEST_CONSTEXPR_CXX20 bool all_the_algorithms()
{
void *a[10] = {};
void *b[10] = {};
auto first = PickyIterator<void**, long>(a);
auto mid = PickyIterator<void**, long>(a+5);
auto last = PickyIterator<void**, long>(a+10);
auto first2 = PickyIterator<void**, long long>(b);
auto mid2 = PickyIterator<void**, long long>(b+5);
auto last2 = PickyIterator<void**, long long>(b+10);
void *value = nullptr;
int count = 1;
(void)std::adjacent_find(first, last);
(void)std::adjacent_find(first, last, std::equal_to<void*>());
#if TEST_STD_VER >= 11
(void)std::all_of(first, last, UnaryTrue());
(void)std::any_of(first, last, UnaryTrue());
#endif
(void)std::binary_search(first, last, value);
(void)std::binary_search(first, last, value, std::less<void*>());
#if TEST_STD_VER > 17
(void)std::clamp(value, value, value);
(void)std::clamp(value, value, value, std::less<void*>());
#endif
(void)std::copy(first, last, first2);
(void)std::copy_backward(first, last, last2);
(void)std::copy_n(first, count, first2);
(void)std::count(first, last, value);
(void)std::count_if(first, last, UnaryTrue());
(void)std::distance(first, last);
(void)std::equal(first, last, first2);
(void)std::equal(first, last, first2, std::equal_to<void*>());
#if TEST_STD_VER > 11
(void)std::equal(first, last, first2, last2);
(void)std::equal(first, last, first2, last2, std::equal_to<void*>());
#endif
(void)std::equal_range(first, last, value);
(void)std::equal_range(first, last, value, std::less<void*>());
(void)std::fill(first, last, value);
(void)std::fill_n(first, count, value);
(void)std::find(first, last, value);
(void)std::find_end(first, last, first2, mid2);
(void)std::find_end(first, last, first2, mid2, std::equal_to<void*>());
(void)std::find_if(first, last, UnaryTrue());
(void)std::find_if_not(first, last, UnaryTrue());
(void)std::for_each(first, last, UnaryVoid());
#if TEST_STD_VER > 14
(void)std::for_each_n(first, count, UnaryVoid());
#endif
(void)std::generate(first, last, NullaryValue());
(void)std::generate_n(first, count, NullaryValue());
(void)std::includes(first, last, first2, last2);
(void)std::includes(first, last, first2, last2, std::less<void*>());
(void)std::is_heap(first, last);
(void)std::is_heap(first, last, std::less<void*>());
(void)std::is_heap_until(first, last);
(void)std::is_heap_until(first, last, std::less<void*>());
(void)std::is_partitioned(first, last, UnaryTrue());
(void)std::is_permutation(first, last, first2);
(void)std::is_permutation(first, last, first2, std::equal_to<void*>());
#if TEST_STD_VER > 11
(void)std::is_permutation(first, last, first2, last2);
(void)std::is_permutation(first, last, first2, last2, std::equal_to<void*>());
#endif
(void)std::is_sorted(first, last);
(void)std::is_sorted(first, last, std::less<void*>());
(void)std::is_sorted_until(first, last);
(void)std::is_sorted_until(first, last, std::less<void*>());
if (!TEST_IS_CONSTANT_EVALUATED) (void)std::inplace_merge(first, mid, last);
if (!TEST_IS_CONSTANT_EVALUATED) (void)std::inplace_merge(first, mid, last, std::less<void*>());
(void)std::iter_swap(first, mid);
(void)std::lexicographical_compare(first, last, first2, last2);
(void)std::lexicographical_compare(first, last, first2, last2, std::less<void*>());
// TODO: lexicographical_compare_three_way
(void)std::lower_bound(first, last, value);
(void)std::lower_bound(first, last, value, std::less<void*>());
(void)std::make_heap(first, last);
(void)std::make_heap(first, last, std::less<void*>());
(void)std::max(value, value);
(void)std::max(value, value, std::less<void*>());
#if TEST_STD_VER >= 11
(void)std::max({ value, value });
(void)std::max({ value, value }, std::less<void*>());
#endif
(void)std::max_element(first, last);
(void)std::max_element(first, last, std::less<void*>());
(void)std::merge(first, mid, mid, last, first2);
(void)std::merge(first, mid, mid, last, first2, std::less<void*>());
(void)std::min(value, value);
(void)std::min(value, value, std::less<void*>());
#if TEST_STD_VER >= 11
(void)std::min({ value, value });
(void)std::min({ value, value }, std::less<void*>());
#endif
(void)std::min_element(first, last);
(void)std::min_element(first, last, std::less<void*>());
(void)std::minmax(value, value);
(void)std::minmax(value, value, std::less<void*>());
#if TEST_STD_VER >= 11
(void)std::minmax({ value, value });
(void)std::minmax({ value, value }, std::less<void*>());
#endif
(void)std::minmax_element(first, last);
(void)std::minmax_element(first, last, std::less<void*>());
(void)std::mismatch(first, last, first2);
(void)std::mismatch(first, last, first2, std::equal_to<void*>());
#if TEST_STD_VER > 11
(void)std::mismatch(first, last, first2, last2);
(void)std::mismatch(first, last, first2, last2, std::equal_to<void*>());
#endif
(void)std::move(first, last, first2);
(void)std::move_backward(first, last, last2);
(void)std::next_permutation(first, last);
(void)std::next_permutation(first, last, std::less<void*>());
(void)std::none_of(first, last, UnaryTrue());
(void)std::nth_element(first, mid, last);
(void)std::nth_element(first, mid, last, std::less<void*>());
(void)std::partial_sort(first, mid, last);
(void)std::partial_sort(first, mid, last, std::less<void*>());
(void)std::partial_sort_copy(first, last, first2, mid2);
(void)std::partial_sort_copy(first, last, first2, mid2, std::less<void*>());
(void)std::partition(first, last, UnaryTrue());
(void)std::partition_copy(first, last, first2, last2, UnaryTrue());
(void)std::partition_point(first, last, UnaryTrue());
(void)std::pop_heap(first, last);
(void)std::pop_heap(first, last, std::less<void*>());
(void)std::prev_permutation(first, last);
(void)std::prev_permutation(first, last, std::less<void*>());
(void)std::push_heap(first, last);
(void)std::push_heap(first, last, std::less<void*>());
(void)std::remove(first, last, value);
(void)std::remove_copy(first, last, first2, value);
(void)std::remove_copy_if(first, last, first2, UnaryTrue());
(void)std::remove_if(first, last, UnaryTrue());
(void)std::replace(first, last, value, value);
(void)std::replace_copy(first, last, first2, value, value);
(void)std::replace_copy_if(first, last, first2, UnaryTrue(), value);
(void)std::replace_if(first, last, UnaryTrue(), value);
(void)std::reverse(first, last);
(void)std::reverse_copy(first, last, first2);
(void)std::rotate(first, mid, last);
(void)std::rotate_copy(first, mid, last, first2);
(void)std::search(first, last, first2, mid2);
(void)std::search(first, last, first2, mid2, std::equal_to<void*>());
(void)std::search_n(first, last, count, value);
(void)std::search_n(first, last, count, value, std::equal_to<void*>());
(void)std::set_difference(first, mid, mid, last, first2);
(void)std::set_difference(first, mid, mid, last, first2, std::less<void*>());
(void)std::set_intersection(first, mid, mid, last, first2);
(void)std::set_intersection(first, mid, mid, last, first2, std::less<void*>());
(void)std::set_symmetric_difference(first, mid, mid, last, first2);
(void)std::set_symmetric_difference(first, mid, mid, last, first2, std::less<void*>());
(void)std::set_union(first, mid, mid, last, first2);
(void)std::set_union(first, mid, mid, last, first2, std::less<void*>());
#if TEST_STD_VER > 17
(void)std::shift_left(first, last, count);
(void)std::shift_right(first, last, count);
#endif
(void)std::sort(first, last);
(void)std::sort(first, last, std::less<void*>());
(void)std::sort_heap(first, last);
(void)std::sort_heap(first, last, std::less<void*>());
if (!TEST_IS_CONSTANT_EVALUATED) (void)std::stable_partition(first, last, UnaryTrue());
if (!TEST_IS_CONSTANT_EVALUATED) (void)std::stable_sort(first, last);
if (!TEST_IS_CONSTANT_EVALUATED) (void)std::stable_sort(first, last, std::less<void*>());
(void)std::swap_ranges(first, last, first2);
(void)std::transform(first, last, first2, UnaryTransform());
(void)std::transform(first, mid, mid, first2, BinaryTransform());
(void)std::unique(first, last);
(void)std::unique(first, last, std::equal_to<void*>());
(void)std::unique_copy(first, last, first2);
(void)std::unique_copy(first, last, first2, std::equal_to<void*>());
(void)std::upper_bound(first, last, value);
(void)std::upper_bound(first, last, value, std::less<void*>());
return true;
}
void test()
{
all_the_algorithms();
#if TEST_STD_VER > 17
static_assert(all_the_algorithms());
#endif
}
| 5,087 |
1,130 |
<reponame>domesticmouse/SmallerC<filename>v0100/srclib/brktime.c
/*
Copyright (c) 2014, <NAME>
2-clause BSD license.
*/
#include "itime.h"
#ifdef __SMALLER_C_32__
static unsigned short DaysSinceEpoch[]=
{
/*1970*/ 0u, 365u, 730u, 1096u, 1461u, 1826u, 2191u,
/*1977*/ 2557u, 2922u, 3287u, 3652u, 4018u, 4383u, 4748u, 5113u,
/*1985*/ 5479u, 5844u, 6209u, 6574u, 6940u, 7305u, 7670u, 8035u,
/*1993*/ 8401u, 8766u, 9131u, 9496u, 9862u,10227u,10592u,10957u,
/*2001*/ 11323u,11688u,12053u,12418u,12784u,13149u,13514u,13879u,
/*2009*/ 14245u,14610u,14975u,15340u,15706u,16071u,16436u,16801u,
/*2017*/ 17167u,17532u,17897u,18262u,18628u,18993u,19358u,19723u,
/*2025*/ 20089u,20454u,20819u,21184u,21550u,21915u,22280u,22645u,
/*2033*/ 23011u,23376u,23741u,24106u,24472u,24837u,25202u,25567u,
/*2041*/ 25933u,26298u,26663u,27028u,27394u,27759u,28124u,28489u,
/*2049*/ 28855u,29220u,29585u,29950u,30316u,30681u,31046u,31411u,
/*2057*/ 31777u,32142u,32507u,32872u,33238u,33603u,33968u,34333u,
/*2065*/ 34699u,35064u,35429u,35794u,36160u,36525u,36890u,37255u,
/*2073*/ 37621u,37986u,38351u,38716u,39082u,39447u,39812u,40177u,
/*2081*/ 40543u,40908u,41273u,41638u,42004u,42369u,42734u,43099u,
/*2089*/ 43465u,43830u,44195u,44560u,44926u,45291u,45656u,46021u,
/*2097*/ 46387u,46752u,47117u,47482u,47847u,48212u,48577u,48942u,
/*2105*/ 49308u,49673u
};
/*
// Used to generate DaysSinceEpoch[]
void mktab(void)
{
unsigned y, d = 0;
for (y = 1970; y <= 2106; d += 365 + __isleap(y), y++)
printf ("%5uu,", d),
(y%8) ? 0 : printf ("\n /%c%u%c/ ", '*', y+1, '*');
printf ("\n");
}
*/
struct tm* __breaktime(time_t* t)
{
static struct tm tm;
time_t trem = *t;
unsigned daysPassed, lidx, ridx, idx, leap;
if (trem == (time_t)-1)
return NULL;
daysPassed = trem / SECONDS_PER_DAY;
trem -= daysPassed * SECONDS_PER_DAY;
tm.tm_wday = (daysPassed + 4) % 7;
tm.tm_hour = trem / SECONDS_PER_HOUR;
trem -= tm.tm_hour * (time_t)SECONDS_PER_HOUR;
tm.tm_min = trem / SECONDS_PER_MINUTE;
trem -= tm.tm_min * SECONDS_PER_MINUTE;
tm.tm_sec = trem;
// Convert integral amount of days since 1970-Jan-01 to the year:
if (daysPassed >=
DaysSinceEpoch[sizeof(DaysSinceEpoch)/sizeof(DaysSinceEpoch[0])-1])
return NULL;
for (lidx=0, ridx=sizeof(DaysSinceEpoch)/sizeof(DaysSinceEpoch[0])-1;;)
{
idx = (lidx + ridx) >> 1;
if (daysPassed < DaysSinceEpoch[idx])
ridx = idx;
else if (daysPassed >= DaysSinceEpoch[idx+1])
lidx = idx;
else
break;
}
tm.tm_year = 70 + idx;
leap = __isleap(1970 + idx);
daysPassed -= DaysSinceEpoch[idx];
tm.tm_yday = daysPassed;
// Convert integral amount of days since Jan-01 to the month:
for (lidx=0, ridx=sizeof(__DaysSinceJan1st[0])/sizeof(__DaysSinceJan1st[0][0])-1;;)
{
idx = (lidx + ridx) >> 1;
if (daysPassed < __DaysSinceJan1st[leap][idx])
ridx = idx;
else if (daysPassed >= __DaysSinceJan1st[leap][idx+1])
lidx = idx;
else
break;
}
tm.tm_mon = idx;
daysPassed -= __DaysSinceJan1st[leap][idx];
tm.tm_mday = 1 + daysPassed;
tm.tm_isdst = 0; // no daylight saving time
return &tm;
}
#endif
| 1,618 |
392 |
package jetbrick.template.exec.directive;
import jetbrick.template.exec.AbstractJetxTest;
import org.junit.Assert;
import org.junit.Test;
public class DirectiveForTest extends AbstractJetxTest {
@Test
public void testForList() {
Assert.assertEquals("", eval("#for(i:[])${i}#end"));
Assert.assertEquals("123", eval("#for(i:[1,2,3])${i}#end"));
}
@Test
public void testForMap() {
Assert.assertEquals("", eval("#for(i:{})${i}#end"));
Assert.assertEquals("a-1,b-2,", eval("#for(e:{a:1,b:2})${e.key}-${e.value},#end"));
}
@Test
public void testForElse() {
Assert.assertEquals("XX", eval("#for(i:[])${i}#else()XX#end"));
Assert.assertEquals("123", eval("#for(i:[1,2,3])${i}#else()XX#end"));
}
@Test
public void testForStatus() {
Assert.assertEquals("1-true,2-false,3-true,", eval("#for(i:[10,11,12])${for.index}-${for.odd},#end"));
}
@Test
public void testForOuter() {
Assert.assertEquals("1.1,1.2,1.3,2.1,2.2,2.3,", eval("#for(x:[1,2])#for(y:[1,2,3])${for.outer.index}.${for.index},#end#end"));
}
@Test
public void testForComplex() {
StringBuilder sb = new StringBuilder();
sb.append("#for(i:[1,2])");
sb.append("${for.index}-${i},");
sb.append("#for(j:['a','b'])");
sb.append("${for.index}-${j},");
sb.append("#end");
sb.append("#end");
Assert.assertEquals("1-1,1-a,2-b,2-2,1-a,2-b,", eval(sb.toString()));
}
}
| 754 |
1,412 |
#ifdef _WIN32
#include "fs.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define FS_PATH_MAX 1024
bool fs_open(const char* path, OpenMode mode, fs_handle* file) {
WCHAR wpath[FS_PATH_MAX];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, FS_PATH_MAX)) {
return false;
}
DWORD access;
DWORD creation;
switch (mode) {
case OPEN_READ: access = GENERIC_READ; creation = OPEN_EXISTING; break;
case OPEN_WRITE: access = GENERIC_WRITE; creation = CREATE_ALWAYS; break;
case OPEN_APPEND: access = GENERIC_WRITE; creation = OPEN_ALWAYS; break;
default: return false;
}
DWORD share = FILE_SHARE_READ | FILE_SHARE_WRITE;
file->handle = CreateFileW(wpath, access, share, NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL);
if (file->handle == INVALID_HANDLE_VALUE) {
return false;
}
if (mode == OPEN_APPEND && SetFilePointer(file->handle, 0, NULL, FILE_END) == INVALID_SET_FILE_POINTER) {
CloseHandle(file->handle);
return false;
}
return true;
}
bool fs_close(fs_handle file) {
return CloseHandle(file.handle);
}
bool fs_read(fs_handle file, void* buffer, size_t* bytes) {
DWORD bytes32 = *bytes > UINT32_MAX ? UINT32_MAX : (DWORD) *bytes;
bool success = ReadFile(file.handle, buffer, bytes32, &bytes32, NULL);
*bytes = bytes32;
return success;
}
bool fs_write(fs_handle file, const void* buffer, size_t* bytes) {
DWORD bytes32 = *bytes > UINT32_MAX ? UINT32_MAX : (DWORD) *bytes;
bool success = WriteFile(file.handle, buffer, bytes32, &bytes32, NULL);
*bytes = bytes32;
return success;
}
void* fs_map(const char* path, size_t* size) {
WCHAR wpath[FS_PATH_MAX];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, FS_PATH_MAX)) {
return false;
}
fs_handle file;
file.handle = CreateFileW(wpath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file.handle == INVALID_HANDLE_VALUE) {
return NULL;
}
DWORD hi;
DWORD lo = GetFileSize(file.handle, &hi);
if (lo == INVALID_FILE_SIZE) {
CloseHandle(file.handle);
return NULL;
}
if (SIZE_MAX > UINT32_MAX) {
*size = ((size_t) hi << 32) | lo;
} else if (hi > 0) {
CloseHandle(file.handle);
return NULL;
} else {
*size = lo;
}
HANDLE mapping = CreateFileMappingA(file.handle, NULL, PAGE_READONLY, hi, lo, NULL);
if (mapping == NULL) {
CloseHandle(file.handle);
return NULL;
}
void* data = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, *size);
CloseHandle(mapping);
CloseHandle(file.handle);
return data;
}
bool fs_unmap(void* data, size_t size) {
return UnmapViewOfFile(data);
}
bool fs_stat(const char* path, FileInfo* info) {
WCHAR wpath[FS_PATH_MAX];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, FS_PATH_MAX)) {
return false;
}
WIN32_FILE_ATTRIBUTE_DATA attributes;
if (!GetFileAttributesExW(wpath, GetFileExInfoStandard, &attributes)) {
return false;
}
FILETIME lastModified = attributes.ftLastWriteTime;
info->type = (attributes.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? FILE_DIRECTORY : FILE_REGULAR;
info->lastModified = ((uint64_t) lastModified.dwHighDateTime << 32) | lastModified.dwLowDateTime;
info->lastModified /= 10000000ULL; // Convert windows 100ns ticks to seconds
info->lastModified -= 11644473600ULL; // Convert windows epoch (1601) to POSIX epoch (1970)
info->size = ((uint64_t) attributes.nFileSizeHigh << 32) | attributes.nFileSizeLow;
return true;
}
bool fs_remove(const char* path) {
WCHAR wpath[FS_PATH_MAX];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, FS_PATH_MAX)) {
return false;
}
return DeleteFileW(wpath) || RemoveDirectoryW(wpath);
}
bool fs_mkdir(const char* path) {
WCHAR wpath[FS_PATH_MAX];
if (!MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, FS_PATH_MAX)) {
return false;
}
return CreateDirectoryW(wpath, NULL);
}
bool fs_list(const char* path, fs_list_cb* callback, void* context) {
WCHAR wpath[FS_PATH_MAX];
int length = MultiByteToWideChar(CP_UTF8, 0, path, -1, wpath, FS_PATH_MAX);
if (length == 0 || length + 3 >= FS_PATH_MAX) {
return false;
} else {
wcscat(wpath, L"/*");
}
WIN32_FIND_DATAW findData;
HANDLE handle = FindFirstFileW(wpath, &findData);
if (handle == INVALID_HANDLE_VALUE) {
return false;
}
char filename[FS_PATH_MAX];
do {
if (!WideCharToMultiByte(CP_UTF8, 0, findData.cFileName, -1, filename, FS_PATH_MAX, NULL, NULL)) {
FindClose(handle);
return false;
}
callback(context, filename);
} while (FindNextFileW(handle, &findData));
FindClose(handle);
return true;
}
#else // !_WIN32
#include "fs.h"
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <dirent.h>
#include <limits.h>
#include <unistd.h>
bool fs_open(const char* path, OpenMode mode, fs_handle* file) {
int flags;
switch (mode) {
case OPEN_READ: flags = O_RDONLY; break;
case OPEN_WRITE: flags = O_WRONLY | O_CREAT | O_TRUNC; break;
case OPEN_APPEND: flags = O_APPEND | O_WRONLY | O_CREAT; break;
default: return false;
}
file->fd = open(path, flags, S_IRUSR | S_IWUSR);
return file->fd >= 0;
}
bool fs_close(fs_handle file) {
return close(file.fd) == 0;
}
bool fs_read(fs_handle file, void* buffer, size_t* bytes) {
ssize_t result = read(file.fd, buffer, *bytes);
if (result < 0 || result > SSIZE_MAX) {
*bytes = 0;
return false;
} else {
*bytes = (uint32_t) result;
return true;
}
}
bool fs_write(fs_handle file, const void* buffer, size_t* bytes) {
ssize_t result = write(file.fd, buffer, *bytes);
if (result < 0 || result > SSIZE_MAX) {
*bytes = 0;
return false;
} else {
*bytes = (uint32_t) result;
return true;
}
}
void* fs_map(const char* path, size_t* size) {
FileInfo info;
fs_handle file;
if (!fs_stat(path, &info) || !fs_open(path, OPEN_READ, &file)) {
return NULL;
}
*size = info.size;
void* data = mmap(NULL, *size, PROT_READ, MAP_PRIVATE, file.fd, 0);
fs_close(file);
return data;
}
bool fs_unmap(void* data, size_t size) {
return munmap(data, size) == 0;
}
bool fs_stat(const char* path, FileInfo* info) {
struct stat stats;
if (stat(path, &stats)) {
return false;
}
if (info) {
info->size = (uint64_t) stats.st_size;
info->lastModified = (uint64_t) stats.st_mtime;
info->type = S_ISDIR(stats.st_mode) ? FILE_DIRECTORY : FILE_REGULAR;
}
return true;
}
bool fs_remove(const char* path) {
return unlink(path) == 0 || rmdir(path) == 0;
}
bool fs_mkdir(const char* path) {
return mkdir(path, S_IRWXU) == 0;
}
bool fs_list(const char* path, fs_list_cb* callback, void* context) {
DIR* dir = opendir(path);
if (!dir) {
return false;
}
struct dirent* entry;
while ((entry = readdir(dir)) != NULL) {
callback(context, entry->d_name);
}
closedir(dir);
return true;
}
#endif
| 2,766 |
892 |
<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-4v94-xg8j-pp22",
"modified": "2022-05-13T01:11:48Z",
"published": "2022-05-13T01:11:48Z",
"aliases": [
"CVE-2017-12982"
],
"details": "The bmp_read_info_header function in bin/jp2/convertbmp.c in OpenJPEG 2.2.0 does not reject headers with a zero biBitCount, which allows remote attackers to cause a denial of service (memory allocation failure) in the opj_image_create function in lib/openjp2/image.c, related to the opj_aligned_alloc_n function in opj_malloc.c.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2017-12982"
},
{
"type": "WEB",
"url": "https://github.com/uclouvain/openjpeg/issues/983"
},
{
"type": "WEB",
"url": "https://github.com/uclouvain/openjpeg/commit/baf0c1ad4572daa89caa3b12985bdd93530f0dd7"
},
{
"type": "WEB",
"url": "https://blogs.gentoo.org/ago/2017/08/14/openjpeg-memory-allocation-failure-in-opj_aligned_alloc_n-opj_malloc-c/"
},
{
"type": "WEB",
"url": "https://security.gentoo.org/glsa/201710-26"
}
],
"database_specific": {
"cwe_ids": [
"CWE-119"
],
"severity": "MODERATE",
"github_reviewed": false
}
}
| 700 |
777 |
<filename>device/usb/android/java/src/org/chromium/device/usb/ChromeUsbService.java<gh_stars>100-1000
// Copyright 2015 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.device.usb;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import org.chromium.base.Log;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import java.util.HashMap;
/**
* Exposes android.hardware.usb.UsbManager as necessary for C++
* device::UsbServiceAndroid.
*
* Lifetime is controlled by device::UsbServiceAndroid.
*/
@JNINamespace("device")
final class ChromeUsbService {
private static final String TAG = "Usb";
private static final String ACTION_USB_PERMISSION = "org.chromium.device.ACTION_USB_PERMISSION";
Context mContext;
long mUsbServiceAndroid;
UsbManager mUsbManager;
BroadcastReceiver mUsbDeviceReceiver;
private ChromeUsbService(Context context, long usbServiceAndroid) {
mContext = context;
mUsbServiceAndroid = usbServiceAndroid;
mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
registerForUsbDeviceIntentBroadcast();
Log.v(TAG, "ChromeUsbService created.");
}
@CalledByNative
private static ChromeUsbService create(Context context, long usbServiceAndroid) {
return new ChromeUsbService(context, usbServiceAndroid);
}
@CalledByNative
private Object[] getDevices() {
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
return deviceList.values().toArray();
}
@CalledByNative
private UsbDeviceConnection openDevice(ChromeUsbDevice wrapper) {
UsbDevice device = wrapper.getDevice();
return mUsbManager.openDevice(device);
}
@CalledByNative
private void requestDevicePermission(ChromeUsbDevice wrapper, long nativeCallback) {
UsbDevice device = wrapper.getDevice();
if (mUsbManager.hasPermission(device)) {
nativeDevicePermissionRequestComplete(mUsbServiceAndroid, device.getDeviceId(), true);
} else {
PendingIntent intent =
PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
mUsbManager.requestPermission(wrapper.getDevice(), intent);
}
}
@CalledByNative
private void close() {
unregisterForUsbDeviceIntentBroadcast();
}
private native void nativeDeviceAttached(long nativeUsbServiceAndroid, UsbDevice device);
private native void nativeDeviceDetached(long nativeUsbServiceAndroid, int deviceId);
private native void nativeDevicePermissionRequestComplete(
long nativeUsbServiceAndroid, int deviceId, boolean granted);
private void registerForUsbDeviceIntentBroadcast() {
mUsbDeviceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(intent.getAction())) {
nativeDeviceAttached(mUsbServiceAndroid, device);
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(intent.getAction())) {
nativeDeviceDetached(mUsbServiceAndroid, device.getDeviceId());
} else if (ACTION_USB_PERMISSION.equals(intent.getAction())) {
nativeDevicePermissionRequestComplete(mUsbServiceAndroid, device.getDeviceId(),
intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false));
}
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(ACTION_USB_PERMISSION);
mContext.registerReceiver(mUsbDeviceReceiver, filter);
}
private void unregisterForUsbDeviceIntentBroadcast() {
mContext.unregisterReceiver(mUsbDeviceReceiver);
mUsbDeviceReceiver = null;
}
}
| 1,705 |
716 |
<filename>src/WindowsUtils/SafeHandleTest.cpp<gh_stars>100-1000
// Copyright (c) 2022 The Orbit 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 <absl/base/casts.h>
#include <gtest/gtest.h>
#include "OrbitBase/ThreadUtils.h"
#include "WindowsUtils/OpenProcess.h"
#include "WindowsUtils/SafeHandle.h"
using orbit_windows_utils::SafeHandle;
TEST(SafeHandle, OwnershipTransfer) {
auto result = orbit_windows_utils::OpenProcessForReading(orbit_base::GetCurrentProcessId());
ASSERT_TRUE(result.has_value());
SafeHandle safe_handle = std::move(result.value());
}
TEST(SafeHandle, NullHandle) { SafeHandle safe_handle(nullptr); }
TEST(SafeHandle, DoubleCloseError) {
HANDLE handle = nullptr;
{
auto result = orbit_windows_utils::OpenProcessForReading(orbit_base::GetCurrentProcessId());
ASSERT_TRUE(result.has_value());
SafeHandle& safe_handle = result.value();
handle = safe_handle.get();
}
// CloseHandle returns 0 on error.
EXPECT_EQ(CloseHandle(handle), 0);
}
| 363 |
1,679 |
<reponame>morganelectronics/raceway_STM32<gh_stars>1000+
/**
******************************************************************************
* @file stm32l0xx_hal_lptim_ex.h
* @author MCD Application Team
* @brief Header file of LPTIM Extended HAL module.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* 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 STMicroelectronics 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.
*
******************************************************************************
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32L0xx_HAL_LPTIM_EX_H
#define __STM32L0xx_HAL_LPTIM_EX_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32l0xx_hal_def.h"
/** @addtogroup STM32L0xx_HAL_Driver
* @{
*/
/** @defgroup LPTIMEx LPTIMEx
* @{
*/
/* Exported constants --------------------------------------------------------*/
/** @defgroup LPTIMEx_Exported_Constants LPTIMEx Exported Constants
* @{
*/
/** @defgroup LPTIM_Trigger_Source Trigger source
* @{
*/
#define LPTIM_TRIGSOURCE_SOFTWARE ((uint32_t)0x0000FFFFU)
#define LPTIM_TRIGSOURCE_0 ((uint32_t)0x00000000U)
#define LPTIM_TRIGSOURCE_1 ((uint32_t)LPTIM_CFGR_TRIGSEL_0)
#define LPTIM_TRIGSOURCE_2 LPTIM_CFGR_TRIGSEL_1
#define LPTIM_TRIGSOURCE_3 ((uint32_t)LPTIM_CFGR_TRIGSEL_0 | LPTIM_CFGR_TRIGSEL_1)
#define LPTIM_TRIGSOURCE_4 LPTIM_CFGR_TRIGSEL_2
#if defined (STM32L083xx) || defined (STM32L082xx) || defined (STM32L081xx) || \
defined (STM32L073xx) || defined (STM32L072xx) || defined (STM32L071xx) || \
defined (STM32L031xx) || defined (STM32L041xx)
#define LPTIM_TRIGSOURCE_5 ((uint32_t)LPTIM_CFGR_TRIGSEL_0 | LPTIM_CFGR_TRIGSEL_2)
#endif
#define LPTIM_TRIGSOURCE_6 ((uint32_t)LPTIM_CFGR_TRIGSEL_1 | LPTIM_CFGR_TRIGSEL_2)
#define LPTIM_TRIGSOURCE_7 LPTIM_CFGR_TRIGSEL
/**
* @}
*/
/**
* @}
*/
/** @addtogroup LPTIMEx_Private
* @{
*/
#if defined (STM32L083xx) || defined (STM32L082xx) || defined (STM32L081xx) || \
defined (STM32L073xx) || defined (STM32L072xx) || defined (STM32L071xx) || \
defined (STM32L031xx) || defined (STM32L041xx)
#define IS_LPTIM_TRG_SOURCE(__TRIG__) (((__TRIG__) == LPTIM_TRIGSOURCE_SOFTWARE) || \
((__TRIG__) == LPTIM_TRIGSOURCE_0) || \
((__TRIG__) == LPTIM_TRIGSOURCE_1) || \
((__TRIG__) == LPTIM_TRIGSOURCE_2) || \
((__TRIG__) == LPTIM_TRIGSOURCE_3) || \
((__TRIG__) == LPTIM_TRIGSOURCE_4) || \
((__TRIG__) == LPTIM_TRIGSOURCE_5) || \
((__TRIG__) == LPTIM_TRIGSOURCE_6) || \
((__TRIG__) == LPTIM_TRIGSOURCE_7))
#else
#define IS_LPTIM_TRG_SOURCE(__TRIG__) (((__TRIG__) == LPTIM_TRIGSOURCE_SOFTWARE) || \
((__TRIG__) == LPTIM_TRIGSOURCE_0) || \
((__TRIG__) == LPTIM_TRIGSOURCE_1) || \
((__TRIG__) == LPTIM_TRIGSOURCE_2) || \
((__TRIG__) == LPTIM_TRIGSOURCE_3) || \
((__TRIG__) == LPTIM_TRIGSOURCE_4) || \
((__TRIG__) == LPTIM_TRIGSOURCE_6) || \
((__TRIG__) == LPTIM_TRIGSOURCE_7))
#endif
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
#ifdef __cplusplus
}
#endif
#endif /* __STM32L0xx_HAL_LPTIM_EX_H */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 2,865 |
348 |
<reponame>chamberone/Leaflet.PixiOverlay
{"nom":"<NAME>","dpt":"Alpes-de-Haute-Provence","inscrits":63,"abs":26,"votants":37,"blancs":2,"nuls":2,"exp":33,"res":[{"panneau":"2","voix":17},{"panneau":"1","voix":16}]}
| 95 |
957 |
<filename>Dev/Cpp/EffekseerRendererDX9/EffekseerRenderer/EffekseerRendererDX9.RenderState.cpp
//----------------------------------------------------------------------------------
// Include
//----------------------------------------------------------------------------------
#include "EffekseerRendererDX9.RenderState.h"
#include "EffekseerRendererDX9.RendererImplemented.h"
//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
namespace EffekseerRendererDX9
{
//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
RenderState::RenderState(RendererImplemented* renderer)
: m_renderer(renderer)
{
}
//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
RenderState::~RenderState()
{
}
//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
void RenderState::Update(bool forced)
{
if (m_active.DepthTest != m_next.DepthTest || forced)
{
if (m_next.DepthTest)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_ZENABLE, TRUE);
}
else
{
m_renderer->GetDevice()->SetRenderState(D3DRS_ZENABLE, FALSE);
}
}
if (m_active.DepthWrite != m_next.DepthWrite || forced)
{
if (m_next.DepthWrite)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
}
else
{
m_renderer->GetDevice()->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
}
}
if (m_active.CullingType != m_next.CullingType || forced)
{
if (m_next.CullingType == ::Effekseer::CullingType::Front)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
}
else if (m_next.CullingType == ::Effekseer::CullingType::Back)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
}
else if (m_next.CullingType == ::Effekseer::CullingType::Double)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
}
}
if (m_active.AlphaBlend != m_next.AlphaBlend || forced)
{
if (m_next.AlphaBlend == ::Effekseer::AlphaBlendType::Opacity || m_renderer->GetRenderMode() == ::Effekseer::RenderMode::Wireframe)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
m_renderer->GetDevice()->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
m_renderer->GetDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO);
m_renderer->GetDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
m_renderer->GetDevice()->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_ONE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ONE);
m_renderer->GetDevice()->SetRenderState(D3DRS_BLENDOPALPHA, D3DBLENDOP_MAX);
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHAREF, 0);
}
else if (m_next.AlphaBlend == ::Effekseer::AlphaBlendType::Blend)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
m_renderer->GetDevice()->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
m_renderer->GetDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
m_renderer->GetDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHAREF, 0);
}
else if (m_next.AlphaBlend == ::Effekseer::AlphaBlendType::Add)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
m_renderer->GetDevice()->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
m_renderer->GetDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHAREF, 0);
}
else if (m_next.AlphaBlend == ::Effekseer::AlphaBlendType::Sub)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
m_renderer->GetDevice()->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_REVSUBTRACT);
m_renderer->GetDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
m_renderer->GetDevice()->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_ONE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ZERO);
m_renderer->GetDevice()->SetRenderState(D3DRS_BLENDOPALPHA, D3DBLENDOP_ADD);
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHAREF, 0);
}
else if (m_next.AlphaBlend == ::Effekseer::AlphaBlendType::Mul)
{
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
m_renderer->GetDevice()->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
m_renderer->GetDevice()->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR);
m_renderer->GetDevice()->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
m_renderer->GetDevice()->SetRenderState(D3DRS_DESTBLENDALPHA, D3DBLEND_ONE);
m_renderer->GetDevice()->SetRenderState(D3DRS_SRCBLENDALPHA, D3DBLEND_ZERO);
m_renderer->GetDevice()->SetRenderState(D3DRS_BLENDOPALPHA, D3DBLENDOP_ADD);
m_renderer->GetDevice()->SetRenderState(D3DRS_ALPHAREF, 0);
}
}
for (int32_t i = 0; i < Effekseer::TextureSlotMax; i++)
{
if (m_active.TextureFilterTypes[i] != m_next.TextureFilterTypes[i] || forced)
{
const uint32_t MinFilterTable[] = {
D3DTEXF_POINT,
D3DTEXF_LINEAR,
};
const uint32_t MagFilterTable[] = {
D3DTEXF_POINT,
D3DTEXF_LINEAR,
};
const uint32_t MipFilterTable[] = {
D3DTEXF_NONE,
D3DTEXF_LINEAR,
};
int32_t filter_ = (int32_t)m_next.TextureFilterTypes[i];
// VTF is not supported
m_renderer->GetDevice()->SetSamplerState(i, D3DSAMP_MINFILTER, MinFilterTable[filter_]);
m_renderer->GetDevice()->SetSamplerState(i, D3DSAMP_MAGFILTER, MagFilterTable[filter_]);
m_renderer->GetDevice()->SetSamplerState(i, D3DSAMP_MIPFILTER, MipFilterTable[filter_]);
}
if (m_active.TextureWrapTypes[i] != m_next.TextureWrapTypes[i] || forced)
{
// for VTF
if (i < 4)
{
m_renderer->GetDevice()->SetSamplerState(
i + D3DVERTEXTEXTURESAMPLER0,
D3DSAMP_ADDRESSU,
m_next.TextureWrapTypes[i] == ::Effekseer::TextureWrapType::Repeat ? D3DTADDRESS_WRAP : D3DTADDRESS_CLAMP);
m_renderer->GetDevice()->SetSamplerState(
i + D3DVERTEXTEXTURESAMPLER0,
D3DSAMP_ADDRESSV,
m_next.TextureWrapTypes[i] == ::Effekseer::TextureWrapType::Repeat ? D3DTADDRESS_WRAP : D3DTADDRESS_CLAMP);
}
m_renderer->GetDevice()->SetSamplerState(
i,
D3DSAMP_ADDRESSU,
m_next.TextureWrapTypes[i] == ::Effekseer::TextureWrapType::Repeat ? D3DTADDRESS_WRAP : D3DTADDRESS_CLAMP);
m_renderer->GetDevice()->SetSamplerState(
i,
D3DSAMP_ADDRESSV,
m_next.TextureWrapTypes[i] == ::Effekseer::TextureWrapType::Repeat ? D3DTADDRESS_WRAP : D3DTADDRESS_CLAMP);
}
}
m_active = m_next;
}
//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
} // namespace EffekseerRendererDX9
//-----------------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------------
| 3,181 |
854 |
<gh_stars>100-1000
__________________________________________________________________________________________________
sample 0 ms submission
class Solution {
public void moveZeroes(int[] nums) {
if(nums == null)
return;
int pos1 = 0;
int pos2 = 0;
while(pos2 < nums.length){
if(nums[pos2] == 0){
++pos2;
continue;
}
if(pos1 != pos2)
swap(nums, pos1, pos2);
++pos1;
++pos2;
}
}
private void swap(int[] arr, int pos1, int pos2){
int cache = arr[pos1];
arr[pos1] = arr[pos2];
arr[pos2] = cache;
}
}
__________________________________________________________________________________________________
sample 35036 kb submission
class Solution {
public void moveZeroes(int[] nums) {
Integer[] n = Arrays.stream( nums ).boxed().toArray( Integer[]::new );
Arrays.sort(n, (a,b)->{
if(a==0) return 1;
if(b==0) return -1;
return 0;
});
for(int i=0;i<n.length;i++){
nums[i]=n[i];
}
}
}
__________________________________________________________________________________________________
| 609 |
1,013 |
/*!
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
*/
#pragma once
#include <pyclustering/cluster/clique_block.hpp>
#include <pyclustering/cluster/cluster_data.hpp>
namespace pyclustering {
namespace clst {
/*!
@brief Sequence container where CLIQUE blocks are stored.
*/
using clique_block_sequence = std::vector<clique_block>;
/*!
@class clique_data clique_data.hpp pyclustering/cluster/clique_data.hpp
@brief A storage where CLIQUE clustering results are stored.
*/
class clique_data : public cluster_data {
private:
clique_block_sequence m_blocks;
clst::noise m_noise;
public:
/*!
@brief Returns constant reference to CLIQUE blocks that are formed during clustering process.
*/
const clique_block_sequence & blocks() const { return m_blocks; }
/*!
@brief Returns reference to CLIQUE blocks that are formed during clustering process.
*/
clique_block_sequence & blocks() { return m_blocks; }
/*!
@brief Returns constant reference to outliers that are allocated during clustering process.
*/
const clst::noise & noise() const { return m_noise; }
/*!
@brief Returns reference to outliers that are allocated during clustering process.
*/
clst::noise & noise() { return m_noise; }
};
}
}
| 571 |
930 |
<reponame>leven-space/matecloud
package vip.mate.core.auth.util;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import vip.mate.core.common.entity.LoginUser;
/**
* 安全服务工具类
*
* @author pangu
*/
@UtilityClass
public class MateAuthUser {
/**
* 获取Authentication
*/
private Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();
}
/**
* 获取用户
*/
public LoginUser getUser() {
Authentication authentication = getAuthentication();
return getUser(authentication);
}
/**
* 获取用户
*
* @param authentication 用户认证
* @return 登录用户
*/
public LoginUser getUser(Authentication authentication) {
Object principal = authentication.getPrincipal();
if (principal instanceof LoginUser) {
return (LoginUser) principal;
}
return null;
}
/**
* 获取用户名称
*
* @return username
*/
public String getUsername() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return null;
}
return authentication.getName();
}
}
| 437 |
582 |
<gh_stars>100-1000
/**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor.diagram.actions;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.ui.actions.SelectionAction;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchPart;
import com.archimatetool.editor.ui.services.ViewManager;
import com.archimatetool.editor.views.tree.ITreeModelView;
import com.archimatetool.model.IDiagramModel;
import com.archimatetool.model.IDiagramModelArchimateComponent;
import com.archimatetool.model.IDiagramModelArchimateConnection;
import com.archimatetool.model.IDiagramModelArchimateObject;
/**
* Action to select the current element in the Tree
*
* @author <NAME>
*/
public class SelectElementInTreeAction extends SelectionAction {
public static final String ID = "SelectElementInTreeAction"; //$NON-NLS-1$
public SelectElementInTreeAction(IWorkbenchPart part) {
super(part);
setText(Messages.SelectElementInTreeAction_0);
setId(ID);
setToolTipText(Messages.SelectElementInTreeAction_1);
}
@Override
public void run() {
List<?> selection = getSelectedObjects();
List<Object> elements = new ArrayList<Object>();
for(Object object : selection) {
if(object instanceof EditPart) {
Object model = ((EditPart)object).getModel();
if(model instanceof IDiagramModel) {
elements.add(model);
}
else if(model instanceof IDiagramModelArchimateComponent) {
elements.add(((IDiagramModelArchimateComponent)model).getArchimateConcept());
}
}
}
ITreeModelView view = (ITreeModelView)ViewManager.showViewPart(ITreeModelView.ID, true);
if(view != null) {
view.getViewer().setSelection(new StructuredSelection(elements), true);
}
}
@Override
protected boolean calculateEnabled() {
List<?> list = getSelectedObjects();
if(list.isEmpty()) {
return false;
}
for(Object object : list) {
if(object instanceof EditPart) {
Object model = ((EditPart)object).getModel();
if(model instanceof IDiagramModel || model instanceof IDiagramModelArchimateConnection || model instanceof IDiagramModelArchimateObject) {
return true;
}
}
}
return false;
}
}
| 1,233 |
2,990 |
/**
GDevelop - Tiled Sprite Extension
Copyright (c) 2012-2016 <NAME> (<EMAIL>)
Copyright (c) 2014-2016 <NAME> (<EMAIL>)
This project is released under the MIT License.
*/
#include "GDCore/Tools/Localization.h"
#include "GDCore/CommonTools.h"
#include "GDCore/Project/InitialInstance.h"
#include "GDCore/Project/Object.h"
#include "GDCore/Project/Project.h"
#include "GDCore/Serialization/SerializerElement.h"
#include "TiledSpriteObject.h"
#if defined(GD_IDE_ONLY)
#include "GDCore/IDE/Project/ArbitraryResourceWorker.h"
#endif
using namespace std;
TiledSpriteObject::TiledSpriteObject(gd::String name_)
: Object(name_), textureName(""), width(32), height(32) {}
void TiledSpriteObject::DoUnserializeFrom(
gd::Project& project, const gd::SerializerElement& element) {
textureName = element.GetStringAttribute("texture");
width = element.GetDoubleAttribute("width", 128);
height = element.GetDoubleAttribute("height", 128);
}
#if defined(GD_IDE_ONLY)
void TiledSpriteObject::DoSerializeTo(gd::SerializerElement& element) const {
element.SetAttribute("texture", textureName);
element.SetAttribute("width", width);
element.SetAttribute("height", height);
}
void TiledSpriteObject::ExposeResources(gd::ArbitraryResourceWorker& worker) {
worker.ExposeImage(textureName);
}
#endif
| 432 |
6,119 |
from functools import reduce
from autograd.core import vspace
from autograd.numpy.numpy_vspaces import ArrayVSpace
from autograd.test_util import check_grads, scalar_close
import numpy as np
import itertools as it
def check_vspace(value):
vs = vspace(value)
# --- required attributes ---
size = vs.size
add = vs.add
scalar_mul = vs.scalar_mul
inner_prod = vs.inner_prod
randn = vs.randn
zeros = vs.zeros
ones = vs.ones
standard_basis = vs.standard_basis
# --- util ---
def randns(N=2):
return [randn() for i in range(N)]
def rand_scalar():
return float(np.random.randn())
def rand_scalars(N=2):
return [rand_scalar() for i in range(N)]
def vector_close(x, y):
z = randn()
return scalar_close(inner_prod(z, x), inner_prod(z, y))
# --- vector space axioms ---
def associativity_of_add(x, y, z):
return vector_close(add(x, add(y, z)),
add(add(x, y), z))
def commutativity_of_add(x, y):
return vector_close(add(x, y), add(y, x))
def identity_element_of_add(x):
return vector_close(add(zeros(), x), x)
def inverse_elements_of_add(x):
return vector_close(zeros(), add(x, scalar_mul(x, -1.0)))
def compatibility_of_scalar_mul_with_field_mul(x, a, b):
return vector_close(scalar_mul(x, a * b),
scalar_mul(scalar_mul(x, a), b))
def identity_element_of_scalar_mul(x):
return vector_close(scalar_mul(x, 1.0), x)
def distributivity_of_scalar_mul_wrt_vector_add(x, y, a):
return vector_close(scalar_mul(add(x, y), a),
add(scalar_mul(x, a),
scalar_mul(y, a)))
def distributivity_of_scalar_mul_wrt_scalar_add(x, a, b):
return vector_close(scalar_mul(x, a + b),
add(scalar_mul(x, a),
scalar_mul(x, b)))
# --- closure ---
def add_preserves_vspace(x, y):
return vs == vspace(add(x, y))
def scalar_mul_preserves_vspace(x, a):
return vs == vspace(scalar_mul(x, a))
# --- inner product axioms ---
def symmetry(x, y): return scalar_close(inner_prod(x, y), inner_prod(y, x))
def linearity(x, y, a): return scalar_close(inner_prod(scalar_mul(x, a), y),
a * inner_prod(x, y))
def positive_definitive(x): return 0 < inner_prod(x, x)
def inner_zeros(): return scalar_close(0, inner_prod(zeros(), zeros()))
# --- basis vectors and special vectors---
def basis_orthonormality():
return all(
[scalar_close(inner_prod(x, y), 1.0 * (ix == iy))
for (ix, x), (iy, y) in it.product(enumerate(standard_basis()),
enumerate(standard_basis()))])
def ones_sum_of_basis_vects():
return vector_close(reduce(add, standard_basis()), ones())
def basis_correct_size():
return len(list(standard_basis())) == size
def basis_correct_vspace():
return (vs == vspace(x) for x in standard_basis())
def zeros_correct_vspace():
return vs == vspace(zeros())
def ones_correct_vspace():
return vs == vspace(ones())
def randn_correct_vspace():
return vs == vspace(randn())
assert associativity_of_add(*randns(3))
assert commutativity_of_add(*randns())
assert identity_element_of_add(randn())
assert inverse_elements_of_add(randn())
assert compatibility_of_scalar_mul_with_field_mul(randn(), *rand_scalars())
assert identity_element_of_scalar_mul(randn())
assert distributivity_of_scalar_mul_wrt_vector_add(randn(), randn(), rand_scalar())
assert distributivity_of_scalar_mul_wrt_scalar_add(randn(), *rand_scalars())
assert add_preserves_vspace(*randns())
assert scalar_mul_preserves_vspace(randn(), rand_scalar())
assert symmetry(*randns())
assert linearity(randn(), randn(), rand_scalar())
assert positive_definitive(randn())
assert inner_zeros()
assert basis_orthonormality()
assert ones_sum_of_basis_vects()
assert basis_correct_size()
assert basis_correct_vspace()
assert zeros_correct_vspace()
assert ones_correct_vspace()
assert randn_correct_vspace()
# --- grads of basic operations ---
check_grads(add)(*randns())
check_grads(scalar_mul)(randn(), rand_scalar())
check_grads(inner_prod)(*randns())
def test_array_vspace(): check_vspace(np.zeros((3,2)))
def test_array_vspace_0_dim(): check_vspace(0.0)
def test_array_vspace_complex(): check_vspace(1.0j*np.zeros((2,1)))
def test_list_vspace(): check_vspace([1.0, np.zeros((2,1))])
def test_tuple_vspace(): check_vspace((1.0, np.zeros((2,1))))
def test_dict_vspace(): check_vspace({'a': 1.0, 'b': np.zeros((2,1))})
def test_mixed_vspace(): check_vspace({'x' : [0.0, np.zeros((3,1))],
'y' : ({'a' : 0.0}, [0.0])})
| 2,408 |
5,169 |
{
"name": "ViewStates",
"version": "1.0.0",
"summary": "ViewStates makes it easier to create a view with loading, success, no data and error states",
"swift_version": "4.0",
"description": "ViewStates makes it easier to create a view with loading, success, no data and error states. It also has an action button, so that we can do some action such as navigate to other view, or retry an async task. The UI can be customized easily.",
"homepage": "https://github.com/thanhtanh/ViewStates",
"screenshots": "https://github.com/thanhtanh/ViewStates/raw/master/images/custom_theme.gif",
"license": {
"type": "MIT",
"file": "LICENSE"
},
"authors": {
"<EMAIL>": "<EMAIL>"
},
"source": {
"git": "https://github.com/thanhtanh/ViewStates.git",
"tag": "1.0.0"
},
"platforms": {
"ios": "9.0"
},
"source_files": "ViewStates/Classes/**/*"
}
| 317 |
14,668 |
// 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.
package org.chromium.android_webview.test.util;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeMethods;
/**
* Utilities for force recording memory metrics.
*/
@JNINamespace("android_webview")
public class MemoryMetricsLoggerUtils {
@NativeMethods
public interface Natives {
/**
* Calls to MemoryMetricsLogger to force recording histograms, returning true on success.
* A value of false means recording failed (most likely because process metrics not
* available.
*/
boolean forceRecordHistograms();
}
}
| 250 |
2,757 |
/*++
Copyright (c) 2004 - 2016, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
Module Name:
BsDataHubStatusCode.c
Abstract:
This implements a status code listener that logs status codes into the data
hub. This is only active during non-runtime DXE.
The status codes are recorded in a extensible buffer, and a event is signalled
to log them to the data hub. The recorder is the producer of the status code in
buffer and the event notify function the consumer.
--*/
#include "BsDataHubStatusCode.h"
//
// Initialize FIFO to cache records.
//
STATIC EFI_LIST_ENTRY mRecordsFifo = INITIALIZE_LIST_HEAD_VARIABLE (mRecordsFifo);
STATIC EFI_LIST_ENTRY mRecordsBuffer = INITIALIZE_LIST_HEAD_VARIABLE (mRecordsBuffer);
STATIC EFI_EVENT mLogDataHubEvent;
STATIC BOOLEAN mEventHandlerActive = FALSE;
//
// Cache data hub protocol.
//
STATIC EFI_DATA_HUB_PROTOCOL *mDataHubProtocol;
STATIC
DATA_HUB_STATUS_CODE_DATA_RECORD *
AcquireRecordBuffer (
VOID
)
/*++
Routine Description:
Return one DATAHUB_STATUSCODE_RECORD space.
The size of free record pool would be extend, if the pool is empty.
Arguments:
None
Returns:
A pointer to the new allocated node or NULL if non available
--*/
{
DATAHUB_STATUSCODE_RECORD *Record;
EFI_TPL CurrentTpl;
EFI_LIST_ENTRY *Node;
UINT32 Index;
Record = NULL;
CurrentTpl = gBS->RaiseTPL (EFI_TPL_HIGH_LEVEL);
if (!IsListEmpty (&mRecordsBuffer)) {
Node = GetFirstNode (&mRecordsBuffer);
RemoveEntryList (Node);
Record = _CR (Node, DATAHUB_STATUSCODE_RECORD, Node);
} else {
if (CurrentTpl > EFI_TPL_NOTIFY) {
gBS->RestoreTPL (CurrentTpl);
return NULL;
}
gBS->RestoreTPL (CurrentTpl);
gBS->AllocatePool (EfiBootServicesData, sizeof (DATAHUB_STATUSCODE_RECORD) * 16, (VOID **) &Record);
if (Record == NULL) {
return NULL;
}
EfiCommonLibZeroMem (Record, sizeof (DATAHUB_STATUSCODE_RECORD) * 16);
CurrentTpl = gBS->RaiseTPL (EFI_TPL_HIGH_LEVEL);
for (Index = 1; Index < 16; Index++) {
InsertTailList (&mRecordsBuffer, &Record[Index].Node);
}
}
Record->Signature = BS_DATA_HUB_STATUS_CODE_SIGNATURE;
InsertTailList (&mRecordsFifo, &Record->Node);
gBS->RestoreTPL (CurrentTpl);
return (DATA_HUB_STATUS_CODE_DATA_RECORD *) (Record->Data);
}
STATIC
DATA_HUB_STATUS_CODE_DATA_RECORD *
RetrieveRecord (
VOID
)
/*++
Routine Description:
Retrieve one record from Records FIFO. The record would be removed from FIFO and
release to free record buffer.
Arguments:
None
Returns:
Point to record which is ready to be logged, or NULL if the FIFO of record is empty.
--*/
{
DATA_HUB_STATUS_CODE_DATA_RECORD *RecordData;
DATAHUB_STATUSCODE_RECORD *Record;
EFI_LIST_ENTRY *Node;
EFI_TPL CurrentTpl;
RecordData = NULL;
CurrentTpl = gBS->RaiseTPL (EFI_TPL_HIGH_LEVEL);
if (!IsListEmpty (&mRecordsFifo)) {
Node = GetFirstNode (&mRecordsFifo);
Record = CR (Node, DATAHUB_STATUSCODE_RECORD, Node, BS_DATA_HUB_STATUS_CODE_SIGNATURE);
RemoveEntryList (&Record->Node);
InsertTailList (&mRecordsBuffer, &Record->Node);
Record->Signature = 0;
RecordData = (DATA_HUB_STATUS_CODE_DATA_RECORD *) Record->Data;
}
gBS->RestoreTPL (CurrentTpl);
return RecordData;
}
EFI_STATUS
EFIAPI
BsDataHubReportStatusCode (
IN EFI_STATUS_CODE_TYPE CodeType,
IN EFI_STATUS_CODE_VALUE Value,
IN UINT32 Instance,
IN EFI_GUID * CallerId,
IN EFI_STATUS_CODE_DATA * Data OPTIONAL
)
/*++
Routine Description:
Boot service report status code listener. This function logs the status code
into the data hub.
Arguments:
Same as gRT->ReportStatusCode (See Tiano Runtime Specification)
Returns:
None
--*/
{
DATA_HUB_STATUS_CODE_DATA_RECORD *Record;
UINT32 ErrorLevel;
VA_LIST Marker;
CHAR8 *Format;
CHAR16 FormatBuffer[BYTES_PER_RECORD];
UINTN Index;
//
// See whether in runtime phase or not.
//
if (EfiAtRuntime ()) {
//
// For now all we do is post code at runtime
//
return EFI_SUCCESS;
}
//
// Discard new DataHubRecord caused by DataHub->LogData()
//
if (mEventHandlerActive) {
return EFI_SUCCESS;
}
Record = AcquireRecordBuffer ();
if (Record == NULL) {
//
// There are no empty record buffer in private buffers
//
return EFI_OUT_OF_RESOURCES;
}
//
// Construct Data Hub Extended Data
//
Record->CodeType = CodeType;
Record->Value = Value;
Record->Instance = Instance;
if (CallerId != NULL) {
EfiCopyMem (&Record->CallerId, CallerId, sizeof (EFI_GUID));
}
if (Data != NULL) {
if (ReportStatusCodeExtractDebugInfo (Data, &ErrorLevel, &Marker, &Format)) {
//
// Convert Ascii Format string to Unicode.
//
for (Index = 0; Format[Index] != '\0' && Index < (BYTES_PER_RECORD - 1); Index += 1) {
FormatBuffer[Index] = (CHAR16) Format[Index];
}
FormatBuffer[Index] = L'\0';
//
// Put processed string into the buffer
//
Index = VSPrint (
(CHAR16 *) (Record + 1),
BYTES_PER_RECORD - (sizeof (DATA_HUB_STATUS_CODE_DATA_RECORD)),
FormatBuffer,
Marker
);
EfiCopyMem (&Record->Data.Type, &gEfiStatusCodeDataTypeDebugGuid, sizeof (EFI_GUID));
Record->Data.HeaderSize = Data->HeaderSize;
Record->Data.Size = (UINT16) (Index * sizeof (CHAR16));
} else {
//
// Copy status code data header
//
EfiCopyMem (&Record->Data, Data, sizeof (EFI_STATUS_CODE_DATA));
if (Data->Size > BYTES_PER_RECORD - sizeof (DATA_HUB_STATUS_CODE_DATA_RECORD)) {
Record->Data.Size = (UINT16) (BYTES_PER_RECORD - sizeof (DATA_HUB_STATUS_CODE_DATA_RECORD));
}
EfiCopyMem ((VOID *) (Record + 1), Data + 1, Record->Data.Size);
}
}
gBS->SignalEvent (mLogDataHubEvent);
return EFI_SUCCESS;
}
VOID
EFIAPI
LogDataHubEventHandler (
IN EFI_EVENT Event,
IN VOID *Context
)
/*++
Routine Description:
The Event handler which will be notified to log data in Data Hub.
Arguments:
Event - Instance of the EFI_EVENT to signal whenever data is
available to be logged in the system.
Context - Context of the event.
Returns:
None.
--*/
{
DATA_HUB_STATUS_CODE_DATA_RECORD *Record;
UINT32 Size;
UINT64 DataRecordClass;
//
// Set global flag so we don't recurse if DataHub->LogData eventually causes new DataHubRecord
//
mEventHandlerActive = TRUE;
//
// Log DataRecord in Data Hub.
// Journal records fifo to find all record entry.
//
while (1) {
Record = RetrieveRecord ();
if (Record == NULL) {
break;
}
//
// Add in the size of the header we added.
//
Size = sizeof (DATA_HUB_STATUS_CODE_DATA_RECORD) + (UINT32) Record->Data.Size;
if ((Record->CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_PROGRESS_CODE) {
DataRecordClass = EFI_DATA_RECORD_CLASS_PROGRESS_CODE;
} else if ((Record->CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_ERROR_CODE) {
DataRecordClass = EFI_DATA_RECORD_CLASS_ERROR;
} else if ((Record->CodeType & EFI_STATUS_CODE_TYPE_MASK) == EFI_DEBUG_CODE) {
DataRecordClass = EFI_DATA_RECORD_CLASS_DEBUG;
} else {
//
// Should never get here.
//
DataRecordClass = EFI_DATA_RECORD_CLASS_DEBUG |
EFI_DATA_RECORD_CLASS_ERROR |
EFI_DATA_RECORD_CLASS_DATA |
EFI_DATA_RECORD_CLASS_PROGRESS_CODE;
}
//
// Log DataRecord in Data Hub
//
mDataHubProtocol->LogData (
mDataHubProtocol,
&gEfiStatusCodeGuid,
&gEfiStatusCodeRuntimeProtocolGuid,
DataRecordClass,
Record,
Size
);
}
mEventHandlerActive = FALSE;
}
EFI_STATUS
EFIAPI
BsDataHubInitializeStatusCode (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
/*++
Routine Description:
Install a data hub listener.
Arguments:
(Standard EFI Image entry - EFI_IMAGE_ENTRY_POINT)
Returns:
EFI_SUCCESS - Logging Hub protocol installed
Other - No protocol installed, unload driver.
--*/
{
EFI_STATUS Status;
Status = gBS->LocateProtocol (
&gEfiDataHubProtocolGuid,
NULL,
(VOID **) &mDataHubProtocol
);
ASSERT_EFI_ERROR (Status);
//
// Create a Notify Event to log data in Data Hub
//
Status = gBS->CreateEvent (
EFI_EVENT_NOTIFY_SIGNAL,
EFI_TPL_CALLBACK,
LogDataHubEventHandler,
NULL,
&mLogDataHubEvent
);
ASSERT_EFI_ERROR (Status);
return EFI_SUCCESS;
}
| 4,875 |
2,100 |
<reponame>isabella232/gapid<gh_stars>1000+
/*
* Copyright (C) 2017 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.
*/
package com.google.gapid.util;
import static com.google.gapid.util.GeoUtils.bottom;
import static java.util.Collections.emptySet;
import com.google.common.collect.Sets;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import java.util.Set;
/**
* Utilities for dealing with {@link Tree Trees} and {@link TreeItem TreeItems}.
*/
public class Trees {
private Trees() {
}
/**
* @return the {@link TreeItem TreeItems} that are currently visible in the tree.
*/
public static Set<TreeItem> getVisibleItems(Tree tree) {
TreeItem top = tree.getTopItem();
if (top == null) {
// Work around bug where getTopItem() returns null when scrolling
// up past the top item (elastic scroll).
return (tree.getItemCount() != 0) ? null : emptySet();
}
int treeBottom = bottom(tree.getClientArea());
Set<TreeItem> visible = Sets.newIdentityHashSet();
if (!getVisibleItems(top, treeBottom, visible)) {
do {
top = getVisibleSiblings(top, treeBottom, visible);
} while (top != null);
}
return visible;
}
/**
* Adds the given item and all visible descendants into the given set.
* @return whether the bottom has been reached.
*/
private static boolean getVisibleItems(TreeItem item, int treeBottom, Set<TreeItem> visible) {
visible.add(item);
if (bottom(item.getBounds()) > treeBottom) {
return true;
}
if (item.getExpanded()) {
for (TreeItem child : item.getItems()) {
if (getVisibleItems(child, treeBottom, visible)) {
return true;
}
}
}
return false;
}
/**
* Adds all visible siblings (and their visible descendants) into the given set.
* @return the next parent or {@code null} if the bottom has been reached.
*/
private static TreeItem getVisibleSiblings(TreeItem item, int treeBottom, Set<TreeItem> visible) {
TreeItem parent = item.getParentItem();
TreeItem[] siblings = (parent == null) ? item.getParent().getItems() : parent.getItems();
int idx = 0;
for (; idx < siblings.length && siblings[idx] != item; idx++) {
// Do nothing.
}
for (idx++; idx < siblings.length; idx++) {
if (getVisibleItems(siblings[idx], treeBottom, visible)) {
return null;
}
}
return parent;
}
}
| 1,019 |
615 |
package org.byron4j.cookbook.rocketmq.transaction;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.MQConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 事务消息消费者
*/
@Slf4j
public class MQTransactionConsumerDemo {
public static void main(String[] args) throws MQClientException {
// 1. 创建推送型消费者
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("repay_tx_con_group");
// 2. 注册
consumer.setNamesrvAddr("localhost:9876");
// 3. 订阅主题
consumer.subscribe("tx-mq-TOPIC", "*");
// 4. 从哪里开始消费
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
// 5. 推送型消费者一定需要注册监听器
consumer.registerMessageListener(new MessageListenerConcurrently() {
Random r = new Random();
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
for (MessageExt msg : list){
log.info("接收到的消息是:" + msg);
log.info("接收到的消息标签是:" + new String(msg.getTags()));
log.info("接收到的消息内容是:" + new String(msg.getBody()));
}
try{
// 模拟业务处理耗时
TimeUnit.SECONDS.sleep(r.nextInt());
}catch (Exception e){
log.error("业务处理异常:", e);
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
// 6. 别玩了启动消费者
consumer.start();
}
}
| 1,337 |
1,695 |
<reponame>happybin92/trino<gh_stars>1000+
/*
* 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.trino.plugin.iceberg;
import io.trino.sql.planner.OptimizerConfig.JoinDistributionType;
import io.trino.testing.BaseDynamicPartitionPruningTest;
import io.trino.testing.QueryRunner;
import org.intellij.lang.annotations.Language;
import org.testng.SkipException;
import java.util.List;
import java.util.Map;
import static java.lang.String.format;
import static java.util.stream.Collectors.joining;
public class TestIcebergDynamicPartitionPruningTest
extends BaseDynamicPartitionPruningTest
{
@Override
protected QueryRunner createQueryRunner()
throws Exception
{
return IcebergQueryRunner.builder()
.setExtraProperties(EXTRA_PROPERTIES)
.setIcebergProperties(Map.of("iceberg.dynamic-filtering.wait-timeout", "1h"))
.setInitialTables(REQUIRED_TABLES)
.build();
}
@Override
public void testJoinDynamicFilteringMultiJoinOnBucketedTables(JoinDistributionType joinDistributionType)
{
throw new SkipException("Iceberg does not support bucketing");
}
@Override
protected void createLineitemTable(String tableName, List<String> columns, List<String> partitionColumns)
{
@Language("SQL") String sql = format(
"CREATE TABLE %s WITH (partitioning=array[%s]) AS SELECT %s FROM tpch.tiny.lineitem",
tableName,
partitionColumns.stream().map(column -> "'" + column + "'").collect(joining(",")),
String.join(",", columns));
getQueryRunner().execute(sql);
}
@Override
protected void createPartitionedTable(String tableName, List<String> columns, List<String> partitionColumns)
{
@Language("SQL") String sql = format(
"CREATE TABLE %s (%s) WITH (partitioning=array[%s])",
tableName,
String.join(",", columns),
partitionColumns.stream().map(column -> "'" + column + "'").collect(joining(",")));
getQueryRunner().execute(sql);
}
@Override
protected void createPartitionedAndBucketedTable(String tableName, List<String> columns, List<String> partitionColumns, List<String> bucketColumns)
{
throw new UnsupportedOperationException();
}
}
| 1,058 |
348 |
{"nom":"Pont-Aven","circ":"8ème circonscription","dpt":"Finistère","inscrits":2238,"abs":1142,"votants":1096,"blancs":66,"nuls":46,"exp":984,"res":[{"nuance":"REM","nom":"<NAME>","voix":577},{"nuance":"SOC","nom":"<NAME>","voix":407}]}
| 95 |
852 |
#include <iostream>
#include "Pythia6ParticleGun.h"
#include "FWCore/Utilities/interface/Exception.h"
#include "FWCore/Framework/interface/EDProducer.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
//#include "SimDataFormats/GeneratorProducts/interface/HepMCProduct.h"
//#include "FWCore/Framework/interface/MakerMacros.h"
using namespace edm;
using namespace gen;
Pythia6ParticleGun::Pythia6ParticleGun(const ParameterSet& pset) : Pythia6Gun(pset) {
ParameterSet pgun_params = pset.getParameter<ParameterSet>("PGunParameters");
fPartIDs = pgun_params.getParameter<std::vector<int> >("ParticleID");
}
Pythia6ParticleGun::~Pythia6ParticleGun() {}
| 261 |
8,514 |
/*
* 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.
*/
/**
* Interface for storing server's connection context.
*/
package org.apache.thrift.server;
public interface ServerContext {
/**
* Returns an object that implements the given interface to allow access to
* application specific contexts.
*
* @param iface A Class defining an interface that the result must implement
* @return an object that implements the interface
* @throws RuntimeException If the context cannot be unwrapped to the provided
* class
*/
<T> T unwrap(Class<T> iface);
/**
* Returns true if this server context is a wrapper for the provided
* application specific context interface argument or returns false otherwise.
*
* @param iface a Class defining the underlying context
* @return true if this implements the interface can be unwrapped to the
* provided class
* @throws RuntimeException if an error occurs while determining whether the
* provided class can be unwrapped from this context.
*/
boolean isWrapperFor(Class<?> iface);
}
| 487 |
488 |
<reponame>maurizioabba/rose
#include "TypeInfoDisplay.h"
#include "TypeSystem.h"
#include <QIcon>
#include <QDebug>
RsTypeDisplay::RsTypeDisplay(const RsType* t, const QString & n, int off)
: type(t), name(n),offset(off)
{
}
QStringList RsTypeDisplay::sectionHeader() const
{
return QStringList() << "Name" << "Size" << "Offset";
}
QVariant RsTypeDisplay::data(int role, int column) const
{
// First column "memberName : className"
// Second column size
// third column offset
if(role == Qt::DisplayRole)
{
if(column ==0)
{
if(!name.isEmpty())
return name + " : " + type->getName().c_str();
else
return QString(type->getName().c_str());
}
else if (column == 1)
return static_cast<unsigned int>(type->getByteSize());
else if (column == 2)
{
QVariant res(offset); // if offset==-1 -> leave column empty
return offset>=0 ? res : QVariant();
}
}
if( role == Qt::DecorationRole && column ==0)
{
const RsClassType* classType = dynamic_cast<const RsClassType*> (type);
if(classType)
return QIcon(":/util/NodeIcons/class.gif");
const RsArrayType* arrType = dynamic_cast<const RsArrayType*> (type);
if(arrType )
return QIcon(":/icons/array.gif");
const RsBasicType * basicType = dynamic_cast<const RsBasicType*> (type);
if(basicType)
return QIcon(":/icons/basic_type.gif");
}
return QVariant();
}
RsTypeDisplay* RsTypeDisplay::build(TypeSystem * t)
{
typedef TypeSystem::NamedTypeContainer::const_iterator ConstIterator;
RsTypeDisplay * root = new RsTypeDisplay(NULL,"root",-1);
for (ConstIterator it = t->begin(); it != t->end(); ++it)
{
root->addChild( build(it->second,-1,"") );
}
return root;
}
RsTypeDisplay * RsTypeDisplay::build (const RsType* t, int memberOffset, const QString& memberName)
{
RsTypeDisplay * curNode = new RsTypeDisplay(t,memberName,memberOffset);
for(int i=0; i< t->getSubtypeCount(); i++)
{
QString subTypeStr( t->getSubTypeString(i).c_str() );
RsTypeDisplay * c =build(t->getSubtype(i),t->getSubtypeOffset(i),subTypeStr);
curNode->addChild(c);
}
return curNode;
}
| 1,007 |
3,301 |
<reponame>okjay/Alink
package com.alibaba.alink.operator.common.feature;
import org.apache.flink.types.Row;
import org.apache.flink.util.Preconditions;
import com.alibaba.alink.operator.common.utils.PrettyDisplayUtils;
import com.alibaba.alink.params.shared.colname.HasSelectedCols;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Summary of OneHotModel.
*/
public class OneHotModelInfo implements Serializable {
private static final long serialVersionUID = -4990829552802168917L;
public Map <String, List <String>> tokensMap;
public Map <String, Long> distinceTokenNumber;
public OneHotModelInfo(List <Row> rows) {
OneHotModelData modelData = new OneHotModelDataConverter().load(rows);
tokensMap = new HashMap <>();
distinceTokenNumber = new HashMap <>();
String[] colNames = modelData.modelData.meta.get(HasSelectedCols.SELECTED_COLS);
for (String s : colNames) {
tokensMap.put(s, modelData.modelData.getTokens(s));
distinceTokenNumber.put(s, modelData.modelData.getNumberOfTokensOfColumn(s));
}
}
public String[] getSelectedColsInModel() {
return tokensMap.keySet().toArray(new String[0]);
}
public Long getDistinctTokenNumber(String columnName) {
Preconditions.checkState(tokensMap.containsKey(columnName),
columnName + "is not contained in the model!");
return distinceTokenNumber.get(columnName);
}
public String[] getTokens(String columnName) {
Preconditions.checkState(tokensMap.containsKey(columnName),
columnName + "is not contained in the model!");
return tokensMap.get(columnName).toArray(new String[0]);
}
@Override
public String toString() {
StringBuilder sbd = new StringBuilder(PrettyDisplayUtils.displayHeadline("OneHotModelInfo", '-'));
sbd.append("OneHotEncoder on ")
.append(tokensMap.size())
.append(" features: ")
.append(PrettyDisplayUtils.displayList(new ArrayList <>(distinceTokenNumber.keySet()), 3, false))
.append("\n")
.append(mapToString(distinceTokenNumber))
.append(QuantileDiscretizerModelInfo.mapToString(tokensMap));
return sbd.toString();
}
static String mapToString(Map <String, Long> categorySize) {
StringBuilder sbd = new StringBuilder();
sbd.append(PrettyDisplayUtils.displayHeadline("DistinctTokenNumber", '='));
sbd.append(PrettyDisplayUtils.displayMap(categorySize, 3, false));
sbd.append("\n");
return sbd.toString();
}
}
| 847 |
517 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
class Closing(object):
"""This mixin implements team closing.
"""
#: Whether the team is closed or not.
is_closed = False
def close(self):
"""Close the team account.
"""
with self.db.get_cursor() as cursor:
cursor.run("UPDATE teams SET is_closed=true WHERE id=%s", (self.id,))
self.app.add_event( cursor
, 'team'
, dict(id=self.id, action='set', values=dict(is_closed=True))
)
self.set_attributes(is_closed=True)
if self.package:
self.package.unlink_team(cursor)
| 382 |
593 |
<reponame>RUB-NDS/TLS-Attacker
/**
* TLS-Attacker - A Modular Penetration Testing Framework for TLS
*
* Copyright 2014-2022 Ruhr University Bochum, Paderborn University, Hackmanit GmbH
*
* Licensed under Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0.txt
*/
package de.rub.nds.tlsattacker.core.protocol.preparator.extension;
import de.rub.nds.tlsattacker.core.config.Config;
import de.rub.nds.tlsattacker.core.constants.ChooserType;
import de.rub.nds.tlsattacker.core.protocol.message.extension.ServerNameIndicationExtensionMessage;
import de.rub.nds.tlsattacker.core.protocol.message.extension.sni.ServerNamePair;
import de.rub.nds.tlsattacker.core.protocol.serializer.extension.ServerNameIndicationExtensionSerializer;
import de.rub.nds.tlsattacker.core.state.TlsContext;
import de.rub.nds.tlsattacker.core.workflow.chooser.Chooser;
import de.rub.nds.tlsattacker.core.workflow.chooser.ChooserFactory;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class ServerNameIndicationExtensionPreparatorTest {
private Chooser chooser;
private ServerNameIndicationExtensionMessage message;
private ServerNameIndicationExtensionSerializer serializer;
private Config config;
@Before
public void setUp() {
config = Config.createConfig();
chooser = ChooserFactory.getChooser(ChooserType.DEFAULT, new TlsContext(config), config);
message = new ServerNameIndicationExtensionMessage();
}
/**
* Test of prepareExtensionContent method, of class ServerNameIndicationExtensionPreparator.
*/
@Test
public void testPrepareExtensionContentWithOnePair() {
List<ServerNamePair> pairList = new LinkedList<>();
ServerNamePair pair = new ServerNamePair((byte) 1, new byte[] { 0x01, 0x02 });
pairList.add(pair);
config.setDefaultSniHostnames(pairList);
ServerNameIndicationExtensionPreparator serverPrep =
new ServerNameIndicationExtensionPreparator(chooser, message, serializer);
serverPrep.prepareExtensionContent();
assertArrayEquals(new byte[] { 0x01, 0x00, 0x02, 0x01, 0x02 },
serverPrep.getObject().getServerNameListBytes().getValue());
assertEquals(5, (long) serverPrep.getObject().getServerNameListLength().getOriginalValue());
}
@Test
public void testPrepareExtensionContentWithTwoPairs() {
List<ServerNamePair> pairList = new LinkedList<>();
ServerNamePair pair = new ServerNamePair((byte) 1, new byte[] { 0x01, 0x02 });
pairList.add(pair);
ServerNamePair pair2 = new ServerNamePair((byte) 2, new byte[] { 0x03, 0x04, 0x05, 0x06 });
pairList.add(pair2);
config.setDefaultSniHostnames(pairList);
ServerNameIndicationExtensionPreparator serverPrep =
new ServerNameIndicationExtensionPreparator(chooser, message, serializer);
serverPrep.prepareExtensionContent();
assertArrayEquals(new byte[] { 0x01, 0x00, 0x02, 0x01, 0x02, 0x02, 0x00, 0x04, 0x03, 0x04, 0x05, 0x06 },
serverPrep.getObject().getServerNameListBytes().getValue());
assertEquals(12, (long) serverPrep.getObject().getServerNameListLength().getOriginalValue());
}
}
| 1,270 |
357 |
/*
* Copyright © 2018 VMware, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the ?~@~\License?~@~]); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ?~@~\AS IS?~@~] BASIS, without
* warranties or conditions of any kind, EITHER EXPRESS OR IMPLIED. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
#include "includes.h"
PSTR
LwCAMetricsReqUrlString(
LWCA_METRICS_REQ_URLS reqUrl
)
{
static PSTR pszReqUrls[LWCA_METRICS_REQ_URL_COUNT] =
{
"/v1/mutentca/root",
"/v1/mutentca/certificate",
"/v1/mutentca/crl",
"/v1/mutentca/intermediate/{ca-id}",
"/v1/mutentca/intermediate/{ca-id}/certificate",
"/v1/mutentca/intermediate/{ca-id}/crl"
};
return pszReqUrls[reqUrl];
}
PSTR
LwCAMetricsHttpMethodString(
LWCA_METRICS_HTTP_METHODS method
)
{
static PSTR pszHttpMethod[LWCA_METRICS_HTTP_METHOD_COUNT] =
{
"GET",
"POST",
"DELETE"
};
return pszHttpMethod[method];
}
PSTR
LwCAMetricsHttpStatusCodeString(
LWCA_METRICS_HTTP_CODES code
)
{
static PSTR pszHttpCodes[LWCA_METRICS_HTTP_CODE_COUNT] =
{
"200",
"204",
"400",
"401",
"403",
"404",
"409",
"500"
};
return pszHttpCodes[code];
}
PSTR
LwCAMetricsApiNameString(
LWCA_METRICS_API_NAMES api
)
{
static PSTR pszApiNames[LWCA_METRICS_API_COUNT] =
{
"CreateRootCA",
"CreateIntermediateCA",
"GetCACertificates",
"GetSignedCertificate",
"GetChainOfTrust",
"GetCACrl",
"RevokeIntermediateCA",
"RevokeCertificate"
};
return pszApiNames[api];
}
PSTR
LwCAMetricsSecurityApiNameString(
LWCA_METRICS_SECURITY_APIS api
)
{
static PSTR pszSecurityApiNames[LWCA_METRICS_SECURITY_COUNT] =
{
"AddKeyPair",
"CreateKeyPair",
"SignX509Cert",
"SignX509Request",
"SignX509CRL"
};
return pszSecurityApiNames[api];
}
PSTR
LwCAMetricsDbApiNameString(
LWCA_METRICS_DB_APIS api
)
{
static PSTR pszDbApiNames[LWCA_METRICS_DB_COUNT] =
{
"AddCA",
"GetCA",
"UpdateCA",
"LockCA",
"UnlockCA",
"AddCACert",
"GetCACert",
"GetCACerts",
"UpdateCACert",
"LockCACert",
"UnlockCACert",
"AddCert",
"GetCert",
"GetCerts",
"GetRevokedCerts",
"UpdateCerts",
"LockCert",
"UnlockCert"
};
return pszDbApiNames[api];
}
PSTR
LwCAMetricsResponseString(
LWCA_METRICS_RESPONSE_CODES code
)
{
static PSTR pszResponseCodes[LWCA_METRICS_RESPONSE_COUNT] =
{
"Success",
"Error"
};
return pszResponseCodes[code];
}
| 1,547 |
3,799 |
<reponame>digitalbuddha/androidx
/**
* Copyright (C) 2015 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.
*/
/**
* <p>Support classes providing high level Leanback user interface building blocks.</p>
* <p>
* Leanback fragments are available both as support fragments (subclassed from
* {@link androidx.fragment.app.Fragment androidx.fragment.app.Fragment}) and as platform
* fragments (subclassed from {@link android.app.Fragment android.app.Fragment}). A few of the most
* commonly used leanback fragments are described here.
* </p>
* <p>
* A {@link androidx.leanback.app.BrowseSupportFragment} by default operates in the "row"
* mode. It includes an optional “fastlane”
* navigation side panel and a list of rows, with one-to-one correspondance between each header
* in the fastlane and a row. The application supplies the
* {@link androidx.leanback.widget.ObjectAdapter} containing the list of
* rows and a {@link androidx.leanback.widget.PresenterSelector} of row presenters.
* </p>
* <p>
* A {@link androidx.leanback.app.BrowseSupportFragment} also works in a "page" mode when
* each row of fastlane is mapped to a fragment that the app registers in
* {@link androidx.leanback.app.BrowseSupportFragment#getMainFragmentRegistry()}.
* </p>
* <p>
* A {@link androidx.leanback.app.DetailsSupportFragment} will typically consist of a
* large overview of an item at the top,
* some actions that a user can perform, and possibly rows of additional or related items.
* The content for this fragment is specified in the same way as for the BrowseSupportFragment, with
* the convention that the first element in the ObjectAdapter corresponds to the overview row.
* The {@link androidx.leanback.widget.DetailsOverviewRow} and
* {@link androidx.leanback.widget.FullWidthDetailsOverviewRowPresenter} provide a
* default template for this row.
* </p>
* <p>
* A {@link androidx.leanback.app.PlaybackSupportFragment} or its subclass
* {@link androidx.leanback.app.VideoSupportFragment} hosts
* {@link androidx.leanback.media.PlaybackTransportControlGlue}
* or {@link androidx.leanback.media.PlaybackBannerControlGlue} with a Leanback
* look and feel. It is recommended to use an instance of
* {@link androidx.leanback.media.PlaybackTransportControlGlue}.
* This helper implements a standard behavior for user interaction with
* the most commonly used controls as well as video scrubbing.
* </p>
* <p>
* A {@link androidx.leanback.app.SearchSupportFragment} allows the developer to accept a
* query from a user and display the results
* using the familiar list rows.
* </p>
* <p>
* A {@link androidx.leanback.app.GuidedStepSupportFragment} is used to guide the user
* through a decision or series of decisions.
* </p>
**/
package androidx.leanback.app;
| 930 |
678 |
<filename>iOSOpenDev/frameworks/HomeSharing.framework/Headers/HomeSharing.h
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/HomeSharing.framework/HomeSharing
*/
#import <HomeSharing/HomeSharing-Structs.h>
#import <HomeSharing/HSServerInfoRequest.h>
#import <HomeSharing/HSItemDataRequest.h>
#import <HomeSharing/HSRemovePlaylistRequest.h>
#import <HomeSharing/HSContainersRequest.h>
#import <HomeSharing/HSConnection.h>
#import <HomeSharing/HSTemporaryFile.h>
#import <HomeSharing/HSGetAuthorizedAccountsTokenResponse.h>
#import <HomeSharing/HSBulkRemovePlaylistRequest.h>
#import <HomeSharing/HSBulkAddPlaylistRequest.h>
#import <HomeSharing/HSAddPlaylistResponse.h>
#import <HomeSharing/HSUpdateRequest.h>
#import <HomeSharing/HSAuthorizedDSIDsUpdatesResponse.h>
#import <HomeSharing/HSActivityRequest.h>
#import <HomeSharing/HSCloudArtworkInfoRequest.h>
#import <HomeSharing/HSCheckInRentalAssetRequest.h>
#import <HomeSharing/HSItemsResponse.h>
#import <HomeSharing/HSItemsRequest.h>
#import <HomeSharing/HSResponseDataParser.h>
#import <HomeSharing/HSFairPlayInfo.h>
#import <HomeSharing/HSLogoutRequest.h>
#import <HomeSharing/HSDatabasesResponse.h>
#import <HomeSharing/HSFairPlaySetupRequest.h>
#import <HomeSharing/HSSetContainersResponse.h>
#import <HomeSharing/NSNetServiceDelegate.h>
#import <HomeSharing/HSArtworkRequest.h>
#import <HomeSharing/HSAddPlaylistRequest.h>
#import <HomeSharing/HSSetRentalPlaybackStartDateRequest.h>
#import <HomeSharing/HSUpdateResponse.h>
#import <HomeSharing/HSLoginResponse.h>
#import <HomeSharing/HSGetAuthorizedAccountsInfoRequest.h>
#import <HomeSharing/HSHomeSharingVerifyRequest.h>
#import <HomeSharing/HSBrowseResponse.h>
#import <HomeSharing/HSSagaClient.h>
#import <HomeSharing/HSBrowser.h>
#import <HomeSharing/HSCloudArtworkInfoResponse.h>
#import <HomeSharing/HSSetItemsRequest.h>
#import <HomeSharing/HSDatabasesRequest.h>
#import <HomeSharing/HSLoginRequest.h>
#import <HomeSharing/HSAuthorizedDSIDsUpdateRequest.h>
#import <HomeSharing/HSConnectionStream.h>
#import <HomeSharing/HSIncrementRequest.h>
#import <HomeSharing/HSBulkCloudArtworkInfoRequest.h>
#import <HomeSharing/HSCheckOutRentalAssetRequest.h>
#import <HomeSharing/HSAuthorizedDSIDsUpdatesRequest.h>
#import <HomeSharing/HSAuthorizedDSIDsUpdateResponse.h>
#import <HomeSharing/HSLibrary.h>
#import <HomeSharing/HSSetPropertyRequest.h>
#import <HomeSharing/HSRequest.h>
#import <HomeSharing/HSGetAuthorizedAccountsTokenRequest.h>
#import <HomeSharing/HSResponse.h>
#import <HomeSharing/XXUnknownSuperclass.h>
#import <HomeSharing/_HSUnresolvedLibrary.h>
#import <HomeSharing/HSBrowseRequest.h>
#import <HomeSharing/HSContainersResponse.h>
#import <HomeSharing/HSBulkSetContainersRequest.h>
#import <HomeSharing/HSBulkCloudArtworkInfoResponse.h>
#import <HomeSharing/HSSetContainersRequest.h>
#import <HomeSharing/HSBulkAddPlaylistResponse.h>
| 1,030 |
320 |
//
// MPInlineAdAdapterDelegate.h
//
// Copyright 2018-2021 Twitter, Inc.
// Licensed under the MoPub SDK License Agreement
// http://www.mopub.com/legal/sdk-license-agreement/
//
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
@class MPInlineAdAdapter;
/**
Instances of your custom subclass of @c MPInlineAdAdapter will have an
@c MPInlineAdAdapterDelegate delegate. You use this delegate to communicate events ad events
back to the MoPub SDK.
When mediating a third party ad network it is important to call as many of these methods
as accurately as possible. Not all ad networks support all these events, and some support
different events. It is your responsibility to find an appropriate mapping between the ad
network's events and the callbacks defined on @c MPInlineAdAdapterDelegate.
*/
@protocol MPInlineAdAdapterDelegate <NSObject>
/**
The view controller instance to use when presenting modals.
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
@return the view controller that was specified when implementing the @c MPAdViewDelegate protocol.
*/
- (UIViewController *)inlineAdAdapterViewControllerForPresentingModalView:(MPInlineAdAdapter *)adapter;
/** @name Banner Ad Event Callbacks - Fetching Ads */
/**
Call this method immediately after an ad loads succesfully.
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
@param adView The @c UIView representing the banner ad. This view will be inserted into the parent
@c MPAdView and presented to the user by the MoPub SDK.
@warning **Important**: Your adapter subclass **must** call this method when it successfully loads an ad.
Failure to do so will disrupt the mediation waterfall and cause future ad requests to stall.
*/
- (void)inlineAdAdapter:(MPInlineAdAdapter *)adapter didLoadAdWithAdView:(UIView *)adView;
/**
Call this method immediately after an ad fails to load.
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
@param error the error describing the failure.
@warning **Important**: Your adapter subclass **must** call this method when it fails to load an ad.
Failure to do so will disrupt the mediation waterfall and cause future ad requests to stall.
*/
- (void)inlineAdAdapter:(MPInlineAdAdapter *)adapter didFailToLoadAdWithError:(NSError *)error;
/** @name Banner Ad Event Callbacks - User Interaction */
/**
Call this method when the user taps on the banner ad.
This method is optional. When automatic click and impression tracking is enabled (the default)
this method will track a click (the click is guaranteed to only be tracked once per ad).
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
@warning **Important**: If you call @c inlineAdAdapterWillBeginUserAction:, you _**must**_ also call
@c inlineAdAdapterDidEndUserAction: at a later point.
*/
- (void)inlineAdAdapterWillBeginUserAction:(MPInlineAdAdapter *)adapter;
/**
Call this method when the user finishes interacting with the banner ad.
For example, the user may have dismissed any modal content. This method is optional.
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
@warning **Important**: If you call @c inlineAdAdapterWillBeginUserAction:, you _**must**_ also call
@c inlineAdAdapterDidEndUserAction: at a later point.
*/
- (void)inlineAdAdapterDidEndUserAction:(MPInlineAdAdapter *)adapter;
/**
Call this method when the banner ad will cause the user to leave the application.
For example, the user may have tapped on a link to visit the App Store or Safari.
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
*/
- (void)inlineAdAdapterWillLeaveApplication:(MPInlineAdAdapter *)adapter;
/**
Call this method when the banner ad is expanding or resizing from its default size.
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
*/
- (void)inlineAdAdapterWillExpand:(MPInlineAdAdapter *)adapter;
/**
Call this method when the banner ad is collapsing back to its default size.
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
*/
- (void)inlineAdAdapterDidCollapse:(MPInlineAdAdapter *)adapter;
/** @name Impression and Click Tracking */
/**
Call this method when an impression was tracked.
The MoPub SDK ensures that only one impression is tracked per adapter. Calling this method after an
impression has been tracked (either by another call to this method, or automatically if
@c enableAutomaticClickAndImpressionTracking is set to @c YES) will do nothing.
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
*/
- (void)inlineAdAdapterDidTrackImpression:(MPInlineAdAdapter *)adapter;
/**
Call this method when a click was tracked.
The MoPub SDK ensures that only one click is tracked per adapter. Calling this method after a click has
been tracked (either by another call to this method, or automatically if
@c enableAutomaticClickAndImpressionTracking is set to @c YES) will do nothing.
@param adapter You should pass @c self to allow the MoPub SDK to associate this event with the correct
instance of your adapter.
*/
- (void)inlineAdAdapterDidTrackClick:(MPInlineAdAdapter *)adapter;
@end
| 1,446 |
1,309 |
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
ConsoleFunctionGroupBegin(Video, "Video control functions.");
/*! @defgroup VideoFunctions Video
@ingroup TorqueScriptFunctions
@{
*/
//--------------------------------------------------------------------------
/*! Use the setDisplayDevice function to select a display device and to set the initial width, height and bits-per-pixel (bpp) setting, as well as whether the application is windowed or in fullScreen.
If no resolution information is specified, the first legal resolution on this device's resolution list will be used. Furthermore, for each optional argument if the subsequent arguments are not specified, the first matching case will be used. Lastly, if the application is not told to display in full screen, but the device only supports windowed, the application will be forced into windowed mode.
@param deviceName A supported display device name.
@param width Resolution width in pixels.
@param height Resolution height in pixels.
@param bpp Pixel resolution in bits-per-pixel (16 or 32).
@param fullScreen A boolean value. If set to true, the application displays in full- screen mode, otherwise it will attempt to display in windowed mode.
@return Returns true on success, false otherwise.
@sa getDesktopResolution, getDisplayDeviceList, getResolutionList, nextResolution, prevResolution, setRes, setScreenMode, switchBitDepth
*/
ConsoleFunctionWithDocs( setDisplayDevice, ConsoleBool, 2, 6, ( deviceName, [width]?, [height]?, [bpp]?, [fullScreen]? ))
{
Resolution currentRes = Video::getResolution();
U32 width = ( argc > 2 ) ? dAtoi( argv[2] ) : currentRes.w;
U32 height = ( argc > 3 ) ? dAtoi( argv[3] ) : currentRes.h;
U32 bpp = ( argc > 4 ) ? dAtoi( argv[4] ) : currentRes.bpp;
bool fullScreen = ( argc > 5 ) ? dAtob( argv[5] ) : Video::isFullScreen();
return( Video::setDevice( argv[1], width, height, bpp, fullScreen ) );
}
//--------------------------------------------------------------------------
/*! Use the setScreenMode function to set the screen to the specified width, height, and bits-per-pixel (bpp). Additionally, if fullScreen is set to true the engine will attempt to display the application in full-screen mode, otherwise it will attempt to used windowed mode.
@param width Resolution width in pixels.
@param height Resolution height in pixels.
@param bpp Pixel resolution in bits-per-pixel (16 or 32).
@param fullScreen A boolean value. If set to true, the application displays in full- screen mode, otherwise it will attempt to display in windowed mode.
@return Returns true if successful, otherwise false.
@sa getDesktopResolution, getDisplayDeviceList, getResolutionList, nextResolution, prevResolution, setDisplayDevice, setRes, switchBitDepth
*/
ConsoleFunctionWithDocs( setScreenMode, ConsoleBool, 5, 5, ( width , height , bpp , fullScreen ))
{
return( Video::setScreenMode( dAtoi( argv[1] ), dAtoi( argv[2] ), dAtoi( argv[3] ), dAtob( argv[4] ) ) );
}
//------------------------------------------------------------------------------
/*! Use the toggleFullScreen function to switch from full-screen mode to windowed, or vice versa.
@return Returns true on success, false otherwise
*/
ConsoleFunctionWithDocs( toggleFullScreen, ConsoleBool, 1, 1, ())
{
return( Video::toggleFullScreen() );
}
//------------------------------------------------------------------------------
/*! Use the isFullScreen function to determine if the current application is displayed in full-screen mode.
@return Returns true if the engine is currently displaying full-screen, otherwise returns false
*/
ConsoleFunctionWithDocs( isFullScreen, ConsoleBool, 1, 1, ())
{
return( Video::isFullScreen() );
}
//--------------------------------------------------------------------------
/*! Use the switchBitDepth function to toggle the bits-per-pixel (bpp) pixel resolution between 16 and 32.
@return Returns true on success, false otherwise.
@sa getDesktopResolution, getDisplayDeviceList, getResolutionList, nextResolution, prevResolution, setDisplayDevice, setRes
*/
ConsoleFunctionWithDocs( switchBitDepth, ConsoleBool, 1, 1, ())
{
if ( !Video::isFullScreen() )
{
Con::warnf( ConsoleLogEntry::General, "Can only switch bit depth in full-screen mode!" );
return( false );
}
Resolution res = Video::getResolution();
return( Video::setResolution( res.w, res.h, ( res.bpp == 16 ? 32 : 16 ) ) );
}
//--------------------------------------------------------------------------
/*! Use the prevResolution function to switch to the previous valid (lower) resolution for the current display device.
@return Returns true if switch was successful, false otherwise.
@sa getDesktopResolution, nextResolution, getResolutionList, setRes, setScreenMode, switchBitDepth
*/
ConsoleFunctionWithDocs( prevResolution, ConsoleBool, 1, 1, ())
{
return( Video::prevRes() );
}
//--------------------------------------------------------------------------
/*! Use the nextResolution function to switch to the next valid (higher) resolution for the current display device.
@return Returns true if switch was successful, false otherwise.
@sa getDesktopResolution, prevResolution, getResolutionList, setRes, setScreenMode, switchBitDepth
*/
ConsoleFunctionWithDocs( nextResolution, ConsoleBool, 1, 1, ())
{
return( Video::nextRes() );
}
//--------------------------------------------------------------------------
/*! Get the width, height, and bitdepth of the screen.
@return A string formatted as \<width> <height> <bitdepth>\
*/
ConsoleFunctionWithDocs( getRes, ConsoleString, 1, 1, ())
{
static char resBuf[16];
Resolution res = Video::getResolution();
dSprintf( resBuf, sizeof(resBuf), "%d %d %d", res.w, res.h, res.bpp );
return( resBuf );
}
//--------------------------------------------------------------------------
/*! Use the setRes function to set the screen to the specified width, height, and bits-per-pixel (bpp).
@param width Resolution width in pixels.
@param height Resolution height in pixels.
@param bpp Pixel resolution in bits-per-pixel (16 or 32).
@return Returns true if successful, otherwise false.
@sa getDesktopResolution, getDisplayDeviceList, getResolutionList, nextResolution, prevResolution, setDisplayDevice, setScreenMode, switchBitDepth
*/
ConsoleFunctionWithDocs( setRes, ConsoleBool, 3, 4, ( width , height , bpp ))
{
U32 width = dAtoi( argv[1] );
U32 height = dAtoi( argv[2] );
U32 bpp = 0;
if ( argc == 4 )
{
bpp = dAtoi( argv[3] );
if ( bpp != 16 && bpp != 32 )
bpp = 0;
}
return( Video::setResolution( width, height, bpp ) );
}
//------------------------------------------------------------------------------
/*! Use the getDesktopResolution function to determine the current resolution of the desktop (not the application).
To get the current resolution of a windowed display of the torque game engine, simply examine the global variable '$pref::Video::resolution'.
@return Returns a string containing the current desktop resolution, including the width height and the current bits per pixel.
@sa getDisplayDeviceList, getResolutionList, nextResolution, prevResolution, setDisplayDevice, setRes, setScreenMode, switchBitDepth
*/
ConsoleFunctionWithDocs( getDesktopResolution, ConsoleString, 1, 1, ())
{
static char resBuf[16];
Resolution res = Video::getDesktopResolution();
dSprintf( resBuf, sizeof(resBuf), "%d %d %d", res.w, res.h, res.bpp );
return( resBuf );
}
//------------------------------------------------------------------------------
/*! Use the getDisplayDeviceList function to get a list of valid display devices.
@return Returns a tab separated list of valid display devices.
@sa getDesktopResolution, getResolutionList, setRes, setScreenMode, switchBitDepth
*/
ConsoleFunctionWithDocs( getDisplayDeviceList, ConsoleString, 1, 1, ())
{
return( Video::getDeviceList() );
}
//------------------------------------------------------------------------------
/*! Use the getResolutionList function to get a semicolon separated list of legal resolutions for a specified device.
Resolutions are always in the form: width height bpp, where width and height are in pixels and bpp is bits-per-pixel.
@param deviceName A string containing a supported display device.
@return Returns a tab separated list of valid display resolutions for devicename.
@sa getDesktopResolution, getDisplayDeviceList, setRes, setScreenMode, switchBitDepth
*/
ConsoleFunctionWithDocs( getResolutionList, ConsoleString, 2, 2, ( devicename ))
{
DisplayDevice* device = Video::getDevice( argv[1] );
if ( !device )
{
Con::warnf( ConsoleLogEntry::General, "\"%s\" display device not found!", argv[1] );
return( NULL );
}
return( device->getResolutionList() );
}
//------------------------------------------------------------------------------
/*! Use the getVideoDriverInfo function to dump information on the video driver to the console.
@return No return value
*/
ConsoleFunctionWithDocs( getVideoDriverInfo, ConsoleString, 1, 1, ())
{
return( Video::getDriverInfo() );
}
//------------------------------------------------------------------------------
/*! Use the isDeviceFullScreenOnly function to determine if the device specified in devicename is for full screen display only, or whether it supports windowed mode too.
@param deviceName A string containing a supported display device.
@return Returns true if the device can only display full scree, false otherwise.
@sa getResolutionList
*/
ConsoleFunctionWithDocs( isDeviceFullScreenOnly, ConsoleBool, 2, 2, ( devicename ))
{
DisplayDevice* device = Video::getDevice( argv[1] );
if ( !device )
{
Con::warnf( ConsoleLogEntry::General, "\"%s\" display device not found!", argv[1] );
return( false );
}
return( device->isFullScreenOnly() );
}
//------------------------------------------------------------------------------
static F32 sgOriginalGamma = -1.0;
static F32 sgGammaCorrection = 0.0;
/*! Use the videoSetGammaCorrection function to adjust the gamma for the video card.
The card will revert to it's default gamma setting as long as the application closes normally
@param gamma A floating-point value between 0.0 and 1.0.
@return No return value.
*/
ConsoleFunctionWithDocs(videoSetGammaCorrection, ConsoleVoid, 2, 2, ( gamma ))
{
F32 g = mClampF(dAtof(argv[1]),0.0,1.0);
F32 d = -(g - 0.5f);
if (d != sgGammaCorrection &&
(sgOriginalGamma != -1.0f || Video::getGammaCorrection(sgOriginalGamma)))
Video::setGammaCorrection(sgOriginalGamma+d);
sgGammaCorrection = d;
}
/*! Use the getVerticalSync function to determine if the application's framerate is currently synchronized to the vertical refresh rate.
@return Returns true if Vertical sync is enabled, false otherwise
*/
ConsoleFunctionWithDocs(getVerticalSync, ConsoleBool, 1, 1, "")
{
return(Video::getVerticalSync());
}
/*! Use the setVerticalSync function to force the framerate to sync up with the vertical refresh rate.
This is used to reduce excessive swapping/rendering. There is generally no purpose in rendering any faster than the monitor will support. Those extra 'ergs' can be used for something else
@param enable A boolean value. If set to true, the engine will only swap front and back buffers on or before a vertical refresh pass.
@return Returns true on success, false otherwise.
*/
ConsoleFunctionWithDocs( setVerticalSync, ConsoleBool, 2, 2, ( enable ))
{
return( Video::setVerticalSync( dAtob( argv[1] ) ) );
}
/*! Minimize the game window
*/
ConsoleFunctionWithDocs( minimizeWindow, ConsoleVoid, 1, 1, ())
{
Platform::minimizeWindow();
}
/*! Restore the game window
*/
ConsoleFunctionWithDocs( restoreWindow, ConsoleVoid, 1, 1, ())
{
Platform::restoreWindow();
}
ConsoleFunctionGroupEnd(Video)
/*! @} */ // group VideoFunctions
| 3,986 |
1,443 |
<reponame>cssence/mit-license
{
"copyright": "<NAME>, http://danielknell.co.uk",
"url": "http://danielknell.co.uk",
"email": "<EMAIL>",
"theme": "material-pink",
"gravatar": true
}
| 82 |
312 |
<reponame>apnadkarni/libgit2
#include "clar_libgit2.h"
#include "git2/sys/stream.h"
#include "streams/tls.h"
#include "streams/socket.h"
#include "stream.h"
static git_stream test_stream;
static int ctor_called;
void test_stream_registration__cleanup(void)
{
cl_git_pass(git_stream_register(GIT_STREAM_TLS | GIT_STREAM_STANDARD, NULL));
}
static int test_stream_init(git_stream **out, const char *host, const char *port)
{
GIT_UNUSED(host);
GIT_UNUSED(port);
ctor_called = 1;
*out = &test_stream;
return 0;
}
static int test_stream_wrap(git_stream **out, git_stream *in, const char *host)
{
GIT_UNUSED(in);
GIT_UNUSED(host);
ctor_called = 1;
*out = &test_stream;
return 0;
}
void test_stream_registration__insecure(void)
{
git_stream *stream;
git_stream_registration registration = {0};
registration.version = 1;
registration.init = test_stream_init;
registration.wrap = test_stream_wrap;
ctor_called = 0;
cl_git_pass(git_stream_register(GIT_STREAM_STANDARD, ®istration));
cl_git_pass(git_socket_stream_new(&stream, "localhost", "80"));
cl_assert_equal_i(1, ctor_called);
cl_assert_equal_p(&test_stream, stream);
ctor_called = 0;
stream = NULL;
cl_git_pass(git_stream_register(GIT_STREAM_STANDARD, NULL));
cl_git_pass(git_socket_stream_new(&stream, "localhost", "80"));
cl_assert_equal_i(0, ctor_called);
cl_assert(&test_stream != stream);
git_stream_free(stream);
}
void test_stream_registration__tls(void)
{
git_stream *stream;
git_stream_registration registration = {0};
int error;
registration.version = 1;
registration.init = test_stream_init;
registration.wrap = test_stream_wrap;
ctor_called = 0;
cl_git_pass(git_stream_register(GIT_STREAM_TLS, ®istration));
cl_git_pass(git_tls_stream_new(&stream, "localhost", "443"));
cl_assert_equal_i(1, ctor_called);
cl_assert_equal_p(&test_stream, stream);
ctor_called = 0;
stream = NULL;
cl_git_pass(git_stream_register(GIT_STREAM_TLS, NULL));
error = git_tls_stream_new(&stream, "localhost", "443");
/* We don't have TLS support enabled, or we're on Windows,
* which has no arbitrary TLS stream support.
*/
#if defined(GIT_WIN32) || !defined(GIT_HTTPS)
cl_git_fail_with(-1, error);
#else
cl_git_pass(error);
#endif
cl_assert_equal_i(0, ctor_called);
cl_assert(&test_stream != stream);
git_stream_free(stream);
}
void test_stream_registration__both(void)
{
git_stream *stream;
git_stream_registration registration = {0};
registration.version = 1;
registration.init = test_stream_init;
registration.wrap = test_stream_wrap;
cl_git_pass(git_stream_register(GIT_STREAM_STANDARD | GIT_STREAM_TLS, ®istration));
ctor_called = 0;
cl_git_pass(git_tls_stream_new(&stream, "localhost", "443"));
cl_assert_equal_i(1, ctor_called);
cl_assert_equal_p(&test_stream, stream);
ctor_called = 0;
cl_git_pass(git_socket_stream_new(&stream, "localhost", "80"));
cl_assert_equal_i(1, ctor_called);
cl_assert_equal_p(&test_stream, stream);
}
| 1,168 |
742 |
<reponame>TotalCaesar659/OpenTESArena<filename>OpenTESArena/src/GameLogic/MapLogicController.h
#ifndef MAP_LOGIC_CONTROLLER_H
#define MAP_LOGIC_CONTROLLER_H
#include "../Game/Physics.h"
#include "../World/Coord.h"
class Game;
class TextBox;
class TransitionDefinition;
namespace MapLogicController
{
// Handles changing night-light-related things on and off.
void handleNightLightChange(Game &game, bool active);
// Sends an "on voxel enter" message for the given voxel and triggers any text or sound events.
void handleTriggers(Game &game, const CoordInt3 &coord, TextBox &triggerTextBox);
// Handles the behavior for when the player activates a map transition block and transitions from one map
// to another (i.e., from an interior to an exterior). This does not handle level transitions.
void handleMapTransition(Game &game, const Physics::Hit &hit, const TransitionDefinition &transitionDef);
// Checks the given transition voxel to see if it's a level transition (i.e., level up/down), and changes
// the current level if it is.
void handleLevelTransition(Game &game, const CoordInt3 &playerCoord, const CoordInt3 &transitionCoord);
}
#endif
| 353 |
1,444 |
<filename>restclient-ui/src/main/java/org/wiztools/restclient/ui/resheader/ResHeaderPanel.java
package org.wiztools.restclient.ui.resheader;
import com.google.inject.ImplementedBy;
import org.wiztools.commons.MultiValueMap;
import org.wiztools.restclient.ui.ViewPanel;
/**
*
* @author subwiz
*/
@ImplementedBy(ResHeaderPanelImpl.class)
public interface ResHeaderPanel extends ViewPanel {
MultiValueMap<String, String> getHeaders();
void setHeaders(MultiValueMap<String, String> headers);
}
| 171 |
2,208 |
<filename>examples/supervised/neuralnets+svm/example_rnn.py
from __future__ import print_function
#!/usr/bin/env python
# Example script for recurrent network usage in PyBrain.
__author__ = "<NAME>"
__version__ = '$Id$'
from pylab import plot, hold, show
from scipy import sin, rand, arange
from pybrain.datasets import SequenceClassificationDataSet
from pybrain.structure.modules import LSTMLayer, SoftmaxLayer
from pybrain.supervised import RPropMinusTrainer
from pybrain.tools.validation import testOnSequenceData
from pybrain.tools.shortcuts import buildNetwork
from .datasets import generateNoisySines
# create training and test data
trndata = generateNoisySines(50, 40)
trndata._convertToOneOfMany( bounds=[0.,1.] )
tstdata = generateNoisySines(50, 20)
tstdata._convertToOneOfMany( bounds=[0.,1.] )
# construct LSTM network - note the missing output bias
rnn = buildNetwork( trndata.indim, 5, trndata.outdim, hiddenclass=LSTMLayer, outclass=SoftmaxLayer, outputbias=False, recurrent=True)
# define a training method
trainer = RPropMinusTrainer( rnn, dataset=trndata, verbose=True )
# instead, you may also try
##trainer = BackpropTrainer( rnn, dataset=trndata, verbose=True, momentum=0.9, learningrate=0.00001 )
# carry out the training
for i in range(100):
trainer.trainEpochs( 2 )
trnresult = 100. * (1.0-testOnSequenceData(rnn, trndata))
tstresult = 100. * (1.0-testOnSequenceData(rnn, tstdata))
print("train error: %5.2f%%" % trnresult, ", test error: %5.2f%%" % tstresult)
# just for reference, plot the first 5 timeseries
plot(trndata['input'][0:250,:],'-o')
hold(True)
plot(trndata['target'][0:250,0])
show()
| 607 |
2,261 |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import unittest.mock as mock
import numpy as np
import pytest
import torchvision.transforms as TF
from mmdet.core import BitmapMasks, PolygonMasks
from PIL import Image
import mmocr.datasets.pipelines.transforms as transforms
@mock.patch('%s.transforms.np.random.random_sample' % __name__)
@mock.patch('%s.transforms.np.random.randint' % __name__)
def test_random_crop_instances(mock_randint, mock_sample):
img_gt = np.array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 1, 1],
[0, 0, 1, 1, 1], [0, 0, 1, 1, 1]])
# test target is bigger than img size in sample_offset
mock_sample.side_effect = [1]
rci = transforms.RandomCropInstances(6, instance_key='gt_kernels')
(i, j) = rci.sample_offset(img_gt, (5, 5))
assert i == 0
assert j == 0
# test the second branch in sample_offset
rci = transforms.RandomCropInstances(3, instance_key='gt_kernels')
mock_sample.side_effect = [1]
mock_randint.side_effect = [1, 2]
(i, j) = rci.sample_offset(img_gt, (5, 5))
assert i == 1
assert j == 2
mock_sample.side_effect = [1]
mock_randint.side_effect = [1, 2]
rci = transforms.RandomCropInstances(5, instance_key='gt_kernels')
(i, j) = rci.sample_offset(img_gt, (5, 5))
assert i == 0
assert j == 0
# test the first bracnh is sample_offset
rci = transforms.RandomCropInstances(3, instance_key='gt_kernels')
mock_sample.side_effect = [0.1]
mock_randint.side_effect = [1, 1]
(i, j) = rci.sample_offset(img_gt, (5, 5))
assert i == 1
assert j == 1
# test crop_img(img, offset, target_size)
img = img_gt
offset = [0, 0]
target = [6, 6]
crop = rci.crop_img(img, offset, target)
assert np.allclose(img, crop[0])
assert np.allclose(crop[1], [0, 0, 5, 5])
target = [3, 2]
crop = rci.crop_img(img, offset, target)
assert np.allclose(np.array([[0, 0], [0, 0], [0, 0]]), crop[0])
assert np.allclose(crop[1], [0, 0, 2, 3])
# test crop_bboxes
canvas_box = np.array([2, 3, 5, 5])
bboxes = np.array([[2, 3, 4, 4], [0, 0, 1, 1], [1, 2, 4, 4],
[0, 0, 10, 10]])
kept_bboxes, kept_idx = rci.crop_bboxes(bboxes, canvas_box)
assert np.allclose(kept_bboxes,
np.array([[0, 0, 2, 1], [0, 0, 2, 1], [0, 0, 3, 2]]))
assert kept_idx == [0, 2, 3]
bboxes = np.array([[10, 10, 11, 11], [0, 0, 1, 1]])
kept_bboxes, kept_idx = rci.crop_bboxes(bboxes, canvas_box)
assert kept_bboxes.size == 0
assert kept_bboxes.shape == (0, 4)
assert len(kept_idx) == 0
# test __call__
rci = transforms.RandomCropInstances(3, instance_key='gt_kernels')
results = {}
gt_kernels = [img_gt, img_gt.copy()]
results['gt_kernels'] = BitmapMasks(gt_kernels, 5, 5)
results['img'] = img_gt.copy()
results['mask_fields'] = ['gt_kernels']
mock_sample.side_effect = [0.1]
mock_randint.side_effect = [1, 1]
output = rci(results)
target = np.array([[0, 0, 0], [0, 1, 1], [0, 1, 1]])
assert output['img_shape'] == (3, 3)
assert np.allclose(output['img'], target)
assert np.allclose(output['gt_kernels'].masks[0], target)
assert np.allclose(output['gt_kernels'].masks[1], target)
@mock.patch('%s.transforms.np.random.random_sample' % __name__)
def test_scale_aspect_jitter(mock_random):
img_scale = [(3000, 1000)] # unused
ratio_range = (0.5, 1.5)
aspect_ratio_range = (1, 1)
multiscale_mode = 'value'
long_size_bound = 2000
short_size_bound = 640
resize_type = 'long_short_bound'
keep_ratio = False
jitter = transforms.ScaleAspectJitter(
img_scale=img_scale,
ratio_range=ratio_range,
aspect_ratio_range=aspect_ratio_range,
multiscale_mode=multiscale_mode,
long_size_bound=long_size_bound,
short_size_bound=short_size_bound,
resize_type=resize_type,
keep_ratio=keep_ratio)
mock_random.side_effect = [0.5]
# test sample_from_range
result = jitter.sample_from_range([100, 200])
assert result == 150
# test _random_scale
results = {}
results['img'] = np.zeros((4000, 1000))
mock_random.side_effect = [0.5, 1]
jitter._random_scale(results)
# scale1 0.5, scale2=1 scale =0.5 650/1000, w, h
# print(results['scale'])
assert results['scale'] == (650, 2600)
@mock.patch('%s.transforms.np.random.random_sample' % __name__)
def test_random_rotate(mock_random):
mock_random.side_effect = [0.5, 0]
results = {}
img = np.random.rand(5, 5)
results['img'] = img.copy()
results['mask_fields'] = ['masks']
gt_kernels = [results['img'].copy()]
results['masks'] = BitmapMasks(gt_kernels, 5, 5)
rotater = transforms.RandomRotateTextDet()
results = rotater(results)
assert np.allclose(results['img'], img)
assert np.allclose(results['masks'].masks, img)
def test_color_jitter():
img = np.ones((64, 256, 3), dtype=np.uint8)
results = {'img': img}
pt_official_color_jitter = TF.ColorJitter()
output1 = pt_official_color_jitter(img)
color_jitter = transforms.ColorJitter()
output2 = color_jitter(results)
assert np.allclose(output1, output2['img'])
def test_affine_jitter():
img = np.ones((64, 256, 3), dtype=np.uint8)
results = {'img': img}
pt_official_affine_jitter = TF.RandomAffine(degrees=0)
output1 = pt_official_affine_jitter(Image.fromarray(img))
affine_jitter = transforms.AffineJitter(
degrees=0,
translate=None,
scale=None,
shear=None,
resample=False,
fillcolor=0)
output2 = affine_jitter(results)
assert np.allclose(np.array(output1), output2['img'])
def test_random_scale():
h, w, c = 100, 100, 3
img = np.ones((h, w, c), dtype=np.uint8)
results = {'img': img, 'img_shape': (h, w, c)}
polygon = np.array([0., 0., 0., 10., 10., 10., 10., 0.])
results['gt_masks'] = PolygonMasks([[polygon]], *(img.shape[:2]))
results['mask_fields'] = ['gt_masks']
size = 100
scale = (2., 2.)
random_scaler = transforms.RandomScaling(size=size, scale=scale)
results = random_scaler(results)
out_img = results['img']
out_poly = results['gt_masks'].masks[0][0]
gt_poly = polygon * 2
assert np.allclose(out_img.shape, (2 * h, 2 * w, c))
assert np.allclose(out_poly, gt_poly)
@mock.patch('%s.transforms.np.random.randint' % __name__)
def test_random_crop_flip(mock_randint):
img = np.ones((10, 10, 3), dtype=np.uint8)
img[0, 0, :] = 0
results = {'img': img, 'img_shape': img.shape}
polygon = np.array([0., 0., 0., 10., 10., 10., 10., 0.])
results['gt_masks'] = PolygonMasks([[polygon]], *(img.shape[:2]))
results['gt_masks_ignore'] = PolygonMasks([], *(img.shape[:2]))
results['mask_fields'] = ['gt_masks', 'gt_masks_ignore']
crop_ratio = 1.1
iter_num = 3
random_crop_fliper = transforms.RandomCropFlip(
crop_ratio=crop_ratio, iter_num=iter_num)
# test crop_target
pad_ratio = 0.1
h, w = img.shape[:2]
pad_h = int(h * pad_ratio)
pad_w = int(w * pad_ratio)
all_polys = results['gt_masks'].masks
h_axis, w_axis = random_crop_fliper.generate_crop_target(
img, all_polys, pad_h, pad_w)
assert np.allclose(h_axis, (0, 11))
assert np.allclose(w_axis, (0, 11))
# test __call__
polygon = np.array([1., 1., 1., 9., 9., 9., 9., 1.])
results['gt_masks'] = PolygonMasks([[polygon]], *(img.shape[:2]))
results['gt_masks_ignore'] = PolygonMasks([[polygon]], *(img.shape[:2]))
mock_randint.side_effect = [0, 1, 2]
results = random_crop_fliper(results)
out_img = results['img']
out_poly = results['gt_masks'].masks[0][0]
gt_img = img
gt_poly = polygon
assert np.allclose(out_img, gt_img)
assert np.allclose(out_poly, gt_poly)
@mock.patch('%s.transforms.np.random.random_sample' % __name__)
@mock.patch('%s.transforms.np.random.randint' % __name__)
def test_random_crop_poly_instances(mock_randint, mock_sample):
results = {}
img = np.zeros((30, 30, 3))
poly_masks = PolygonMasks([[
np.array([5., 5., 25., 5., 25., 10., 5., 10.])
], [np.array([5., 20., 25., 20., 25., 25., 5., 25.])]], 30, 30)
results['img'] = img
results['gt_masks'] = poly_masks
results['gt_masks_ignore'] = PolygonMasks([], 30, 30)
results['mask_fields'] = ['gt_masks', 'gt_masks_ignore']
results['gt_labels'] = [1, 1]
rcpi = transforms.RandomCropPolyInstances(
instance_key='gt_masks', crop_ratio=1.0, min_side_ratio=0.3)
# test sample_crop_box(img_size, results)
mock_randint.side_effect = [0, 0, 0, 0, 30, 0, 0, 0, 15]
crop_box = rcpi.sample_crop_box((30, 30), results)
assert np.allclose(np.array(crop_box), np.array([0, 0, 30, 15]))
# test __call__
mock_randint.side_effect = [0, 0, 0, 0, 30, 0, 15, 0, 30]
mock_sample.side_effect = [0.1]
output = rcpi(results)
target = np.array([5., 5., 25., 5., 25., 10., 5., 10.])
assert len(output['gt_masks']) == 1
assert len(output['gt_masks_ignore']) == 0
assert np.allclose(output['gt_masks'].masks[0][0], target)
assert output['img'].shape == (15, 30, 3)
# test __call__ with blank instace_key masks
mock_randint.side_effect = [0, 0, 0, 0, 30, 0, 15, 0, 30]
mock_sample.side_effect = [0.1]
rcpi = transforms.RandomCropPolyInstances(
instance_key='gt_masks_ignore', crop_ratio=1.0, min_side_ratio=0.3)
results['img'] = img
results['gt_masks'] = poly_masks
output = rcpi(results)
assert len(output['gt_masks']) == 2
assert np.allclose(output['gt_masks'].masks[0][0], poly_masks.masks[0][0])
assert np.allclose(output['gt_masks'].masks[1][0], poly_masks.masks[1][0])
assert output['img'].shape == (30, 30, 3)
@mock.patch('%s.transforms.np.random.random_sample' % __name__)
def test_random_rotate_poly_instances(mock_sample):
results = {}
img = np.zeros((30, 30, 3))
poly_masks = PolygonMasks(
[[np.array([10., 10., 20., 10., 20., 20., 10., 20.])]], 30, 30)
results['img'] = img
results['gt_masks'] = poly_masks
results['mask_fields'] = ['gt_masks']
rrpi = transforms.RandomRotatePolyInstances(rotate_ratio=1.0, max_angle=90)
mock_sample.side_effect = [0., 1.]
output = rrpi(results)
assert np.allclose(output['gt_masks'].masks[0][0],
np.array([10., 20., 10., 10., 20., 10., 20., 20.]))
assert output['img'].shape == (30, 30, 3)
@mock.patch('%s.transforms.np.random.random_sample' % __name__)
def test_square_resize_pad(mock_sample):
results = {}
img = np.zeros((15, 30, 3))
polygon = np.array([10., 5., 20., 5., 20., 10., 10., 10.])
poly_masks = PolygonMasks([[polygon]], 15, 30)
results['img'] = img
results['gt_masks'] = poly_masks
results['mask_fields'] = ['gt_masks']
srp = transforms.SquareResizePad(target_size=40, pad_ratio=0.5)
# test resize with padding
mock_sample.side_effect = [0.]
output = srp(results)
target = 4. / 3 * polygon
target[1::2] += 10.
assert np.allclose(output['gt_masks'].masks[0][0], target)
assert output['img'].shape == (40, 40, 3)
# test resize to square without padding
results['img'] = img
results['gt_masks'] = poly_masks
mock_sample.side_effect = [1.]
output = srp(results)
target = polygon.copy()
target[::2] *= 4. / 3
target[1::2] *= 8. / 3
assert np.allclose(output['gt_masks'].masks[0][0], target)
assert output['img'].shape == (40, 40, 3)
def test_pyramid_rescale():
img = np.random.randint(0, 256, size=(128, 100, 3), dtype=np.uint8)
x = {'img': copy.deepcopy(img)}
f = transforms.PyramidRescale()
results = f(x)
assert results['img'].shape == (128, 100, 3)
# Test invalid inputs
with pytest.raises(AssertionError):
transforms.PyramidRescale(base_shape=(128))
with pytest.raises(AssertionError):
transforms.PyramidRescale(base_shape=128)
with pytest.raises(AssertionError):
transforms.PyramidRescale(factor=[])
with pytest.raises(AssertionError):
transforms.PyramidRescale(randomize_factor=[])
with pytest.raises(AssertionError):
f({})
# Test factor = 0
f_derandomized = transforms.PyramidRescale(
factor=0, randomize_factor=False)
results = f_derandomized({'img': copy.deepcopy(img)})
assert np.all(results['img'] == img)
| 5,551 |
737 |
/* tree.cc
<NAME>, 24 April 2006
Copyright (c) 2006 <NAME>. All rights reserved.
$Source$
Tree class.
*/
#include "tree.h"
#include "jml/db/persistent.h"
#include "feature_space.h"
#include "config_impl.h"
using namespace std;
using namespace DB;
namespace ML {
/*****************************************************************************/
/* TREE::NODE */
/*****************************************************************************/
void Tree::Node::
serialize(DB::Store_Writer & store, const Feature_Space & fs) const
{
store << compact_size_t(4); // version
split.serialize(store, fs);
store << z << examples << pred;
child_true.serialize(store, fs);
child_false.serialize(store, fs);
child_missing.serialize(store, fs);
}
void Tree::Node::
reconstitute(DB::Store_Reader & store, const Feature_Space & fs,
Tree & parent)
{
compact_size_t version(store);
switch (version) {
case 3: {
split.reconstitute(store, fs);
store >> z >> examples;
child_true.reconstitute(store, fs, parent);
child_false.reconstitute(store, fs, parent);
child_missing.reconstitute(store, fs, parent);
pred.clear();
break;
}
case 4: {
split.reconstitute(store, fs);
store >> z >> examples >> pred;
child_true.reconstitute(store, fs, parent);
child_false.reconstitute(store, fs, parent);
child_missing.reconstitute(store, fs, parent);
break;
}
default:
throw Exception("Attempt to reconstitute decision tree node of unknown "
"version " + ostream_format(version.size_));
}
}
/*****************************************************************************/
/* TREE::BASE */
/*****************************************************************************/
void Tree::Base::
serialize(DB::Store_Writer & store) const
{
store << compact_size_t(1); // version
store << pred << examples;
}
void Tree::Base::
reconstitute(DB::Store_Reader & store)
{
compact_size_t version(store);
switch (version) {
case 1:
store >> pred >> examples;
break;
default:
throw Exception("Attempt to reconstitute decision tree base of unknown "
"version " + ostream_format(version.size_));
}
}
/*****************************************************************************/
/* TREE::PTR */
/*****************************************************************************/
void Tree::Ptr::
serialize(DB::Store_Writer & store, const Feature_Space & fs) const
{
store << compact_size_t(1); // version
store << compact_size_t(is_node_);
if (is_node_) node()->serialize(store, fs);
else leaf()->serialize(store);
}
void Tree::Ptr::
reconstitute(DB::Store_Reader & store, const Feature_Space & fs,
Tree & parent)
{
compact_size_t version(store);
switch (version) {
case 1: {
compact_size_t is_node(store);
is_node_ = is_node;
if (is_node_) {
ptr_.node = parent.new_node();
node()->reconstitute(store, fs, parent);
}
else {
ptr_.leaf = parent.new_leaf();
leaf()->reconstitute(store);
}
break;
}
default:
throw Exception("Attempt to reconstitute decision tree ptr of unknown "
"version " + ostream_format(version.size_));
}
}
/*****************************************************************************/
/* TREE */
/*****************************************************************************/
Tree::Tree()
: nodes_allocated(0), leafs_allocated(0),
nodes_destroyed(0), leafs_destroyed(0)
{
}
Tree::Ptr
tree_copy_recursive(const Tree::Ptr & from,
Tree & to)
{
if (from.node()) {
const Tree::Node * nfrom = from.node();
Tree::Node * result = to.new_node();
*result = *from.node();
result->child_true = tree_copy_recursive(nfrom->child_true, to);
result->child_false = tree_copy_recursive(nfrom->child_false, to);
result->child_missing = tree_copy_recursive(nfrom->child_missing, to);
return result;
}
else if (from.leaf())
return to.new_leaf(from.leaf()->pred, from.leaf()->examples);
return Tree::Ptr(); // null
}
Tree::Tree(const Tree & other)
: nodes_allocated(0), leafs_allocated(0),
nodes_destroyed(0), leafs_destroyed(0)
{
root = tree_copy_recursive(other.root, *this);
}
Tree &
Tree::
operator = (const Tree & other)
{
if (&other == this) return *this;
clear();
root = tree_copy_recursive(other.root, *this);
return *this;
}
Tree::~Tree()
{
//clear();
}
static Lock tree_alloc_lock;
void
Tree::
clear_recursive(Tree::Ptr & root)
{
Guard guard(tree_alloc_lock);
if (root.node()) {
Node * nroot = root.node();
clear_recursive(nroot->child_true);
clear_recursive(nroot->child_false);
clear_recursive(nroot->child_missing);
node_pool.destroy(nroot);
++nodes_destroyed;
}
else if (root.leaf()) {
leaf_pool.destroy(root.leaf());
++leafs_destroyed;
}
root = Tree::Ptr();
}
void Tree::clear()
{
clear_recursive(root);
//cerr << "Tree::clear(): after clear: alloc " << nodes_allocated
// << "/" << leafs_allocated << " destr "
// << nodes_destroyed << "/" << leafs_destroyed << endl;
}
Tree::Node * Tree::new_node()
{
Guard guard(tree_alloc_lock);
++nodes_allocated;
return node_pool.construct();
}
Tree::Leaf *
Tree::new_leaf(const distribution<float> & dist, float examples)
{
Guard guard(tree_alloc_lock);
++leafs_allocated;
return leaf_pool.construct(dist, examples);
}
Tree::Leaf *
Tree::new_leaf()
{
Guard guard(tree_alloc_lock);
++leafs_allocated;
return leaf_pool.construct();
}
void Tree::
serialize(DB::Store_Writer & store, const Feature_Space & fs) const
{
store << compact_size_t(1); // version
root.serialize(store, fs);
store << compact_size_t(3212345); // end marker
store << string("END_TREE");
}
void Tree::
reconstitute(DB::Store_Reader & store, const Feature_Space & fs)
{
compact_size_t version(store);
switch (version) {
case 1: {
root.reconstitute(store, fs, *this);
break;
}
default:
throw Exception("Decision tree: Attempt to reconstitute tree of "
"unknown version " + ostream_format(version.size_));
}
compact_size_t marker(store);
if (marker != 3212345)
throw Exception("Tree::reconstitute: "
"read bad marker at end");
string s;
store >> s;
if (s != "END_TREE")
throw Exception("Bad end Tree marker " + s);
}
std::string
printLabels(const distribution<float> & dist);
std::string print_outcome(const ML::Tree::Leaf & outcome)
{
string result;
const distribution<float> & dist = outcome.pred;
result += format(" (weight = %.2f) ", outcome.examples);
result += printLabels(dist);
return result;
}
} // namespace ML
| 3,086 |
1,210 |
// Style Guide => https://github.com/Bhupesh-V/30-Seconds-Of-STL/blob/master/CONTRIBUTING.md/#Style Guide
/*
Author : <NAME>
Date : 30/05/2019
Time : 01:00 PM
Description : emplace() function is used to add a new element at the end of the queue, after its current last element. The element is added to the queue container and the size of the queue is increased by 1.
*/
#include <iostream>
#include <queue>
int main(){
// Empty queue
std::queue<int> myqueue;
// adding elements into queue using emplace()
myqueue.emplace(0);
myqueue.emplace(1);
myqueue.emplace(2);
// print contents of queue
while (!myqueue.empty()){
std::cout << ' ' << myqueue.front();
myqueue.pop();
}
}
| 274 |
1,126 |
<filename>trie/trie.cpp
#include <iostream>
#include <cstring>
using namespace std;
// Determine size of array
#define ARRAY_SIZE(a) sizeof(a) / sizeof(a[0])
// Alphabet size (# of symbols)
#define ALPHABET_SIZE 26
// Convert char to int value
// only 'a' to 'z' are allowed chars
#define CHAR_TO_INT(c) ((int)c - (int)'a')
// TrieNode class
class TrieNode {
private:
// Children of every Node
class TrieNode *children[ALPHABET_SIZE];
// Status of Leaf Node
bool isLeaf;
public:
// Default Constructor
TrieNode() {
this->isLeaf = false;
for (int i = 0; i < ALPHABET_SIZE; ++i)
this->children[i] = NULL;
}
// Get leaf node status
bool get_leaf_status() { return isLeaf; }
// Set leaf node status
void set_leaf_status(bool status) { this->isLeaf = status; }
// Get Child status
// Check if it is null or not
bool get_child_status(int index) {
if (!(this->children[index]))
return true;
return false;
}
// Initialize the child node, at specific index
void initialize_child(int index) {
this->children[index] = new TrieNode();
}
// Get child node at specific index
class TrieNode *get_children(int index) {
return this->children[index];
}
// Insert into the Trie, Implemetation is below
void insert(string key);
// Search into the Trie, Implementation is below
bool search(string key);
};
/* Insert into the Trie
* args :
* key : String to insert into Trie
* Time Complexity: O(len(key))
*/
void TrieNode::insert(string key) {
// Determines the length of the key
int length = key.length();
// Temp variable for Crawling into the Trie
class TrieNode *pCrawl = this;
for (int level = 0; level < length; ++level) {
// determine the index of the child node to use
int index = CHAR_TO_INT(key[level]);
/* Check status of that child node
* If it is empty, them fill it
* If it is present, them use this as the next root
*/
if (pCrawl->get_child_status(index))
pCrawl->initialize_child(index);
pCrawl = pCrawl->get_children(index);
}
// set the last node status as leaf node
pCrawl->set_leaf_status(true);
};
/* Searches into the Trie
* args:
* key : string to search into Trie
* Time complexity : O(len(key))
*/
bool TrieNode::search(string key) {
// determines the length of the key
int length = key.length();
// Temp variable for crawling into the Trie
class TrieNode *pCrawl = this;
for (int level = 0; level < length; ++level) {
// determine index of the child node to use
int index = CHAR_TO_INT(key[level]);
/* Check status of the child node
* If it is empty, them return false i.e. key not present into Trie
* If it is present, them start crawling from that node
*/
if (pCrawl->get_child_status(index))
return false;
pCrawl = pCrawl->get_children(index);
}
// Check that the last node reached is leaf node and not null as well
return (pCrawl != NULL && pCrawl->get_leaf_status());
};
// Driver function
int main() {
// keys to insert into Trie
char keys[][8] = {"the", "a", "there", "answer", "any",
"by", "bye", "their"};
// Output the status of key
char output[][32] = {"Not present in trie", "Present in trie"};
// Root of Trie (Crawling starts from root, insertion as well)
class TrieNode *root = new TrieNode();
// Insertion into Trie
for (unsigned long i = 0; i < ARRAY_SIZE(keys); ++i)
root->insert(keys[i]);
// Output of searched keys
cout << output[root->search("the")] << endl;
cout << output[root->search("these")] << endl;
cout << output[root->search("thaw")] << endl;
cout << output[root->search("their")] << endl;
return 0;
}
| 1,281 |
403 |
package com.camunda.example.message.neworder;
import org.springframework.cloud.stream.annotation.Input;
import org.springframework.messaging.SubscribableChannel;
public interface NewOrderSink {
String channel = "newOrderInputChannel";
@Input(NewOrderSink.channel)
SubscribableChannel submitOrder();
}
| 96 |
4,538 |
<filename>solutions/eduk1_demo/k1_apps/aircraftBattle/aircraftBattle.c
#include "aircraftBattle.h"
#include <stdio.h>
#include <stdlib.h>
MENU_COVER_TYP aircraftBattle_cover = {MENU_COVER_FUNC, NULL, NULL,
aircraftBattle_cover_draw};
MENU_TASK_TYP aircraftBattle_tasks = {aircraftBattle_init,
aircraftBattle_uninit};
MENU_TYP aircraftBattle = {"aircraftBattle", &aircraftBattle_cover,
&aircraftBattle_tasks, aircraftBattle_key_handel,
NULL};
static aos_task_t aircraftBattle_task_handle;
#define MAX_L_CRAFT 1
#define MAX_M_CRAFT 5
#define MAX_S_CRAFT 10
#define MAX_BULLET 30
#define MY_CHANCE 3
#define AUTO_RELOAD -1024
uint8_t g_chance = MY_CHANCE;
dfo_t *my_craft;
dfo_t **bullet_group;
dfo_t **enemy_crafts;
static map_t achilles_normal0_map = {&icon_Mycraft0_19_19, -9, -9};
static map_t achilles_normal1_map = {&icon_Mycraft1_19_19, -9, -9};
static map_t achilles_normal2_map = {&icon_Mycraft2_19_19, -9, -9};
static map_t *achilles_normal_maplist[3] = {
&achilles_normal0_map, &achilles_normal1_map, &achilles_normal2_map};
static map_t achilles_destory0_map = {&icon_Mycraft_destory0_19_19, -9, -9};
static map_t achilles_destory1_map = {&icon_Mycraft_destory1_19_19, -9, -9};
static map_t achilles_destory2_map = {&icon_Mycraft_destory2_16_16, -7, -7};
static map_t *achilles_destory_maplist[3] = {
&achilles_destory0_map, &achilles_destory1_map, &achilles_destory2_map};
static arms_t achilles_arms0 = {-6, -3};
static arms_t achilles_arms1 = {6, -3};
static arms_t *achilles_arms_list[2] = {&achilles_arms0, &achilles_arms1};
static map_t titan_normal0_map = {&icon_Lcraft_32_32, -15, -15};
static map_t *titan_normal_maplist[1] = {&titan_normal0_map};
static map_t titan_destory0_map = {&icon_Lcraft_destory0_32_32, -15, -15};
static map_t titan_destory1_map = {&icon_Lcraft_destory1_32_32, -15, -15};
static map_t titan_destory2_map = {&icon_Lcraft_destory2_32_32, -15, -15};
static map_t *titan_destory_maplist[3] = {
&titan_destory0_map, &titan_destory1_map, &titan_destory2_map};
static map_t ares_normal0_map = {&icon_Mcraft_12_12, -5, -5};
static map_t *ares_normal_maplist[1] = {&ares_normal0_map};
static map_t ares_destory0_map = {&icon_Mcraft_destory0_12_12, -5, -5};
static map_t ares_destory1_map = {&icon_Mcraft_destory1_12_12, -5, -5};
static map_t ares_destory2_map = {&icon_Mcraft_destory2_12_12, -5, -5};
static map_t *ares_destory_maplist[3] = {&ares_destory0_map, &ares_destory1_map,
&ares_destory2_map};
static map_t venture_normal0_map = {&icon_Scraft_7_8, -3, -3};
static map_t *venture_normal_maplist[1] = {&venture_normal0_map};
static map_t venture_destory0_map = {&icon_Scraft_destory0_9_8, -4, -4};
static map_t venture_destory1_map = {&icon_Scraft_destory1_9_8, -4, -4};
static map_t venture_destory2_map = {&icon_Scraft_destory2_7_6, -3, -3};
static map_t *venture_destory_maplist[3] = {
&venture_destory0_map, &venture_destory1_map, &venture_destory2_map};
static map_t bullet_map = {&icon_bullet_2_1, 0, -1};
static map_t *bullet_maplist[1] = {&bullet_map};
void aircraftBattle_cover_draw(int *draw_index)
{
OLED_Clear();
OLED_Icon_Draw(0, 0, &img_craft_bg_132_64, 1);
for (int i = 0; i < random() % 20; i++) {
OLED_DrawPoint(random() % 132, random() % 64, 1);
}
for (int i = 0; i < random() % 10; i++) {
OLED_Icon_Draw(random() % 132, random() % 64, &icon_mini_start_3_3, 0);
}
OLED_Icon_Draw(2, 24, &icon_skip_left, 0);
OLED_Icon_Draw(122, 24, &icon_skip_right, 0);
OLED_Refresh_GRAM();
aos_msleep(800);
return 0;
}
dfo_t *create_achilles()
{
dfo_t *achilles = (dfo_t *)malloc(sizeof(dfo_t));
achilles->act_seq_list_len = 2;
act_seq_t *achilles_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t));
achilles_normal_act->act_seq_maps = achilles_normal_maplist;
achilles_normal_act->act_seq_len = 3;
achilles_normal_act->act_seq_interval = 10;
achilles_normal_act->act_is_destory = 0;
act_seq_t *achilles_destory_act = (act_seq_t *)malloc(sizeof(act_seq_t));
achilles_destory_act->act_seq_maps = achilles_destory_maplist;
achilles_destory_act->act_seq_len = 3;
achilles_destory_act->act_seq_interval = 4;
achilles_destory_act->act_is_destory = 1;
act_seq_t **achilles_act_seq_list =
(act_seq_t **)malloc(sizeof(act_seq_t *) * achilles->act_seq_list_len);
achilles_act_seq_list[0] = achilles_normal_act;
achilles_act_seq_list[1] = achilles_destory_act;
achilles->model = Achilles;
achilles->speed = 4;
achilles->range = -1;
achilles->act_seq_list = achilles_act_seq_list;
achilles->act_seq_type = 0;
achilles->damage = 8;
achilles->full_life = 10;
achilles->cur_life = 10;
achilles->arms_list_len = 2;
achilles->arms_list = achilles_arms_list;
reload_dfo(achilles, 31, 116);
return achilles;
}
dfo_t *create_titan()
{
dfo_t *titan = (dfo_t *)malloc(sizeof(dfo_t));
titan->act_seq_list_len = 2;
act_seq_t *titan_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t));
titan_normal_act->act_seq_maps = titan_normal_maplist;
titan_normal_act->act_seq_len = 1;
titan_normal_act->act_seq_interval = 0;
titan_normal_act->act_is_destory = 0;
act_seq_t *titan_destory_act = (act_seq_t *)malloc(sizeof(act_seq_t));
titan_destory_act->act_seq_maps = titan_destory_maplist;
titan_destory_act->act_seq_len = 3;
titan_destory_act->act_seq_interval = 4;
titan_destory_act->act_is_destory = 1;
act_seq_t **titan_act_seq_list =
(act_seq_t **)malloc(sizeof(act_seq_t *) * titan->act_seq_list_len);
titan_act_seq_list[0] = titan_normal_act;
titan_act_seq_list[1] = titan_destory_act;
titan->model = TiTan;
titan->speed = 1;
titan->range = -1;
titan->act_seq_list = titan_act_seq_list;
titan->act_seq_type = 0;
titan->damage = 100;
titan->full_life = 60;
titan->cur_life = 60;
titan->arms_list_len = 0;
titan->arms_list = NULL;
reload_dfo(titan, AUTO_RELOAD, AUTO_RELOAD);
return titan;
}
dfo_t *create_ares()
{
dfo_t *ares = (dfo_t *)malloc(sizeof(dfo_t));
ares->act_seq_list_len = 2;
act_seq_t *ares_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t));
ares_normal_act->act_seq_maps = ares_normal_maplist;
ares_normal_act->act_seq_len = 1;
ares_normal_act->act_seq_interval = 0;
ares_normal_act->act_is_destory = 0;
act_seq_t *ares_destory_act = (act_seq_t *)malloc(sizeof(act_seq_t));
ares_destory_act->act_seq_maps = ares_destory_maplist;
ares_destory_act->act_seq_len = 3;
ares_destory_act->act_seq_interval = 3;
ares_destory_act->act_is_destory = 1;
act_seq_t **ares_act_seq_list =
(act_seq_t **)malloc(sizeof(act_seq_t *) * ares->act_seq_list_len);
ares_act_seq_list[0] = ares_normal_act;
ares_act_seq_list[1] = ares_destory_act;
ares->model = Ares;
ares->speed = 2;
ares->range = -1;
ares->act_seq_list = ares_act_seq_list;
ares->act_seq_type = 0;
ares->damage = 8;
ares->full_life = 10;
ares->cur_life = 10;
ares->arms_list_len = 0;
ares->arms_list = NULL;
reload_dfo(ares, AUTO_RELOAD, AUTO_RELOAD);
return ares;
}
dfo_t *create_venture()
{
dfo_t *venture = (dfo_t *)malloc(sizeof(dfo_t));
venture->act_seq_list_len = 2;
act_seq_t *venture_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t));
venture_normal_act->act_seq_maps = venture_normal_maplist;
venture_normal_act->act_seq_len = 1;
venture_normal_act->act_seq_interval = 0;
venture_normal_act->act_is_destory = 0;
act_seq_t *venture_destory_act = (act_seq_t *)malloc(sizeof(act_seq_t));
venture_destory_act->act_seq_maps = venture_destory_maplist;
venture_destory_act->act_seq_len = 3;
venture_destory_act->act_seq_interval = 2;
venture_destory_act->act_is_destory = 1;
act_seq_t **venture_act_seq_list =
(act_seq_t **)malloc(sizeof(act_seq_t *) * venture->act_seq_list_len);
venture_act_seq_list[0] = venture_normal_act;
venture_act_seq_list[1] = venture_destory_act;
venture->model = Venture;
venture->speed = 3;
venture->range = -1;
venture->act_seq_list = venture_act_seq_list;
venture->act_seq_type = 0;
venture->damage = 5;
venture->full_life = 2;
venture->cur_life = 2;
venture->arms_list_len = 0;
venture->arms_list = NULL;
reload_dfo(venture, AUTO_RELOAD, AUTO_RELOAD);
return venture;
}
dfo_t *create_bullet()
{
dfo_t *bullet = (dfo_t *)malloc(sizeof(dfo_t));
bullet->act_seq_list_len = 1;
act_seq_t *bullet_normal_act = (act_seq_t *)malloc(sizeof(act_seq_t));
bullet_normal_act->act_seq_maps = bullet_maplist;
bullet_normal_act->act_seq_len = 1;
bullet_normal_act->act_seq_interval = 0;
bullet_normal_act->act_is_destory = 0;
act_seq_t **bullet_act_seq_list =
(act_seq_t **)malloc(sizeof(act_seq_t *) * bullet->act_seq_list_len);
bullet_act_seq_list[0] = bullet_normal_act;
bullet->model = Bullet;
bullet->speed = 10;
bullet->range = 120;
bullet->act_seq_list = bullet_act_seq_list;
bullet->act_seq_type = 0;
bullet->damage = 1;
bullet->full_life = 1;
bullet->cur_life = 0;
bullet->arms_list_len = 0;
bullet->arms_list = NULL;
bullet->start_x = -100;
bullet->start_y = -100;
bullet->cur_x = -100;
bullet->cur_y = -100;
return bullet;
}
void free_dfo(dfo_t *dfo)
{
for (int i = 0; i < dfo->act_seq_list_len; i++) {
free(dfo->act_seq_list[i]);
}
free(dfo->act_seq_list);
free(dfo);
}
void global_create(void)
{
my_craft = create_achilles();
bullet_group = (dfo_t **)malloc(sizeof(dfo_t *) * MAX_BULLET);
for (int i = 0; i < MAX_BULLET; i++) {
bullet_group[i] = create_bullet();
}
enemy_crafts = (dfo_t **)malloc(sizeof(dfo_t *) *
(MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT));
for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) {
if (i < MAX_L_CRAFT)
enemy_crafts[i] = create_titan();
else if (i < MAX_L_CRAFT + MAX_M_CRAFT && i >= MAX_L_CRAFT)
enemy_crafts[i] = create_ares();
else if (i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT &&
i >= MAX_L_CRAFT + MAX_M_CRAFT)
enemy_crafts[i] = create_venture();
}
}
void aircraftBattle_key_handel(key_code_t key_code)
{
switch (key_code) {
case 0b1000:
move_MyCraft(my_craft, LEFT);
break;
case 0b0001:
move_MyCraft(my_craft, UP);
break;
case 0b0100:
move_MyCraft(my_craft, DOWN);
break;
case 0b0010:
move_MyCraft(my_craft, RIGHT);
break;
default:
break;
}
}
map_t *get_cur_map(dfo_t *craft)
{
act_seq_t *cur_act_seq = craft->act_seq_list[craft->act_seq_type];
map_t *cur_map = cur_act_seq->act_seq_maps[cur_act_seq->act_seq_index];
return cur_map;
}
void reload_dfo(dfo_t *craft, int pos_x, int pos_y)
{
for (int i = 0; i < craft->act_seq_list_len; i++) {
craft->act_seq_list[i]->act_seq_index = 0;
craft->act_seq_list[i]->act_seq_interval_cnt = 0;
}
craft->start_x = pos_x;
craft->start_y = pos_y;
if (pos_x == AUTO_RELOAD) {
uint16_t height = get_cur_map(craft)->icon->width;
craft->start_x = random() % (64 - height) + height / 2;
}
if (pos_y == AUTO_RELOAD) {
uint16_t width = get_cur_map(craft)->icon->height;
craft->start_y = -(random() % 1000) - width / 2;
}
if (craft->model != Bullet)
LOGI(EDU_TAG, "reset craft %d at %d,%d\n", craft->model, craft->start_x,
craft->start_y);
craft->cur_x = craft->start_x;
craft->cur_y = craft->start_y;
craft->cur_life = craft->full_life;
craft->act_seq_type = 0;
}
void destory(dfo_t *craft)
{
craft->act_seq_type = 1;
craft->cur_life = 0;
}
void move_enemy(dfo_t *craft)
{
if (craft->cur_life <= 0)
return;
map_t *cur_map = get_cur_map(craft);
craft->cur_y += craft->speed;
int top = craft->cur_y + cur_map->offset_y;
if (top > 132)
reload_dfo(craft, AUTO_RELOAD, AUTO_RELOAD);
}
void move_MyCraft(dfo_t *my_craft, my_craft_dir_e_t dir)
{
if (my_craft->cur_life <= 0)
return;
map_t *cur_map = get_cur_map(my_craft);
int top = my_craft->cur_y + cur_map->offset_y;
int bottom = my_craft->cur_y + cur_map->offset_y + cur_map->icon->width;
int left = my_craft->cur_x + cur_map->offset_x;
int right = my_craft->cur_x + cur_map->offset_x + cur_map->icon->height;
switch (dir) {
case UP:
if (!(top - my_craft->speed < 0))
my_craft->cur_y -= my_craft->speed;
break;
case DOWN:
if (!(bottom + my_craft->speed > 132))
my_craft->cur_y += my_craft->speed;
break;
case LEFT:
if (!(left - my_craft->speed < 0))
my_craft->cur_x -= my_craft->speed;
break;
case RIGHT:
if (!(right + my_craft->speed > 64))
my_craft->cur_x += my_craft->speed;
break;
default:
break;
}
}
void move_bullet(dfo_t *bullet)
{
if (bullet->cur_life <= 0)
return;
map_t *cur_map = get_cur_map(bullet);
bullet->cur_y -= bullet->speed;
int bottom = bullet->cur_y + cur_map->offset_y + cur_map->icon->width;
if (bottom < 0 || (bullet->start_y - bullet->cur_y) > bullet->range) {
bullet->cur_life = 0;
bullet->cur_x = -100;
}
}
dfo_t *get_deactived_bullet()
{
for (int i = 0; i < MAX_BULLET; i++) {
if (bullet_group[i]->cur_life <= 0)
return bullet_group[i];
}
return NULL;
}
void shut_craft(dfo_t *craft)
{
if (craft->cur_life <= 0)
return;
if (craft->arms_list == NULL || craft->arms_list_len == 0)
return;
for (int i = 0; i < craft->arms_list_len; i++) {
dfo_t *bullet = get_deactived_bullet();
if (bullet == NULL)
return;
reload_dfo(bullet, craft->cur_x + craft->arms_list[i]->offset_x,
craft->cur_y + craft->arms_list[i]->offset_y);
}
}
void draw_dfo(dfo_t *dfo)
{
map_t *cur_map = get_cur_map(dfo);
int top = dfo->cur_y + cur_map->offset_y;
int bottom = dfo->cur_y + cur_map->offset_y + cur_map->icon->width;
int left = dfo->cur_x + cur_map->offset_x;
int right = dfo->cur_x + cur_map->offset_x + cur_map->icon->height;
if (top > 132 || bottom < 0 || left > 64 || right < 0)
return;
OLED_Icon_Draw(dfo->cur_y + cur_map->offset_y,
64 -
(dfo->cur_x + cur_map->offset_x + cur_map->icon->height),
cur_map->icon, 2);
}
void craft_update_act(dfo_t *craft)
{
act_seq_t *cur_act_seq = craft->act_seq_list[craft->act_seq_type];
if (cur_act_seq->act_seq_interval == 0)
return;
++(cur_act_seq->act_seq_interval_cnt);
if (cur_act_seq->act_seq_interval_cnt >= cur_act_seq->act_seq_interval) {
cur_act_seq->act_seq_interval_cnt = 0;
++(cur_act_seq->act_seq_index);
if (cur_act_seq->act_seq_index >= cur_act_seq->act_seq_len) {
cur_act_seq->act_seq_index = 0;
if (cur_act_seq->act_is_destory == 1) {
switch (craft->model) {
case Achilles:
reload_dfo(craft, 31, 116);
break;
case Venture:
case Ares:
case TiTan:
reload_dfo(craft, AUTO_RELOAD, AUTO_RELOAD);
break;
case Bullet:
break;
default:
break;
}
}
}
}
}
void global_update(void)
{
for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) {
craft_update_act(enemy_crafts[i]);
move_enemy(enemy_crafts[i]);
}
for (int i = 0; i < MAX_BULLET; i++) {
move_bullet(bullet_group[i]);
}
craft_update_act(my_craft);
shut_craft(my_craft);
global_hit_check();
}
void global_draw(void)
{
for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) {
draw_dfo(enemy_crafts[i]);
}
for (int i = 0; i < MAX_BULLET; i++) {
draw_dfo(bullet_group[i]);
}
draw_dfo(my_craft);
}
int hit_check(dfo_t *bullet, dfo_t *craft)
{
if (craft->cur_y <= 0 || craft->cur_x <= 0)
return 0;
if (craft->cur_life <= 0)
return 0;
if (bullet->cur_life <= 0)
return 0;
act_seq_t *cur_act_seq = bullet->act_seq_list[bullet->act_seq_type];
map_t *cur_map = cur_act_seq->act_seq_maps[cur_act_seq->act_seq_index];
for (int bullet_bit_x = 0; bullet_bit_x < (cur_map->icon->height);
bullet_bit_x++) {
for (int bullet_bit_y = 0; bullet_bit_y < (cur_map->icon->width);
bullet_bit_y++) {
uint8_t bit =
(cur_map->icon->p_icon_mask == NULL) ?
cur_map->icon
->p_icon_data[bullet_bit_x / 8 + bullet_bit_y] &
(0x01 << bullet_bit_x % 8) :
cur_map->icon
->p_icon_mask[bullet_bit_x / 8 + bullet_bit_y] &
(0x01 << bullet_bit_x % 8);
if (bit == 0)
continue;
int bit_cur_x = bullet->cur_x + cur_map->offset_x +
cur_map->icon->height - bullet_bit_x;
int bit_cur_y = bullet->cur_y + cur_map->offset_y + bullet_bit_y;
act_seq_t *cur_craft_act_seq =
craft->act_seq_list[craft->act_seq_type];
map_t *cur_craft_map =
cur_craft_act_seq
->act_seq_maps[cur_craft_act_seq->act_seq_index];
for (int craft_bit_x = 0;
craft_bit_x < (cur_craft_map->icon->height); craft_bit_x++) {
for (int craft_bit_y = 0;
craft_bit_y < (cur_craft_map->icon->width);
craft_bit_y++) {
uint8_t craft_bit =
(cur_craft_map->icon->p_icon_mask == NULL) ?
cur_craft_map->icon->p_icon_data[craft_bit_x / 8 +
craft_bit_y] &
(0x01 << craft_bit_x % 8) :
cur_craft_map->icon->p_icon_mask[craft_bit_x / 8 +
craft_bit_y] &
(0x01 << craft_bit_x % 8);
if (craft_bit == 0)
continue;
// 找到有效点对应的绝对坐标
int craft_bit_cur_x =
craft->cur_x + cur_craft_map->offset_x +
cur_craft_map->icon->height - craft_bit_x;
int craft_bit_cur_y =
craft->cur_y + cur_craft_map->offset_y + craft_bit_y;
// 开始遍历所有可撞击对象
if (craft_bit_cur_x == bit_cur_x &&
craft_bit_cur_y == bit_cur_y) {
return 1;
}
}
}
}
}
return 0;
}
void global_hit_check(void)
{
// 子弹撞击检测
for (int j = 0; j < MAX_BULLET; j++) {
dfo_t *bullet = bullet_group[j];
if (bullet->cur_life <= 0)
continue;
for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) {
dfo_t *craft = enemy_crafts[i];
if (craft->cur_life <= 0)
continue;
if (hit_check(bullet, craft)) {
craft->cur_life -= bullet->damage;
bullet->cur_life = 0;
bullet->cur_x = -100;
if (craft->cur_life <= 0) {
destory(craft);
}
continue;
}
}
}
// 我方飞机撞击检测
for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++) {
dfo_t *craft = enemy_crafts[i];
if (craft->cur_life <= 0)
continue;
if (hit_check(my_craft, craft)) {
craft->cur_life -= my_craft->damage;
my_craft->cur_life -= craft->damage;
if (craft->cur_life <= 0) {
destory(craft);
}
if (my_craft->cur_life <= 0) {
destory(my_craft);
g_chance--;
}
continue;
}
}
}
int aircraftBattle_init(void)
{
OLED_Clear();
OLED_Refresh_GRAM();
global_create();
g_chance = MY_CHANCE;
aos_task_new_ext(&aircraftBattle_task_handle, "aircraftBattle_task", aircraftBattle_task, NULL, 1024, AOS_DEFAULT_APP_PRI);
LOGI(EDU_TAG, "aos_task_new aircraftBattle_task\n");
return 0;
}
int aircraftBattle_uninit(void)
{
free_dfo(my_craft);
for (int i = 0; i < MAX_L_CRAFT + MAX_M_CRAFT + MAX_S_CRAFT; i++)
free_dfo(enemy_crafts[i]);
for (int i = 0; i < MAX_BULLET; i++)
free_dfo(bullet_group[i]);
aos_task_delete(&aircraftBattle_task_handle);
LOGI(EDU_TAG, "aos_task_delete aircraftBattle_task\n");
return 0;
}
void aircraftBattle_task()
{
while (1) {
if (g_chance > 0) {
OLED_Clear();
global_update();
global_draw();
OLED_Refresh_GRAM();
aos_msleep(40);
} else {
OLED_Clear();
OLED_Show_String(30, 12, "GAME OVER", 16, 1);
OLED_Show_String(10, 40, "press K1&K2 to quit", 12, 1);
OLED_Refresh_GRAM();
aos_msleep(1000);
}
}
}
| 11,956 |
17,085 |
<gh_stars>1000+
/* Copyright (c) 2021 PaddlePaddle Authors. 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. */
#ifdef PADDLE_WITH_ASCEND_CL
#include <memory>
#include <string>
#include "paddle/fluid/operators/kron_op.h"
#include "paddle/fluid/operators/npu_op_runner.h"
#include "paddle/fluid/operators/scatter_op.h"
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
template <typename DeviceContext, typename T>
class ScatterNPUKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* x = ctx.Input<Tensor>("X");
auto* index = ctx.Input<Tensor>("Ids");
auto* updates = ctx.Input<Tensor>("Updates");
bool overwrite = ctx.Attr<bool>("overwrite");
auto* out = ctx.Output<Tensor>("Out");
auto place = ctx.GetPlace();
out->mutable_data<T>(place);
framework::Tensor tmp_tensor(index->type());
const auto index_dims = index->dims();
if (index_dims.size() == 1) {
tmp_tensor.ShareDataWith(*index);
std::vector<int64_t> new_dim = {index_dims[0], 1};
tmp_tensor.Resize(framework::make_ddim(new_dim));
index = &tmp_tensor;
}
auto stream =
ctx.template device_context<paddle::platform::NPUDeviceContext>()
.stream();
if (overwrite) {
const auto& runner_update = NpuOpRunner(
"TensorScatterUpdate", {*x, *index, *updates}, {*out}, {});
runner_update.Run(stream);
} else {
const auto& runner_add =
NpuOpRunner("TensorScatterAdd", {*x, *index, *updates}, {*out}, {});
runner_add.Run(stream);
}
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP_NPU_KERNEL(
scatter, ops::ScatterNPUKernel<paddle::platform::NPUDeviceContext, float>,
ops::ScatterNPUKernel<paddle::platform::NPUDeviceContext,
paddle::platform::float16>);
#endif
| 919 |
6,181 |
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#pragma once
#include <map>
#include "api/replay/rdcarray.h"
#include "api/replay/replay_enums.h"
typedef unsigned int GLuint;
inline constexpr GPUCounter MakeIntelGlCounter(int index)
{
return GPUCounter((int)GPUCounter::FirstIntel + index);
}
class IntelGlCounters
{
public:
IntelGlCounters();
bool Init();
~IntelGlCounters();
rdcarray<GPUCounter> GetPublicCounterIds() const;
CounterDescription GetCounterDescription(GPUCounter index) const;
void EnableCounter(GPUCounter index);
void DisableAllCounters();
uint32_t GetPassCount();
void BeginSession();
void EndSession();
void BeginPass(uint32_t passID);
void EndPass();
void BeginSample(uint32_t sampleID);
void EndSample();
rdcarray<CounterResult> GetCounterData(uint32_t maxSampleIndex, const rdcarray<uint32_t> &eventIDs,
const rdcarray<GPUCounter> &counters);
private:
static uint32_t GPUCounterToCounterIndex(GPUCounter counter)
{
return (uint32_t)(counter) - (uint32_t)(GPUCounter::FirstIntel);
}
struct IntelGlCounter
{
CounterDescription desc;
GLuint queryId = 0;
GLuint offset = 0;
GLuint type = 0;
GLuint dataType = 0;
CompType originalType = CompType::Typeless;
uint32_t originalByteWidth = 0;
};
rdcarray<IntelGlCounter> m_Counters;
bool m_Paranoid = false;
struct IntelGlQuery
{
GLuint queryId = 0;
rdcstr name;
GLuint size = 0;
};
std::map<GLuint, IntelGlQuery> m_Queries;
void addCounter(const IntelGlQuery &query, GLuint counterId);
void addQuery(GLuint queryId);
uint32_t CounterPass(const IntelGlCounter &counter);
void CopyData(void *dest, const IntelGlCounter &counter, uint32_t sample, uint32_t maxSampleIndex);
rdcarray<uint32_t> m_EnabledQueries;
uint32_t m_passIndex;
rdcarray<GLuint> m_glQueries;
};
| 986 |
1,350 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.applicationinsights.generated;
import com.azure.core.util.Context;
import com.azure.resourcemanager.applicationinsights.models.StorageType;
/** Samples for ComponentLinkedStorageAccountsOperation Delete. */
public final class ComponentLinkedStorageAccountsOperationDeleteSamples {
/*
* x-ms-original-file: specification/applicationinsights/resource-manager/Microsoft.Insights/preview/2020-03-01-preview/examples/ComponentLinkedStorageAccountsDelete.json
*/
/**
* Sample code: ComponentLinkedStorageAccountsDelete.
*
* @param manager Entry point to ApplicationInsightsManager.
*/
public static void componentLinkedStorageAccountsDelete(
com.azure.resourcemanager.applicationinsights.ApplicationInsightsManager manager) {
manager
.componentLinkedStorageAccountsOperations()
.deleteWithResponse("someResourceGroupName", "myComponent", StorageType.SERVICE_PROFILER, Context.NONE);
}
}
| 353 |
334 |
//
// EChartViewController.h
// EChart
//
// Created by <NAME> on 11/12/13.
// Copyright (c) 2013 <NAME>. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface EChartViewController : UIViewController
@end
| 80 |
3,861 |
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "AutoRest Swagger BAT Header Service",
"description": "Test Infrastructure for AutoRest"
},
"host": "localhost:3000",
"schemes": [
"http"
],
"paths": {},
"responses": {
"200": {
"description": "The request was successful. Code was downloaded.",
"schema": {
"type": "file"
}
},
"401": {
"description": "The caller failed authentication"
},
"403": {
"description": "The caller does not have proper access to this API"
},
"default": {
"description": "Error response describing the reason for operation failure. The request failed.",
"schema": {
"$ref": "#/definitions/ErrorResponse"
}
}
},
"definitions": {
"ErrorDetails": {
"properties": {
"code": {
"description": "Status code for the error.",
"type": "string",
"readOnly": true
},
"message": {
"description": "Error message describing the error in detail.",
"type": "string",
"readOnly": true
},
"target": {
"description": "The target of the particular error.",
"type": "string",
"readOnly": true
}
}
},
"ErrorResponse": {
"description": "Error response indicates that the service is not able to process the incoming request. The reason is provided in the error message.",
"properties": {
"error": {
"$ref": "#/definitions/ErrorDetails",
"description": "The details of the error."
}
}
}
}
}
| 699 |
716 |
/* ============================================================
Copyright (c) 2002-2015 Advanced Micro Devices, 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:
+ Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
+ 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.
+ Neither the name of Advanced Micro Devices, Inc. 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 ADVANCED MICRO DEVICES,
INC. 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.
It is licensee's responsibility to comply with any export
regulations applicable in licensee's jurisdiction.
============================================================ */
#include "libm_amd.h"
#include "libm_util_amd.h"
#define USE_SPLITEXP
#define USE_SCALEDOUBLE_2
#define USE_VAL_WITH_FLAGS
#include "libm_inlines_amd.h"
#undef USE_SPLITEXP
#undef USE_SCALEDOUBLE_2
#undef USE_VAL_WITH_FLAGS
#include "libm_errno_amd.h"
double
FN_PROTOTYPE(mth_i_dtanh)(double x)
{
/*
The definition of tanh(x) is sinh(x)/cosh(x), which is also equivalent
to the following three formulae:
1. (exp(x) - exp(-x))/(exp(x) + exp(-x))
2. (1 - (2/(exp(2*x) + 1 )))
3. (exp(2*x) - 1)/(exp(2*x) + 1)
but computationally, some formulae are better on some ranges.
*/
static const double thirtytwo_by_log2 =
4.61662413084468283841e+01, /* 0x40471547652b82fe */
log2_by_32_lead = 2.16608493356034159660e-02, /* 0x3f962e42fe000000 */
log2_by_32_tail = 5.68948749532545630390e-11, /* 0x3dcf473de6af278e */
large_threshold = 20.0; /* 0x4034000000000000 */
__UINT8_T ux, aux, xneg;
double y, z, p, z1, z2;
int m;
/* Special cases */
GET_BITS_DP64(x, ux);
aux = ux & ~SIGNBIT_DP64;
if (aux < 0x3e30000000000000) /* |x| small enough that tanh(x) = x */
{
if (aux == 0)
return x; /* with no inexact */
else
return val_with_flags(x, AMD_F_INEXACT);
} else if (aux > 0x7ff0000000000000) /* |x| is NaN */
return x + x;
xneg = (aux != ux);
y = x;
if (xneg)
y = -x;
if (y > large_threshold) {
/* If x is large then exp(-x) is negligible and
formula 1 reduces to plus or minus 1.0 */
z = 1.0;
} else if (y <= 1.0) {
double y2;
y2 = y * y;
if (y < 0.9) {
/* Use a [3,3] Remez approximation on [0,0.9]. */
z = y +
y * y2 * (-0.274030424656179760118928e0 +
(-0.176016349003044679402273e-1 +
(-0.200047621071909498730453e-3 -
0.142077926378834722618091e-7 * y2) *
y2) *
y2) /
(0.822091273968539282568011e0 +
(0.381641414288328849317962e0 +
(0.201562166026937652780575e-1 +
0.2091140262529164482568557e-3 * y2) *
y2) *
y2);
} else {
/* Use a [3,3] Remez approximation on [0.9,1]. */
z = y +
y * y2 * (-0.227793870659088295252442e0 +
(-0.146173047288731678404066e-1 +
(-0.165597043903549960486816e-3 -
0.115475878996143396378318e-7 * y2) *
y2) *
y2) /
(0.683381611977295894959554e0 +
(0.317204558977294374244770e0 +
(0.167358775461896562588695e-1 +
0.173076050126225961768710e-3 * y2) *
y2) *
y2);
}
} else {
/* Compute p = exp(2*y) + 1. The code is basically inlined
from exp_amd. */
splitexp(2 * y, 1.0, thirtytwo_by_log2, log2_by_32_lead, log2_by_32_tail,
&m, &z1, &z2);
p = scaleDouble_2(z1 + z2, m) + 1.0;
/* Now reconstruct tanh from p. */
z = (1.0 - 2.0 / p);
}
if (xneg)
z = -z;
return z;
}
| 2,422 |
973 |
<filename>pcap4j-core/src/main/java/org/pcap4j/packet/RadiotapDataFhss.java
/*_##########################################################################
_##
_## Copyright (C) 2016 Pcap4J.org
_##
_##########################################################################
*/
package org.pcap4j.packet;
import org.pcap4j.packet.RadiotapPacket.RadiotapData;
import org.pcap4j.util.ByteArrays;
/**
* Radiotap FHSS field. The hop set and pattern for frequency-hopping radios.
*
* @see <a href="http://www.radiotap.org/defined-fields/FHSS">Radiotap</a>
* @author <NAME>
* @since pcap4j 1.6.5
*/
public final class RadiotapDataFhss implements RadiotapData {
/** */
private static final long serialVersionUID = 132223820938643993L;
private static final int LENGTH = 2;
private final byte hopSet;
private final byte hopPattern;
/**
* A static factory method. This method validates the arguments by {@link
* ByteArrays#validateBounds(byte[], int, int)}, which may throw exceptions undocumented here.
*
* @param rawData rawData
* @param offset offset
* @param length length
* @return a new RadiotapFhss object.
* @throws IllegalRawDataException if parsing the raw data fails.
*/
public static RadiotapDataFhss newInstance(byte[] rawData, int offset, int length)
throws IllegalRawDataException {
ByteArrays.validateBounds(rawData, offset, length);
return new RadiotapDataFhss(rawData, offset, length);
}
private RadiotapDataFhss(byte[] rawData, int offset, int length) throws IllegalRawDataException {
if (length < LENGTH) {
StringBuilder sb = new StringBuilder(200);
sb.append("The data is too short to build a RadiotapFhss (")
.append(LENGTH)
.append(" bytes). data: ")
.append(ByteArrays.toHexString(rawData, " "))
.append(", offset: ")
.append(offset)
.append(", length: ")
.append(length);
throw new IllegalRawDataException(sb.toString());
}
this.hopSet = ByteArrays.getByte(rawData, offset);
this.hopPattern = ByteArrays.getByte(rawData, offset + 1);
}
private RadiotapDataFhss(Builder builder) {
if (builder == null) {
throw new NullPointerException("builder is null.");
}
this.hopSet = builder.hopSet;
this.hopPattern = builder.hopPattern;
}
/** @return hopSet */
public byte getHopSet() {
return hopSet;
}
/** @return hopSet */
public int getHopSetAsInt() {
return hopSet & 0xFF;
}
/** @return hopPattern */
public byte getHopPattern() {
return hopPattern;
}
/** @return hopPattern */
public int getHopPatternAsInt() {
return hopPattern & 0xFF;
}
@Override
public int length() {
return LENGTH;
}
@Override
public byte[] getRawData() {
byte[] data = new byte[2];
data[0] = hopSet;
data[1] = hopPattern;
return data;
}
/** @return a new Builder object populated with this object's fields. */
public Builder getBuilder() {
return new Builder(this);
}
@Override
public String toString() {
return toString("");
}
@Override
public String toString(String indent) {
StringBuilder sb = new StringBuilder();
String ls = System.getProperty("line.separator");
sb.append(indent)
.append("FHSS: ")
.append(ls)
.append(indent)
.append(" Hop set: ")
.append(getHopSetAsInt())
.append(ls)
.append(indent)
.append(" Hop pattern: ")
.append(getHopPatternAsInt())
.append(ls);
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + hopPattern;
result = prime * result + hopSet;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
RadiotapDataFhss other = (RadiotapDataFhss) obj;
if (hopPattern != other.hopPattern) return false;
if (hopSet != other.hopSet) return false;
return true;
}
/**
* @author <NAME>
* @since pcap4j 1.6.5
*/
public static final class Builder {
private byte hopSet;
private byte hopPattern;
/** */
public Builder() {}
private Builder(RadiotapDataFhss obj) {
this.hopSet = obj.hopSet;
this.hopPattern = obj.hopPattern;
}
/**
* @param hopSet hopSet
* @return this Builder object for method chaining.
*/
public Builder hopSet(byte hopSet) {
this.hopSet = hopSet;
return this;
}
/**
* @param hopPattern hopPattern
* @return this Builder object for method chaining.
*/
public Builder hopPattern(byte hopPattern) {
this.hopPattern = hopPattern;
return this;
}
/** @return a new RadiotapFhss object. */
public RadiotapDataFhss build() {
return new RadiotapDataFhss(this);
}
}
}
| 1,871 |
1,091 |
<reponame>meodaiduoi/onos
/*
* Copyright 2015-present Open Networking Foundation
*
* 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.onosproject.cli.net;
import org.onlab.packet.ICMP6;
/**
* Known values for ICMPv6 type field that can be supplied to the CLI.
*/
public enum Icmp6Type {
/** Destination Unreachable. */
DEST_UNREACH(ICMP6.DEST_UNREACH),
/** Packet Too Big. */
PKT_TOO_BIG(ICMP6.PKT_TOO_BIG),
/** Time Exceeded. */
TIME_EXCEED(ICMP6.TIME_EXCEED),
/** Parameter Problem. */
PARAM_ERR(ICMP6.PARAM_ERR),
/** Echo Request. */
ECHO_REQUEST(ICMP6.ECHO_REQUEST),
/** Echo Reply. */
ECHO_REPLY(ICMP6.ECHO_REPLY),
/** Multicast Listener Query. */
MCAST_QUERY(ICMP6.MCAST_QUERY),
/** Multicast Listener Report. */
MCAST_REPORT(ICMP6.MCAST_REPORT),
/** Multicast Listener Done. */
MCAST_DONE(ICMP6.MCAST_DONE),
/** Router Solicitation. */
ROUTER_SOLICITATION(ICMP6.ROUTER_SOLICITATION),
/** Router Advertisement. */
ROUTER_ADVERTISEMENT(ICMP6.ROUTER_ADVERTISEMENT),
/** Neighbor Solicitation. */
NEIGHBOR_SOLICITATION(ICMP6.NEIGHBOR_SOLICITATION),
/** Neighbor Advertisement. */
NEIGHBOR_ADVERTISEMENT(ICMP6.NEIGHBOR_ADVERTISEMENT),
/** Redirect Message. */
REDIRECT(ICMP6.REDIRECT);
private byte value;
/**
* Constructs an Icmp6Type with the given value.
*
* @param value value to use when this Icmp6Type is seen
*/
private Icmp6Type(byte value) {
this.value = value;
}
/**
* Gets the value to use for this Icmp6Type.
*
* @return short value to use for this Icmp6Type
*/
public byte value() {
return this.value;
}
/**
* Parse a string input that could contain an Icmp6Type value. The value
* may appear in the string either as a known type name (one of the
* values of this enum), or a numeric type value.
*
* @param input the input string to parse
* @return the numeric value of the parsed ICMPv6 type
* @throws IllegalArgumentException if the input string does not contain a
* value that can be parsed into an ICMPv6 type
*/
public static byte parseFromString(String input) {
try {
return valueOf(input).value();
} catch (IllegalArgumentException e) {
// The input is not a known ICMPv6 type name, let's see if it's an ICMP6
// type value (byte). We parse with Byte to handle unsigned values
// correctly.
try {
return Byte.parseByte(input);
} catch (NumberFormatException e1) {
throw new IllegalArgumentException(
"Icmp6Type value must be either a string type name"
+ " or an 8-bit type value");
}
}
}
}
| 1,337 |
344 |
/* Copyright (c) 2014, ENEA Software AB
* Copyright (c) 2014, Nokia
* All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef __SOCKET_SEND_RECV_TCP_H__
#define __SOCKET_SEND_RECV_TCP_H__
int send_tcp4_local_ip(int fd);
int send_tcp4_any(int fd);
int send_multi_tcp4_any(int fd);
int send_tcp4_msg_waitall(int fd);
#ifdef INET6
int send_tcp6_local_ip(int fd);
int send_tcp6_any(int fd);
#endif /* INET6 */
int receive_tcp(int fd);
int receive_multi_tcp(int fd);
int receive_tcp4_msg_waitall(int fd);
#endif /* __SOCKET_SEND_RECV_TCP_H__ */
| 264 |
417 |
/*
** Copyright 2018 Bloomberg Finance L.P.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
#ifndef BLOOMBERG_QUANTUM_FIXTURE_H
#define BLOOMBERG_QUANTUM_FIXTURE_H
#include <gtest/gtest.h>
#include <quantum/quantum.h>
#include <unordered_map>
#include <memory>
#include <functional>
namespace quantum = Bloomberg::quantum;
struct TestConfiguration
{
TestConfiguration(bool loadBalance, bool coroutineSharingForAny) :
_loadBalance(loadBalance),
_coroutineSharingForAny(coroutineSharingForAny)
{
}
bool operator == (const TestConfiguration& that) const
{
return _loadBalance == that._loadBalance &&
_coroutineSharingForAny == that._coroutineSharingForAny;
}
bool _loadBalance;
bool _coroutineSharingForAny;
};
namespace std {
template<> struct hash<TestConfiguration>
{
size_t operator()(const TestConfiguration & x) const
{
return std::hash<bool>()(x._loadBalance) +
std::hash<bool>()(x._coroutineSharingForAny);
}
};
}
/// @brief Singleton class
class DispatcherSingleton
{
public:
static std::shared_ptr<quantum::Dispatcher> createInstance(const TestConfiguration& taskConfig)
{
quantum::Configuration config;
config.setNumCoroutineThreads(numCoro);
config.setNumIoThreads(numThreads);
config.setLoadBalanceSharedIoQueues(taskConfig._loadBalance);
config.setLoadBalancePollIntervalMs(std::chrono::milliseconds(10));
config.setCoroQueueIdRangeForAny(std::make_pair(1,numCoro-1));
config.setCoroutineSharingForAny(taskConfig._coroutineSharingForAny);
return std::make_shared<quantum::Dispatcher>(config);
}
static quantum::Dispatcher& instance(const TestConfiguration& config)
{
auto it = _dispatchers.find(config);
if (it == _dispatchers.end())
{
it = _dispatchers.emplace(config, createInstance(config)).first;
}
return *it->second;
}
static void deleteInstances()
{
_dispatchers.clear();
}
static constexpr int numCoro{4};
static constexpr int numThreads{5};
private:
using DispatcherMap = std::unordered_map<TestConfiguration, std::shared_ptr<quantum::Dispatcher>>;
static DispatcherMap _dispatchers;
};
/// @brief Fixture used for certain tests
class DispatcherFixture : public ::testing::TestWithParam<TestConfiguration>
{
public:
DispatcherFixture():
_dispatcher()
{
quantum::StackTraits::defaultSize() = 1 << 14; //16k stack for testing
}
/// @brief Create a dispatcher object with equal number of coroutine and IO threads
void SetUp()
{
_dispatcher = &DispatcherSingleton::instance(GetParam());
//Don't drain in the TearDown() because of the final CleanupTest::DeleteDispatcherInstance()
_dispatcher->drain();
_dispatcher->resetStats();
}
void TearDown()
{
_dispatcher = nullptr;
}
quantum::Dispatcher& getDispatcher()
{
return *_dispatcher;
}
protected:
quantum::Dispatcher* _dispatcher;
};
#endif //BLOOMBERG_QUANTUM_FIXTURE_H
| 1,444 |
400 |
<filename>tremor-cli/tests/integration/rest-linked-correlation/in.json
{"foo":"bar", "correlation": ["1", "2", "3"]}
{"foo":"baz", "correlation": "snot"}
{"foo":"booze", "correlation": ["badger"]}
{"foo": "snooze"}
{"exit": true}
| 91 |
2,151 |
<filename>chrome/browser/autocomplete/contextual_suggestions_service_factory.h
// 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 CHROME_BROWSER_AUTOCOMPLETE_CONTEXTUAL_SUGGESTIONS_SERVICE_FACTORY_H_
#define CHROME_BROWSER_AUTOCOMPLETE_CONTEXTUAL_SUGGESTIONS_SERVICE_FACTORY_H_
#include "base/macros.h"
#include "base/memory/singleton.h"
#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
class ContextualSuggestionsService;
class Profile;
class ContextualSuggestionsServiceFactory
: public BrowserContextKeyedServiceFactory {
public:
static ContextualSuggestionsService* GetForProfile(Profile* profile,
bool create_if_necessary);
static ContextualSuggestionsServiceFactory* GetInstance();
private:
friend struct base::DefaultSingletonTraits<
ContextualSuggestionsServiceFactory>;
ContextualSuggestionsServiceFactory();
~ContextualSuggestionsServiceFactory() override;
// Overrides from BrowserContextKeyedServiceFactory:
KeyedService* BuildServiceInstanceFor(
content::BrowserContext* context) const override;
DISALLOW_COPY_AND_ASSIGN(ContextualSuggestionsServiceFactory);
};
#endif // CHROME_BROWSER_AUTOCOMPLETE_CONTEXTUAL_SUGGESTIONS_SERVICE_FACTORY_H_
| 472 |
313 |
<gh_stars>100-1000
#ifndef RELAPACK_H
#define RELAPACK_H
void RELAPACK_slauum(const char *, const int *, float *, const int *, int *);
void RELAPACK_dlauum(const char *, const int *, double *, const int *, int *);
void RELAPACK_clauum(const char *, const int *, float *, const int *, int *);
void RELAPACK_zlauum(const char *, const int *, double *, const int *, int *);
void RELAPACK_strtri(const char *, const char *, const int *, float *, const int *, int *);
void RELAPACK_dtrtri(const char *, const char *, const int *, double *, const int *, int *);
void RELAPACK_ctrtri(const char *, const char *, const int *, float *, const int *, int *);
void RELAPACK_ztrtri(const char *, const char *, const int *, double *, const int *, int *);
void RELAPACK_spotrf(const char *, const int *, float *, const int *, int *);
void RELAPACK_dpotrf(const char *, const int *, double *, const int *, int *);
void RELAPACK_cpotrf(const char *, const int *, float *, const int *, int *);
void RELAPACK_zpotrf(const char *, const int *, double *, const int *, int *);
void RELAPACK_spbtrf(const char *, const int *, const int *, float *, const int *, int *);
void RELAPACK_dpbtrf(const char *, const int *, const int *, double *, const int *, int *);
void RELAPACK_cpbtrf(const char *, const int *, const int *, float *, const int *, int *);
void RELAPACK_zpbtrf(const char *, const int *, const int *, double *, const int *, int *);
void RELAPACK_ssytrf(const char *, const int *, float *, const int *, int *, float *, const int *, int *);
void RELAPACK_dsytrf(const char *, const int *, double *, const int *, int *, double *, const int *, int *);
void RELAPACK_csytrf(const char *, const int *, float *, const int *, int *, float *, const int *, int *);
void RELAPACK_chetrf(const char *, const int *, float *, const int *, int *, float *, const int *, int *);
void RELAPACK_zsytrf(const char *, const int *, double *, const int *, int *, double *, const int *, int *);
void RELAPACK_zhetrf(const char *, const int *, double *, const int *, int *, double *, const int *, int *);
void RELAPACK_ssytrf_rook(const char *, const int *, float *, const int *, int *, float *, const int *, int *);
void RELAPACK_dsytrf_rook(const char *, const int *, double *, const int *, int *, double *, const int *, int *);
void RELAPACK_csytrf_rook(const char *, const int *, float *, const int *, int *, float *, const int *, int *);
void RELAPACK_chetrf_rook(const char *, const int *, float *, const int *, int *, float *, const int *, int *);
void RELAPACK_zsytrf_rook(const char *, const int *, double *, const int *, int *, double *, const int *, int *);
void RELAPACK_zhetrf_rook(const char *, const int *, double *, const int *, int *, double *, const int *, int *);
void RELAPACK_sgetrf(const int *, const int *, float *, const int *, int *, int *);
void RELAPACK_dgetrf(const int *, const int *, double *, const int *, int *, int *);
void RELAPACK_cgetrf(const int *, const int *, float *, const int *, int *, int *);
void RELAPACK_zgetrf(const int *, const int *, double *, const int *, int *, int *);
void RELAPACK_sgbtrf(const int *, const int *, const int *, const int *, float *, const int *, int *, int *);
void RELAPACK_dgbtrf(const int *, const int *, const int *, const int *, double *, const int *, int *, int *);
void RELAPACK_cgbtrf(const int *, const int *, const int *, const int *, float *, const int *, int *, int *);
void RELAPACK_zgbtrf(const int *, const int *, const int *, const int *, double *, const int *, int *, int *);
void RELAPACK_ssygst(const int *, const char *, const int *, float *, const int *, const float *, const int *, int *);
void RELAPACK_dsygst(const int *, const char *, const int *, double *, const int *, const double *, const int *, int *);
void RELAPACK_chegst(const int *, const char *, const int *, float *, const int *, const float *, const int *, int *);
void RELAPACK_zhegst(const int *, const char *, const int *, double *, const int *, const double *, const int *, int *);
void RELAPACK_strsyl(const char *, const char *, const int *, const int *, const int *, const float *, const int *, const float *, const int *, float *, const int *, float *, int *);
void RELAPACK_dtrsyl(const char *, const char *, const int *, const int *, const int *, const double *, const int *, const double *, const int *, double *, const int *, double *, int *);
void RELAPACK_ctrsyl(const char *, const char *, const int *, const int *, const int *, const float *, const int *, const float *, const int *, float *, const int *, float *, int *);
void RELAPACK_ztrsyl(const char *, const char *, const int *, const int *, const int *, const double *, const int *, const double *, const int *, double *, const int *, double *, int *);
void RELAPACK_stgsyl(const char *, const int *, const int *, const int *, const float *, const int *, const float *, const int *, float *, const int *, const float *, const int *, const float *, const int *, float *, const int *, float *, float *, float *, const int *, int *, int *);
void RELAPACK_dtgsyl(const char *, const int *, const int *, const int *, const double *, const int *, const double *, const int *, double *, const int *, const double *, const int *, const double *, const int *, double *, const int *, double *, double *, double *, const int *, int *, int *);
void RELAPACK_ctgsyl(const char *, const int *, const int *, const int *, const float *, const int *, const float *, const int *, float *, const int *, const float *, const int *, const float *, const int *, float *, const int *, float *, float *, float *, const int *, int *, int *);
void RELAPACK_ztgsyl(const char *, const int *, const int *, const int *, const double *, const int *, const double *, const int *, double *, const int *, const double *, const int *, const double *, const int *, double *, const int *, double *, double *, double *, const int *, int *, int *);
void RELAPACK_sgemmt(const char *, const char *, const char *, const int *, const int *, const float *, const float *, const int *, const float *, const int *, const float *, float *, const int *);
void RELAPACK_dgemmt(const char *, const char *, const char *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);
void RELAPACK_cgemmt(const char *, const char *, const char *, const int *, const int *, const float *, const float *, const int *, const float *, const int *, const float *, float *, const int *);
void RELAPACK_zgemmt(const char *, const char *, const char *, const int *, const int *, const double *, const double *, const int *, const double *, const int *, const double *, double *, const int *);
#endif /* RELAPACK_H */
| 2,312 |
9,491 |
#define TSRMLS_D
#define TSRMLS_DC
#define TSRMLS_CC
#include <string.h>
| 37 |
9,724 |
/*
* Copyright 2014 The Emscripten Authors. All rights reserved.
* Emscripten is available under two separate licenses, the MIT license and the
* University of Illinois/NCSA Open Source License. Both these licenses can be
* found in the LICENSE file.
*/
#include <assert.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
FILE *fp;
int res;
long len;
fp = fopen("testappend", "wb+");
res = fwrite("1234567890", 10, 1, fp);
fclose(fp);
fp = fopen("testappend", "ab+");
res = fwrite("1234567890", 10, 1, fp);
fseek(fp, -7, SEEK_END);
len = ftell(fp);
assert(len == 13);
fclose(fp);
puts("success");
return 0;
}
| 257 |
532 |
/*******************************************************************************
MACROS.H
Author: <NAME>
Date: 13-APR-89
Copyright (c) 1992-5 MusculoGraphics, Inc.
All rights reserved.
Portions of this source code are copyrighted by MusculoGraphics, Inc.
*******************************************************************************/
#ifndef MACROS_H
#define MACROS_H
#define ABS(a) ((a)>0?(a):(-(a)))
#define DABS(a) ((a)>(double)0.0?(a):(-(a)))
#define EQUAL_WITHIN_ERROR(a,b) (DABS(((a)-(b))) <= ROUNDOFF_ERROR)
#define NOT_EQUAL_WITHIN_ERROR(a,b) (DABS(((a)-(b))) > ROUNDOFF_ERROR)
#define EQUAL_WITHIN_TOLERANCE(a,b,c) (DABS(((a)-(b))) <= (c))
#define NOT_EQUAL_WITHIN_TOLERANCE(a,b,c) (DABS(((a)-(b))) > (c))
#define NEAR_LT_OR_EQ(a, b) ((a) <= (b) + ROUNDOFF_ERROR)
#define NEAR_GT_OR_EQ(a, b) ((a) >= (b) - ROUNDOFF_ERROR)
#define SIGN(a) ((a)>=0?(1):(-1))
#define _MAX(a,b) ((a)>=(b)?(a):(b))
#define _MIN(a,b) ((a)<=(b)?(a):(b))
#define SQR(x) ((x) * (x))
#define CUBE(x) ((x) * (x) * (x))
#define DSIGN(a) ((a)>=0.0?(1):(-1))
#define CEILING(a,b) (((a)+(b)-1)/(b))
#define SETCOLOR(i,r,g,b) {root.color.cmap[i].red=r; root.color.cmap[i].green=g; \
root.color.cmap[i].blue=b;}
#define POP3FROMQ qread(&val);qread(&val);qread(&val)
#define IS_ODD(a) ((a) & 0x01)
#define IS_EVEN(a) ( ! IS_ODD(a))
#define FREE_IFNOTNULL(p) {if (p != NULL) {free(p); p = NULL;}}
#define STRLEN(p) (strlen(p)+1)
#define CURSOR_IN_BOX(mx,my,vp) ((SBoolean) ((mx) >= (vp).x1 && (mx) <= (vp).x2 && \
(my) >= (vp).y1 && (my) <= (vp).y2))
#define CURSOR_IN_VIEWPORT(mx,my,vp) ((SBoolean) ((mx) >= (vp)[0] && (mx) <= ((vp)[0] + (vp)[2]) && \
(my) >= (vp)[1] && (my) <= ((vp)[1] + (vp)[3])))
#define DISTANCE_FROM_MIDPOINT(mx,vp) ((mx) - (vp)[0] - ((vp)[2] * 0.5))
#define PERCENT_FROM_MIDPOINT(mx,vp) ((double)(((mx) - (vp)[0] - ((vp)[2] * 0.5)) / ((vp)[2] * 0.5)))
#define VECTOR_MAGNITUDE(vec) (sqrt((vec[0]*vec[0])+(vec[1]*vec[1])+(vec[2]*vec[2])))
#define CHAR_IS_WHITE_SPACE(ch) ((ch) == ' ' || (ch) == '\t' || (ch) == '\n' || (ch) == '\r')
#define CHAR_IS_NOT_WHITE_SPACE(ch) ((ch) != ' ' && (ch) != '\t' && (ch) != '\n' && (ch) != '\r')
#define NULLIFY_STRING(str) ((str)[0] = '\0')
#define STRING_IS_NULL(str) (str[0] == '\0')
#define STRING_IS_NOT_NULL(str) (str[0] != '\0')
#define STRINGS_ARE_EQUAL(ptr1,ptr2) (!strcmp(ptr1,ptr2))
#define STRINGS_ARE_NOT_EQUAL(ptr1,ptr2) (strcmp(ptr1,ptr2))
#define STRINGS_ARE_EQUAL_CI(ptr1,ptr2) (!stricmp(ptr1,ptr2))
#define STRINGS_ARE_NOT_EQUAL_CI(ptr1,ptr2) (stricmp(ptr1,ptr2))
#define FORCE_VALUE_INTO_RANGE(a,b,c) if ((a)<(b)) (a)=(b); else if ((a)>(c)) (a)=(c);
#define MODULATE_VALUE_INTO_RANGE(a,b,c) while ((a)<(b)) (a)+=((c)-(b)); \
while ((a)>(c)) (a)-=((c)-(b));
#define BOX_BIG_ENOUGH(box) (((box.x2 - box.x1 < 10) || (box.y2 - box.y1 < 10)) ? 0 : 1)
#define CHECK_DIVIDE(t,b) ((ABS(b))<TINY_NUMBER)?(ERROR_DOUBLE):((t)/(b))
#define SET_BOX1221(box,a,b,c,d) (box).x1=(a);(box).x2=(b);(box).y2=(c);(box).y1=(d)
#define SET_BOX(box,a,b,c,d) (box).x1=(a); (box).x2=(b); (box).y1=(c); (box).y2=(d)
#define GET_PATH(mod,f1,f2) (ms->pathptrs[ms->numsegments*f1+f2])
#define MAKE_3DVECTOR(pt1,pt2,pt3) {pt3[XX]=pt2[XX]-pt1[XX];pt3[YY]=pt2[YY]-pt1[YY];pt3[ZZ]=pt2[ZZ]-pt1[ZZ];}
#define MAKE_3DVECTOR21(pt1,pt2,pt3) {pt3[XX]=pt1[XX]-pt2[XX];pt3[YY]=pt1[YY]-pt2[YY];pt3[ZZ]=pt1[ZZ]-pt2[ZZ];}
#define DOT_VECTORS(u,v) ( (u[0])*(v[0]) + (u[1])*(v[1]) + (u[2])*(v[2]) )
#define CALC_DETERMINANT(m) (((m[0][0]) * ((m[1][1])*(m[2][2]) - (m[1][2])*(m[2][1]))) - \
((m[0][1]) * ((m[1][0])*(m[2][2]) - (m[1][2])*(m[2][0]))) + \
((m[0][2]) * ((m[1][0])*(m[2][1]) - (m[1][1])*(m[2][0]))))
#define ANGLES_APX_EQ(x, y) (DABS((x) - (y)) <= ANGLE_EPSILON)
#define PTS_ARE_EQUAL(Pt1, Pt2) (BOOL_APX_EQ(Pt1[0], Pt2[0]) && \
BOOL_APX_EQ(Pt1[1], Pt2[1]) && \
BOOL_APX_EQ(Pt1[2], Pt2[2]))
#define PTS_ARE_EQUAL3(Pt1, Pt2) (BOOL_APX_EQ3(Pt1[0], Pt2[0]) && \
BOOL_APX_EQ3(Pt1[1], Pt2[1]) && \
BOOL_APX_EQ3(Pt1[2], Pt2[2]))
#define READ4(ptr,fp) {\
*(((char*)(ptr)) )=getc(fp);\
*(((char*)(ptr))+1)=getc(fp);\
*(((char*)(ptr))+2)=getc(fp);\
*(((char*)(ptr))+3)=getc(fp);\
}
#define COPY_1X4VECTOR(from,to) {\
to[0] = from[0];\
to[1] = from[1];\
to[2] = from[2];\
to[3] = from[3];\
}
#define COPY_1X3VECTOR(from,to) {\
to[0] = from[0];\
to[1] = from[1];\
to[2] = from[2];\
}
#define MAKE_IDENTITY_MATRIX(mat) {\
mat[0][1] = mat[0][2] = mat[0][3] = 0.0;\
mat[1][0] = mat[1][2] = mat[1][3] = 0.0;\
mat[2][0] = mat[2][1] = mat[2][3] = 0.0;\
mat[3][0] = mat[3][1] = mat[3][2] = 0.0;\
mat[0][0] = mat[1][1] = mat[2][2] = mat[3][3] = 1.0;\
}
#define ADD_VECTORS(v1, v2, out) {\
out[0] = v1[0] + v2[0];\
out[1] = v1[1] + v2[1];\
out[2] = v1[2] + v2[2];\
}
#define SUB_VECTORS(v1, v2, out) {\
out[0] = v1[0] - v2[0];\
out[1] = v1[1] - v2[1];\
out[2] = v1[2] - v2[2];\
}
#endif /*MACROS_H*/
| 2,735 |
2,151 |
<reponame>DmPo/Schemaorg_CivicOS<filename>lib/html5lib/filters/inject_meta_charset.py
import _base
class Filter(_base.Filter):
def __init__(self, source, encoding):
_base.Filter.__init__(self, source)
self.encoding = encoding
def __iter__(self):
state = "pre_head"
meta_found = (self.encoding is None)
pending = []
for token in _base.Filter.__iter__(self):
type = token["type"]
if type == "StartTag":
if token["name"].lower() == u"head":
state = "in_head"
elif type == "EmptyTag":
if token["name"].lower() == u"meta":
# replace charset with actual encoding
has_http_equiv_content_type = False
for (namespace,name),value in token["data"].iteritems():
if namespace != None:
continue
elif name.lower() == u'charset':
token["data"][(namespace,name)] = self.encoding
meta_found = True
break
elif name == u'http-equiv' and value.lower() == u'content-type':
has_http_equiv_content_type = True
else:
if has_http_equiv_content_type and (None, u"content") in token["data"]:
token["data"][(None, u"content")] = u'text/html; charset=%s' % self.encoding
meta_found = True
elif token["name"].lower() == u"head" and not meta_found:
# insert meta into empty head
yield {"type": "StartTag", "name": u"head",
"data": token["data"]}
yield {"type": "EmptyTag", "name": u"meta",
"data": {(None, u"charset"): self.encoding}}
yield {"type": "EndTag", "name": u"head"}
meta_found = True
continue
elif type == "EndTag":
if token["name"].lower() == u"head" and pending:
# insert meta into head (if necessary) and flush pending queue
yield pending.pop(0)
if not meta_found:
yield {"type": "EmptyTag", "name": u"meta",
"data": {(None, u"charset"): self.encoding}}
while pending:
yield pending.pop(0)
meta_found = True
state = "post_head"
if state == "in_head":
pending.append(token)
else:
yield token
| 1,553 |
399 |
# -----------------------------------------------------------------------
# This script computes a weight value for each basis block of each functions. the algorithm is:
# 1. for each outgoing edge (i->j) of a BB i, assign a equal probability Eij, i.e. Eij= 1/n for a "n edges" BB.
# 2. assign root BB a weight of 1 (this is always reachable).
# 3. for each BB j, its weight is: W(j) = SUM (over i \in Pred(j)) W(i)*Eij
# after completion, it creates a pickle file that contains weights of BBs.
##Addintion: it also scans each function to find CMD instruction and check if it has some byte to compare with. All such bytes are saved in a pickle file that will be used to mutate inputs.
import idaapi
import idautils
import idc
#from idaapi import *
#from idautils import *
#from idc import *
from collections import deque
#import json
import timeit
import pickle
import string
## global definitions ##
edges=dict()## dictionary to keep edge's weights. key=(srcBB,dstBB), value=weight
weight=dict() ## dictionary to keep weight of a BB. key=BB_startAddr, value=(weight, BB_endAddr)
fweight=dict()## similar to weight. only value is replaced by (1.0/weight, BB_endAddr)
fCount=0
def findCMPopnds():
''' This funstion scans whole binary to find CMP instruction and get its operand which is immediate. Function returns a set of such values.
'''
cmpl=['cmp','CMP']
names=set()
result1=set()#contains full strings as they appear in the instruction
result2=set()#contains bytes of strings in instruction
# For each of the segments
for seg_ea in Segments():
for head in Heads(seg_ea, SegEnd(seg_ea)):
if isCode(GetFlags(head)):
mnem = GetMnem(head)
#print mnem
if mnem in cmpl:
for i in range(2):
if GetOpType(head,i)==5:
names.add(GetOpnd(head,i))
for el in names:
tm=el.rstrip('h')
if not all(c in string.hexdigits for c in tm):
continue # strange case: sometimes ida returns not immediate!!
if len(tm)%2 !=0:
tm='0'+tm
whx=''
for i in xrange(0,len(tm),2):
#hx=chr('\\x'+tm[i:i+2]
hx=chr(int(tm[i:i+2],16))
result2.add(hx)
whx=whx+hx
result1.add(whx)
#for e in result:
#print e
result1.difference_update(result2)
print result1, result2
return [result1,result2]
def get_children(BB):
'''
This function returns a list of BB ids which are children (transitive) of given BB.
'''
print "[*] finding childrens of BB: %x"%(BB.startEA,)
child=[]
tmp=deque([])
tmpShadow=deque([])
#visited=[]
for sbb in BB.succs():
tmp.append(sbb)
tmpShadow.append(sbb.startEA)
if len(tmp) == 0:
return child
while len(tmp)>0:
cur=tmp.popleft()
tmpShadow.popleft()
if cur.startEA not in child:
child.append(cur.startEA)
for cbbs in cur.succs():
if (cbbs.startEA not in child) and (cbbs.startEA not in tmpShadow):
tmp.append(cbbs)
tmpShadow.append(cbbs.startEA)
del tmp
del tmpShadow
return child
def calculate_weight(func, fAddr):
''' This function calculates weight for each BB, in the given function func.
'''
# We start by iterating all BBs and assigning weights to each outgoing edges.
# we assign a weight 0 to loopback edge because it does not point (i.e., leading) to "new" BB.
edges.clear()
temp = deque([]) # working queue
rootFound= False
visited=[] # list of BBid that are visited (weight calculated)
shadow=[]
noorphan=True
for block in func:
pLen=len(list(block.succs()))
if pLen == 0: # exit BB
continue
eProb=1.0/pLen #probability of each outgoing edge
#print "probability = %3.1f"%(eProb,), eProb
for succBB in block.succs():
if (succBB.startEA <= block.startEA) and (len(list(succBB.preds()))>1):
#this is for backedge. this is not entirely correct as BB which are shared or are at lower
#addresses are tagged as having zero value!! TO FIX.
edges[(block.startEA,succBB.startEA)]=1.0
else:
edges[(block.startEA,succBB.startEA)]=eProb
print "[*] Finished edge probability calculation"
#for edg in edges:
#print " %x -> %x: %3.1f "%(edg[0],edg[1],edges[edg])
# lets find the root BB
#orphanage=[]#home for orphan BBs
orphID=[]
for block in func:
if len(list(block.preds())) == 0:
#Note: this only check was not working as there are orphan BB in code. Really!!!
if block.startEA == fAddr:
rootFound=True
root = block
else:
if rootFound==True:
noorphan=False
break
pass
#now, all the BBs should be children of root node and those that are not children are orphans. This check is required only if we have orphans.
if noorphan == False:
rch=get_children(root)
rch.append(fAddr)# add root also as a non-orphan BB
for blk in func:
if blk.startEA not in rch:
weight[blk.startEA]=(1.0,blk.endEA)
visited.append(blk.id)
orphID.append(blk.id)
#print "[*] orphanage calculation done."
del rch
if rootFound==True:
#print "[*] found root BB at %x"%(root.startEA,)
weight[root.startEA] = (1.0,root.endEA)
visited.append(root.id)
print "[*] Root found. Starting weight calculation."
for sBlock in root.succs():
#if sBlock.id not in shadow:
#print "Pushing successor %x"%(sBlock.startEA,)
temp.append(sBlock)
shadow.append(sBlock.id)
loop=dict()# this is a temp dictionary to avoid get_children() call everytime a BB is analysed.
while len(temp) > 0:
current=temp.popleft()
shadow.remove(current.id)
print "current: %x"%(current.startEA,)
if current.id not in loop:
loop[current.id]=[]
# we check for orphan BB and give them a lower score
# by construction and assumptions, this case should not hit!
if current.id in orphID:
#weight[current.startEA]=(0.5,current.endEA)
#visited.append(current.id)
continue
tempSum=0.0
stillNot=False
chCalculated=False
for pb in current.preds():
#print "[*] pred of current %x"%(pb.startEA,)
if pb.id not in visited:
if edges[(pb.startEA,current.startEA)]==0.0:
weight[pb.startEA]=(0.5,pb.endEA)
#artificial insertion
#print "artificial insertion branch"
continue
if pb.id not in [k[0] for k in loop[current.id]]:
if chCalculated == False:
chCurrent=get_children(current)
chCalculated=True
if pb.startEA in chCurrent:
# this BB is in a loop. we give less score to such BB
weight[pb.startEA]=(0.5,pb.endEA)
loop[current.id].append((pb.id,True))
#print "loop branch"
continue
else:
loop[current.id].append((pb.id,False))
else:
if (pb.id,True) in loop[current.id]:
weight[pb.startEA]=(0.5,pb.endEA)
continue
#print "not pred %x"%(pb.startEA,)
if current.id not in shadow:
temp.append(current)
#print "pushed back %x"%(current.startEA,)
shadow.append(current.id)
stillNot=True
break
if stillNot == False:
# as we sure to get weight for current, we push its successors
for sb in current.succs():
if sb.id in visited:
continue
if sb.id not in shadow:
temp.append(sb)
shadow.append(sb.id)
for pb in current.preds():
tempSum = tempSum+ (weight[pb.startEA][0]*edges[(pb.startEA,current.startEA)])
weight[current.startEA] = (tempSum,current.endEA)
visited.append(current.id)
del loop[current.id]
print "completed %x"%(current.startEA,)
#print "remaining..."
#for bs in temp:
#print "\t %x"%(bs.startEA,)
def analysis():
global fCount
all_funcs = idautils.Functions()
for f in all_funcs:
fflags=idc.GetFunctionFlags(f)
if (fflags & FUNC_LIB) or (fflags & FUNC_THUNK):
continue
fCount = fCount+1
print "In %s:\n"%(idc.GetFunctionName(f),)
fAddr=GetFunctionAttr(f,FUNCATTR_START)
f = idaapi.FlowChart(idaapi.get_func(f),flags=idaapi.FC_PREDS)
calculate_weight(f,fAddr)
def main():
# TODO: ask for the pickled file that contains so far discovered BB's weights.
## TODO: it is perhaps a better idea to check "idaapi.get_imagebase()" so that at runtime, we can calculate correct address from this static compile time address.
strings=[]
start = timeit.default_timer()
analysis()
strings=findCMPopnds()
stop = timeit.default_timer()
for bb in weight:
fweight[bb]=(1.0/weight[bb][0],weight[bb][1])
print"[**] Printing weights..."
for bb in fweight:
print "BB [%x-%x] -> %3.2f"%(bb,fweight[bb][1],fweight[bb][0])
print " [**] Total Time: ", stop - start
print "[**] Total functions analyzed: %d"%(fCount,)
print "[**] Total BB analyzed: %d"%(len(fweight),)
outFile=GetInputFile() # name of the that is being analysed
strFile=outFile+".names"
outFile=outFile+".pkl"
fd=open(outFile,'w')
pickle.dump(fweight,fd)
fd.close()
strFD=open(strFile,'w')
pickle.dump(strings,strFD)
strFD.close()
print "[*] Saved results in pickle files: %s, %s"%(outFile,strFile)
if __name__ == "__main__":
main()
| 5,306 |
2,937 |
<reponame>dawlane/ogre
#ifndef __Character_H__
#define __Character_H__
#include "SdkSample.h"
#include "SinbadCharacterController.h"
using namespace Ogre;
using namespace OgreBites;
class _OgreSampleClassExport Sample_Character : public SdkSample
{
public:
Sample_Character()
{
mInfo["Title"] = "Character";
mInfo["Description"] = "A demo showing 3rd-person character control and use of TagPoints.";
mInfo["Thumbnail"] = "thumb_char.png";
mInfo["Category"] = "Animation";
mInfo["Help"] = "Use the WASD keys to move Sinbad, and the space bar to jump. "
"Use mouse to look around and mouse wheel to zoom. Press Q to take out or put back "
"Sinbad's swords. With the swords equipped, you can left click to slice vertically or "
"right click to slice horizontally. When the swords are not equipped, press E to "
"start/stop a silly dance routine.";
}
bool frameRenderingQueued(const FrameEvent& evt)
{
// let character update animations and camera
mChara->addTime(evt.timeSinceLastFrame);
return SdkSample::frameRenderingQueued(evt);
}
bool keyPressed(const KeyboardEvent& evt)
{
// relay input events to character controller
if (!mTrayMgr->isDialogVisible()) mChara->injectKeyDown(evt);
return SdkSample::keyPressed(evt);
}
bool keyReleased(const KeyboardEvent& evt)
{
// relay input events to character controller
if (!mTrayMgr->isDialogVisible()) mChara->injectKeyUp(evt);
return SdkSample::keyReleased(evt);
}
bool mouseMoved(const MouseMotionEvent& evt)
{
// Relay input events to character controller.
if (!mTrayMgr->isDialogVisible()) mChara->injectMouseMove(evt);
return SdkSample::mouseMoved(evt);
}
virtual bool mouseWheelRolled(const MouseWheelEvent& evt) {
// Relay input events to character controller.
if (!mTrayMgr->isDialogVisible()) mChara->injectMouseWheel(evt);
return SdkSample::mouseWheelRolled(evt);
}
bool mousePressed(const MouseButtonEvent& evt)
{
// Relay input events to character controller.
if (!mTrayMgr->isDialogVisible()) mChara->injectMouseDown(evt);
return SdkSample::mousePressed(evt);
}
protected:
void setupContent()
{
// set background and some fog
mViewport->setBackgroundColour(ColourValue(1.0f, 1.0f, 0.8f));
mSceneMgr->setFog(Ogre::FOG_LINEAR, ColourValue(1.0f, 1.0f, 0.8f), 0, 15, 100);
// set shadow properties
mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE);
mSceneMgr->setShadowColour(ColourValue(0.5, 0.5, 0.5));
mSceneMgr->setShadowTextureSize(1024);
mSceneMgr->setShadowTextureCount(1);
mSceneMgr->setShadowDirLightTextureOffset(0);
mSceneMgr->setShadowFarDistance(50);
mSceneMgr->setShadowCameraSetup(FocusedShadowCameraSetup::create());
// disable default camera control so the character can do its own
mCameraMan->setStyle(CS_MANUAL);
// use a small amount of ambient lighting
mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3));
// add a bright light above the scene
Light* light = mSceneMgr->createLight(Light::LT_POINT);
mSceneMgr->getRootSceneNode()
->createChildSceneNode(Vector3(-10, 40, 20))
->attachObject(light);
light->setSpecularColour(ColourValue::White);
// create a floor mesh resource
MeshManager::getSingleton().createPlane("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Plane(Vector3::UNIT_Y, 0), 100, 100, 10, 10, true, 1, 10, 10, Vector3::UNIT_Z);
// create a floor entity, give it a material, and place it at the origin
Entity* floor = mSceneMgr->createEntity("Floor", "floor");
floor->setMaterialName("Examples/Rockwall");
floor->setCastShadows(false);
mSceneMgr->getRootSceneNode()->attachObject(floor);
// LogManager::getSingleton().logMessage("creating sinbad");
// create our character controller
mChara = new SinbadCharacterController(mCamera);
// LogManager::getSingleton().logMessage("toggling stats");
mTrayMgr->toggleAdvancedFrameStats();
// LogManager::getSingleton().logMessage("creating panel");
StringVector items;
items.push_back("Help");
ParamsPanel* help = mTrayMgr->createParamsPanel(TL_TOPLEFT, "HelpMessage", 100, items);
help->setParamValue("Help", "H / F1");
// LogManager::getSingleton().logMessage("all done");
}
void cleanupContent()
{
// clean up character controller and the floor mesh
if (mChara)
{
delete mChara;
mChara = 0;
}
MeshManager::getSingleton().remove("floor", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
}
SinbadCharacterController* mChara;
};
#endif
| 2,045 |
357 |
/**
*
*/
package com.vmware.identity;
import static com.vmware.identity.SharedUtils.bootstrap;
import static com.vmware.identity.SharedUtils.buildMockRequestObject;
import static com.vmware.identity.SharedUtils.buildMockResponseSuccessObject;
import static com.vmware.identity.SharedUtils.createSamlAuthnRequest;
import static com.vmware.identity.SharedUtils.createSamlAuthnResponse;
import static com.vmware.identity.SharedUtils.getMockIdmAccessorFactory;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opensaml.saml.saml2.core.AuthnRequest;
import org.opensaml.saml.saml2.core.Response;
import com.vmware.identity.idm.ServerConfig;
import com.vmware.identity.proxyservice.LogonProcessorImpl;
import com.vmware.identity.samlservice.AuthenticationFilter;
import com.vmware.identity.samlservice.AuthnRequestState;
import com.vmware.identity.samlservice.Shared;
import com.vmware.identity.samlservice.TestAuthnRequestStateAuthenticationFilter;
import com.vmware.identity.samlservice.impl.AuthnRequestStateCookieWrapper;
import com.vmware.identity.session.impl.SessionManagerImpl;
/**
* @author root
*
*/
public class LogonProcessorImplTest {
private static final int tenantId = 0;
static LogonProcessorImpl processor;
private static SessionManagerImpl sessionManager;
private static String tenant;
private static AuthenticationFilter<AuthnRequestState> filter;
@BeforeClass
public static void setUp() throws Exception {
sessionManager = new SessionManagerImpl();
Shared.bootstrap();
bootstrap();
tenant = ServerConfig.getTenant(0);
processor = new LogonProcessorImpl();
filter = new AuthnRequestStateCookieWrapper(
new TestAuthnRequestStateAuthenticationFilter(tenantId));
}
@Test
public void testRegisterRequestState() throws Exception {
String incomingReqId = "200";
String outRequestId = "42";
AuthnRequest authnRequest = createSamlAuthnRequest(outRequestId, tenantId);
StringBuffer sbRequestUrl = new StringBuffer();
sbRequestUrl.append(authnRequest.getDestination());
HttpServletRequest incomingRequest = buildMockRequestObject(authnRequest, null, null, null, sbRequestUrl,
TestConstants.AUTHORIZATION, null, tenantId);
HttpServletResponse response = buildMockResponseSuccessObject(new StringWriter(), Shared.HTML_CONTENT_TYPE,
false, null);
AuthnRequestState requestState = new AuthnRequestState(incomingRequest, response, sessionManager, tenant,
getMockIdmAccessorFactory(tenantId, 0));
requestState.parseRequestForTenant(tenant, filter);
processor.registerRequestState(incomingReqId, outRequestId, requestState);
Response authnResponse = createSamlAuthnResponse(outRequestId, tenantId, 0);
HttpServletRequest outgoingRequest = buildMockRequestObject(authnResponse, null, null, null, sbRequestUrl, null,
null, tenantId);
Method method = LogonProcessorImpl.class.getDeclaredMethod("findOriginalRequestState", HttpServletRequest.class);
method.setAccessible(true);
AuthnRequestState result = (AuthnRequestState) method.invoke(processor, outgoingRequest);
Assert.assertEquals(requestState.getAuthnRequest().getID(), result.getAuthnRequest().getID());
}
@SuppressWarnings("unchecked")
@Test
public void testStateMapCleanup() throws Exception {
//clean maps in logonprocessimpl
Field outgoingReqToIncomingReqMap = LogonProcessorImpl.class.getDeclaredField("outgoingReqToIncomingReqMap");
outgoingReqToIncomingReqMap.setAccessible(true);
Field authnReqStateMap = LogonProcessorImpl.class.getDeclaredField("authnReqStateMap");
authnReqStateMap.setAccessible(true);
Map<String, String> inReqIDMap = (Map<String, String>) outgoingReqToIncomingReqMap.get(processor);
Map<String, AuthnRequestState> stateMap = (Map<String, AuthnRequestState>) authnReqStateMap.get(processor);
stateMap.clear();
inReqIDMap.clear();
//add entries
int diff = 1000;
Integer incomingReqId = 1;
Integer outRequestId = incomingReqId + diff;
Integer threshHoldSize = LogonProcessorImpl.THRESHHOLD_SIZE_FOR_MAP_CHECK;
Integer numberOfEntriesToBeAdded = threshHoldSize + 10;
Date dateOld = new Date(System.currentTimeMillis()-24*60*60*1000);
HttpServletRequest incomingRequest = null;
StringBuffer sbRequestUrl = null;
AuthnRequestState requestState = null;
while (incomingReqId <= numberOfEntriesToBeAdded) {
AuthnRequest authnRequest = createSamlAuthnRequest(outRequestId.toString(), tenantId);
sbRequestUrl = new StringBuffer();
sbRequestUrl.append(authnRequest.getDestination());
incomingRequest = buildMockRequestObject(authnRequest, null, null, null, sbRequestUrl,
TestConstants.AUTHORIZATION, null, tenantId);
HttpServletResponse response = buildMockResponseSuccessObject(new StringWriter(), Shared.HTML_CONTENT_TYPE,
false, null);
requestState = new AuthnRequestState(incomingRequest, response, sessionManager, tenant,
getMockIdmAccessorFactory(tenantId, 0));
requestState.setStartTime(dateOld);
requestState.parseRequestForTenant(tenant, filter);
processor.registerRequestState(incomingReqId.toString(), outRequestId.toString(), requestState);
outRequestId++;
incomingReqId++;
}
//check map size == nubmerOfEntriesRemain. all other entries were removed in the last add operation
Integer nubmerOfEntriesRemain = numberOfEntriesToBeAdded - threshHoldSize;
Assert.assertTrue(nubmerOfEntriesRemain == inReqIDMap.size());
Assert.assertTrue(nubmerOfEntriesRemain == stateMap.size());
Integer inReqIdofLastItem = numberOfEntriesToBeAdded;
Integer outReqIdofLastItem = inReqIdofLastItem + diff;
Response authnResponse = createSamlAuthnResponse(outReqIdofLastItem.toString(), tenantId, 0);
HttpServletRequest outgoingRequest = buildMockRequestObject(authnResponse, null, null, null, sbRequestUrl, null,
null, tenantId);
Method method = LogonProcessorImpl.class.getDeclaredMethod("findOriginalRequestState", HttpServletRequest.class);
method.setAccessible(true);
AuthnRequestState result = (AuthnRequestState)method.invoke(processor, outgoingRequest);
//we should be able to find the last added request state.
Assert.assertEquals(requestState.getAuthnRequest().getID(), result.getAuthnRequest().getID());
}
}
| 2,603 |
404 |
<filename>Python/Tests/TestData/TestDiscoverer/ConfigPythonFunctions/test_misc_prefixes.py
def test_func():
pass
def check_func():
pass
def example_func():
pass
def verify_func():
pass
| 77 |
1,615 |
<reponame>jackwiy/MLN<gh_stars>1000+
//
// UIView+MLNCore.h
// MLNCore
//
// Created by MoMo on 2019/7/23.
//
#import <UIKit/UIKit.h>
#import "NSObject+MLNCore.h"
NS_ASSUME_NONNULL_BEGIN
@interface UIView (MLNCore)
/**
Lua创建的对象会默认调用该初始化方法
@note 如果需要自定义初始化方法,第一个参数必须是luaCore。
@param luaCore 对应的lua状态机
@return Lua创建的实例对象
*/
- (instancetype)initWithLuaCore:(MLNLuaCore *)luaCore frame:(CGRect)frame;
@end
NS_ASSUME_NONNULL_END
| 287 |
892 |
{
"schema_version": "1.2.0",
"id": "GHSA-p2c5-vvpj-4jv2",
"modified": "2022-05-01T06:48:28Z",
"published": "2022-05-01T06:48:28Z",
"aliases": [
"CVE-2006-1346"
],
"details": "Directory traversal vulnerability in inc/setLang.php in <NAME> gCards 1.45 and earlier allows remote attackers to include and execute arbitrary local files via directory traversal sequences in a lang[*][file] parameter, as demonstrated by injecting PHP sequences into an Apache access_log file, which is then included by index.php.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2006-1346"
},
{
"type": "WEB",
"url": "https://www.exploit-db.com/exploits/1595"
},
{
"type": "WEB",
"url": "http://attrition.org/pipermail/vim/2006-April/000698.html"
},
{
"type": "WEB",
"url": "http://secunia.com/advisories/19322"
},
{
"type": "WEB",
"url": "http://www.osvdb.org/24016"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/bid/17165"
},
{
"type": "WEB",
"url": "http://www.vupen.com/english/advisories/2006/1015"
}
],
"database_specific": {
"cwe_ids": [
],
"severity": "MODERATE",
"github_reviewed": false
}
}
| 617 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.