answer
stringlengths 15
1.25M
|
|---|
package gov.va.med.imaging.pathology.rest.translator;
import java.util.Date;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author VHAISWWERFEJ
*
*/
public class <API key>
{
@Test
public void testDateTranslation()
{
try
{
Date date = <API key>.translateDate("201207101435");
System.out.println("Date: " + date);
}
catch(Exception ex)
{
ex.printStackTrace();
fail(ex.getMessage());
}
}
}
|
package io.quarkus.grpc.examples.hello;
import static io.restassured.RestAssured.get;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.QuarkusTest;
@QuarkusTest
class <API key> {
@Test
public void <API key>() {
String response = get("/hello/blocking/neo").asString();
assertThat(response).isEqualTo("Hello neo");
}
@Test
public void <API key>() {
String response = get("/hello/mutiny/neo-mutiny").asString();
assertThat(response).isEqualTo("Hello neo-mutiny");
}
}
|
local json = require "cjson"
local http_client = require "kong.tools.http_client"
local spec_helper = require "spec.spec_helpers"
local BASE_URL = spec_helper.API_URL.."/apis/%s/plugins/"
describe("Rate Limiting API", function()
setup(function()
spec_helper.prepare_db()
spec_helper.insert_fixtures {
api = {
{ name = "<API key>", request_host = "test1.com", upstream_url = "http://mockbin.com" }
}
}
spec_helper.start_kong()
local response = http_client.get(spec_helper.API_URL.."/apis/")
BASE_URL = string.format(BASE_URL, json.decode(response).data[1].id)
end)
teardown(function()
spec_helper.stop_kong()
end)
describe("POST", function()
it("should not save with empty config", function()
local response, status = http_client.post(BASE_URL, { name = "rate-limiting" })
local body = json.decode(response)
assert.are.equal(400, status)
assert.are.equal("You need to set at least one limit: second, minute, hour, day, month, year", body.message)
end)
it("should save with proper config", function()
local response, status = http_client.post(BASE_URL, { name = "rate-limiting", ["config.second"] = 10 })
local body = json.decode(response)
assert.are.equal(201, status)
assert.are.equal(10, body.config.second)
end)
end)
end)
|
define([
'jquery',
'underscore',
'backbone',
'app'
],
function (
$, _, Backbone, app
) {
var Models = {},
Collections = {},
Views = {};
Models.Project = Backbone.Model.extend();
Collections.Projects = Backbone.Model.extend({
model: Models.Project,
url: function() {
return app.api('projects/' + this.get('platform') +
(this.get('uri') ? '/' + this.get('uri') : ''));
},
parse: function(res) {
return { projects: res };
}
});
Models.Project = Backbone.Model.extend({
url: function() {
return app.api('projects?' + this.get('params'));
}
});
return {
Models: Models,
Collections: Collections,
Views: Views
};
});
|
package pl.matisoft.soy.config;
import com.google.template.soy.jssrc.SoyJsSrcOptions;
import com.google.template.soy.tofu.SoyTofuOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.<API key>;
import org.springframework.web.servlet.ViewResolver;
import pl.matisoft.soy.ContentNegotiator;
import pl.matisoft.soy.<API key>;
import pl.matisoft.soy.<API key>;
import pl.matisoft.soy.bundle.<API key>;
import pl.matisoft.soy.bundle.<API key>;
import pl.matisoft.soy.compile.DefaultTofuCompiler;
import pl.matisoft.soy.compile.TofuCompiler;
import pl.matisoft.soy.data.<API key>;
import pl.matisoft.soy.data.ToSoyDataConverter;
import pl.matisoft.soy.data.adjust.ModelAdjuster;
import pl.matisoft.soy.data.adjust.SpringModelAdjuster;
import pl.matisoft.soy.global.compile.<API key>;
import pl.matisoft.soy.global.compile.<API key>;
import pl.matisoft.soy.global.runtime.<API key>;
import pl.matisoft.soy.global.runtime.<API key>;
import pl.matisoft.soy.holder.<API key>;
import pl.matisoft.soy.holder.<API key>;
import pl.matisoft.soy.locale.LocaleProvider;
import pl.matisoft.soy.locale.<API key>;
import pl.matisoft.soy.render.<API key>;
import pl.matisoft.soy.render.TemplateRenderer;
import pl.matisoft.soy.template.<API key>;
import pl.matisoft.soy.template.<API key>;
import javax.inject.Inject;
import javax.servlet.ServletContext;
@Configuration
public class <API key> {
@Value("${soy.hot.reload.mode:false}")
private boolean hotReloadMode;
@Value("${soy.templates.resolve.recursively:true}")
private boolean recursive;
@Value("${soy.templates.file.extension:soy}")
private String fileExtension;
@Value("${soy.templates.directory:/WEB-INF/templates}")
private String templatesPath;
@Value("${soy.i18n.xliff.path:xliffs/messages}")
private String messagesPath;
@Value("${soy.encoding:utf-8}")
private String encoding;
@Value("${soy.i18n.fallback.to.english:true}")
private boolean fallbackToEnglish;
@Value("${soy.preCompile.templates:false}")
private boolean preCompileTemplates;
@Value("${soy.indexView:index}")
private String indexView;
@Value("${soy.logical.prefix:soy:}")
private String logicalPrefix;
@Value("${soy.resolver.order:2147483647}")
private int order;
@Inject
private ServletContext servletContext;
@Bean
public LocaleProvider soyLocaleProvider() {
return new <API key>();
}
@Bean
public <API key> <API key>() throws Exception {
final <API key> <API key> = new <API key>();
<API key>.setHotReloadMode(hotReloadMode);
<API key>.setRecursive(recursive);
<API key>.setFilesExtension(fileExtension);
<API key>.<API key>(new <API key>(servletContext, templatesPath));
return <API key>;
}
@Bean
public <API key> <API key>() {
return new <API key>();
}
@Bean
public ToSoyDataConverter <API key>() {
return new <API key>();
}
@Bean
public SoyJsSrcOptions soyJsSourceOptions() {
return new SoyJsSrcOptions();
}
@Bean
public SoyTofuOptions soyTofuOptions() {
final SoyTofuOptions soyTofuOptions = new SoyTofuOptions();
soyTofuOptions.setUseCaching(!hotReloadMode);
return soyTofuOptions;
}
@Bean
public TofuCompiler soyTofuCompiler(final <API key> <API key>, final SoyJsSrcOptions soyJsSrcOptions, final SoyTofuOptions soyTofuOptions) {
final DefaultTofuCompiler defaultTofuCompiler = new DefaultTofuCompiler();
defaultTofuCompiler.setHotReloadMode(hotReloadMode);
defaultTofuCompiler.<API key>(<API key>);
defaultTofuCompiler.setSoyJsSrcOptions(soyJsSrcOptions);
defaultTofuCompiler.setSoyTofuOptions(soyTofuOptions);
return defaultTofuCompiler;
}
@Bean
public <API key> <API key>() {
final <API key> <API key> = new <API key>();
<API key>.setHotReloadMode(hotReloadMode);
<API key>.setMessagesPath(messagesPath);
<API key>.<API key>(fallbackToEnglish);
return <API key>;
}
@Bean
public <API key> soyTemplatesHolder(final <API key> <API key>, final TofuCompiler tofuCompiler) throws Exception {
final <API key> <API key> = new <API key>();
<API key>.setHotReloadMode(hotReloadMode);
<API key>.<API key>(preCompileTemplates);
<API key>.<API key>(<API key>);
<API key>.setTofuCompiler(tofuCompiler);
return <API key>;
}
@Bean
public TemplateRenderer soyTemplateRenderer(final ToSoyDataConverter toSoyDataConverter) {
final <API key> <API key> = new <API key>();
<API key>.setHotReloadMode(hotReloadMode);
<API key>.<API key>(toSoyDataConverter);
return <API key>;
}
@Bean
public ModelAdjuster <API key>() {
return new SpringModelAdjuster();
}
@Bean
public <API key> <API key>() {
return new <API key>();
}
@Bean
public ContentNegotiator contentNegotiator() {
return new <API key>();
}
@Bean
public ViewResolver soyViewResolver(final <API key> <API key>,
final ModelAdjuster modelAdjuster,
final TemplateRenderer templateRenderer,
final LocaleProvider localeProvider,
final <API key> <API key>,
final ContentNegotiator contentNegotiator,
final <API key> msgBundleResolver)
throws Exception {
final <API key> <API key> = new <API key>();
<API key>.<API key>(msgBundleResolver);
<API key>.<API key>(<API key>);
<API key>.setEncoding(encoding);
<API key>.<API key>(<API key>);
<API key>.setHotReloadMode(hotReloadMode);
<API key>.setIndexView(indexView);
<API key>.setLocaleProvider(localeProvider);
<API key>.setModelAdjuster(modelAdjuster);
<API key>.setTemplateRenderer(templateRenderer);
<API key>.setPrefix(logicalPrefix);
<API key>.setOrder(order);
<API key>.<API key>(true);
<API key>.<API key>(true);
<API key>.<API key>(contentNegotiator);
return <API key>;
}
}
|
package userstoreauth.servlets;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import userstoreauth.model.UserVer2;
import userstoreauth.service.UserStoreMb;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class EditUserTest {
@BeforeEach
void setUp() {
UserStoreMb us = new UserStoreMb();
us.deleteAll();
}
@Test
void editUser() throws ServletException, IOException {
EditUser editUser = new EditUser();
UserStoreMb us = new UserStoreMb();
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getParameter("login")).thenReturn("login");
when(request.getParameter("password")).thenReturn("password0");
when(request.getParameter("name")).thenReturn("name0");
when(request.getParameter("email")).thenReturn("email0");
when(request.getParameter("role")).thenReturn("admin");
when(request.getParameter("country")).thenReturn("Россия");
when(request.getParameter("city")).thenReturn("Москва");
UserVer2 user = new UserVer2("login", "password", "name", "email", "Россия", "Москва", Timestamp.valueOf(LocalDateTime.now()), "user");
us.addUser(user);
assertEquals(user, us.getByLogin("login"));
editUser.doPost(request, response);
user.setPassword("password0");
user.setName("name0");
user.setEmail("email0");
user.setRole("admin");
assertEquals(user, us.getByLogin("login"));
}
}
|
from socket import inet_ntoa
from struct import pack
def calcDottedNetmask(mask):
bits = 0
for i in xrange(32 - mask, 32):
bits |= (1 << i)
packed_value = pack('!I', bits)
addr = inet_ntoa(packed_value)
return addr
|
import pytest
import salt.engines
from tests.support.mock import MagicMock, patch
def <API key>():
engine = salt.engines.Engine({}, "foobar.start", {}, {}, {}, {}, name="foobar")
assert engine.name == "foobar"
def <API key>():
engine = salt.engines.Engine({}, "foobar.start", {}, {}, {}, {}, name="foobar")
with patch("salt.utils.process.appendproctitle", MagicMock()) as mm:
with pytest.raises(KeyError):
# The method does not exist so a KeyError will be raised.
engine.run()
mm.assert_called_with("foobar")
|
// ExportXmlParser.cpp
// Simple callback non-validating XML parser implementation.
// Microsoft XNA Developer Connection.
#include "stdafx.h"
#include "ExportXmlParser.h"
namespace ATG
{
// Name: XMLParser::XMLParser
XMLParser::XMLParser()
{
m_pWritePtr = m_pWriteBuf;
m_pReadPtr = m_pReadBuf;
m_pISAXCallback = NULL;
m_hFile = <API key>;
}
// Name: XMLParser::~XMLParser
XMLParser::~XMLParser()
{
}
// Name: XMLParser::FillBuffer
// Desc: Reads a block from the current open file
VOID XMLParser::FillBuffer()
{
DWORD NChars;
m_pReadPtr = m_pReadBuf;
if( m_hFile == NULL )
{
if( <API key> > <API key> )
NChars = <API key>;
else
NChars = <API key>;
CopyMemory( m_pReadBuf, m_pInXMLBuffer, NChars );
<API key> -= NChars;
m_pInXMLBuffer += NChars;
}
else
{
ReadFile( m_hFile, m_pReadBuf, <API key>, &NChars, NULL );
}
m_dwCharsConsumed += NChars;
__int64 iProgress = ( (__int64)m_dwCharsConsumed * 1000 ) / (__int64)m_dwCharsTotal;
m_pISAXCallback->SetParseProgress( (DWORD)iProgress );
m_pReadBuf[ NChars ] = '\0';
m_pReadBuf[ NChars + 1] = '\0';
}
// Name: XMLParser::SkipNextAdvance
// Desc: Puts the last character read back on the input stream
VOID XMLParser::SkipNextAdvance()
{
m_bSkipNextAdvance = TRUE;
}
// Name: XMLParser::ConsumeSpace
// Desc: Skips spaces in the current stream
HRESULT XMLParser::ConsumeSpace()
{
HRESULT hr;
// Skip spaces
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
while ( ( m_Ch == ' ' ) || ( m_Ch == '\t' ) ||
( m_Ch == '\n' ) || ( m_Ch == '\r' ) )
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
}
SkipNextAdvance();
return S_OK;
}
// Name: XMLParser::ConvertEscape
// Desc: Copies and converts an escape sequence into m_pWriteBuf
HRESULT XMLParser::ConvertEscape()
{
HRESULT hr;
WCHAR wVal = 0;
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
// all escape sequences start with &, so ignore the first character
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if ( m_Ch == '#' ) // character as hex or decimal
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if ( m_Ch == 'x' ) // hex number
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
while ( m_Ch != ';' )
{
wVal *= 16;
if ( ( m_Ch >= '0' ) && ( m_Ch <= '9' ) )
{
wVal += m_Ch - '0';
}
else if ( ( m_Ch >= 'a' ) && ( m_Ch <= 'f' ) )
{
wVal += m_Ch - 'a' + 10;
}
else if ( ( m_Ch >= 'A' ) && ( m_Ch <= 'F' ) )
{
wVal += m_Ch - 'A' + 10;
}
else
{
Error( <API key>, "Expected hex digit as part of &#x escape sequence" );
return <API key>;
}
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
}
}
else // decimal number
{
while ( m_Ch != ';' )
{
wVal *= 10;
if ( ( m_Ch >= '0' ) && ( m_Ch <= '9' ) )
{
wVal += m_Ch - '0';
}
else
{
Error( <API key>, "Expected decimal digit as part of &# escape sequence" );
return <API key>;
}
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
}
}
// copy character into the buffer
m_Ch = wVal;
return S_OK;
}
// must be an entity reference
WCHAR *pEntityRefVal = m_pWritePtr;
UINT EntityRefLen;
SkipNextAdvance();
if( FAILED( hr = AdvanceName() ) )
return hr;
EntityRefLen = (UINT)( m_pWritePtr - pEntityRefVal );
m_pWritePtr = pEntityRefVal;
if ( EntityRefLen == 0 )
{
Error( <API key>, "Expecting entity name after &" );
return <API key>;
}
if( !wcsncmp( pEntityRefVal, L"lt", EntityRefLen ) )
wVal = '<';
else if( !wcsncmp( pEntityRefVal, L"gt", EntityRefLen ) )
wVal = '>';
else if( !wcsncmp( pEntityRefVal, L"amp", EntityRefLen ) )
wVal = '&';
else if( !wcsncmp( pEntityRefVal, L"apos", EntityRefLen ) )
wVal = '\'';
else if( !wcsncmp( pEntityRefVal, L"quot", EntityRefLen ) )
wVal = '"';
else
{
Error( <API key>, "Unrecognized entity name after & - (should be lt, gt, amp, apos, or quot)" );
return <API key>; // return false if unrecognized token sequence
}
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != ';' )
{
Error( <API key>, "Expected terminating ; for entity reference" );
return <API key>; // malformed reference - needs terminating ;
}
m_Ch = wVal;
return S_OK;
}
// Name: XMLParser::AdvanceAttrVal
// Desc: Copies an attribute value into m_pWrite buf, skipping surrounding quotes
HRESULT XMLParser::AdvanceAttrVal()
{
HRESULT hr;
WCHAR wQuoteChar;
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( ( m_Ch != '"' ) && ( m_Ch != '\'' ) )
{
Error( <API key>, "Attribute values must be enclosed in quotes" );
return <API key>;
}
wQuoteChar = m_Ch;
for( ;; )
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
else if( m_Ch == wQuoteChar )
break;
else if( m_Ch == '&' )
{
SkipNextAdvance();
if( FAILED( hr = ConvertEscape() ) )
return hr;
}
else if( m_Ch == '<' )
{
Error( <API key>, "Illegal character '<' in element tag" );
return <API key>;
}
// copy character into the buffer
if( m_pWritePtr - m_pWriteBuf >= <API key> )
{
Error( <API key>, "Total element tag size may not be more than %d characters", <API key> );
return <API key>;
}
*m_pWritePtr = m_Ch;
m_pWritePtr++;
}
return S_OK;
}
// Name: XMLParser::AdvanceName
// Desc: Copies a name into the m_pWriteBuf - returns TRUE on success, FALSE on failure
// Ignores leading whitespace. Currently does not support unicode names
HRESULT XMLParser::AdvanceName()
{
HRESULT hr;
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( ( ( m_Ch < 'A' ) || ( m_Ch > 'Z' ) ) &&
( ( m_Ch < 'a' ) || ( m_Ch > 'z' ) ) &&
( m_Ch != '_' ) && ( m_Ch != ':' ) )
{
Error( <API key>, "Names must start with an alphabetic character or _ or :" );
return <API key>;
}
while( ( ( m_Ch >= 'A' ) && ( m_Ch <= 'Z' ) ) ||
( ( m_Ch >= 'a' ) && ( m_Ch <= 'z' ) ) ||
( ( m_Ch >= '0' ) && ( m_Ch <= '9' ) ) ||
( m_Ch == '_' ) || ( m_Ch == ':' ) ||
( m_Ch == '-' ) || ( m_Ch == '.' ) )
{
if( m_pWritePtr - m_pWriteBuf >= <API key> )
{
Error( <API key>, "Total element tag size may not be more than %d characters", <API key> );
return <API key>;
}
*m_pWritePtr = m_Ch;
m_pWritePtr++;
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
}
SkipNextAdvance();
return S_OK;
}
// Name: XMLParser::AdvanceCharacter
// Desc: Copies the character at *m_pReadPtr to m_Ch
// handling difference in UTF16 / UTF8, and big/little endian
// and getting another chunk of the file if needed
// Returns S_OK if there are more characters, E_ABORT for no characters to read
HRESULT XMLParser::AdvanceCharacter( BOOL bOkToFail )
{
if( m_bSkipNextAdvance )
{
m_bSkipNextAdvance = FALSE;
return S_OK;
}
// If we hit EOF in the middle of a character,
// it's ok-- we'll just have a corrupt last character
// (the buffer is padded with double NULLs )
if( *m_pReadPtr == '\0' )
{
// Read more from the file
FillBuffer();
// We are at EOF if it is still NULL
if( *m_pReadPtr == '\0' )
{
if( !bOkToFail )
{
Error( <API key>, "Unexpected EOF while parsing XML file" );
return <API key>;
}
else
{
return E_FAIL;
}
}
}
if( m_bUnicode == FALSE )
{
m_Ch = *((CHAR *)m_pReadPtr);
m_pReadPtr++;
}
else // if( m_bUnicode == TRUE )
{
m_Ch = *((WCHAR *)m_pReadPtr);
if( m_bReverseBytes )
{
m_Ch = ( m_Ch << 8 ) + ( m_Ch >> 8 );
}
m_pReadPtr += 2;
}
if( m_Ch == '\n' )
{
m_pISAXCallback->m_LineNum++;
m_pISAXCallback->m_LinePos = 0;
}
else if( m_Ch != '\r' )
m_pISAXCallback->m_LinePos++;
return S_OK;
}
// Name: XMLParser::AdvanceElement
// Desc: Builds <element> data, calls callback
HRESULT XMLParser::AdvanceElement()
{
HRESULT hr;
// write ptr at the beginning of the buffer
m_pWritePtr = m_pWriteBuf;
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
// if first character wasn't '<', we wouldn't be here
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch == '!' )
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if ( m_Ch == '-' )
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != '-' )
{
Error( <API key>, "Expecting '-' after '<!-'" );
return <API key>;
}
if( FAILED( hr = AdvanceComment() ) )
return hr;
return S_OK;
}
if( m_Ch != '[' )
{
Error( <API key>, "Expecting '<![CDATA['" );
return <API key>;
}
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != 'C' )
{
Error( <API key>, "Expecting '<![CDATA['" );
return <API key>;
}
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != 'D' )
{
Error( <API key>, "Expecting '<![CDATA['" );
return <API key>;
}
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != 'A' )
{
Error( <API key>, "Expecting '<![CDATA['" );
return <API key>;
}
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != 'T' )
{
Error( <API key>, "Expecting '<![CDATA['" );
return <API key>;
}
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != 'A' )
{
Error( <API key>, "Expecting '<![CDATA['" );
return <API key>;
}
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != '[' )
{
Error( <API key>, "Expecting '<![CDATA['" );
return <API key>;
}
if( FAILED( hr = AdvanceCDATA() ) )
return hr;
}
else if( m_Ch == '/' )
{
WCHAR *pEntityRefVal = m_pWritePtr;
if( FAILED( hr = AdvanceName() ) )
return hr;
if( FAILED( m_pISAXCallback->ElementEnd( pEntityRefVal,
(UINT) ( m_pWritePtr - pEntityRefVal ) ) ) )
return E_ABORT;
if( FAILED( hr = ConsumeSpace() ) )
return hr;
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != '>' )
{
Error( <API key>, "Expecting '>' after name for closing entity reference" );
return <API key>;
}
}
else if( m_Ch == '?' )
{
// just skip any xml header tag since not really important after identifying character set
for( ;; )
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if ( m_Ch == '>' )
return S_OK;
}
}
else
{
XMLAttribute Attributes[ <API key> ];
UINT NumAttrs;
WCHAR *pEntityRefVal = m_pWritePtr;
UINT EntityRefLen;
NumAttrs = 0;
SkipNextAdvance();
// Entity tag
if( FAILED( hr = AdvanceName() ) )
return hr;
EntityRefLen = (UINT)( m_pWritePtr - pEntityRefVal );
if( FAILED( hr = ConsumeSpace() ) )
return hr;
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
// read attributes
while( ( m_Ch != '>' ) && ( m_Ch != '/' ) )
{
SkipNextAdvance();
if ( NumAttrs >= <API key> )
{
Error( <API key>, "Elements may not have more than %d attributes", <API key> );
return <API key>;
}
Attributes[ NumAttrs ].strName = m_pWritePtr;
// Attribute name
if( FAILED( hr = AdvanceName() ) )
return hr;
Attributes[ NumAttrs ].NameLen = (UINT)( m_pWritePtr - Attributes[ NumAttrs ].strName );
if( FAILED( hr = ConsumeSpace() ) )
return hr;
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != '=' )
{
Error( <API key>, "Expecting '=' character after attribute name" );
return <API key>;
}
if( FAILED( hr = ConsumeSpace() ) )
return hr;
Attributes[ NumAttrs ].strValue = m_pWritePtr;
if( FAILED( hr = AdvanceAttrVal() ) )
return hr;
Attributes[ NumAttrs ].ValueLen = (UINT)( m_pWritePtr -
Attributes[ NumAttrs ].strValue );
++NumAttrs;
if( FAILED( hr = ConsumeSpace() ) )
return hr;
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
}
if( m_Ch == '/' )
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if( m_Ch != '>' )
{
Error( <API key>, "Expecting '>' after '/' in element tag" );
return <API key>;
}
if( FAILED( m_pISAXCallback->ElementBegin( pEntityRefVal, EntityRefLen,
Attributes, NumAttrs ) ) )
return E_ABORT;
if( FAILED( m_pISAXCallback->ElementEnd( pEntityRefVal, EntityRefLen ) ) )
return E_ABORT;
}
else
{
if( FAILED( m_pISAXCallback->ElementBegin( pEntityRefVal, EntityRefLen,
Attributes, NumAttrs ) ) )
return E_ABORT;
}
}
return S_OK;
}
// Name: XMLParser::AdvanceCDATA
// Desc: Read a CDATA section
HRESULT XMLParser::AdvanceCDATA()
{
HRESULT hr;
WORD wStage = 0;
if( FAILED( m_pISAXCallback->CDATABegin() ) )
return E_ABORT;
for( ;; )
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
*m_pWritePtr = m_Ch;
m_pWritePtr++;
if( ( m_Ch == ']' ) && ( wStage == 0 ) )
wStage = 1;
else if( ( m_Ch == ']' ) && ( wStage == 1 ) )
wStage = 2;
else if( ( m_Ch == '>' ) && ( wStage == 2 ) )
{
m_pWritePtr -= 3;
break;
}
else
wStage = 0;
if( m_pWritePtr - m_pWriteBuf >= <API key> )
{
if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), TRUE ) ) )
return E_ABORT;
m_pWritePtr = m_pWriteBuf;
}
}
if( FAILED( m_pISAXCallback->CDATAData( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), FALSE ) ) )
return E_ABORT;
m_pWritePtr = m_pWriteBuf;
if( FAILED( m_pISAXCallback->CDATAEnd() ) )
return E_ABORT;
return S_OK;
}
// Name: XMLParser::AdvanceComment
// Desk: Skips over a comment
HRESULT XMLParser::AdvanceComment()
{
HRESULT hr;
WORD wStage;
wStage = 0;
for( ;; )
{
if( FAILED( hr = AdvanceCharacter() ) )
return hr;
if (( m_Ch == '-' ) && ( wStage == 0 ))
wStage = 1;
else if (( m_Ch == '-' ) && ( wStage == 1 ))
wStage = 2;
else if (( m_Ch == '>' ) && ( wStage == 2 ))
break;
else
wStage = 0;
}
return S_OK;
}
// Name: XMLParser::<API key>
// Desc: Registers callback interface
VOID XMLParser::<API key>( ISAXCallback *pISAXCallback )
{
m_pISAXCallback = pISAXCallback;
}
// Name: XMLParser::<API key>
// Desc: Returns current callback interface
ISAXCallback* XMLParser::<API key>()
{
return m_pISAXCallback;
}
// Name: XMLParser::MainParseLoop
// Desc: Main Loop to Parse Data - source agnostic
HRESULT XMLParser::MainParseLoop()
{
BOOL bWhiteSpaceOnly = TRUE;
HRESULT hr = S_OK;
if( FAILED( m_pISAXCallback->StartDocument() ) )
return E_ABORT;
m_pWritePtr = m_pWriteBuf;
FillBuffer();
if ( *((WCHAR *) m_pReadBuf ) == 0xFEFF )
{
m_bUnicode = TRUE;
m_bReverseBytes = FALSE;
m_pReadPtr += 2;
}
else if ( *((WCHAR *) m_pReadBuf ) == 0xFFFE )
{
m_bUnicode = TRUE;
m_bReverseBytes = TRUE;
m_pReadPtr += 2;
}
else if ( *((WCHAR *) m_pReadBuf ) == 0x003C )
{
m_bUnicode = TRUE;
m_bReverseBytes = FALSE;
}
else if ( *((WCHAR *) m_pReadBuf ) == 0x3C00 )
{
m_bUnicode = TRUE;
m_bReverseBytes = TRUE;
}
else if ( m_pReadBuf[ 0 ] == 0x3C )
{
m_bUnicode = FALSE;
m_bReverseBytes = FALSE;
}
else
{
Error( <API key>, "Unrecognized encoding (parser does not support UTF-8 language encodings)" );
return <API key>;
}
for( ;; )
{
if( FAILED( AdvanceCharacter( TRUE ) ) )
{
if ( ( (UINT) ( m_pWritePtr - m_pWriteBuf ) != 0 ) && ( !bWhiteSpaceOnly ) )
{
if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), FALSE ) ) )
return E_ABORT;
bWhiteSpaceOnly = TRUE;
}
if( FAILED( m_pISAXCallback->EndDocument() ) )
return E_ABORT;
return S_OK;
}
if( m_Ch == '<' )
{
if( ( (UINT) ( m_pWritePtr - m_pWriteBuf ) != 0 ) && ( !bWhiteSpaceOnly ) )
{
if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf, (UINT)( m_pWritePtr - m_pWriteBuf ), FALSE ) ) )
return E_ABORT;
bWhiteSpaceOnly = TRUE;
}
SkipNextAdvance();
m_pWritePtr = m_pWriteBuf;
if( FAILED( hr = AdvanceElement() ) )
return hr;
m_pWritePtr = m_pWriteBuf;
}
else
{
if( m_Ch == '&' )
{
SkipNextAdvance();
if( FAILED( hr = ConvertEscape() ) )
return hr;
}
if( bWhiteSpaceOnly && ( m_Ch != ' ' ) && ( m_Ch != '\n' ) && ( m_Ch != '\r' ) &&
( m_Ch != '\t' ) )
{
bWhiteSpaceOnly = FALSE;
}
*m_pWritePtr = m_Ch;
m_pWritePtr++;
if( m_pWritePtr - m_pWriteBuf >= <API key> )
{
if( !bWhiteSpaceOnly )
{
if( FAILED( m_pISAXCallback->ElementContent( m_pWriteBuf,
( UINT ) ( m_pWritePtr - m_pWriteBuf ),
TRUE ) ) )
{
return E_ABORT;
}
}
m_pWritePtr = m_pWriteBuf;
bWhiteSpaceOnly = TRUE;
}
}
}
}
// Name: XMLParser::ParseXMLFile
// Desc: Builds element data
HRESULT XMLParser::ParseXMLFile( CONST CHAR *strFilename )
{
HRESULT hr;
if( m_pISAXCallback == NULL )
return E_NOINTERFACE;
m_pISAXCallback->m_LineNum = 1;
m_pISAXCallback->m_LinePos = 0;
m_pISAXCallback->m_strFilename = strFilename; // save this off only while we parse the file
m_bSkipNextAdvance = FALSE;
m_pReadPtr = m_pReadBuf;
m_pReadBuf[ 0 ] = '\0';
m_pReadBuf[ 1 ] = '\0';
m_pInXMLBuffer = NULL;
<API key> = 0;
m_hFile = CreateFile( strFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, <API key>, NULL );
if( m_hFile == <API key> )
{
Error( <API key>, "Error opening file" );
hr = <API key>;
}
else
{
LARGE_INTEGER iFileSize;
GetFileSizeEx( m_hFile, &iFileSize );
m_dwCharsTotal = (DWORD)iFileSize.QuadPart;
m_dwCharsConsumed = 0;
hr = MainParseLoop();
}
// Close the file
if( m_hFile != <API key> )
CloseHandle( m_hFile );
m_hFile = <API key>;
// we no longer own strFilename, so un-set it
m_pISAXCallback->m_strFilename = NULL;
return hr;
}
// Name: XMLParser::ParseXMLFile
// Desc: Builds element data
HRESULT XMLParser::ParseXMLBuffer( CONST CHAR *strBuffer, UINT uBufferSize )
{
HRESULT hr;
if( m_pISAXCallback == NULL )
return E_NOINTERFACE;
m_pISAXCallback->m_LineNum = 1;
m_pISAXCallback->m_LinePos = 0;
m_pISAXCallback->m_strFilename = ""; // save this off only while we parse the file
m_bSkipNextAdvance = FALSE;
m_pReadPtr = m_pReadBuf;
m_pReadBuf[ 0 ] = '\0';
m_pReadBuf[ 1 ] = '\0';
m_hFile = NULL;
m_pInXMLBuffer = strBuffer;
<API key> = uBufferSize;
m_dwCharsTotal = <API key>;
m_dwCharsConsumed = 0;
hr = MainParseLoop();
// we no longer own strFilename, so un-set it
m_pISAXCallback->m_strFilename = NULL;
return hr;
}
// XMLParser::Error()
// Logs an error through the callback interface
VOID XMLParser::Error( HRESULT hErr, CONST CHAR* strFormat, ... )
{
CONST INT MAX_OUTPUT_STR = 160;
CHAR strBuffer[ MAX_OUTPUT_STR ];
va_list pArglist;
va_start( pArglist, strFormat );
vsprintf_s( strBuffer, strFormat, pArglist );
m_pISAXCallback->Error( hErr, strBuffer );
va_end( pArglist );
}
} // namespace ATG
|
package com.intellij.execution.testframework.sm.runner;
import com.intellij.execution.testframework.sm.<API key>;
import com.intellij.execution.testframework.sm.runner.events.*;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.*;
public class <API key> extends <API key> {
private final Map<String, SMTestProxy> <API key> = ContainerUtil.newConcurrentMap();
private final TestSuiteStack mySuitesStack;
private final Map<String, List<SMTestProxy>> myCurrentChildren = new HashMap<>();
private boolean myIsTestingFinished;
public <API key>(Project project, @NotNull SMTestProxy.SMRootTestProxy testsRootNode,
@NotNull String testFrameworkName) {
super(project, testFrameworkName, testsRootNode);
mySuitesStack = new TestSuiteStack(testFrameworkName);
}
@Override
protected SMTestProxy createProxy(String testName, String locationHint, String metaInfo, String id, String parentNodeId) {
SMTestProxy proxy = super.createProxy(testName, locationHint, metaInfo, id, parentNodeId);
SMTestProxy currentSuite = getCurrentSuite();
currentSuite.addChild(proxy);
return proxy;
}
@Override
protected SMTestProxy createSuite(String suiteName, String locationHint, String metaInfo, String id, String parentNodeId) {
SMTestProxy newSuite = super.createSuite(suiteName, locationHint, metaInfo, id, parentNodeId);
final SMTestProxy parentSuite = getCurrentSuite();
parentSuite.addChild(newSuite);
mySuitesStack.pushSuite(newSuite);
return newSuite;
}
@Override
public void onSuiteTreeEnded(String suiteName) {
<API key>.add(() -> mySuitesStack.popSuite(suiteName));
super.onSuiteTreeEnded(suiteName);
}
@Override
public void onStartTesting() {
//fire
mySuitesStack.pushSuite(myTestsRootProxy);
myTestsRootProxy.setStarted();
//fire
<API key>(myTestsRootProxy);
}
@Override
public void <API key>() {
<API key>(myTestsRootProxy);
}
@Override
public void onFinishTesting() {
<API key>(myTestsRootProxy);
// has been already invoked!
// We don't know whether process was destroyed by user
// or it finished after all tests have been run
// Lets assume, if at finish all suites except root suite are passed
// then all is ok otherwise process was terminated by user
if (myIsTestingFinished) {
// has been already invoked!
return;
}
myIsTestingFinished = true;
// We don't know whether process was destroyed by user
// or it finished after all tests have been run
// Lets assume, if at finish all suites except root suite are passed
// then all is ok otherwise process was terminated by user
if (!isTreeComplete(<API key>.keySet(), myTestsRootProxy)) {
myTestsRootProxy.setTerminated();
<API key>.clear();
}
mySuitesStack.clear();
myTestsRootProxy.setFinished();
myCurrentChildren.clear();
//fire events
<API key>(myTestsRootProxy);
super.onFinishTesting();
}
@Override
public void setPrinterProvider(@NotNull <API key> printerProvider) {
}
@Override
public void onTestStarted(@NotNull final TestStartedEvent testStartedEvent) {
//Duplicated event
// creates test
// adds to running tests map
//Progress started
//fire events
final String testName = testStartedEvent.getName();
final String locationUrl = testStartedEvent.getLocationUrl();
final boolean isConfig = testStartedEvent.isConfig();
final String fullName = getFullTestName(testName);
if (<API key>.containsKey(fullName)) {
//Duplicated event
logProblem("Test [" + fullName + "] has been already started");
if (<API key>.isInDebugMode()) {
return;
}
}
SMTestProxy parentSuite = getCurrentSuite();
SMTestProxy testProxy = findChild(parentSuite, locationUrl != null ? locationUrl : fullName, false);
if (testProxy == null) {
// creates test
testProxy = new SMTestProxy(testName, false, locationUrl, testStartedEvent.getMetainfo(), false);
testProxy.setConfig(isConfig);
if (<API key>) testProxy.<API key>();
if (myLocator != null) {
testProxy.setLocator(myLocator);
}
parentSuite.addChild(testProxy);
}
// adds to running tests map
<API key>.put(fullName, testProxy);
//Progress started
testProxy.setStarted();
//fire events
fireOnTestStarted(testProxy);
}
@Override
public void onSuiteStarted(@NotNull final <API key> suiteStartedEvent) {
//new suite
//Progress started
//fire event
final String suiteName = suiteStartedEvent.getName();
final String locationUrl = suiteStartedEvent.getLocationUrl();
SMTestProxy parentSuite = getCurrentSuite();
SMTestProxy newSuite = findChild(parentSuite, locationUrl != null ? locationUrl : suiteName, true);
if (newSuite == null) {
//new suite
newSuite = new SMTestProxy(suiteName, true, locationUrl, suiteStartedEvent.getMetainfo(), parentSuite.<API key>());
if (<API key>) {
newSuite.<API key>();
}
if (myLocator != null) {
newSuite.setLocator(myLocator);
}
parentSuite.addChild(newSuite);
}
initCurrentChildren(newSuite, true);
mySuitesStack.pushSuite(newSuite);
//Progress started
newSuite.setSuiteStarted();
//fire event
fireOnSuiteStarted(newSuite);
}
private void initCurrentChildren(SMTestProxy newSuite, boolean preferSuite) {
if (<API key>) {
for (SMTestProxy proxy : newSuite.getChildren()) {
if (!proxy.isFinal() || preferSuite && proxy.isSuite()) {
String url = proxy.getLocationUrl();
if (url != null) {
myCurrentChildren.computeIfAbsent(url, l -> new ArrayList<>()).add(proxy);
}
myCurrentChildren.computeIfAbsent(proxy.getName(), l -> new ArrayList<>()).add(proxy);
}
}
}
}
private SMTestProxy findChild(SMTestProxy parentSuite, String fullName, boolean preferSuite) {
if (<API key>) {
Set<SMTestProxy> acceptedProxies = new LinkedHashSet<>();
Collection<? extends SMTestProxy> children = myCurrentChildren.get(fullName);
if (children == null) {
initCurrentChildren(parentSuite, preferSuite);
children = myCurrentChildren.get(fullName);
}
if (children != null) { //null if child started second time
for (SMTestProxy proxy : children) {
if (!proxy.isFinal() || preferSuite && proxy.isSuite()) {
acceptedProxies.add(proxy);
}
}
if (!acceptedProxies.isEmpty()) {
return acceptedProxies.stream()
.filter(proxy -> proxy.isSuite() == preferSuite && proxy.getParent() == parentSuite)
.findFirst()
.orElse(acceptedProxies.iterator().next());
}
}
}
return null;
}
@Override
public void onTestFinished(@NotNull final TestFinishedEvent testFinishedEvent) {
final String testName = testFinishedEvent.getName();
final Long duration = testFinishedEvent.getDuration();
final String fullTestName = getFullTestName(testName);
final SMTestProxy testProxy = <API key>(fullTestName);
if (testProxy == null) {
logProblem("Test wasn't started! TestFinished event: name = {" + testName + "}. " +
<API key>(fullTestName));
return;
}
testProxy.setDuration(duration != null ? duration : 0);
testProxy.<API key>(testFinishedEvent.getOutputFile());
testProxy.setFinished();
<API key>.remove(fullTestName);
<API key>(fullTestName, testProxy);
//fire events
fireOnTestFinished(testProxy);
}
private void <API key>(String fullTestName, SMTestProxy testProxy) {
myCurrentChildren.remove(fullTestName);
String url = testProxy.getLocationUrl();
if (url != null) {
myCurrentChildren.remove(url);
}
}
@Override
public void onSuiteFinished(@NotNull final <API key> suiteFinishedEvent) {
//fire events
final String suiteName = suiteFinishedEvent.getName();
final SMTestProxy mySuite = mySuitesStack.popSuite(suiteName);
if (mySuite != null) {
mySuite.setFinished();
myCurrentChildren.remove(suiteName);
String locationUrl = mySuite.getLocationUrl();
if (locationUrl != null) {
myCurrentChildren.remove(locationUrl);
}
//fire events
fireOnSuiteFinished(mySuite);
}
}
@Override
public void onUncapturedOutput(@NotNull final String text, final Key outputType) {
final SMTestProxy currentProxy = <API key>();
currentProxy.addOutput(text, outputType);
}
@Override
public void onError(@NotNull final String localizedMessage,
@Nullable final String stackTrace,
final boolean isCritical) {
final SMTestProxy currentProxy = <API key>();
currentProxy.addError(localizedMessage, stackTrace, isCritical);
}
@Override
public void onTestFailure(@NotNull final TestFailedEvent testFailedEvent) {
// if hasn't been already reported
// 1. report
// 2. add failure
// fire event
final String testName = testFailedEvent.getName();
if (testName == null) {
logProblem("No test name specified in " + testFailedEvent);
return;
}
final String localizedMessage = testFailedEvent.<API key>();
final String stackTrace = testFailedEvent.getStacktrace();
final boolean isTestError = testFailedEvent.isTestError();
final String <API key> = testFailedEvent.<API key>();
final String <API key> = testFailedEvent.<API key>();
final boolean inDebugMode = <API key>.isInDebugMode();
final String fullTestName = getFullTestName(testName);
SMTestProxy testProxy = <API key>(fullTestName);
if (testProxy == null) {
logProblem("Test wasn't started! TestFailure event: name = {" + testName + "}" +
", message = {" + localizedMessage + "}" +
", stackTrace = {" + stackTrace + "}. " +
<API key>(fullTestName));
if (inDebugMode) {
return;
}
else {
// if hasn't been already reported
// 1. report
onTestStarted(new TestStartedEvent(testName, null));
// 2. add failure
testProxy = <API key>(fullTestName);
}
}
if (testProxy == null) {
return;
}
if (<API key> != null && <API key> != null) {
testProxy.<API key>(localizedMessage, stackTrace, <API key>, <API key>,
testFailedEvent);
}
else if (<API key> == null && <API key> == null) {
testProxy.setTestFailed(localizedMessage, stackTrace, isTestError);
}
else {
testProxy.setTestFailed(localizedMessage, stackTrace, isTestError);
logProblem("Comparison failure actual and expected texts should be both null or not null.\n"
+ "Expected:\n"
+ <API key> + "\n"
+ "Actual:\n"
+ <API key>);
}
// fire event
fireOnTestFailed(testProxy);
}
@Override
public void onTestIgnored(@NotNull final TestIgnoredEvent testIgnoredEvent) {
// try to fix
// 1. report test opened
// 2. report failure
// fire event
final String testName = testIgnoredEvent.getName();
if (testName == null) {
logProblem("TestIgnored event: no name");
}
String ignoreComment = testIgnoredEvent.getIgnoreComment();
final String stackTrace = testIgnoredEvent.getStacktrace();
final String fullTestName = getFullTestName(testName);
SMTestProxy testProxy = <API key>(fullTestName);
if (testProxy == null) {
final boolean debugMode = <API key>.isInDebugMode();
logProblem("Test wasn't started! " +
"TestIgnored event: name = {" + testName + "}, " +
"message = {" + ignoreComment + "}. " +
<API key>(fullTestName));
if (debugMode) {
return;
}
else {
// try to fix
// 1. report test opened
onTestStarted(new TestStartedEvent(testName, null));
// 2. report failure
testProxy = <API key>(fullTestName);
}
}
if (testProxy == null) {
return;
}
testProxy.setTestIgnored(ignoreComment, stackTrace);
// fire event
fireOnTestIgnored(testProxy);
}
@Override
public void onTestOutput(@NotNull final TestOutputEvent testOutputEvent) {
final String testName = testOutputEvent.getName();
final String text = testOutputEvent.getText();
final Key outputType = testOutputEvent.getOutputType();
final String fullTestName = getFullTestName(testName);
final SMTestProxy testProxy = <API key>(fullTestName);
if (testProxy == null) {
logProblem("Test wasn't started! TestOutput event: name = {" + testName + "}, " +
"outputType = " + outputType + ", " +
"text = {" + text + "}. " +
<API key>(fullTestName));
return;
}
testProxy.addOutput(text, outputType);
}
@Override
public void onTestsCountInSuite(final int count) {
<API key>(count);
}
@NotNull
protected final SMTestProxy getCurrentSuite() {
final SMTestProxy currentSuite = mySuitesStack.getCurrentSuite();
if (currentSuite != null) {
return currentSuite;
}
// current suite shouldn't be null otherwise test runner isn't correct
// or may be we are in debug mode
logProblem("Current suite is undefined. Root suite will be used.");
return myTestsRootProxy;
}
protected String getFullTestName(final String testName) {
// Test name should be unique
return testName;
}
protected int <API key>() {
return <API key>.size();
}
@Nullable
protected SMTestProxy <API key>(final String fullTestName) {
return <API key>.get(fullTestName);
}
@TestOnly
protected void <API key>() {
mySuitesStack.clear();
}
private String <API key>(String fullTestName) {
return "Cant find running test for ["
+ fullTestName
+ "]. Current running tests: {"
+ <API key>() + "}";
}
private StringBuilder <API key>() {
final Set<String> names = <API key>.keySet();
final StringBuilder namesDump = new StringBuilder();
for (String name : names) {
namesDump.append('[').append(name).append(']').append(',');
}
return namesDump;
}
/*
* Remove listeners, etc
*/
@Override
public void dispose() {
super.dispose();
if (!<API key>.isEmpty()) {
final Application application = ApplicationManager.getApplication();
if (!application.<API key>() && !application.isUnitTestMode()) {
logProblem("Not all events were processed! " + <API key>());
}
}
<API key>.clear();
mySuitesStack.clear();
}
private SMTestProxy <API key>() {
//if we can locate test - we will send output to it, otherwise to current test suite
SMTestProxy currentProxy = null;
Iterator<SMTestProxy> iterator = <API key>.values().iterator();
if (iterator.hasNext()) {
//current test
currentProxy = iterator.next();
if (iterator.hasNext()) { //if there are multiple tests running call put output to the suite
currentProxy = null;
}
}
if (currentProxy == null) {
//current suite
// ProcessHandler can fire output available event before processStarted event
final SMTestProxy currentSuite = mySuitesStack.getCurrentSuite();
currentProxy = currentSuite != null ? currentSuite : myTestsRootProxy;
}
return currentProxy;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SQLite;
using System.Data.Common;
using System.IO;
namespace GatherAll
{
class Cls_SqliteMng
{
//string m_DBName = "";
//string connStr = "";
//HyData
public void CreateDB(string dbName)
{
// string databaseFileName = System.Environment.CurrentDirectory + @"/HyData/" + dbName;
SQLiteConnection.CreateFile(dbName);
}
//Sql
// ExecuteSql("create table HyTest(TestID TEXT)");
// ExecuteSql("insert into HyTest(TestID) values('1001')");
public void ExecuteSql(string sqlStr, string strConStr)
{
//connStr = connStr1 + m_DBName + connStr;
using (DbConnection conn = new SQLiteConnection(strConStr))
{
conn.Open();
DbCommand comm = conn.CreateCommand();
comm.CommandText = sqlStr;
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
}
}
/DataSet
//private DataSet ExecDataSet(string sqlStr)
// //connStr = "";
// //connStr = connStr1 + m_DBName + connStr;
// using (SQLiteConnection conn = new SQLiteConnection(sqlStr))
// conn.Open();
// SQLiteCommand cmd = conn.CreateCommand();
// cmd.CommandText = sqlStr;
// cmd.CommandType = CommandType.Text;
// SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
// DataSet ds = new DataSet();
// da.Fill(ds);
// return ds;
}
}
|
package br.copacabana;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import javax.cache.Cache;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import br.com.copacabana.cb.entities.Address;
import br.com.copacabana.cb.entities.Client;
import br.com.copacabana.cb.entities.MealOrder;
import br.com.copacabana.cb.entities.OrderedPlate;
import br.com.copacabana.cb.entities.Plate;
import br.com.copacabana.cb.entities.Restaurant;
import br.com.copacabana.cb.entities.TurnType;
import br.com.copacabana.cb.entities.WorkingHours.DayOfWeek;
import br.copacabana.order.paypal.PayPalProperties.PayPalConfKeys;
import br.copacabana.spring.AddressManager;
import br.copacabana.spring.ClientManager;
import br.copacabana.spring.<API key>;
import br.copacabana.spring.PlateManager;
import br.copacabana.spring.RestaurantManager;
import br.copacabana.usecase.control.UserActionManager;
import br.copacabana.util.TimeController;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
/**
* @author Rafael Coutinho
*/
public class <API key> extends JsonViewController {
private String formView;
private String successView;
@Override
protected ModelAndView <API key>(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
model.put("mode", "view");
try {
Cache cache = CacheController.getCache();
if (cache.get(PayPalConfKeys.pppFixedRate.name()) == null) {
<API key> cm = new <API key>();
cache.put(PayPalConfKeys.pppFixedRate.name(), cm.<API key>(PayPalConfKeys.pppFixedRate.name()));
cache.put(PayPalConfKeys.pppPercentageValue.name(), cm.<API key>(PayPalConfKeys.pppPercentageValue.name()));
}
if (!Authentication.isUserLoggedIn(request.getSession())) {
String orderData = request.getParameter("orderData");
request.getSession().setAttribute("orderData", orderData);
model.put("forwardUrl", "/continueOrder.jsp");
UserActionManager.startOrderNotLogged(orderData, request.getSession().getId());
return new ModelAndView(getFormView(), model);
} else {
String orderData = "";
JsonObject user = Authentication.getLoggedUser(request.getSession());
String loggedUserId = user.get("entity").getAsJsonObject().get("id").getAsString();
if (request.getParameter("orderData") == null) {
orderData = (String) request.getSession().getAttribute("orderData");
} else {
orderData = request.getParameter("orderData");
}
log.log(Level.INFO, "OrderJSon: {0}", orderData);
JsonParser pa = new JsonParser();
JsonObject orderDataJson = (JsonObject) pa.parse(orderData);
ClientManager cman = new ClientManager();
Client c = cman.find(KeyFactory.stringToKey(loggedUserId), Client.class);
MealOrder mo = getMealOrder(c, orderDataJson);
request.getSession().setAttribute("clientPhone", "");
DateSerializer dateSerializer = new DateSerializer(request);
DateDeSerializer dateDeSerializer = new DateDeSerializer(request);
GsonBuilder gsonBuilder = GsonBuilderFactory.getInstance();// new
// GsonBuilder().setPrettyPrinting().serializeNulls().<API key>();
gsonBuilder.registerTypeAdapter(Date.class, dateSerializer);
gsonBuilder.registerTypeAdapter(Date.class, dateDeSerializer);
gsonBuilder.registerTypeAdapter(Key.class, new KeyDeSerializer());
gsonBuilder.registerTypeAdapter(Key.class, new KeySerializer());
Gson gson = gsonBuilder.create();
model.putAll(updateModelData(mo, c, gson));
String json = gson.toJson(mo); // Or use new
json = GsonBuilderFactory.escapeString(json);
request.getSession().setAttribute("orderData", json);
UserActionManager.startOrder(json, loggedUserId, request.getSession().getId());
return new ModelAndView(getSuccessView(), model);
}
} catch (Exception e) {
log.log(Level.SEVERE, "Failed to place order.");
try {
String orderData = "";
log.log(Level.SEVERE, "Checking logged user.");
JsonObject user = Authentication.getLoggedUser(request.getSession());
if (user == null) {
log.log(Level.SEVERE, "user is not logged in.");
}
String loggedUserId = user.get("entity").getAsJsonObject().get("id").getAsString();
log.log(Level.SEVERE, "logged user id {0}", loggedUserId);
if (request.getParameter("orderData") == null) {
log.log(Level.SEVERE, "Order is not in request, checking session");
orderData = (String) request.getSession().getAttribute("orderData");
} else {
log.log(Level.SEVERE, "Order is in request");
orderData = request.getParameter("orderData");
}
if (orderData == null) {
log.log(Level.SEVERE, "Order was null!");
}
log.log(Level.SEVERE, "Order is order :" + orderData);
log.log(Level.SEVERE, "Exception was {0}.", e);
log.log(Level.SEVERE, "Error was {0}.", e.getMessage());
UserActionManager.registerMajorError(request, e, loggedUserId, request.getSession().getId(), "placing order");
} catch (Exception ex) {
log.log(Level.SEVERE, "Failed during loggin of error was {0}.", e);
UserActionManager.registerMajorError(request, e, "placing order 2");
}
throw e;
}
}
public static Map<String, Object> updateModelData(MealOrder mo, Client c, Gson gson) {
Map<String, Object> model = new HashMap<String, Object>();
RestaurantManager rman = new RestaurantManager();
Restaurant r = rman.getRestaurant(mo.getRestaurant());
Boolean b = r.getOnlyForRetrieval();
if (b != null && true == b) {
model.put("onlyForRetrieval", Boolean.TRUE);
} else {
model.put("onlyForRetrieval", Boolean.FALSE);
}
model.put("<API key>", KeyFactory.keyToString(r.getAddress()));
model.put("clientCpf", c.getCpf());
model.put("level", c.getLevel().ordinal());
JsonObject json = new JsonObject();
<API key> cm = new <API key>();
String hasSpecificLogic = cm.<API key>("hasSpecificLogic");
model.put("noTakeAwayOrders", "false");
if (hasSpecificLogic != null && hasSpecificLogic.endsWith("true")) {
json = <API key>(mo, c, gson);
<API key>(mo, c, gson, json);
<API key>(mo, c, gson, json);
<API key>(mo,c,gson,json);
if (noTakeAwayOrders(mo) == true) {
model.put("noTakeAwayOrders", "true");
}
}
model.put("hasSpecificLogic", json.toString());
if (json.get("javascript") != null && json.get("javascript").getAsString().length() > 0) {
model.put("<API key>", json.get("javascript").getAsString());
}
Address restAddress = new AddressManager().getAddress(r.getAddress());
model.put("restaurantAddress", gson.toJson(restAddress));
return model;
}
private static boolean noTakeAwayOrders(MealOrder mo) {
<API key> cm = new <API key>();
String ids = cm.<API key>("no.takeaway.ids");
String restId = KeyFactory.keyToString(mo.getRestaurant());
if (ids.contains(restId)) {
return true;
}
return false;
}
private static void <API key>(MealOrder mo, Client c, Gson gson, JsonObject json) {
<API key> cm = new <API key>();
String idStr = cm.<API key>("papagaios.id");
if (idStr != null && idStr.length() > 0) {
Key k = KeyFactory.stringToKey(idStr);
if (k.equals(mo.getRestaurant())) {
json.add("javascript", new JsonPrimitive("/scripts/custom/papagaios.js"));
}
}
}
private static void <API key>(MealOrder mo, Client c, Gson gson, JsonObject json) {
<API key> cm = new <API key>();
String idStr = cm.<API key>("pizzadoro.id");
if (idStr != null && idStr.length() > 0) {
Key k = KeyFactory.stringToKey(idStr);
if (k.equals(mo.getRestaurant())) {
json.add("javascript", new JsonPrimitive("/scripts/custom/pizzadoro.js"));
}
}
}
private static void <API key>(MealOrder mo, Client c, Gson gson, JsonObject json) {
try {
<API key> cm = new <API key>();
PlateManager pm = new PlateManager();
String makisIdStr = cm.<API key>("makis.Id");
if (makisIdStr != null && makisIdStr.length() > 0) {
Key makis = KeyFactory.stringToKey(makisIdStr);
if (makis != null && makis.equals(mo.getRestaurant())) {
String packageId = cm.<API key>("makis.package.id");
if (packageId != null && packageId.length() > 0) {
json.add("makisPackageCostId", new JsonPrimitive(packageId));
json.add("makisMsg", new JsonPrimitive(cm.<API key>("makis.msg")));
boolean isIncluded = false;
Key packageKey = KeyFactory.stringToKey(packageId);
for (Iterator<OrderedPlate> iterator = mo.getPlates().iterator(); iterator.hasNext();) {
OrderedPlate plate = (OrderedPlate) iterator.next();
if (Boolean.FALSE.equals(plate.getIsFraction()) && plate.getPlate().equals(packageKey)) {
isIncluded = true;
break;
}
}
if (isIncluded == false) {
Plate packagePlate = pm.get(packageKey);
OrderedPlate oplate = new OrderedPlate();
oplate.setName(packagePlate.getName());
oplate.setPrice(packagePlate.getPrice());
oplate.setPriceInCents(packagePlate.getPriceInCents());
oplate.setQty(1);
oplate.setPlate(packageKey);
mo.getPlates().add(oplate);
}
}
}
}
} catch (Exception e) {
log.log(Level.SEVERE, "failed to add makis specific logic", e);
}
}
private static JsonObject <API key>(MealOrder mo, Client c, Gson gson) {
JsonObject json = new JsonObject();
json.add("freeDelivery", new JsonPrimitive("false"));
try {
<API key> cm = new <API key>();
String steakIdStr = cm.<API key>("steakHouse.Id");
if (steakIdStr != null && steakIdStr.length() > 0) {
Key steak = KeyFactory.stringToKey(steakIdStr);
if (steak.equals(mo.getRestaurant())) {
if (!TimeController.getDayOfWeek().equals(DayOfWeek.SATURDAY) && !TimeController.getDayOfWeek().equals(DayOfWeek.SUNDAY)) {
if (TimeController.getCurrentTurn().equals(TurnType.LUNCH)) {
String foodCatsStr = cm.<API key>("steakHouse.FoodCats");
if (foodCatsStr != null && foodCatsStr.length() > 0) {
String[] foodCatsArray = foodCatsStr.split("\\|");
Set<Key> foodCats = new HashSet<Key>();
for (int i = 0; i < foodCatsArray.length; i++) {
if (foodCatsArray[i].length() > 0) {
foodCats.add(KeyFactory.stringToKey(foodCatsArray[i]));
}
}
List<OrderedPlate> plates = mo.getPlates();
PlateManager pm = new PlateManager();
for (Iterator iterator = plates.iterator(); iterator.hasNext();) {
OrderedPlate orderedPlate = (OrderedPlate) iterator.next();
Plate p = null;
if (Boolean.TRUE.equals(orderedPlate.getIsFraction())) {
p = pm.getPlate(orderedPlate.getFractionPlates().iterator().next());
} else {
p = pm.getPlate(orderedPlate.getPlate());
}
if (!foodCats.contains(p.getFoodCategory())) {
json.add("freeDelivery", new JsonPrimitive("false"));
return json;
}
}
json.add("freeDelivery", new JsonPrimitive("true"));
json.add("msg", new JsonPrimitive(cm.<API key>("steakHouse.msg")));
}
}
}
}
}
} catch (Exception e) {
log.log(Level.SEVERE, "Could not set up things for SteakHouse", e);
}
return json;
}
public MealOrder getMealOrder(Client c, JsonObject sessionOderData) {
MealOrder mo = new MealOrder();
mo.setClient(c);
if (c.getContact() != null) {
mo.setClientPhone(c.getContact().getPhone());
}
mo.setAddress(getAddress(sessionOderData, c));
mo.setObservation(getObservation(sessionOderData));
mo.setRestaurant(getRestKey(sessionOderData));
mo.setPlates(getPlates(sessionOderData));
return mo;
}
private Key getAddress(JsonObject sessionOderData, Client c) {
try {
if (sessionOderData.get("address") == null) {
if (c.getMainAddress() != null) {
return c.getMainAddress();
} else {
return null;
}
} else {
if (sessionOderData.get("address") != null && !sessionOderData.get("address").isJsonNull() ) {
return KeyFactory.stringToKey(sessionOderData.get("address").getAsString());
}else{
return null;
}
}
} catch (Exception e) {
log.log(Level.SEVERE, "no address da sessão havia {0}", sessionOderData.get("address"));
log.log(Level.SEVERE, "Error ao buscar endereço de cliente ou em sessão", e);
return null;
}
}
public List<OrderedPlate> getPlates(JsonObject sessionOderData) {
List<OrderedPlate> orderedPlates = new ArrayList<OrderedPlate>();
JsonArray array = sessionOderData.get("plates").getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
JsonObject pjson = array.get(i).getAsJsonObject();
orderedPlates.add(getOrdered(pjson));
}
return orderedPlates;
}
private OrderedPlate getOrdered(JsonObject pjson) {
OrderedPlate oplate = new OrderedPlate();
oplate.setName(pjson.get("name").getAsString());
oplate.setPrice(pjson.get("price").getAsDouble());
oplate.setPriceInCents(Double.valueOf(pjson.get("price").getAsDouble() * 100.0).intValue());
oplate.setQty(pjson.get("qty").getAsInt());
if (pjson.get("isFraction").getAsBoolean() == true) {
oplate.setIsFraction(Boolean.TRUE);
Set<Key> fractionPlates = new HashSet<Key>();
JsonArray fractionKeys = pjson.get("fractionKeys").getAsJsonArray();
for (int i = 0; i < fractionKeys.size(); i++) {
Key fractionKey = KeyFactory.stringToKey(fractionKeys.get(i).getAsString());
fractionPlates.add(fractionKey);
}
oplate.setFractionPlates(fractionPlates);
return oplate;
} else {
String pkey = "";
if (pjson.get("plate").isJsonObject()) {
pkey = pjson.get("plate").getAsJsonObject().get("id").getAsString();
} else {
pkey = pjson.get("plate").getAsString();
}
oplate.setPlate(KeyFactory.stringToKey(pkey));
return oplate;
}
}
public Key getRestKey(JsonObject sessionOderData) {
String restKey;
if (sessionOderData.get("restaurant") != null) {
if (sessionOderData.get("restaurant").isJsonObject()) {
restKey = sessionOderData.get("restaurant").getAsJsonObject().get("id").getAsString();
} else {
restKey = sessionOderData.get("restaurant").getAsString();
}
} else {
restKey = sessionOderData.get("plates").getAsJsonArray().get(0).getAsJsonObject().get("plate").getAsJsonObject().get("value").getAsJsonObject().get("restaurant").getAsString();
}
return KeyFactory.stringToKey(restKey);
}
public String getObservation(JsonObject sessionOderData) {
return sessionOderData.get("observation").getAsString();
}
public String getFormView() {
return formView;
}
public void setFormView(String formView) {
this.formView = formView;
}
public String getSuccessView() {
return successView;
}
public void setSuccessView(String successView) {
this.successView = successView;
}
}
|
current_dir = File.dirname(__FILE__)
log_level :info
log_location STDOUT
node_name "user"
client_key "#{ENV['HOME']}/.ssh/user.pem"
<API key> "user-validator"
validation_key "#{current_dir}/validator.pem"
chef_server_url "https://api.opscode.com/organizations/user-organization"
cache_type 'BasicFile'
cache_options(:path => "#{ENV['HOME']}/.chef/checksums" )
cookbook_path "#{current_dir}/../cookbooks"
# required to extract the right interface for knife ssh
knife[:ssh_attribute] = "ipaddress"
knife[:joyent_username] = ENV['SDC_USERNAME'] || 'user'
knife[:joyent_keyname] = ENV['SDC_CLI_KEY_ID'] || 'keyname'
knife[:joyent_keyfile] = ENV['SDC_CLI_IDENTITY'] || "#{ENV['HOME']}/.ssh/id_rsa"
knife[:joyent_api_url] = 'https://us-sw-1.api.joyentcloud.com/'
|
using System.Threading;
using System.Threading.Tasks;
using MediatR;
namespace CoreDocker.Core.Framework.CommandQuery
{
public class MediatorCommander : ICommander
{
private readonly IMediator _mediator;
public MediatorCommander(IMediator mediator)
{
_mediator = mediator;
}
#region Implementation of ICommander
public async Task Notify<T>(T notificationRequest, Cancellation<API key>) where T : <API key>
{
await _mediator.Publish(notificationRequest);
}
public async Task<CommandResult> Execute<T>(T commandRequest, Cancellation<API key>) where T : CommandRequestBase
{
return await _mediator.Send(commandRequest);
}
#endregion
}
}
|
package hska.iwi.eShopMaster.model.businessLogic.manager.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import hska.iwi.eShopMaster.model.businessLogic.manager.CategoryManager;
import hska.iwi.eShopMaster.model.businessLogic.manager.entity.Category;
import hska.iwi.eShopMaster.model.businessLogic.manager.entity.User;
import java.util.List;
import javax.ws.rs.core.MediaType;
import org.apache.log4j.Logger;
public class CategoryManagerImpl implements CategoryManager {
private final static String BASIS_URL_CATEGORY = "http://localhost:8081/api/catalog/category/";
private final Logger logger = Logger.getLogger(CategoryManagerImpl.class);
private final ObjectMapper parser = new ObjectMapper();
private final User currentUser;
public CategoryManagerImpl(User currentUser) {
this.currentUser = currentUser;
}
@Override
public List<Category> getCategories() {
List<Category> categories = null;
try {
Client client = Client.create();
WebResource webResource = client
.resource(BASIS_URL_CATEGORY);
ClientResponse response = webResource.accept(MediaType.<API key>)
.get(ClientResponse.class);
categories = parser.readValue(response.getEntity(String.class), List.class);
} catch (Exception ex) {
logger.error(ex);
}
return categories;
}
@Override
public Category getCategory(int id) {
Category category = null;
try {
Client client = Client.create();
WebResource webResource = client
.resource(BASIS_URL_CATEGORY)
.path(String.valueOf(id));
ClientResponse response = webResource.accept(MediaType.<API key>)
.get(ClientResponse.class);
category = parser.readValue(response.getEntity(String.class), Category.class);
} catch (Exception ex) {
logger.error(ex);
}
return category;
}
@Override
public void addCategory(String name) {
Category category = new Category(name);
try {
Client client = Client.create();
WebResource webResource = client
.resource(BASIS_URL_CATEGORY);
webResource.type(MediaType.<API key>)
.accept(MediaType.<API key>)
.header("usr", currentUser.getUsername())
.header("pass", currentUser.getPassword())
.post(ClientResponse.class, parser.writeValueAsString(category));
} catch (Exception ex) {
logger.error(ex);
}
}
@Override
public void delCategoryById(int id) {
try {
Client client = Client.create();
WebResource webResource = client
.resource(BASIS_URL_CATEGORY)
.path(String.valueOf(id));
webResource.accept(MediaType.<API key>)
.header("usr", currentUser.getUsername())
.header("pass", currentUser.getPassword())
.delete();
} catch (Exception ex) {
logger.error(ex);
}
}
}
|
function f() {
var x=arguments[12];
}
|
import App from '../containers/App';
import { PageNotFound } from '../components';
import homeRoute from '../features/home/route';
import taggrRoute from '../features/taggr/route';
const routes = [{
path: '/',
component: App,
childRoutes: [
homeRoute,
taggrRoute,
{ path: '*', name: 'Page not found', component: PageNotFound },
],
}];
// Handle isIndex property of route config:
// 1. remove the first child with isIndex=true from childRoutes
// 2. assign it to the indexRoute property of the parent.
function handleIndexRoute(route) {
if (!route.childRoutes || !route.childRoutes.length) {
return;
}
route.childRoutes = route.childRoutes.filter(child => { // eslint-disable-line
if (child.isIndex) {
/* istanbul ignore next */
if (process.env.NODE_ENV === 'dev' && route.indexRoute) {
console.error('More than one index route: ', route);
}
/* istanbul ignore else */
if (!route.indexRoute) {
delete child.path; // eslint-disable-line
route.indexRoute = child; // eslint-disable-line
return false;
}
}
return true;
});
route.childRoutes.forEach(handleIndexRoute);
}
routes.forEach(handleIndexRoute);
export default routes;
|
public class Student {
String name;
int grade;
@Override
public String toString() {
String temp = "";
temp += "name: " + name + "\n";
temp += "grade: " + grade + "\n";
return temp;
}
@Override
public boolean equals(Object obj) {
if(this==obj) return true;
boolean r = false;
if(obj instanceof Student){
Student temp = (Student)obj;
if(this.name.equals(temp.name)
&& this.grade == temp.grade)
r = true;
}
return r;
}
}
|
# Arduino Debug
## Install
1. install Arduino IDE (free)
www.arduino.cc > download
2. install Microsoft Visual Studio 2015 Community Edition (free)
* get vs2015.com_chs.iso
* select C++ from the available VS2015 setup options.
>It requires Visual Studio C++ to be installed before Arduino projects can be created or opened.
3. install plugin
https://visualstudiogallery.msdn.microsoft.com/<API key>
## Use
Visual Studio 2015 Community
1. Open File (Ctrl + O), select Arduino src file.
2. add breakpoint by click line number.
3. add watching expressiong by adding actions like {x} {y}
4. run debug
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class io.permazen.util.NavigableSetPager (Permazen 4.1.9-SNAPSHOT API)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class io.permazen.util.NavigableSetPager (Permazen 4.1.9-SNAPSHOT API)";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../io/permazen/util/NavigableSetPager.html" title="class in io.permazen.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?io/permazen/util/class-use/NavigableSetPager.html" target="_top">Frames</a></li>
<li><a href="NavigableSetPager.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h2 title="Uses of Class io.permazen.util.NavigableSetPager" class="title">Uses of Class<br>io.permazen.util.NavigableSetPager</h2>
</div>
<div class="classUseContainer">No usage of io.permazen.util.NavigableSetPager</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../io/permazen/util/NavigableSetPager.html" title="class in io.permazen.util">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?io/permazen/util/class-use/NavigableSetPager.html" target="_top">Frames</a></li>
<li><a href="NavigableSetPager.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
<p class="legalCopy"><small>Copyright &
</body>
</html>
|
using System;
using System.IO;
using System.Reflection;
using Moq;
using NUnit.Framework;
using Weald.Service;
namespace Weald.Tests
{
[TestFixture]
public class <API key>
{
private string _tempFilePath;
[SetUp]
public void SetUp()
{
_tempFilePath = Path.GetTempFileName();
}
[TearDown]
public void TearDown()
{
try
{
File.Delete(_tempFilePath);
}
catch
{
}
}
[Test]
public void <API key>()
{
var <API key> = new Mock<<API key>>();
<API key>.Setup(x => x.ServiceExePath)
.Returns(Guid.NewGuid().ToString());
var <API key> = new Mock<<API key>>();
<API key>.Setup(x => x.GetValue("SvnServerAlias"))
.Returns("Foo");
var serverInfo = new <API key>(<API key>.Object, <API key>.Object);
Assert.IsFalse(serverInfo.<API key>);
Assert.IsNullOrEmpty(serverInfo.RepoStoragePath);
Assert.IsNullOrEmpty(serverInfo.SvnLookExePath);
}
[Test]
public void <API key>()
{
File.WriteAllLines(_tempFilePath, new[] { "FOO", "#BAR", " SVNParentPath \"E:/svn/repos/\"", " BAZ" });
var <API key> = new Mock<<API key>>();
<API key>.Setup(x => x.ServiceExePath)
.Returns(Assembly.<API key>().Location);
<API key>.Setup(x => x.<API key>)
.Returns(_tempFilePath);
<API key>.Setup(x => x.ServiceBinDirectory)
.Returns("C:\\Foo");
var <API key> = new Mock<<API key>>();
<API key>.Setup(x => x.GetValue("SvnServerAlias"))
.Returns("Foo");
var serverInfo = new <API key>(<API key>.Object, <API key>.Object);
Assert.IsTrue(serverInfo.<API key>);
Assert.IsNotNullOrEmpty(serverInfo.RepoStoragePath);
Assert.AreEqual(@"e:\svn\repos", serverInfo.RepoStoragePath.ToLowerInvariant());
}
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Mon Mar 03 10:44:38 EST 2014 -->
<title>Uses of Interface org.hibernate.event.spi.<API key> (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.hibernate.event.spi.<API key> (Hibernate JavaDocs)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/hibernate/event/spi/class-use/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h2 title="Uses of Interface org.hibernate.event.spi.<API key>" class="title">Uses of Interface<br>org.hibernate.event.spi.<API key></h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.hibernate.cfg.beanvalidation">org.hibernate.cfg.beanvalidation</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.hibernate.event.spi">org.hibernate.event.spi</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#org.hibernate.secure.internal">org.hibernate.secure.internal</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.hibernate.cfg.beanvalidation">
</a>
<h3>Uses of <a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi"><API key></a> in <a href="../../../../../org/hibernate/cfg/beanvalidation/package-summary.html">org.hibernate.cfg.beanvalidation</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../org/hibernate/cfg/beanvalidation/package-summary.html">org.hibernate.cfg.beanvalidation</a> that implement <a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/hibernate/cfg/beanvalidation/<API key>.html" title="class in org.hibernate.cfg.beanvalidation"><API key></a></strong></code>
<div class="block"><div class="paragraph"></div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.hibernate.event.spi">
</a>
<h3>Uses of <a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi"><API key></a> in <a href="../../../../../org/hibernate/event/spi/package-summary.html">org.hibernate.event.spi</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../org/hibernate/event/spi/package-summary.html">org.hibernate.event.spi</a> with type parameters of type <a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../org/hibernate/event/spi/EventType.html" title="class in org.hibernate.event.spi">EventType</a><<a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi"><API key></a>></code></td>
<td class="colLast"><span class="strong">EventType.</span><code><strong><a href="../../../../../org/hibernate/event/spi/EventType.html#PRE_UPDATE">PRE_UPDATE</a></strong></code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.hibernate.secure.internal">
</a>
<h3>Uses of <a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi"><API key></a> in <a href="../../../../../org/hibernate/secure/internal/package-summary.html">org.hibernate.secure.internal</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../org/hibernate/secure/internal/package-summary.html">org.hibernate.secure.internal</a> that implement <a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../org/hibernate/secure/internal/<API key>.html" title="class in org.hibernate.secure.internal"><API key></a></strong></code>
<div class="block"><div class="paragraph"></div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/hibernate/event/spi/<API key>.html" title="interface in org.hibernate.event.spi">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/hibernate/event/spi/class-use/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small>Copyright © 2001-2014 <a href="http:
</body>
</html>
|
package com.intellij.openapi.vcs;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.<API key>;
import com.intellij.util.containers.ContainerUtil;
import consulo.util.lang.Pair;
import consulo.util.lang.StringUtil;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
public final class VcsConsoleLine {
private final List<Pair<String, <API key>>> myChunks;
private VcsConsoleLine(@Nonnull List<Pair<String, <API key>>> chunks) {
myChunks = chunks;
}
public void print(@Nonnull ConsoleView console) {
<API key> lastType = <API key>.NORMAL_OUTPUT;
for (Pair<String, <API key>> chunk : myChunks) {
console.print(chunk.first, chunk.second);
lastType = chunk.second;
}
console.print("\n", lastType);
}
@Nullable
public static VcsConsoleLine create(@Nullable String message, @Nonnull <API key> contentType) {
return create(Collections.singletonList(Pair.create(message, contentType)));
}
@Nullable
public static VcsConsoleLine create(@Nonnull List<Pair<String, <API key>>> lineChunks) {
List<Pair<String, <API key>>> chunks = ContainerUtil.filter(lineChunks, it -> !StringUtil.isEmptyOrSpaces(it.first));
if (chunks.isEmpty()) return null;
return new VcsConsoleLine(chunks);
}
}
|
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.09.09 at 01:22:27 PM CEST
package test;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"content"
})
@XmlRootElement(name = "fpage")
public class Fpage {
@XmlValue
protected String content;
@XmlAttribute(name = "content-type")
@XmlSchemaType(name = "anySimpleType")
protected String contentType;
@XmlAttribute
@XmlSchemaType(name = "anySimpleType")
protected String seq;
/**
* Gets the value of the content property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContent() {
return content;
}
/**
* Sets the value of the content property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContent(String value) {
this.content = value;
}
/**
* Gets the value of the contentType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContentType() {
return contentType;
}
/**
* Sets the value of the contentType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContentType(String value) {
this.contentType = value;
}
/**
* Gets the value of the seq property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSeq() {
return seq;
}
/**
* Sets the value of the seq property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSeq(String value) {
this.seq = value;
}
}
|
'use strict';
const Task = require('co-task');
const sql = require('../api/helpers/sql');
module.exports = {
up: function (queryInterface, Sequelize) {
return Task.spawn(function* () {
yield queryInterface.addColumn('ClassicSalads', '<API key>', Sequelize.INTEGER);
yield sql.foreignKeyUp(queryInterface, 'ClassicSalads', '<API key>', '<API key>', 'id');
});
},
down: function (queryInterface, Sequelize) {
return Task.spawn(function* () {
yield sql.foreignKeyDown(queryInterface, 'ClassicSalads', '<API key>', '<API key>', 'id');
yield queryInterface.removeColumn('ClassicSalads', '<API key>');
});
}
};
|
<div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav in" id="side-menu">
<li>
</li>
<li ng-class="{active: collapseVar==key}" ng-repeat="(key, value) in doc.data">
<a href="" ng-click="check(key)"><i class="fa fa-info-circle fa-fw"></i> {{key}}<span class="fa arrow"></span></a>
<ul class="nav nav-second-level" collapse="collapseVar!=key">
<li ng-repeat="(key2, value2) in value" ng-show="key2 != 'info'">
<a href="/#/dashboard/doc/{{docapp.id}}/api/{{value2.info.id}}">{{key2}}</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
|
# Package : filebeat
# Version : 7.2.0
# Tested on : RHEL 7.5
# Maintainer : Edmond Chan <ckchan@hk1.ibm.com>
# It may not work as expected with newer versions of the
# package and/or distribution. In such case, please
# contact "Maintainer" of this script.
#!/bin/bash
# install dependencies
yum install golang make git
mkdir go
export GOPATH=~/go
mkdir -p ${GOPATH}/src/github.com/elastic
cd ${GOPATH}/src/github.com/elastic
git clone https://github.com/elastic/beats.git
cd $GOPATH/src/github.com/elastic/beats/filebeat
git checkout v7.2.0
make
|
// Code generated - DO NOT EDIT.
package topology
import (
"github.com/skydive-project/skydive/graffiti/getter"
"strings"
)
func (obj *NextHop) GetFieldBool(key string) (bool, error) {
return false, getter.ErrFieldNotFound
}
func (obj *NextHop) GetFieldInt64(key string) (int64, error) {
switch key {
case "Priority":
return int64(obj.Priority), nil
case "IfIndex":
return int64(obj.IfIndex), nil
}
return 0, getter.ErrFieldNotFound
}
func (obj *NextHop) GetFieldString(key string) (string, error) {
switch key {
case "IP":
return obj.IP.String(), nil
case "MAC":
return string(obj.MAC), nil
}
return "", getter.ErrFieldNotFound
}
func (obj *NextHop) GetFieldKeys() []string {
return []string{
"Priority",
"IP",
"MAC",
"IfIndex",
}
}
func (obj *NextHop) MatchBool(key string, predicate getter.BoolPredicate) bool {
return false
}
func (obj *NextHop) MatchInt64(key string, predicate getter.Int64Predicate) bool {
if b, err := obj.GetFieldInt64(key); err == nil {
return predicate(b)
}
return false
}
func (obj *NextHop) MatchString(key string, predicate getter.StringPredicate) bool {
if b, err := obj.GetFieldString(key); err == nil {
return predicate(b)
}
return false
}
func (obj *NextHop) GetField(key string) (interface{}, error) {
if s, err := obj.GetFieldString(key); err == nil {
return s, nil
}
if i, err := obj.GetFieldInt64(key); err == nil {
return i, nil
}
return nil, getter.ErrFieldNotFound
}
func init() {
strings.Index("", ".")
}
|
# <API key>: true
module Beta
module Types
module Objects
class PrefectureType < Beta::Types::Objects::Base
implements GraphQL::Types::Relay::Node
global_id_field :id
field :annict_id, Integer, null: false
field :name, String, null: false
end
end
end
end
|
import java.util.Scanner;
/**
* @author Oleg Cherednik
* @since 13.07.2018
*/
public class Solution {
static int palindromeIndex(String s) {
for (int i = 0, j = s.length() - 1; i < j; i++, j
if (s.charAt(i) == s.charAt(j))
continue;
for (int k = i, m = j - 1; k < m; k++, m
if (s.charAt(k) != s.charAt(m))
return i;
return j;
}
return -1;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int q = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int qItr = 0; qItr < q; qItr++) {
String s = scanner.nextLine();
int result = palindromeIndex(s);
System.out.println(String.valueOf(result));
}
scanner.close();
}
}
|
package de.newsarea.homecockpit.connector.facade.registration.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public final class ClassLoaderHelper {
private static Logger log = LoggerFactory.getLogger(ClassLoaderHelper.class);
private ClassLoaderHelper() { }
public static Constructor<?> <API key>(Class<?> clazz) {
try {
for(Constructor<?> constructor : clazz.getConstructors()) {
return constructor;
}
} catch (SecurityException e) {
log.error(e.getMessage(), e);
}
return null;
}
public static Constructor<?> <API key>(Class<?> clazz, Class<?>[] argumentTypes) {
try {
for(Constructor<?> constructor : clazz.getConstructors()) {
if(isAssignableFrom(constructor, argumentTypes)) {
return constructor;
}
}
} catch (SecurityException e) {
log.error(e.getMessage(), e);
}
return null;
}
private static boolean isAssignableFrom(Constructor<?> constructor, Class<?>[] argumentTypes) {
Class<?>[] constructorArgTypes = constructor.getParameterTypes();
if(constructorArgTypes.length != argumentTypes.length) {
return false;
}
for(int i=0; i < argumentTypes.length; i++) {
if(!argumentTypes[i].isAssignableFrom(constructorArgTypes[i])) {
return false;
}
}
return true;
}
public static List<Class<?>> determineClasses(String packageName) throws <API key>, IOException {
ClassLoader classLoader = Thread.currentThread().<API key>();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile().replaceAll("%20", " ")));
}
ArrayList<Class<?>> classes = new ArrayList<>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes;
}
public static List<Class<?>> findClasses(File directory, String packageName) throws <API key> {
List<Class<?>> classes = new ArrayList<>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
return classes;
}
public static Method <API key>(Class<?> clazz, String name) {
for(Method method : clazz.getMethods()) {
if(method.getName().equalsIgnoreCase("set" + name)) {
return method;
}
}
return null;
}
}
|
package com.github.database.rider.core.script;
import org.assertj.core.api.SoftAssertions;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import javax.script.ScriptException;
import static org.assertj.core.api.Java6Assertions.assertThat;
public class <API key> {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
private <API key> scriptEngineManager = <API key>.getInstance();
private SoftAssertions softly = new SoftAssertions();
@Before
public void init() {
softly = new SoftAssertions();
}
@Test
public void <API key>() throws ScriptException {
Object scriptResult = <API key>.getInstance().getScriptResult("js: 1+1");
assertThat(scriptResult).isEqualTo(2);
}
@Test
public void <API key>() throws ScriptException {
Object scriptResult = scriptEngineManager.getScriptResult("groovy: 1+1");
assertThat(scriptResult).isEqualTo(2);
}
@Test
public void <API key>() throws ScriptException {
exceptionRule.expect(RuntimeException.class);
exceptionRule.expectMessage("Could not find script engine by name 'kotlin'");
scriptEngineManager.getScriptResult("kotlin: 1+1");
}
@Test
public void <API key>() throws ScriptException {
String script = "js:(value > 0)";
softly.assertThat(scriptEngineManager.getScriptAssert(script, 2)).as("js script with value=2").isTrue();
softly.assertThat(scriptEngineManager.getScriptAssert(script, 0)).as("js script with value=0").isFalse();
softly.assertThat(scriptEngineManager.getScriptAssert(script, -1)).as("js script with value=-1").isFalse();
script = "groovy:(value > 0)";
softly.assertThat(scriptEngineManager.getScriptAssert(script, 2)).as("groovy script with value=2").isTrue();
softly.assertThat(scriptEngineManager.getScriptAssert(script, 0)).as("groovy script with value=0").isFalse();
softly.assertThat(scriptEngineManager.getScriptAssert(script, -1)).as("groovy script with value=-1").isFalse();
softly.assertAll();
}
@Test
public void <API key>() throws ScriptException {
SoftAssertions soft = new SoftAssertions();
String script = "js:(value == null)";
soft.assertThat(scriptEngineManager.getScriptAssert(script, null)).as("js script with null value").isTrue();
soft.assertThat(scriptEngineManager.getScriptAssert(script, 1)).as("js script with non-null value").isFalse();
script = "groovy:(value == null)";
soft.assertThat(scriptEngineManager.getScriptAssert(script, null)).as("groovy script with null value").isTrue();
soft.assertThat(scriptEngineManager.getScriptAssert(script, 1)).as("groovy script with non-null value").isFalse();
soft.assertAll();
}
@Test
public void <API key>() throws ScriptException {
SoftAssertions soft = new SoftAssertions();
String script = "js:(value.contains('dbunit'))";
soft.assertThat(scriptEngineManager.getScriptAssert(script, "dbunit rules")).as("js script with 'dbunit rules' value").isTrue();
soft.assertThat(scriptEngineManager.getScriptAssert(script, "database rider rules")).as("js script 'database rider' value").isFalse();
script = "groovy:(value.contains('dbunit'))";
soft.assertThat(scriptEngineManager.getScriptAssert(script, "dbunit rules")).as("groovy script with 'dbunit rules' value").isTrue();
soft.assertThat(scriptEngineManager.getScriptAssert(script, "database rider rules")).as("groovy script 'database rider' value").isFalse();
soft.assertAll();
}
@Test
public void <API key>() throws ScriptException {
exceptionRule.expect(ScriptException.class);
exceptionRule.expectMessage("value.includes is not a function");
String script = "js:(value.includes('dbunit'))";
scriptEngineManager.getScriptAssert(script, "dbunit rules");
}
}
|
/*global describe, beforeEach, it*/
'use strict';
var assert = require('yeoman-generator').assert;
var helper = require('./helper');
describe('mcap:connections', function () {
beforeEach(function (done) {
var answers = {
name: 'MyApp'
};
// Creates a generateor with the default options / arguments
helper.createAppGenerator({
answers: answers
}, done);
});
it('creates expected files', function (done) {
var expectedFiles = [
'connections/sap.json'
];
var expectedContent = {
name: 'SAP',
description: 'SAP API',
type: 'rest',
properties: {
descriptorUrl: 'http://sap.mway.io',
username: 'admin',
password: 'root'
}
};
var answers = {
name: 'SAP',
description: 'SAP API',
descriptorUrl: 'http://sap.mway.io',
username: 'admin',
password: 'root'
};
helper.createSubGenerator('connection', {answers: answers}, function () {
assert.file(expectedFiles);
helper.deepEqual('connections/sap.json', expectedContent);
done();
});
});
});
|
package com.github.agourlay.cornichon.steps.wrapped
import com.github.agourlay.cornichon.core._
import com.github.agourlay.cornichon.steps.regular.assertStep.{ AssertStep, <API key> }
import com.github.agourlay.cornichon.testHelpers.CommonTestSuite
import munit.FunSuite
import scala.concurrent.duration._
class WithinStepSpec extends FunSuite with CommonTestSuite {
test("controls duration of 'within' wrapped steps") {
val d = 50.millis
val nested = AssertStep(
"possible random value step",
_ => {
Thread.sleep(10)
<API key>(true, true)
}
) :: Nil
val withinStep = WithinStep(nested, d)
val s = Scenario("scenario with Within", withinStep :: Nil)
val res = awaitIO(ScenarioRunner.runScenario(Session.newEmpty)(s))
assert(res.isSuccess)
}
test("fails if duration of 'within' is exceeded") {
val d = 10.millis
val nested = AssertStep(
"possible random value step",
_ => {
Thread.sleep(20)
<API key>(true, true)
}
) :: Nil
val withinStep = WithinStep(nested, d)
val s = Scenario("scenario with Within", withinStep :: Nil)
val res = awaitIO(ScenarioRunner.runScenario(Session.newEmpty)(s))
assert(!res.isSuccess)
}
}
|
const browserSync = require('../../../');
const utils = require('../utils');
const register = require('../../../dist/plugins/clients').ClientEvents.register;
const assert = require('chai').assert;
describe('Client connection stream', function () {
it('does not have duplicates', function (done) {
browserSync.create({}).subscribe(function (bs) {
const client = utils.getClientSocket(bs);
client.emit(register, utils.getClient('123456'));
client.emit(register, utils.getClient('123456'));
bs.clients$.skip(1)
.take(2)
.toArray()
.subscribe(function (clients) {
assert.equal(clients[0].size, 1);
assert.equal(clients[1].size, 1);
const jsClients1 = clients[0].toList().toJS();
const jsClients2 = clients[1].toList().toJS();
assert.equal(jsClients1[0].id, '123456');
assert.equal(jsClients2[0].id, '123456');
bs.cleanup();
done();
}, function (err) {done(err)});
});
});
it('allows unique clients', function (done) {
browserSync.create({}).subscribe(function (bs) {
const client = utils.getClientSocket(bs);
client.emit(register, utils.getClient('xyz'));
client.emit(register, utils.getClient('zxy'));
bs.clients$.skip(1)
.take(2)
.toArray()
.subscribe(function (clients) {
assert.equal(clients[0].size, 1);
assert.equal(clients[1].size, 2);
const jsClients1 = clients[0].toList().toJS();
const jsClients2 = clients[1].toList().toJS();
assert.equal(jsClients1[0].id, 'xyz');
assert.equal(jsClients2[0].id, 'xyz');
assert.equal(jsClients2[1].id, 'zxy');
bs.cleanup();
done();
}, function(err) { done(err) });
});
});
it('allows unique clients (stress)', function (done) {
browserSync.create({}).subscribe(function (bs) {
for (var i = 1, n = 51; i < n; i += 1) {
utils.getClientSocket(bs).emit(register, utils.getClient('id-' + i));
}
bs.clients$.skip(1)
.take(50)
.toArray()
.subscribe(function (clients) {
assert.equal(clients[49].size, 50);
assert.ok(clients[49].get('id-40'));
assert.equal(clients[49].get('id-40').get('id'), 'id-40');
bs.cleanup();
done();
}, function(err) { done(err) });
});
});
});
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_112) on Tue Sep 12 14:31:26 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.config.management.security_realm.Ldap<API key> (BOM: * : All 2017.9.5 API)</title>
<meta name="date" content="2017-09-12">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.wildfly.swarm.config.management.security_realm.Ldap<API key> (BOM: * : All 2017.9.5 API)";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/Ldap<API key>.html" title="interface in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.9.5</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/Ldap<API key>.html" target="_top">Frames</a></li>
<li><a href="Ldap<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.config.management.security_realm.Ldap<API key> class="title">Uses of Interface<br>org.wildfly.swarm.config.management.security_realm.Ldap<API key></h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/Ldap<API key>.html" title="interface in org.wildfly.swarm.config.management.security_realm">Ldap<API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management">org.wildfly.swarm.config.management</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.management">
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/Ldap<API key>.html" title="interface in org.wildfly.swarm.config.management.security_realm">Ldap<API key></a> in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/Ldap<API key>.html" title="interface in org.wildfly.swarm.config.management.security_realm">Ldap<API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/SecurityRealm.html" title="type parameter in SecurityRealm">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">SecurityRealm.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/SecurityRealm.html#<API key>.wildfly.swarm.config.management.security_realm.Ldap<API key>>ldapAuthorization</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/Ldap<API key>.html" title="interface in org.wildfly.swarm.config.management.security_realm">Ldap<API key></a> supplier)</code>
<div class="block">Configuration to use LDAP as the user repository.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/Ldap<API key>.html" title="interface in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.9.5</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/Ldap<API key>.html" target="_top">Frames</a></li>
<li><a href="Ldap<API key>.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip.navbar.bottom">
</a></div>
<p class="legalCopy"><small>Copyright &
</body>
</html>
|
#!/usr/bin/env python
"""A flow to run checks for a host."""
from grr.lib import aff4
from grr.lib import flow
from grr.lib import rdfvalue
from grr.lib.checks import checks
from grr.proto import flows_pb2
class CheckFlowArgs(rdfvalue.RDFProtoStruct):
protobuf = flows_pb2.CheckFlowArgs
class CheckRunner(flow.GRRFlow):
"""This flow runs checks on a host.
CheckRunner:
- Identifies what checks should be run for a host.
- Identifies the artifacts that need to be collected to perform those checks.
- Orchestrates collection of the host data.
- Routes host data to the relevant checks.
- Returns check data ready for reporting.
"""
friendly_name = "Run Checks"
category = "/Checks/"
behaviours = flow.GRRFlow.behaviours + "BASIC"
@flow.StateHandler(next_state=["MapArtifactData"])
def Start(self):
client = aff4.FACTORY.Open(self.client_id, token=self.token)
self.state.Register("knowledge_base",
client.Get(client.Schema.KNOWLEDGE_BASE))
self.state.Register("labels", client.GetLabels())
self.state.Register("artifacts_wanted", set())
self.state.Register("artifacts_fetched", set())
self.state.Register("checks_run", [])
self.state.Register("<API key>", [])
self.state.Register("results_store", None)
self.state.Register("host_data", {})
self.CallState(next_state="MapArtifactData")
@flow.StateHandler(next_state=["AddResponses", "RunChecks"])
def MapArtifactData(self, responses):
"""Get processed data, mapped to artifacts."""
self.state.artifacts_wanted = checks.CheckRegistry.SelectArtifacts(
os=self.state.knowledge_base.os)
# Fetch Artifacts and map results to the artifacts that generated them.
# This is an inefficient collection, but necessary because results need to
# be mapped to the originating artifact. An alternative would be to have
# rdfvalues labeled with originating artifact ids.
for artifact_id in self.state.artifacts_wanted:
self.CallFlow("<API key>", artifact_list=[artifact_id],
request_data={"artifact_id": artifact_id},
next_state="AddResponses")
self.CallState(next_state="RunChecks")
@flow.StateHandler()
def AddResponses(self, responses):
artifact_id = responses.request_data["artifact_id"]
# TODO(user): Check whether artifact collection succeeded.
self.state.host_data[artifact_id] = list(responses)
@flow.StateHandler(next_state=["Done"])
def RunChecks(self, responses):
if not responses.success:
raise RuntimeError("Checks did not run successfully.")
# Hand host data across to checks. Do this after all data has been collected
# in case some checks require multiple artifacts/results.
for finding in checks.CheckHost(self.state.host_data,
os=self.state.knowledge_base.os):
self.state.checks_run.append(finding.check_id)
if finding.anomaly:
self.state.<API key>.append(finding.check_id)
self.SendReply(finding)
|
package fi.rivermouth.talous.auth;
import java.util.ArrayList;
import java.util.List;
import org.springframework.security.authentication.<API key>;
import org.springframework.security.authentication.Username<API key>;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.<API key>;
import fi.rivermouth.talous.domain.User;
public class User<API key> implements <API key> {
@Override
public Authentication authenticate(Authentication authentication) {
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
grantedAuths.add(new <API key>(User.ROLE));
return new Username<API key>(authentication.getName(), authentication.getCredentials(), grantedAuths);
}
}
|
#include <assert.h>
#include <pthread.h>
#include <stdint.h>
#include <time.h>
#include "../lib/includes.h"
#include "../lib/blacklist.h"
#include "../lib/logger.h"
#include "../lib/xalloc.h"
#include "iterator.h"
#include "aesrand.h"
#include "shard.h"
#include "state.h"
struct iterator {
cycle_t cycle;
uint8_t num_threads;
shard_t *thread_shards;
uint8_t *complete;
pthread_mutex_t mutex;
uint32_t curr_threads;
};
void shard_complete(uint8_t thread_id, void *arg)
{
iterator_t *it = (iterator_t *) arg;
assert(thread_id < it->num_threads);
pthread_mutex_lock(&it->mutex);
it->complete[thread_id] = 1;
it->curr_threads
shard_t *s = &it->thread_shards[thread_id];
zsend.sent += s->state.sent;
zsend.blacklisted += s->state.blacklisted;
zsend.whitelisted += s->state.whitelisted;
zsend.sendto_failures += s->state.failures;
uint8_t done = 1;
for (uint8_t i = 0; done && (i < it->num_threads); ++i) {
done = done && it->complete[i];
}
if (done) {
zsend.finish = now();
zsend.complete = 1;
zsend.first_scanned = it->thread_shards[0].state.first_scanned;
}
<API key>(&it->mutex);
}
iterator_t* iterator_init(uint8_t num_threads, uint8_t shard,
uint8_t num_shards)
{
uint64_t num_addrs = <API key>();
iterator_t *it = xmalloc(sizeof(struct iterator));
const cyclic_group_t *group = get_group(num_addrs);
if (num_addrs > (1LL << 32)) {
zsend.max_index = 0xFFFFFFFF;
} else {
zsend.max_index = (uint32_t) num_addrs;
}
it->cycle = make_cycle(group, zconf.aes);
it->num_threads = num_threads;
it->curr_threads = num_threads;
it->thread_shards = xcalloc(num_threads, sizeof(shard_t));
it->complete = xcalloc(it->num_threads, sizeof(uint8_t));
pthread_mutex_init(&it->mutex, NULL);
for (uint8_t i = 0; i < num_threads; ++i) {
shard_init(&it->thread_shards[i],
shard,
num_shards,
i,
num_threads,
&it->cycle,
shard_complete,
it
);
}
zconf.generator = it->cycle.generator;
return it;
}
uint32_t iterator_get_sent(iterator_t *it)
{
uint32_t sent = 0;
for (uint8_t i = 0; i < it->num_threads; ++i) {
sent += it->thread_shards[i].state.sent;
}
return sent;
}
shard_t* get_shard(iterator_t *it, uint8_t thread_id)
{
assert(thread_id < it->num_threads);
return &it->thread_shards[thread_id];
}
uint32_t <API key>(iterator_t *it)
{
assert(it);
return it->curr_threads;
}
|
package org.elasticsearch.rest.action.admin.indices;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.DataStreamAlias;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.RestBuilderListener;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import static org.elasticsearch.rest.RestRequest.Method.GET;
import static org.elasticsearch.rest.RestRequest.Method.HEAD;
/**
* The REST handler for get alias and head alias APIs.
*/
public class <API key> extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_alias"),
new Route(GET, "/_aliases"),
new Route(GET, "/_alias/{name}"),
new Route(HEAD, "/_alias/{name}"),
new Route(GET, "/{index}/_alias"),
new Route(HEAD, "/{index}/_alias"),
new Route(GET, "/{index}/_alias/{name}"),
new Route(HEAD, "/{index}/_alias/{name}"));
}
@Override
public String getName() {
return "get_aliases_action";
}
static RestResponse buildRestResponse(boolean <API key>, String[] requestedAliases,
ImmutableOpenMap<String, List<AliasMetadata>> responseAliasMap,
Map<String, List<DataStreamAlias>> dataStreamAliases, XContentBuilder builder) throws Exception {
final Set<String> indicesToDisplay = new HashSet<>();
final Set<String> returnedAliasNames = new HashSet<>();
for (final ObjectObjectCursor<String, List<AliasMetadata>> cursor : responseAliasMap) {
for (final AliasMetadata aliasMetadata : cursor.value) {
if (<API key>) {
// only display indices that have aliases
indicesToDisplay.add(cursor.key);
}
returnedAliasNames.add(aliasMetadata.alias());
}
}
// compute explicitly requested aliases that have are not returned in the result
final SortedSet<String> missingAliases = new TreeSet<>();
// first wildcard index, leading "-" as an alias name after this index means
// that it is an exclusion
int firstWildcardIndex = requestedAliases.length;
for (int i = 0; i < requestedAliases.length; i++) {
if (Regex.<API key>(requestedAliases[i])) {
firstWildcardIndex = i;
break;
}
}
for (int i = 0; i < requestedAliases.length; i++) {
if (Metadata.ALL.equals(requestedAliases[i]) || Regex.<API key>(requestedAliases[i])
|| (i > firstWildcardIndex && requestedAliases[i].charAt(0) == '-')) {
// only explicitly requested aliases will be called out as missing (404)
continue;
}
// check if aliases[i] is subsequently excluded
int j = Math.max(i + 1, firstWildcardIndex);
for (; j < requestedAliases.length; j++) {
if (requestedAliases[j].charAt(0) == '-') {
// this is an exclude pattern
if (Regex.simpleMatch(requestedAliases[j].substring(1), requestedAliases[i])
|| Metadata.ALL.equals(requestedAliases[j].substring(1))) {
// aliases[i] is excluded by aliases[j]
break;
}
}
}
if (j == requestedAliases.length) {
// explicitly requested aliases[i] is not excluded by any subsequent "-" wildcard in expression
if (false == returnedAliasNames.contains(requestedAliases[i])) {
// aliases[i] is not in the result set
missingAliases.add(requestedAliases[i]);
}
}
}
final RestStatus status;
builder.startObject();
{
if (missingAliases.isEmpty()) {
status = RestStatus.OK;
} else {
status = RestStatus.NOT_FOUND;
final String message;
if (missingAliases.size() == 1) {
message = String.format(Locale.ROOT, "alias [%s] missing", Strings.<API key>(missingAliases));
} else {
message = String.format(Locale.ROOT, "aliases [%s] missing", Strings.<API key>(missingAliases));
}
builder.field("error", message);
builder.field("status", status.getStatus());
}
for (final var entry : responseAliasMap) {
if (<API key> == false || (<API key> && indicesToDisplay.contains(entry.key))) {
builder.startObject(entry.key);
{
builder.startObject("aliases");
{
for (final AliasMetadata alias : entry.value) {
AliasMetadata.Builder.toXContent(alias, builder, ToXContent.EMPTY_PARAMS);
}
}
builder.endObject();
}
builder.endObject();
}
}
for (var entry : dataStreamAliases.entrySet()) {
builder.startObject(entry.getKey());
{
builder.startObject("aliases");
{
for (DataStreamAlias alias : entry.getValue()) {
builder.startObject(alias.getName());
builder.endObject();
}
}
builder.endObject();
}
builder.endObject();
}
}
builder.endObject();
return new BytesRestResponse(status, builder);
}
@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
// The <API key> was improved do the same post processing as is happening here.
// We can't remove this logic yet to support mixed clusters. We should be able to remove this logic here
// in when 8.0 becomes the new version in the master branch.
final boolean namesProvided = request.hasParam("name");
final String[] aliases = request.<API key>("name");
final GetAliasesRequest getAliasesRequest = new GetAliasesRequest(aliases);
final String[] indices = Strings.<API key>(request.param("index"));
getAliasesRequest.indices(indices);
getAliasesRequest.indicesOptions(IndicesOptions.fromRequest(request, getAliasesRequest.indicesOptions()));
getAliasesRequest.local(request.paramAsBoolean("local", getAliasesRequest.local()));
//we may want to move this logic to <API key> but it is based on the original provided aliases, which will
//not always be available there (they may get replaced so retrieving request.aliases is not quite the same).
return channel -> client.admin().indices().getAliases(getAliasesRequest, new RestBuilderListener<GetAliasesResponse>(channel) {
@Override
public RestResponse buildResponse(GetAliasesResponse response, XContentBuilder builder) throws Exception {
return buildRestResponse(namesProvided, aliases, response.getAliases(), response.<API key>(), builder);
}
});
}
}
|
# Sample : put() : Put a single request message to a queue
require 'wmq'
WMQ::QueueManager.connect(q_mgr_name: 'REID') do |qmgr|
message = WMQ::Message.new
message.data = 'Hello World'
message.descriptor = {
msg_type: WMQ::MQMT_REQUEST,
reply_to_q: 'TEST.REPLY.QUEUE'
}
qmgr.put(q_name: 'TEST.QUEUE', message: message)
end
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Moq.Protected;
using Riganti.Utils.Infrastructure.Core;
using Xunit;
#if EFCORE
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Riganti.Utils.Infrastructure.EntityFrameworkCore.Transactions;
#else
using System.Data.Entity;
using Riganti.Utils.Infrastructure.EntityFramework.Transactions;
#endif
#if EFCORE
namespace Riganti.Utils.Infrastructure.EntityFrameworkCore.Tests.UnitOfWork
#else
namespace Riganti.Utils.Infrastructure.EntityFramework.Tests.UnitOfWork
#endif
{
public class <API key>
{
[Fact]
public void <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
var <API key> = new Mock<<API key>>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext) { CallBase = true };
using (var unitOfWorkParent = <API key>.Object)
{
<API key>.RegisterUnitOfWork(unitOfWorkParent);
var unitOfWorkChildMock = new Mock<<API key>>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext) { CallBase = true };
using (var unitOfWorkChild = unitOfWorkChildMock.Object)
{
unitOfWorkChild.Commit();
}
unitOfWorkChildMock.Protected().Verify("CommitCore", Times.Never());
unitOfWorkParent.Commit();
}
<API key>.Protected().Verify("CommitCore", Times.Once());
}
[Fact]
public void <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
Assert.Throws<<API key>>(() =>
{
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
using (var unitOfWorkChild = unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
unitOfWorkChild.Commit();
}
}
});
// test that unit of work provider keeps working after caught exception
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
}
}
}
[Fact]
public void <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
using (var unitOfWorkParent = unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 1st level, context 1
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 2nd level, context 1
using (unitOfWorkProvider.Create(DbContextOptions.<API key>))
{
// 3rd level, context 2
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 4th level, context 2
using (var unitOfWorkParent3 = unitOfWorkProvider.Create(DbContextOptions.<API key>))
{
// 5th level, context 3
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 6th level, context 3
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
}
using (var unitOfWorkChild3 = unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 7th level, context 3 commit requested
unitOfWorkChild3.Commit();
}
}
// commit mandatory, context 3 commit pending
unitOfWorkParent3.Commit();
}
}
}
}
// commit optional, no reusing child commit pending
unitOfWorkParent.Commit();
}
}
[Fact]
public void <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
var <API key> = new Mock<<API key>>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext) { CallBase = true };
using (var unitOfWorkParent = <API key>.Object)
{
unitOfWorkParent.Commit();
}
<API key>.Protected().Verify("CommitCore", Times.Once());
}
[Fact]
public void <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
var <API key> = new Mock<<API key>>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext) { CallBase = true };
using (var unitOfWorkParent = <API key>.Object)
{
<API key>.RegisterUnitOfWork(unitOfWorkParent);
using (var unitOfWorkChild = new <API key>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext))
{
unitOfWorkChild.Commit();
}
unitOfWorkParent.Commit();
}
<API key>.Protected().Verify("CommitCore", Times.Once());
}
[Fact]
public async Task <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
var <API key> = new Mock<<API key>>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext) { CallBase = true };
using (var unitOfWorkParent = <API key>.Object)
{
<API key>.RegisterUnitOfWork(unitOfWorkParent);
var unitOfWorkChildMock = new Mock<<API key>>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext) { CallBase = true };
using (var unitOfWorkChild = unitOfWorkChildMock.Object)
{
await unitOfWorkChild.CommitAsync();
}
unitOfWorkChildMock.Protected().Verify("CommitAsyncCore", Times.Never(), new CancellationToken());
await unitOfWorkParent.CommitAsync();
}
<API key>.Protected().Verify("CommitAsyncCore", Times.Once(), new CancellationToken());
}
[Fact]
public async Task <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
await Assert.ThrowsAsync<<API key>>(async () =>
{
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
using (var unitOfWorkChild = unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
await unitOfWorkChild.CommitAsync();
}
}
});
// test that unit of work provider keeps working after caught exception
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
}
}
}
[Fact]
public async Task <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
using (var unitOfWorkParent = unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 1st level, context 1
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 2nd level, context 1
using (unitOfWorkProvider.Create(DbContextOptions.<API key>))
{
// 3rd level, context 2
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 4th level, context 2
using (var unitOfWorkParent3 = unitOfWorkProvider.Create(DbContextOptions.<API key>))
{
// 5th level, context 3
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 6th level, context 3
using (unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
}
using (var unitOfWorkChild3 = unitOfWorkProvider.Create(DbContextOptions.ReuseParentContext))
{
// 7th level, context 3 commit requested
await unitOfWorkChild3.CommitAsync();
}
}
// commit mandatory, context 3 commit pending
await unitOfWorkParent3.CommitAsync();
}
}
}
}
// commit optional, no reusing child commit pending
await unitOfWorkParent.CommitAsync();
}
}
[Fact]
public async Task <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
var <API key> = new Mock<<API key>>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext) { CallBase = true };
using (var unitOfWorkParent = <API key>.Object)
{
await unitOfWorkParent.CommitAsync();
}
<API key>.Protected().Verify("CommitAsyncCore", Times.Once(), new CancellationToken());
}
[Fact]
public async Task <API key>()
{
Func<DbContext> dbContextFactory = () => new Mock<DbContext>().Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
var <API key> = new Mock<<API key>>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext) { CallBase = true };
using (var unitOfWorkParent = <API key>.Object)
{
<API key>.RegisterUnitOfWork(unitOfWorkParent);
using (var unitOfWorkChild = new <API key>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext))
{
await unitOfWorkChild.CommitAsync();
}
await unitOfWorkParent.CommitAsync();
}
<API key>.Protected().Verify("CommitAsyncCore", Times.Once(), new CancellationToken());
}
[Fact]
public async Task <API key>()
{
var dbContextFactory = GetContextFactory();
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key><InMemoryDbContext>(<API key>, dbContextFactory);
var scopeMock = new Mock<<API key><InMemoryDbContext>>(unitOfWorkProvider);
var scope = scopeMock.Object;
await scope.ExecuteAsync(async uowParent =>
{
Assert.True(uowParent.IsInTransaction);
await uowParent.CommitAsync();
Assert.Equal(1, uowParent.CommitsCount);
Assert.False(uowParent.CommitPending);
using (var uowChild = (<API key><InMemoryDbContext>)unitOfWorkProvider.Create())
{
await uowChild.CommitAsync();
Assert.Equal(1, uowChild.CommitsCount);
Assert.False(uowChild.CommitPending);
Assert.Equal(2, uowParent.CommitsCount);
Assert.False(uowParent.CommitPending);
}
throw Assert.Throws<<API key>>(() => { uowParent.RollbackTransaction(); });
});
scopeMock.Protected().Verify("AfterRollback", Times.Once());
}
[Fact]
public async Task <API key>()
{
var dbContextFactory = GetContextFactory();
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key><InMemoryDbContext>(<API key>, dbContextFactory);
var scopeMock = new Mock<<API key><InMemoryDbContext>>(unitOfWorkProvider);
var scope = scopeMock.Object;
await scope.ExecuteAsync(async uowParent =>
{
Assert.True(uowParent.IsInTransaction);
await uowParent.CommitAsync();
using (var uowChild = (<API key><InMemoryDbContext>)unitOfWorkProvider.Create())
{
await uowChild.CommitAsync();
try
{
uowParent.RollbackTransaction();
}
catch (Exception)
{
// user catches any exceptions
}
}
});
scopeMock.Protected().Verify("AfterRollback", Times.Once());
}
[Fact]
public async Task <API key>()
{
var dbContextFactory = GetContextFactory();
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key><InMemoryDbContext>(<API key>, dbContextFactory);
var scope = unitOfWorkProvider.<API key>();
var exceptionKey = Guid.NewGuid().ToString();
try
{
await scope.ExecuteAsync(async uowParent =>
{
Assert.True(uowParent.IsInTransaction);
await uowParent.CommitAsync();
throw new Exception(exceptionKey);
});
}
catch (Exception e) when (e.Message == exceptionKey)
{
// test exception caught, passed
}
}
[Fact]
public async Task <API key>()
{
var dbContextFactory = GetContextFactory();
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key><InMemoryDbContext>(<API key>, dbContextFactory);
var scopeMock = new Mock<<API key><InMemoryDbContext>>(unitOfWorkProvider);
var scope = scopeMock.Object;
await scope.ExecuteAsync(async uowParent =>
{
Assert.True(uowParent.IsInTransaction);
await uowParent.CommitAsync();
Assert.Equal(1, uowParent.CommitsCount);
Assert.False(uowParent.CommitPending);
});
scopeMock.Protected().Verify("AfterCommit", Times.Once());
}
[Fact]
public async Task <API key>()
{
var dbContextFactory = GetContextFactory();
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key><InMemoryDbContext>(<API key>, dbContextFactory);
var scopeMock = new Mock<<API key><InMemoryDbContext>>(unitOfWorkProvider);
var scope = scopeMock.Object;
await scope.ExecuteAsync(async uowParent =>
{
Assert.True(uowParent.IsInTransaction);
await uowParent.CommitAsync();
Assert.Equal(1, uowParent.CommitsCount);
Assert.False(uowParent.CommitPending);
using (var uowChild = (<API key><InMemoryDbContext>)unitOfWorkProvider.Create())
{
await uowChild.CommitAsync();
Assert.Equal(1, uowChild.CommitsCount);
Assert.False(uowChild.CommitPending);
Assert.Equal(2, uowParent.CommitsCount);
Assert.False(uowParent.CommitPending);
using (var uowChildChild = (<API key><InMemoryDbContext>)unitOfWorkProvider.Create())
{
await uowChildChild.CommitAsync();
}
Assert.Equal(2, uowChild.CommitsCount);
Assert.False(uowChild.CommitPending);
Assert.Equal(3, uowParent.CommitsCount);
Assert.False(uowParent.CommitPending);
}
});
scopeMock.Protected().Verify("AfterCommit", Times.Once());
}
[Fact]
public void <API key>()
{
var dbContextFactory = GetContextFactory();
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key><InMemoryDbContext>(<API key>, dbContextFactory);
var scopeMock = new Mock<<API key><InMemoryDbContext>>(unitOfWorkProvider);
var scope = scopeMock.Object;
scope.Execute(uowParent =>
{
Assert.True(uowParent.IsInTransaction);
uowParent.Commit();
Assert.Equal(1, uowParent.CommitsCount);
Assert.False(uowParent.CommitPending);
});
scopeMock.Protected().Verify("AfterCommit", Times.Once());
}
[Fact]
public void <API key>()
{
var dbContext = new Mock<DbContext>().Object;
Func<DbContext> dbContextFactory = () => dbContext;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
var unitOfWork = new <API key>(unitOfWorkProvider, dbContextFactory, DbContextOptions.ReuseParentContext);
<API key>.RegisterUnitOfWork(unitOfWork);
var uowDbContext = <API key>.TryGetDbContext(unitOfWorkProvider);
Assert.NotNull(uowDbContext);
Assert.Same(dbContext, uowDbContext);
}
[Fact]
public void <API key>()
{
var dbContext = new Mock<DbContext>().Object;
Func<DbContext> dbContextFactory = () => dbContext;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
var value = <API key>.TryGetDbContext(unitOfWorkProvider);
Assert.Null(value);
}
[Fact]
public async Task <API key><API key>()
{
var dbContext = new Mock<DbContext>();
Func<DbContext> dbContextFactory = () => dbContext.Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
using (var uow = unitOfWorkProvider.Create())
{
using (var nested = unitOfWorkProvider.Create())
{
await nested.CommitAsync(new CancellationToken());
// verify, that method has NEVER been called
dbContext.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
}
await uow.CommitAsync(new CancellationToken());
// verify, that method has been called ONCE
dbContext.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
}
[Fact]
public async Task <API key><API key>()
{
var dbContext = new Mock<DbContext>();
Func<DbContext> dbContextFactory = () => dbContext.Object;
var <API key> = new <API key>();
var unitOfWorkProvider = new <API key>(<API key>, dbContextFactory);
using (var uow = unitOfWorkProvider.Create())
{
using (var nested = unitOfWorkProvider.Create())
{
await nested.CommitAsync();
// verify, that method has NEVER been called
dbContext.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Never);
}
await uow.CommitAsync();
// verify, that method has been called ONCE
dbContext.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
}
}
public class InMemoryDbContext : DbContext
{
#if EFCORE
protected override void OnConfiguring(<API key> optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.ConfigureWarnings(w => w.Ignore(InMemoryEventId.<API key>));
}
}
#endif
}
private static Func<InMemoryDbContext> GetContextFactory()
{
return () =>
#if EFCORE
new InMemoryDbContext();
#else
new Mock<InMemoryDbContext>().Object;
#endif
}
}
}
|
<?php
namespace Modules\IzCore\Repositories;
use Modules\IzCore\Repositories\Object\DataObject;
use Modules\IzCore\Repositories\Theme\View\<API key>;
use Pingpong\Modules\Repository;
class Theme extends DataObject {
/**
* @var
*/
protected $currentPath;
/**
* [
*'path'=>['Modules\IzCore\Repositories\Theme\View\AdditionView]
* ]
*
* @var array
*/
protected $additionData = [];
/**
* @var \Teepluss\Theme\Contracts\Theme
*/
protected $theme;
/**
* @var string
*/
protected $_currentThemeName;
/**
* @var string
*/
protected $_currentLayoutName;
/**
* [
*'path'=>[]
* ]
*
* @var array
*/
protected $data = [];
/**
* @var \Pingpong\Modules\Repository
*/
protected $module;
/**
* All Asset
*
* @var
*/
private $assets;
/**
* @var \Modules\IzCore\Entities\Theme
*/
private $themeModel;
/**
* Theme constructor.
*
* @param \Pingpong\Modules\Repository $module
* @param array $data
*/
public function __construct(
Repository $module,
\Modules\IzCore\Entities\Theme $themeModel,
array $data = []
) {
$this->themeModel = $themeModel;
$this->module = $module;
parent::__construct($data);
}
public function addAdditionData($path, $data) {
foreach ($data as $item) {
if (!isset($this->additionData[$path]))
$this->additionData[$path] = [];
$this->additionData[$path][] = $item;
}
}
/**
* Merge data from another modules to current path
*
* @param null $path
*
* @return $this
*/
public function initAdditionData($path = null) {
if (is_null($path))
$path = $this->getCurrentPath();
if (isset($this->additionData[$path])) {
foreach ($this->additionData[$path] as $item) {
/** @var <API key> $item */
$item = app()->make($item);
if (!isset($this->data[$path]))
$this->data[$path] = [];
$this->data[$path] = array_merge($this->data[$path], $item->handle());
}
}
return $this;
}
/**
* @return mixed
*/
public function getCurrentPath() {
return $this->currentPath;
}
/**
* @param mixed $currentPath
*
* @return $this
*/
public function setCurrentPath($currentPath) {
$this->currentPath = $currentPath;
return $this;
}
/**
* Set data to view of current path
*
* @param \Teepluss\Theme\Theme $theme
* @param $path
*
* @return $this
*/
public function initViewData(\Teepluss\Theme\Theme $theme, $path) {
/*Merge from another modules*/
$this->initAdditionData($path);
if (isset($this->data[$path])) {
foreach ($this->data[$path] as $items) {
foreach ($items as $k => $item) {
$theme->set($k, $item);
}
}
}
return $this;
}
/**
* Get all assets in each theme in each module
*
* @return array
* @throws \Exception
*/
public function getAssetsTree() {
if (is_null($this->assets)) {
$this->assets = [];
$pathModules = $this->module->getPath();
$moduleDirs = scandir($pathModules);
foreach ($moduleDirs as $moduleDir) {
if (!in_array($moduleDir, [".", ".."])) {
$<API key> = $pathModules . '/' . $moduleDir . '/themes';
if (!file_exists($<API key>))
continue;
$themePath = scandir($<API key>);
foreach ($themePath as $themDir) {
if (!in_array($themDir, [".", ".."])) {
$currentThemeDir = $<API key> . '/' . $themDir . '/config.php';
// Check file config.php existed
if (!file_exists($currentThemeDir))
continue;
$themeConfig = (include $currentThemeDir);
if (isset($themeConfig['assets'])) {
$assetWithThemeName = [];
foreach ($themeConfig['assets'] as $k => $asset) {
$asset['theme_name'] = $themDir;
$assetWithThemeName[$k] = $asset;
}
$this->assets = array_merge($this->assets, $assetWithThemeName);
}
}
}
}
}
}
return $this->assets;
}
/**
* Retrieve current theme name
*
* @return string
*/
public function getCurrentThemeName() {
if (is_null($this->_currentThemeName))
$this->_currentThemeName = $this->getTheme()->getThemeName();
return $this->_currentThemeName;
}
/**
* @param string $currentThemeName
*
* @return $this
*/
public function setCurrentThemeName($currentThemeName) {
$this->_currentThemeName = $currentThemeName;
return $this;
}
/**
* @return string
*/
public function <API key>() {
if (is_null($this->_currentLayoutName))
$this->_currentLayoutName = $this->getTheme()->getLayoutName();
return $this->_currentLayoutName;
}
/**
* Retrive current layout use in theme
*
* @param string $currentLayoutName
*
* @return $this
*/
public function <API key>($currentLayoutName) {
$this->_currentLayoutName = $currentLayoutName;
return $this;
}
/**
* @return \Teepluss\Theme\Theme
* @throws \Exception
*/
public function getTheme() {
if (is_null($this->theme)) {
$this->theme = app()->make('\Teepluss\Theme\Contracts\Theme');
};
return $this->theme;
}
public function registerTheme($themeName, $isAdmin = true) {
/* FIXME: need cache here */
$theme = $this->themeModel->query()->firstOrNew(['name' => $themeName]);
$theme->type = $isAdmin == true ? \Modules\IzCore\Entities\Theme::TYPE_ADMIN : \Modules\IzCore\Entities\Theme::TYPE_FRONTEND;
$theme->save();
return $this;
}
}
|
package com.ejlchina.searcher.implement;
import com.ejlchina.searcher.*;
import com.ejlchina.searcher.bean.InheritType;
import java.lang.reflect.Field;
import java.util.*;
import java.lang.reflect.Modifier;
import java.util.concurrent.ConcurrentHashMap;
/***
*
* @author Troy.Zhou @ 2021-10-30
* @since v3.0.0
*/
public class DefaultMetaResolver implements MetaResolver {
private final Map<Class<?>, BeanMeta<?>> cache = new ConcurrentHashMap<>();
private SnippetResolver snippetResolver = new <API key>();
private DbMapping dbMapping;
public DefaultMetaResolver() {
this(new DefaultDbMapping());
}
public DefaultMetaResolver(DbMapping dbMapping) {
this.dbMapping = dbMapping;
}
@Override
public <T> BeanMeta<T> resolve(Class<T> beanClass) {
@SuppressWarnings("unchecked")
BeanMeta<T> beanMeta = (BeanMeta<T>) cache.get(beanClass);
if (beanMeta != null) {
return beanMeta;
}
synchronized (cache) {
beanMeta = resolveMetadata(beanClass);
cache.put(beanClass, beanMeta);
return beanMeta;
}
}
protected <T> BeanMeta<T> resolveMetadata(Class<T> beanClass) {
DbMapping.Table table = dbMapping.table(beanClass);
if (table == null) {
throw new SearchException("The class [" + beanClass.getName() + "] can not be searched, because it can not be resolved by " + dbMapping.getClass());
}
BeanMeta<T> beanMeta = new BeanMeta<>(beanClass, table.getDataSource(),
snippetResolver.resolve(table.getTables()),
snippetResolver.resolve(table.getJoinCond()),
snippetResolver.resolve(table.getGroupBy()),
table.isDistinct());
Field[] fields = getBeanFields(beanClass);
for (int index = 0; index < fields.length; index++) {
Field field = fields[index];
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
DbMapping.Column column = dbMapping.column(beanClass, fields[index]);
if (column == null) {
continue;
}
field.setAccessible(true);
SqlSnippet snippet = snippetResolver.resolve(column.getFieldSql());
// Oracle
FieldMeta fieldMeta = new FieldMeta(beanMeta, field, snippet, "c_" + index,
column.isConditional(), column.getOnlyOn());
beanMeta.addFieldMeta(field.getName(), fieldMeta);
}
if (beanMeta.getFieldCount() == 0) {
throw new SearchException("[" + beanClass.getName() + "] is not a valid SearchBean, because there is no field mapping to database.");
}
return beanMeta;
}
protected Field[] getBeanFields(Class<?> beanClass) {
InheritType iType = dbMapping.inheritType(beanClass);
List<Field> fieldList = new ArrayList<>();
Set<String> fieldNames = new HashSet<>();
while (beanClass != Object.class) {
for (Field field : beanClass.getDeclaredFields()) {
String name = field.getName();
int modifiers = field.getModifiers();
if (field.isSynthetic() || Modifier.isStatic(modifiers)
|| Modifier.isTransient(modifiers)
|| fieldNames.contains(name)) {
continue;
}
fieldList.add(field);
fieldNames.add(name);
}
if (iType != InheritType.FIELD && iType != InheritType.ALL) {
break;
}
beanClass = beanClass.getSuperclass();
}
return fieldList.toArray(new Field[0]);
}
public SnippetResolver getSnippetResolver() {
return snippetResolver;
}
public void setSnippetResolver(SnippetResolver snippetResolver) {
this.snippetResolver = Objects.requireNonNull(snippetResolver);
}
public DbMapping getDbMapping() {
return dbMapping;
}
public void setDbMapping(DbMapping dbMapping) {
this.dbMapping = Objects.requireNonNull(dbMapping);
}
}
|
# AUTOGENERATED FILE
FROM balenalib/<API key>:bullseye-run
ENV NODE_VERSION 14.18.3
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
<API key> \
; do \
gpg --batch --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --batch --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --<API key> \
|
'use strict';
var aCallable = require('../internals/a-callable');
var anObject = require('../internals/an-object');
var getBuiltIn = require('../internals/get-built-in');
var getMethod = require('../internals/get-method');
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
var createMethod = function (TYPE) {
var IS_TO_ARRAY = TYPE == 0;
var IS_FOR_EACH = TYPE == 1;
var IS_EVERY = TYPE == 2;
var IS_SOME = TYPE == 3;
return function (iterator, fn, target) {
anObject(iterator);
var Promise = getBuiltIn('Promise');
var next = aCallable(iterator.next);
var index = 0;
var MAPPING = fn !== undefined;
if (MAPPING || !IS_TO_ARRAY) aCallable(fn);
return new Promise(function (resolve, reject) {
var closeIteration = function (method, argument) {
try {
var returnMethod = getMethod(iterator, 'return');
if (returnMethod) {
return Promise.resolve(returnMethod.call(iterator)).then(function () {
method(argument);
}, function (error) {
reject(error);
});
}
} catch (error2) {
return reject(error2);
} method(argument);
};
var onError = function (error) {
closeIteration(reject, error);
};
var loop = function () {
try {
if (IS_TO_ARRAY && (index > MAX_SAFE_INTEGER) && MAPPING) {
throw TypeError('The allowed number of iterations has been exceeded');
}
Promise.resolve(anObject(next.call(iterator))).then(function (step) {
try {
if (anObject(step).done) {
if (IS_TO_ARRAY) {
target.length = index;
resolve(target);
} else resolve(IS_SOME ? false : IS_EVERY || undefined);
} else {
var value = step.value;
if (MAPPING) {
Promise.resolve(IS_TO_ARRAY ? fn(value, index) : fn(value)).then(function (result) {
if (IS_FOR_EACH) {
loop();
} else if (IS_EVERY) {
result ? loop() : closeIteration(resolve, false);
} else if (IS_TO_ARRAY) {
target[index++] = result;
loop();
} else {
result ? closeIteration(resolve, IS_SOME || value) : loop();
}
}, onError);
} else {
target[index++] = value;
loop();
}
}
} catch (error) { onError(error); }
}, onError);
} catch (error2) { onError(error2); }
};
loop();
});
};
};
module.exports = {
toArray: createMethod(0),
forEach: createMethod(1),
every: createMethod(2),
some: createMethod(3),
find: createMethod(4)
};
|
sap.ui.require([
"jquery.sap.global",
"sap/ui/base/SyncPromise",
"sap/ui/model/BindingMode",
"sap/ui/model/ChangeReason",
"sap/ui/model/ClientListBinding",
"sap/ui/model/Context",
"sap/ui/model/ContextBinding",
"sap/ui/model/Filter",
"sap/ui/model/MetaModel",
"sap/ui/model/PropertyBinding",
"sap/ui/model/Sorter",
"sap/ui/model/odata/OperationMode",
"sap/ui/model/odata/type/Int64",
"sap/ui/model/odata/type/Raw",
"sap/ui/model/odata/v4/AnnotationHelper",
"sap/ui/model/odata/v4/Context",
"sap/ui/model/odata/v4/lib/_Helper",
"sap/ui/model/odata/v4/ODataMetaModel",
"sap/ui/model/odata/v4/ODataModel",
"sap/ui/model/odata/v4/ValueListType",
"sap/ui/test/TestUtils",
"sap/ui/thirdparty/URI"
], function (jQuery, SyncPromise, BindingMode, ChangeReason, ClientListBinding, BaseContext,
ContextBinding, Filter, MetaModel, PropertyBinding, Sorter, OperationMode, Int64, Raw,
AnnotationHelper, Context, _Helper, ODataMetaModel, ODataModel, ValueListType, TestUtils,
URI) {
/*global QUnit, sinon */
/*eslint <API key>: 0, no-loop-func: 0, no-warning-comments: 0 */
"use strict";
// Common := com.sap.vocabularies.Common.v1
// tea_busi := com.sap.gateway.default.iwbep.tea_busi.v0001
// tea_busi_product.v0001 := com.sap.gateway.default.iwbep.tea_busi_product.v0001
// tea_busi_supplier.v0001 := com.sap.gateway.default.iwbep.tea_busi_supplier.v0001
// UI := com.sap.vocabularies.UI.v1
var mMostlyEmptyScope = {
"$EntityContainer" : "empty.DefaultContainer",
"$Version" : "4.0",
"empty." : {
"$kind" : "Schema"
},
"empty.DefaultContainer" : {
"$kind" : "EntityContainer"
}
},
sODataMetaModel = "sap.ui.model.odata.v4.ODataMetaModel",
mProductScope = {
"$EntityContainer" : "tea_busi_product.v0001.DefaultContainer",
"$Reference" : {
"../../../../default/iwbep/tea_busi_supplier/0001/$metadata" : {
"$Include" : [
"tea_busi_supplier.v0001."
]
}
},
"$Version" : "4.0",
"tea_busi_product.v0001." : {
"$kind" : "Schema",
"$Annotations" : { // Note: simulate result of _MetadataRequestor#read
"tea_busi_product.v0001.Category/CategoryName" : {
"@Common.Label" : "CategoryName from tea_busi_product.v0001."
}
}
},
"tea_busi_product.v0001.Category" : {
"$kind" : "EntityType",
"CategoryName" : {
"$kind" : "Property",
"$Type" : "Edm.String"
}
},
"tea_busi_product.v0001.DefaultContainer" : {
"$kind" : "EntityContainer"
},
"tea_busi_product.v0001.Product" : {
"$kind" : "EntityType",
"Name" : {
"$kind" : "Property",
"$Type" : "Edm.String"
},
"PRODUCT_2_CATEGORY" : {
"$kind" : "NavigationProperty",
"$Type" : "tea_busi_product.v0001.Category"
},
"PRODUCT_2_SUPPLIER" : {
"$kind" : "NavigationProperty",
"$Type" : "tea_busi_supplier.v0001.Supplier"
}
}
},
sSampleServiceUrl
= "/sap/opu/odata4/sap/zui5_testv4/default/sap/zui5_epm_sample/0002/",
mScope = {
"$Annotations" : {
"name.space.Id" : {
"@Common.Label" : "ID"
},
"tea_busi.DefaultContainer" : {
"@DefaultContainer" : {}
},
"tea_busi.DefaultContainer/T€AMS" : {
"@T€AMS" : {}
},
"tea_busi.TEAM" : {
"@Common.Text" : {
"$Path" : "Name"
},
"@Common.Text@UI.TextArrangement" : {
"$EnumMember" : "UI.TextArrangementType/TextLast"
},
"@UI.Badge" : {
"@Common.Label" : "Label inside",
"$Type" : "UI.BadgeType",
"HeadLine" : {
"$Type" : "UI.DataField",
"Value" : {
"$Path" : "Name"
}
},
"Title" : {
"$Type" : "UI.DataField",
"Value" : {
"$Path" : "Team_Id"
}
}
},
"@UI.Badge@Common.Label" : "Best Badge Ever!",
"@UI.LineItem" : [{
"@UI.Importance" : {
"$EnumMember" : "UI.ImportanceType/High"
},
"$Type" : "UI.DataField",
"Label" : "Team ID",
"Label@Common.Label" : "Team ID's Label",
"Value" : {
"$Path" : "Team_Id"
}
}]
},
"tea_busi.TEAM/Team_Id" : {
"@Common.Label" : "Team ID",
"@Common.Text" : {
"$Path" : "Name"
},
"@Common.Text@UI.TextArrangement" : {
"$EnumMember" : "UI.TextArrangementType/TextLast"
}
},
"tea_busi.Worker" : {
"@UI.Facets" : [{
"$Type" : "UI.ReferenceFacet",
"Target" : {
// term cast
"$AnnotationPath" : "@UI.LineItem"
}
}, {
"$Type" : "UI.ReferenceFacet",
"Target" : {
// term cast at navigation property itself
"$AnnotationPath" : "EMPLOYEE_2_TEAM@Common.Label"
}
}, {
"$Type" : "UI.ReferenceFacet",
"Target" : {
// navigation property and term cast
"$AnnotationPath" : "EMPLOYEE_2_TEAM/@UI.LineItem"
}
}, {
"$Type" : "UI.ReferenceFacet",
"Target" : {
// type cast, navigation properties and term cast (at its type)
"$AnnotationPath"
: "tea_busi.TEAM/TEAM_2_EMPLOYEES/EMPLOYEE_2_TEAM/@UI.LineItem"
}
}],
"@UI.LineItem" : [{
"$Type" : "UI.DataField",
"Label" : "Team ID",
"Value" : {
"$Path" : "EMPLOYEE_2_TEAM/Team_Id"
}
}]
},
"tea_busi.Worker/EMPLOYEE_2_TEAM" : {
"@Common.Label" : "Employee's Team"
}
},
"$EntityContainer" : "tea_busi.DefaultContainer",
"empty." : {
"$kind" : "Schema"
},
"name.space." : {
"$kind" : "Schema"
},
"tea_busi." : {
"$kind" : "Schema",
"@Schema" : {}
},
"empty.Container" : {
"$kind" : "EntityContainer"
},
"name.space.BadContainer" : {
"$kind" : "EntityContainer",
"<API key>" : {
"$kind" : "ActionImport",
"$Action" : "not.Found"
},
"<API key>" : {
"$kind" : "FunctionImport",
"$Function" : "not.Found"
}
},
"name.space.Broken" : {
"$kind" : "Term",
"$Type" : "not.Found"
},
"name.space.BrokenFunction" : [{
"$kind" : "Function",
"$ReturnType" : {
"$Type" : "not.Found"
}
}],
"name.space.BrokenOverloads" : [{
"$kind" : "Operation"
}],
"name.space.<API key>" : [{
"$kind" : "Function",
"$ReturnType" : {
"$Type" : "name.space.Id"
}
}],
"name.space.EmptyOverloads" : [],
"name.space.Id" : {
"$kind" : "TypeDefinition",
"$UnderlyingType" : "Edm.String",
"$MaxLength" : 10
},
"name.space.Term" : { // only case with a qualified name and a $Type
"$kind" : "Term",
"$Type" : "tea_busi.Worker"
},
"name.space.OverloadedAction" : [{
"$kind" : "Action",
"$IsBound" : true,
"$Parameter" : [{
// "$Name" : "_it",
"$Type" : "tea_busi.EQUIPMENT"
}],
"$ReturnType" : {
"$Type" : "tea_busi.EQUIPMENT"
}
}, {
"$kind" : "Action",
"$IsBound" : true,
"$Parameter" : [{
// "$Name" : "_it",
"$Type" : "tea_busi.TEAM"
}],
"$ReturnType" : {
"$Type" : "tea_busi.TEAM"
}
}, { // "An unbound action MAY have the same name as a bound action."
"$kind" : "Action",
"$ReturnType" : {
"$Type" : "tea_busi.ComplexType_Salary"
}
}, {
"$kind" : "Action",
"$IsBound" : true,
"$Parameter" : [{
// "$Name" : "_it",
"$Type" : "tea_busi.Worker"
}],
"$ReturnType" : {
"$Type" : "tea_busi.Worker"
}
}],
"name.space.OverloadedFunction" : [{
"$kind" : "Function",
"$ReturnType" : {
"$Type" : "Edm.String"
}
}, {
"$kind" : "Function",
"$ReturnType" : {
"$Type" : "Edm.String"
}
}],
"name.space.VoidAction" : [{
"$kind" : "Action"
}],
"tea_busi.<API key>" : [{
"$kind" : "Action",
"$ReturnType" : {
"$Type" : "tea_busi.TEAM",
"@Common.Label" : "Hail to the Chief"
}
}],
"tea_busi.ComplexType_Salary" : {
"$kind" : "ComplexType",
"AMOUNT" : {
"$kind" : "Property",
"$Type" : "Edm.Decimal"
},
"CURRENCY" : {
"$kind" : "Property",
"$Type" : "Edm.String"
}
},
"tea_busi.ContainedC" : {
"$kind" : "EntityType",
"$Key" : ["Id"],
"Id" : {
"$kind" : "Property",
"$Type" : "Edm.String"
},
"C_2_EMPLOYEE" : {
"$kind" : "NavigationProperty",
"$Type" : "tea_busi.Worker"
},
"C_2_S" : {
"$ContainsTarget" : true,
"$kind" : "NavigationProperty",
"$Type" : "tea_busi.ContainedS"
}
},
"tea_busi.ContainedS" : {
"$kind" : "EntityType",
"$Key" : ["Id"],
"Id" : {
"$kind" : "Property",
"$Type" : "Edm.String"
},
"S_2_C" : {
"$ContainsTarget" : true,
"$kind" : "NavigationProperty",
"$isCollection" : true,
"$Type" : "tea_busi.ContainedC"
},
"S_2_EMPLOYEE" : {
"$kind" : "NavigationProperty",
"$Type" : "tea_busi.Worker"
}
},
"tea_busi.DefaultContainer" : {
"$kind" : "EntityContainer",
"ChangeManagerOfTeam" : {
"$kind" : "ActionImport",
"$Action" : "tea_busi.<API key>"
},
"EMPLOYEES" : {
"$kind" : "EntitySet",
"$<API key>" : {
"EMPLOYEE_2_TEAM" : "T€AMS",
"EMPLOYEE_2_EQUIPM€NTS" : "EQUIPM€NTS"
},
"$Type" : "tea_busi.Worker"
},
"EQUIPM€NTS" : {
"$kind" : "EntitySet",
"$Type" : "tea_busi.EQUIPMENT"
},
"GetEmployeeMaxAge" : {
"$kind" : "FunctionImport",
"$Function" : "tea_busi.FuGetEmployeeMaxAge"
},
"Me" : {
"$kind" : "Singleton",
"$<API key>" : {
"EMPLOYEE_2_TEAM" : "T€AMS",
"EMPLOYEE_2_EQUIPM€NTS" : "EQUIPM€NTS"
},
"$Type" : "tea_busi.Worker"
},
"OverloadedAction" : {
"$kind" : "ActionImport",
"$Action" : "name.space.OverloadedAction"
},
"TEAMS" : {
"$kind" : "EntitySet",
"$<API key>" : {
"TEAM_2_EMPLOYEES" : "EMPLOYEES",
"TEAM_2_CONTAINED_S/S_2_EMPLOYEE" : "EMPLOYEES"
},
"$Type" : "tea_busi.TEAM"
},
"T€AMS" : {
"$kind" : "EntitySet",
"$<API key>" : {
"TEAM_2_EMPLOYEES" : "EMPLOYEES"
},
"$Type" : "tea_busi.TEAM"
},
"VoidAction" : {
"$kind" : "ActionImport",
"$Action" : "name.space.VoidAction"
}
},
"tea_busi.EQUIPMENT" : {
"$kind" : "EntityType",
"$Key" : ["ID"],
"ID" : {
"$kind" : "Property",
"$Type" : "Edm.Int32",
"$Nullable" : false
}
},
"tea_busi.FuGetEmployeeMaxAge" : [{
"$kind" : "Function",
"$ReturnType" : {
"$Type" : "Edm.Int16"
}
}],
"tea_busi.TEAM" : {
"$kind" : "EntityType",
"$Key" : ["Team_Id"],
"Team_Id" : {
"$kind" : "Property",
"$Type" : "name.space.Id",
"$Nullable" : false,
"$MaxLength" : 10
},
"Name" : {
"$kind" : "Property",
"$Type" : "Edm.String",
"$Nullable" : false,
"$MaxLength" : 40
},
"TEAM_2_EMPLOYEES" : {
"$kind" : "NavigationProperty",
"$isCollection" : true,
"$OnDelete" : "None",
"$OnDelete@Common.Label" : "None of my business",
"$<API key>" : {
"foo" : "bar",
"foo@Common.Label" : "Just a Gigolo"
},
"$Type" : "tea_busi.Worker"
},
"TEAM_2_CONTAINED_S" : {
"$ContainsTarget" : true,
"$kind" : "NavigationProperty",
"$Type" : "tea_busi.ContainedS"
},
"TEAM_2_CONTAINED_C" : {
"$ContainsTarget" : true,
"$kind" : "NavigationProperty",
"$isCollection" : true,
"$Type" : "tea_busi.ContainedC"
},
// Note: "value" is a symbolic name for an operation's return type iff. it is
// primitive
"value" : {
"$kind" : "Property",
"$Type" : "Edm.String"
}
},
"tea_busi.Worker" : {
"$kind" : "EntityType",
"$Key" : ["ID"],
"ID" : {
"$kind" : "Property",
"$Type" : "Edm.String",
"$Nullable" : false,
"$MaxLength" : 4
},
"AGE" : {
"$kind" : "Property",
"$Type" : "Edm.Int16",
"$Nullable" : false
},
"<API key>" : {
"$ContainsTarget" : true,
"$kind" : "NavigationProperty",
"$Type" : "tea_busi.ContainedS"
},
"EMPLOYEE_2_EQUIPM€NTS" : {
"$kind" : "NavigationProperty",
"$isCollection" : true,
"$Type" : "tea_busi.EQUIPMENT",
"$Nullable" : false
},
"EMPLOYEE_2_TEAM" : {
"$kind" : "NavigationProperty",
"$Type" : "tea_busi.TEAM",
"$Nullable" : false
},
"SALÃRY" : {
"$kind" : "Property",
"$Type" : "tea_busi.ComplexType_Salary"
}
},
"$$Loop" : "$$Loop/", // some endless loop
"$$Term" : "name.space.Term" // replacement for any reference to the term
},
oContainerData = mScope["tea_busi.DefaultContainer"],
aOverloadedAction = mScope["name.space.OverloadedAction"],
mSupplierScope = {
"$Version" : "4.0",
"tea_busi_supplier.v0001." : {
"$kind" : "Schema"
},
"tea_busi_supplier.v0001.Supplier" : {
"$kind" : "EntityType",
"Supplier_Name" : {
"$kind" : "Property",
"$Type" : "Edm.String"
}
}
},
oTeamData = mScope["tea_busi.TEAM"],
oTeamLineItem = mScope.$Annotations["tea_busi.TEAM"]["@UI.LineItem"],
oWorkerData = mScope["tea_busi.Worker"],
mXServiceScope = {
"$Version" : "4.0",
"$Annotations" : {}, // simulate ODataMetaModel#_mergeAnnotations
"$EntityContainer" : "tea_busi.v0001.DefaultContainer",
"$Reference" : {
// Note: Do not reference tea_busi_supplier directly from here! We want to test the
// special case that it is only indirectly referenced.
"../../../../default/iwbep/tea_busi_foo/0001/$metadata" : {
"$Include" : [
"tea_busi_foo.v0001."
]
},
"../../../../default/iwbep/tea_busi_product/0001/$metadata" : {
"$Include" : [
"ignore.me.",
"tea_busi_product.v0001."
]
},
"/empty/$metadata" : {
"$Include" : [
"empty.",
"I.still.haven't.found.what.I'm.looking.for."
]
}
},
"tea_busi.v0001." : {
"$kind" : "Schema"
},
"tea_busi.v0001.DefaultContainer" : {
"$kind" : "EntityContainer",
"EQUIPM€NTS" : {
"$kind" : "EntitySet",
"$Type" : "tea_busi.v0001.EQUIPMENT"
}
},
"tea_busi.v0001.EQUIPMENT" : {
"$kind" : "EntityType",
"EQUIPMENT_2_PRODUCT" : {
"$kind" : "NavigationProperty",
"$Type" : "tea_busi_product.v0001.Product"
}
}
},
aAllScopes = [
mMostlyEmptyScope,
mProductScope,
mScope,
mSupplierScope,
mXServiceScope
];
/**
* Checks the "get*" and "request*" methods corresponding to the named "fetch*" method,
* using the given arguments.
*
* @param {object} oTestContext
* the QUnit "this" object
* @param {object} assert
* the QUnit "assert" object
* @param {string} sMethodName
* method name "fetch*"
* @param {object[]} aArguments
* method arguments
* @param {boolean} [bThrow=false]
* whether the "get*" method throws if the promise is not fulfilled
* @returns {Promise}
* the "request*" method's promise
*/
function checkGetAndRequest(oTestContext, assert, sMethodName, aArguments, bThrow) {
var oExpectation,
sGetMethodName = sMethodName.replace("fetch", "get"),
oMetaModel = oTestContext.oMetaModel,
oReason = new Error("rejected"),
oRejectedPromise = Promise.reject(oReason),
sRequestMethodName = sMethodName.replace("fetch", "request"),
oResult = {},
oSyncPromise = SyncPromise.resolve(oRejectedPromise);
// resolve...
oExpectation = oTestContext.mock(oMetaModel).expects(sMethodName).exactly(4);
oExpectation = oExpectation.withExactArgs.apply(oExpectation, aArguments);
oExpectation.returns(SyncPromise.resolve(oResult));
// get: fulfilled
assert.strictEqual(oMetaModel[sGetMethodName].apply(oMetaModel, aArguments), oResult);
// reject...
oExpectation.returns(oSyncPromise);
oTestContext.mock(Promise).expects("resolve")
.withExactArgs(sinon.match.same(oSyncPromise))
.returns(oRejectedPromise); // return any promise (this is not unwrapping!)
// request (promise still pending!)
assert.strictEqual(oMetaModel[sRequestMethodName].apply(oMetaModel, aArguments),
oRejectedPromise);
// get: pending
if (bThrow) {
assert.throws(function () {
oMetaModel[sGetMethodName].apply(oMetaModel, aArguments);
}, new Error("Result pending"));
} else {
assert.strictEqual(oMetaModel[sGetMethodName].apply(oMetaModel, aArguments), undefined,
"pending");
}
return oSyncPromise.catch(function () {
// get: rejected
if (bThrow) {
assert.throws(function () {
oMetaModel[sGetMethodName].apply(oMetaModel, aArguments);
}, oReason);
} else {
assert.strictEqual(oMetaModel[sGetMethodName].apply(oMetaModel, aArguments),
undefined, "rejected");
}
});
}
/**
* Returns a clone, that is a deep copy, of the given object.
*
* @param {object} o
* any serializable object
* @returns {object}
* a deep copy of <code>o</code>
*/
function clone(o) {
return JSON.parse(JSON.stringify(o));
}
/**
* Runs the given test for each name/value pair in the given fixture. The name is interpreted
* as a path "[<sContextPath>'|']<sMetaPath>" and cut accordingly. The test is called with
* an almost resolved sPath (just '|' replaced by '/').
*
* @param {object} mFixture
* map<string, any>
* @param {function} fnTest
* function(string sPath, any vResult, string sContextPath, string sMetaPath)
*/
function forEach(mFixture, fnTest) {
var sPath;
for (sPath in mFixture) {
var i = sPath.indexOf("|"),
sContextPath = "",
sMetaPath = sPath.slice(i + 1),
vValue = mFixture[sPath];
if (i >= 0) {
sContextPath = sPath.slice(0, i);
sPath = sContextPath + "/" + sMetaPath;
}
fnTest(sPath, vValue, sContextPath, sMetaPath);
}
}
/*
* Allow warnings if told to; always suppress debug messages.
*/
allowWarnings : function (assert, bWarn) {
this.mock(jQuery.sap.log).expects("isLoggable").atLeast(1)
.withExactArgs(sinon.match.number, sODataMetaModel)
.callsFake(function (iLogLevel) {
switch (iLogLevel) {
case jQuery.sap.log.Level.DEBUG:
return false;
case jQuery.sap.log.Level.WARNING:
return bWarn;
default:
return true;
}
});
},
beforeEach : function () {
var oMetadataRequestor = {
read : function () { throw new Error(); }
},
sUrl = "/a/b/c/d/e/$metadata";
this.oLogMock = this.mock(jQuery.sap.log);
this.oLogMock.expects("warning").never();
this.oLogMock.expects("error").never();
this.oMetaModel = new ODataMetaModel(oMetadataRequestor, sUrl);
this.oMetaModelMock = this.mock(this.oMetaModel);
this.oModel = {
reportError : function () {
throw new Error("Unsupported operation");
},
resolve : ODataModel.prototype.resolve
};
},
/*
* Expect the given debug message with the given path, but only if debug level is on.
*/
expectDebug : function (bDebug, sMessage, sPath) {
this.oLogMock.expects("isLoggable")
.withExactArgs(jQuery.sap.log.Level.DEBUG, sODataMetaModel).returns(bDebug);
this.oLogMock.expects("debug").exactly(bDebug ? 1 : 0)
.withExactArgs(sMessage, sPath, sODataMetaModel);
},
/*
* Expects "<API key>" to be called at least once on the current meta model,
* returning a clone of the given scope.
*
* @param {object} mScope
*/
<API key> : function (mScope) {
mScope = clone(mScope);
this.oMetaModel.validate("n/a", mScope); // fill mSchema2MetadataUrl!
this.oMetaModelMock.expects("<API key>").atLeast(1)
.returns(SyncPromise.resolve(mScope));
}
});
/*
* Expect the given debug message with the given path.
*/
function expectDebug(sMessage, sPath) {
that.expectDebug(bDebug, sMessage, sPath);
}
/*
* Code under test: ODataMetaModel#fetchObject with the given path should yield the
* given expected result.
*/
function codeUnderTest(sPath, vExpectedResult) {
aPromises.push(that.oMetaModel.fetchObject(sPath).then(function (vResult) {
assert.strictEqual(vResult, vExpectedResult);
}));
}
this.<API key>(mXServiceScope);
oRequestorMock.expects("read")
.withExactArgs("/a/default/iwbep/tea_busi_product/0001/$metadata")
.returns(Promise.resolve(mClonedProductScope));
oRequestorMock.expects("read")
.withExactArgs("/a/default/iwbep/tea_busi_supplier/0001/$metadata")
.returns(Promise.resolve(mSupplierScope));
oRequestorMock.expects("read")
.withExactArgs("/empty/$metadata")
.returns(Promise.resolve(mMostlyEmptyScope));
expectDebug("Namespace tea_busi_product.v0001. found in $Include"
+ " of /a/default/iwbep/tea_busi_product/0001/$metadata"
+ " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name");
expectDebug("Reading /a/default/iwbep/tea_busi_product/0001/$metadata"
+ " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name");
expectDebug("Waiting for tea_busi_product.v0001."
+ " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name");
codeUnderTest("/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name",
mClonedProductScope["tea_busi_product.v0001.Product"].Name);
expectDebug("Waiting for tea_busi_product.v0001."
+ " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_CATEGORY/CategoryName");
codeUnderTest("/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_CATEGORY/CategoryName",
mClonedProductScope["tea_busi_product.v0001.Category"].CategoryName);
expectDebug("Waiting for tea_busi_product.v0001.",
"/tea_busi_product.v0001.Category/CategoryName");
codeUnderTest("/tea_busi_product.v0001.Category/CategoryName",
mClonedProductScope["tea_busi_product.v0001.Category"].CategoryName);
expectDebug("Waiting for tea_busi_product.v0001.",
"/tea_busi_product.v0001.Category/CategoryName@Common.Label");
codeUnderTest("/tea_busi_product.v0001.Category/CategoryName@Common.Label",
"CategoryName from tea_busi_product.v0001.");
expectDebug("Waiting for tea_busi_product.v0001."
+ " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name");
codeUnderTest("/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name",
mSupplierScope["tea_busi_supplier.v0001.Supplier"].Supplier_Name);
expectDebug("Namespace empty. found in $Include of /empty/$metadata",
"/empty.DefaultContainer");
expectDebug("Reading /empty/$metadata", "/empty.DefaultContainer");
expectDebug("Waiting for empty.",
"/empty.DefaultContainer");
codeUnderTest("/empty.DefaultContainer", mMostlyEmptyScope["empty.DefaultContainer"]);
// Note: these are logged asynchronously!
expectDebug("Including tea_busi_product.v0001."
+ " from /a/default/iwbep/tea_busi_product/0001/$metadata"
+ " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name");
expectDebug("Including empty. from /empty/$metadata",
"/empty.DefaultContainer");
expectDebug("Namespace tea_busi_supplier.v0001. found in $Include"
+ " of /a/default/iwbep/tea_busi_supplier/0001/$metadata"
+ " at /tea_busi_product.v0001.Product/PRODUCT_2_SUPPLIER/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name");
expectDebug("Reading /a/default/iwbep/tea_busi_supplier/0001/$metadata"
+ " at /tea_busi_product.v0001.Product/PRODUCT_2_SUPPLIER/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name");
expectDebug("Waiting for tea_busi_supplier.v0001."
+ " at /tea_busi_product.v0001.Product/PRODUCT_2_SUPPLIER/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name");
expectDebug("Including tea_busi_supplier.v0001."
+ " from /a/default/iwbep/tea_busi_supplier/0001/$metadata"
+ " at /tea_busi_product.v0001.Product/PRODUCT_2_SUPPLIER/$Type",
"/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name");
return Promise.all(aPromises);
});
});
//TODO Decision: It is an error if a namespace is referenced multiple times with different URIs.
// This should be checked even when load-on-demand is used.
// (It should not even be included multiple times with the same URI!)
//TODO Check that no namespace is included which is already present!
//TODO API to load "transitive closure"
//TODO support for sync. XML Templating
return checkGetAndRequest(this, assert, "fetchObject", ["sPath", {/*oContext*/}]);
+ oProperty.$Type.slice(4)/*cut off "Edm."*/;
.returns(SyncPromise.resolve(/*no property metadata for path*/));
this.oList = [{/*a context*/}];
? oFixture.contextPath + "|"/*make cut more visible*/ + oFixture.metaPath
"value_list.VH_BusinessPartner/Foo" : {/* some other field w/ value list*/}
|
export const removeWeight = (element) => {
try {
element.removeAttribute('data-weight');
} catch (e) {
// We are now in IE11 territory
if (!!element) {
element.setAttribute('data-weight', null);
}
}
};
|
using MO.Core.Forms.Common;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace MO.Core.Forms.Controls
{
public partial class QColorPicker : QControl
{
protected int _heighMax = 20;
protected int _colorWidth = 18;
protected Color _selectColor = Color.Black;
public QColorPicker() {
InitializeComponent();
}
protected void InnerSetSize(int width, int height) {
Width = width;
Height = height = _heighMax;
int contentLeft = _borderOuter.Left.Width + _borderInner.Left.Width;
int contentRight = _borderOuter.Bottom.Width + _borderInner.Bottom.Width;
int contentTop = _borderOuter.Top.Width + _borderInner.Top.Width;
int contentBottom = _borderOuter.Bottom.Width + _borderInner.Bottom.Width;
pnlContanier.SetBounds(
contentLeft,
contentTop,
width - contentLeft - contentRight,
height - contentTop - contentBottom);
txtValue.SetBounds(
contentLeft,
contentTop,
width - _colorWidth - contentLeft - contentRight - 2,
height - contentTop - contentBottom);
pnlColor.SetBounds(
width - _colorWidth - contentLeft - contentRight,
contentTop - 2,
_colorWidth,
height - contentTop - contentBottom);
Invalidate();
}
[Browsable(true)]
public new Size Size {
get { return base.Size; }
set { InnerSetSize(value.Width, value.Height); }
}
public void RefreshColor(){
pnlColor.BackColor = _selectColor;
txtValue.Text = RColor.FormatHex(_selectColor.ToArgb());
}
[Browsable(true)]
[DefaultValue(typeof(Color), "Color.Black")]
public Color SelectColor {
get { return _selectColor; }
set {
_selectColor = value;
RefreshColor();
}
}
[Browsable(true)]
[DefaultValue("FF000000")]
public string SelectColorText {
get { return RColor.FormatHex(_selectColor.ToArgb()); }
set {
_selectColor = RColor.ParseHexColor(value);
RefreshColor();
}
}
[Browsable(true)]
[DefaultValue(-16777216)]
public int SelectColorValue {
get { return _selectColor.ToArgb(); }
set {
_selectColor = Color.FromArgb(value);
RefreshColor();
}
}
private void QColorPicker_Resize(object sender, EventArgs e) {
InnerSetSize(Width, Height);
}
private void pnlColor_Click(object sender, EventArgs e) {
dlgColor.Color = _selectColor;
DialogResult resultCd = dlgColor.ShowDialog();
if (resultCd == DialogResult.OK) {
_selectColor = dlgColor.Color;
RefreshColor();
}
}
private void txtValue_Leave(object sender, EventArgs e) {
_selectColor = RColor.ParseHexColor(txtValue.Text);
RefreshColor();
}
}
}
|
package io.really.model
import akka.contrib.pattern.ShardRegion
import _root_.io.really.{ <API key>, ReallyConfig }
class CollectionSharding(config: ReallyConfig) {
implicit val implicitConfig = config
val maxShards = config.Sharding.maxShards
/**
* ID Extractor for Akka Sharding extension
* ID is the BucketId
*/
val idExtractor: ShardRegion.IdExtractor = {
case req: <API key> => Helpers.getBucketIDFromR(req.r) -> req
}
/**
* Shard Resolver for Akka Sharding extension
*/
val shardResolver: ShardRegion.ShardResolver = {
case req: <API key> => (Helpers.getBucketIDFromR(req.r).hashCode % maxShards).toString
}
}
|
#!/bin/bash
echo "bootstrap"
service ssh restart
cd /MapRouletteAPI
# Delete any RUNNING_PID file on restart
rm RUNNING_PID || true
./setupServer.sh > setupServer.log 2>&1
while true; do sleep 1000; done
|
#define NETCORE
using System;
using System.Linq;
using System.Reflection;
namespace Foundatio.Force.DeepCloner.Helpers
{
internal static class ReflectionHelper
{
public static bool IsEnum(this Type t)
{
#if NETCORE
return t.GetTypeInfo().IsEnum;
#else
return t.IsEnum;
#endif
}
public static bool IsValueType(this Type t)
{
#if NETCORE
return t.GetTypeInfo().IsValueType;
#else
return t.IsValueType;
#endif
}
public static bool IsClass(this Type t)
{
#if NETCORE
return t.GetTypeInfo().IsClass;
#else
return t.IsClass;
#endif
}
public static Type BaseType(this Type t)
{
#if NETCORE
return t.GetTypeInfo().BaseType;
#else
return t.BaseType;
#endif
}
public static FieldInfo[] GetAllFields(this Type t)
{
#if NETCORE
return t.GetTypeInfo().DeclaredFields.Where(x => !x.IsStatic).ToArray();
#else
return t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
#endif
}
public static PropertyInfo[] GetPublicProperties(this Type t)
{
#if NETCORE
return t.GetTypeInfo().DeclaredProperties.ToArray();
#else
return t.GetProperties(BindingFlags.Instance | BindingFlags.Public);
#endif
}
public static FieldInfo[] GetDeclaredFields(this Type t)
{
#if NETCORE
return t.GetTypeInfo().DeclaredFields.Where(x => !x.IsStatic).ToArray();
#else
return t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly);
#endif
}
public static ConstructorInfo[] <API key>(this Type t)
{
#if NETCORE
return t.GetTypeInfo().<API key>.ToArray();
#else
return t.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);
#endif
}
public static ConstructorInfo[] <API key>(this Type t)
{
#if NETCORE
return t.GetTypeInfo().<API key>.ToArray();
#else
return t.GetConstructors(BindingFlags.Public | BindingFlags.Instance);
#endif
}
public static MethodInfo GetPrivateMethod(this Type t, string methodName)
{
#if NETCORE
return t.GetTypeInfo().GetDeclaredMethod(methodName);
#else
return t.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
#endif
}
public static MethodInfo GetMethod(this Type t, string methodName)
{
#if NETCORE
return t.GetTypeInfo().GetDeclaredMethod(methodName);
#else
return t.GetMethod(methodName);
#endif
}
public static MethodInfo <API key>(this Type t, string methodName)
{
#if NETCORE
return t.GetTypeInfo().GetDeclaredMethod(methodName);
#else
return t.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static);
#endif
}
public static FieldInfo GetPrivateField(this Type t, string fieldName)
{
#if NETCORE
return t.GetTypeInfo().GetDeclaredField(fieldName);
#else
return t.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
#endif
}
public static FieldInfo <API key>(this Type t, string fieldName)
{
#if NETCORE
return t.GetTypeInfo().GetDeclaredField(fieldName);
#else
return t.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Static);
#endif
}
#if NETCORE
public static bool <API key>(this Type t, string typeName)
{
while (t != null)
{
if (t.Name == typeName)
return true;
t = t.BaseType();
}
return false;
}
#endif
#if NETCORE
public static bool IsAssignableFrom(this Type from, Type to)
{
return from.GetTypeInfo().IsAssignableFrom(to.GetTypeInfo());
}
public static bool IsInstanceOfType(this Type from, object to)
{
return from.IsAssignableFrom(to.GetType());
}
#endif
public static Type[] GenericArguments(this Type t)
{
#if NETCORE
return t.GetTypeInfo().<API key>;
#else
return t.GetGenericArguments();
#endif
}
}
}
|
"""Translation helper functions."""
import locale
import os
import re
import sys
import gettext as gettext_module
from cStringIO import StringIO
from django.utils.importlib import import_module
from django.utils.safestring import mark_safe, SafeData
from django.utils.thread_support import currentThread
# Translations are cached in a dictionary for every language+app tuple.
# The active translations are stored by threadid to make them thread local.
_translations = {}
_active = {}
# The default translation is based on the settings file.
_default = None
# This is a cache for normalized accept-header languages to prevent multiple
# file lookups when checking the same locale on repeated requests.
_accepted = {}
# Format of Accept-Language header values. From RFC 2616, section 14.4 and 3.9.
accept_language_re = re.compile(r'''
([A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*|\*) # "en", "en-au", "x-y-z", "*"
(?:;q=(0(?:\.\d{,3})?|1(?:.0{,3})?))? # Optional "q=1.00", "q=0.8"
(?:\s*,\s*|$) # Multiple accepts per header.
''', re.VERBOSE)
def to_locale(language, to_lower=False):
"""
Turns a language name (en-us) into a locale name (en_US). If 'to_lower' is
True, the last component is lower-cased (en_us).
"""
p = language.find('-')
if p >= 0:
if to_lower:
return language[:p].lower()+'_'+language[p+1:].lower()
else:
return language[:p].lower()+'_'+language[p+1:].upper()
else:
return language.lower()
def to_language(locale):
"""Turns a locale name (en_US) into a language name (en-us)."""
p = locale.find('_')
if p >= 0:
return locale[:p].lower()+'-'+locale[p+1:].lower()
else:
return locale.lower()
class DjangoTranslation(gettext_module.GNUTranslations):
"""
This class sets up the GNUTranslations context with regard to output
charset. Django uses a defined DEFAULT_CHARSET as the output charset on
Python 2.4. With Python 2.3, use DjangoTranslation23.
"""
def __init__(self, *args, **kw):
from django.conf import settings
gettext_module.GNUTranslations.__init__(self, *args, **kw)
# Starting with Python 2.4, there's a function to define
# the output charset. Before 2.4, the output charset is
# identical with the translation file charset.
try:
self.set_output_charset('utf-8')
except AttributeError:
pass
self.<API key> = 'utf-8'
self.__language = '??'
def merge(self, other):
self._catalog.update(other._catalog)
def set_language(self, language):
self.__language = language
def language(self):
return self.__language
def __repr__(self):
return "<DjangoTranslation lang:%s>" % self.__language
class DjangoTranslation23(DjangoTranslation):
"""
Compatibility class that is only used with Python 2.3.
Python 2.3 doesn't support set_output_charset on translation objects and
needs this wrapper class to make sure input charsets from translation files
are correctly translated to output charsets.
With a full switch to Python 2.4, this can be removed from the source.
"""
def gettext(self, msgid):
res = self.ugettext(msgid)
return res.encode(self.<API key>)
def ngettext(self, msgid1, msgid2, n):
res = self.ungettext(msgid1, msgid2, n)
return res.encode(self.<API key>)
def translation(language):
"""
Returns a translation object.
This translation object will be constructed out of multiple GNUTranslations
objects by merging their catalogs. It will construct a object for the
requested language and add a fallback to the default language, if it's
different from the requested language.
"""
global _translations
t = _translations.get(language, None)
if t is not None:
return t
from django.conf import settings
# set up the right translation class
klass = DjangoTranslation
if sys.version_info < (2, 4):
klass = DjangoTranslation23
globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
if settings.SETTINGS_MODULE is not None:
parts = settings.SETTINGS_MODULE.split('.')
project = import_module(parts[0])
projectpath = os.path.join(os.path.dirname(project.__file__), 'locale')
else:
projectpath = None
def _fetch(lang, fallback=None):
global _translations
loc = to_locale(lang)
res = _translations.get(lang, None)
if res is not None:
return res
def _translation(path):
try:
t = gettext_module.translation('django', path, [loc], klass)
t.set_language(lang)
return t
except IOError, e:
return None
res = _translation(globalpath)
# We want to ensure that, for example, "en-gb" and "en-us" don't share
# the same translation object (thus, merging en-us with a local update
# doesn't affect en-gb), even though they will both use the core "en"
# translation. So we have to subvert Python's internal gettext caching.
base_lang = lambda x: x.split('-', 1)[0]
if base_lang(lang) in [base_lang(trans) for trans in _translations]:
res._info = res._info.copy()
res._catalog = res._catalog.copy()
def _merge(path):
t = _translation(path)
if t is not None:
if res is None:
return t
else:
res.merge(t)
return res
for localepath in settings.LOCALE_PATHS:
if os.path.isdir(localepath):
res = _merge(localepath)
if projectpath and os.path.isdir(projectpath):
res = _merge(projectpath)
for appname in settings.INSTALLED_APPS:
app = import_module(appname)
apppath = os.path.join(os.path.dirname(app.__file__), 'locale')
if os.path.isdir(apppath):
res = _merge(apppath)
if res is None:
if fallback is not None:
res = fallback
else:
return gettext_module.NullTranslations()
_translations[lang] = res
return res
default_translation = _fetch(settings.LANGUAGE_CODE)
current_translation = _fetch(language, fallback=default_translation)
return current_translation
def activate(language):
"""
Fetches the translation object for a given tuple of application name and
language and installs it as the current translation object for the current
thread.
"""
_active[currentThread()] = translation(language)
def deactivate():
"""
Deinstalls the currently active translation object so that further _ calls
will resolve against the default translation object, again.
"""
global _active
if currentThread() in _active:
del _active[currentThread()]
def deactivate_all():
"""
Makes the active translation object a NullTranslations() instance. This is
useful when we want delayed translations to appear as the original string
for some reason.
"""
_active[currentThread()] = gettext_module.NullTranslations()
def get_language():
"""Returns the currently selected language."""
t = _active.get(currentThread(), None)
if t is not None:
try:
return to_language(t.language())
except AttributeError:
pass
# If we don't have a real translation object, assume it's the default language.
from django.conf import settings
return settings.LANGUAGE_CODE
def get_language_bidi():
"""
Returns selected language's BiDi layout.
False = left-to-right layout
True = right-to-left layout
"""
from django.conf import settings
base_lang = get_language().split('-')[0]
return base_lang in settings.LANGUAGES_BIDI
def catalog():
"""
Returns the current active catalog for further processing.
This can be used if you need to modify the catalog or want to access the
whole message catalog instead of just translating one string.
"""
global _default, _active
t = _active.get(currentThread(), None)
if t is not None:
return t
if _default is None:
from django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
return _default
def do_translate(message, <API key>):
"""
Translates 'message' using the given '<API key>' name -- which
will be either gettext or ugettext. It uses the current thread to find the
translation object to use. If no current translation is activated, the
message will be run through the default translation object.
"""
global _default, _active
t = _active.get(currentThread(), None)
if t is not None:
result = getattr(t, <API key>)(message)
else:
if _default is None:
from django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
result = getattr(_default, <API key>)(message)
if isinstance(message, SafeData):
return mark_safe(result)
return result
def gettext(message):
return do_translate(message, 'gettext')
def ugettext(message):
return do_translate(message, 'ugettext')
def gettext_noop(message):
"""
Marks strings for translation but doesn't translate them now. This can be
used to store strings in global variables that should stay in the base
language (because they might be used externally) and will be translated
later.
"""
return message
def do_ntranslate(singular, plural, number, <API key>):
global _default, _active
t = _active.get(currentThread(), None)
if t is not None:
return getattr(t, <API key>)(singular, plural, number)
if _default is None:
from django.conf import settings
_default = translation(settings.LANGUAGE_CODE)
return getattr(_default, <API key>)(singular, plural, number)
def ngettext(singular, plural, number):
"""
Returns a UTF-8 bytestring of the translation of either the singular or
plural, based on the number.
"""
return do_ntranslate(singular, plural, number, 'ngettext')
def ungettext(singular, plural, number):
"""
Returns a unicode strings of the translation of either the singular or
plural, based on the number.
"""
return do_ntranslate(singular, plural, number, 'ungettext')
def check_for_language(lang_code):
"""
Checks whether there is a global language file for the given language
code. This is used to decide whether a user-provided language is
available. This is only used for language codes from either the cookies or
session.
"""
from django.conf import settings
globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
if gettext_module.find('django', globalpath, [to_locale(lang_code)]) is not None:
return True
else:
return False
def <API key>(request):
"""
Analyzes the request to find what language the user wants the system to
show. Only languages listed in settings.LANGUAGES are taken into account.
If the user requests a sublanguage where we have a main language, we send
out the main language.
"""
global _accepted
from django.conf import settings
globalpath = os.path.join(os.path.dirname(sys.modules[settings.__module__].__file__), 'locale')
supported = dict(settings.LANGUAGES)
if hasattr(request, 'session'):
lang_code = request.session.get('django_language', None)
if lang_code in supported and lang_code is not None and check_for_language(lang_code):
return lang_code
lang_code = request.COOKIES.get(settings.<API key>)
if lang_code and lang_code in supported and check_for_language(lang_code):
return lang_code
accept = request.META.get('<API key>', '')
for accept_lang, unused in <API key>(accept):
if accept_lang == '*':
break
# We have a very restricted form for our language files (no encoding
# specifier, since they all must be UTF-8 and only one possible
# language each time. So we avoid the overhead of gettext.find() and
# work out the MO file manually.
# 'normalized' is the root name of the locale in POSIX format (which is
# the format used for the directories holding the MO files).
normalized = locale.locale_alias.get(to_locale(accept_lang, True))
if not normalized:
continue
# Remove the default encoding from locale_alias.
normalized = normalized.split('.')[0]
if normalized in _accepted:
# We've seen this locale before and have an MO file for it, so no
# need to check again.
return _accepted[normalized]
for lang, dirname in ((accept_lang, normalized),
(accept_lang.split('-')[0], normalized.split('_')[0])):
if lang.lower() not in supported:
continue
langfile = os.path.join(globalpath, dirname, 'LC_MESSAGES',
'django.mo')
if os.path.exists(langfile):
_accepted[normalized] = lang
return lang
return settings.LANGUAGE_CODE
def get_date_formats():
"""
Checks whether translation files provide a translation for some technical
message ID to store date and time formats. If it doesn't contain one, the
formats provided in the settings will be used.
"""
from django.conf import settings
date_format = ugettext('DATE_FORMAT')
datetime_format = ugettext('DATETIME_FORMAT')
time_format = ugettext('TIME_FORMAT')
if date_format == 'DATE_FORMAT':
date_format = settings.DATE_FORMAT
if datetime_format == 'DATETIME_FORMAT':
datetime_format = settings.DATETIME_FORMAT
if time_format == 'TIME_FORMAT':
time_format = settings.TIME_FORMAT
return date_format, datetime_format, time_format
def <API key>():
"""
Checks whether translation files provide a translation for some technical
message ID to store partial date formats. If it doesn't contain one, the
formats provided in the settings will be used.
"""
from django.conf import settings
year_month_format = ugettext('YEAR_MONTH_FORMAT')
month_day_format = ugettext('MONTH_DAY_FORMAT')
if year_month_format == 'YEAR_MONTH_FORMAT':
year_month_format = settings.YEAR_MONTH_FORMAT
if month_day_format == 'MONTH_DAY_FORMAT':
month_day_format = settings.MONTH_DAY_FORMAT
return year_month_format, month_day_format
dot_re = re.compile(r'\S')
def blankout(src, char):
"""
Changes every non-whitespace character to the given char.
Used in the templatize function.
"""
return dot_re.sub(char, src)
inline_re = re.compile(r"""^\s*trans\s+((?:".*?")|(?:'.*?'))\s*""")
block_re = re.compile(r"""^\s*blocktrans(?:\s+|$)""")
endblock_re = re.compile(r"""^\s*endblocktrans$""")
plural_re = re.compile(r"""^\s*plural$""")
constant_re = re.compile(r)
def templatize(src):
"""
Turns a Django template into something that is understood by xgettext. It
does so by translating the Django translation tags into standard gettext
function invocations.
"""
from django.template import Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK
out = StringIO()
intrans = False
inplural = False
singular = []
plural = []
for t in Lexer(src, None).tokenize():
if intrans:
if t.token_type == TOKEN_BLOCK:
endbmatch = endblock_re.match(t.contents)
pluralmatch = plural_re.match(t.contents)
if endbmatch:
if inplural:
out.write(' ngettext(%r,%r,count) ' % (''.join(singular), ''.join(plural)))
for part in singular:
out.write(blankout(part, 'S'))
for part in plural:
out.write(blankout(part, 'P'))
else:
out.write(' gettext(%r) ' % ''.join(singular))
for part in singular:
out.write(blankout(part, 'S'))
intrans = False
inplural = False
singular = []
plural = []
elif pluralmatch:
inplural = True
else:
raise SyntaxError("Translation blocks must not include other block tags: %s" % t.contents)
elif t.token_type == TOKEN_VAR:
if inplural:
plural.append('%%(%s)s' % t.contents)
else:
singular.append('%%(%s)s' % t.contents)
elif t.token_type == TOKEN_TEXT:
if inplural:
plural.append(t.contents)
else:
singular.append(t.contents)
else:
if t.token_type == TOKEN_BLOCK:
imatch = inline_re.match(t.contents)
bmatch = block_re.match(t.contents)
cmatches = constant_re.findall(t.contents)
if imatch:
g = imatch.group(1)
if g[0] == '"': g = g.strip('"')
elif g[0] == "'": g = g.strip("'")
out.write(' gettext(%r) ' % g)
elif bmatch:
for fmatch in constant_re.findall(t.contents):
out.write(' _(%s) ' % fmatch)
intrans = True
inplural = False
singular = []
plural = []
elif cmatches:
for cmatch in cmatches:
out.write(' _(%s) ' % cmatch)
else:
out.write(blankout(t.contents, 'B'))
elif t.token_type == TOKEN_VAR:
parts = t.contents.split('|')
cmatch = constant_re.match(parts[0])
if cmatch:
out.write(' _(%s) ' % cmatch.group(1))
for p in parts[1:]:
if p.find(':_(') >= 0:
out.write(' %s ' % p.split(':',1)[1])
else:
out.write(blankout(p, 'F'))
else:
out.write(blankout(t.contents, 'X'))
return out.getvalue()
def <API key>(lang_string):
"""
Parses the lang_string, which is the body of an HTTP Accept-Language
header, and returns a list of (lang, q-value), ordered by 'q' values.
Any format errors in lang_string results in an empty list being returned.
"""
result = []
pieces = accept_language_re.split(lang_string)
if pieces[-1]:
return []
for i in range(0, len(pieces) - 1, 3):
first, lang, priority = pieces[i : i + 3]
if first:
return []
priority = priority and float(priority) or 1.0
result.append((lang, priority))
result.sort(lambda x, y: -cmp(x[1], y[1]))
return result
|
#pragma once
#include "DBC/DBC__File.h"
DBC_DEF_BEGIN(<API key>)
__DBC_REF_ID(<API key>, CreatureModelDataID, 2);
__DBC_TVALUE(uint32, SoundID, 3);
__DBC_REF_ID(<API key>, HumanoidData, 4);
__DBC_TVALUE(float_t, Scale, 5);
__DBC_TVALUE(uint32, Opacity, 6); // 0 - 255
__DBC_STRING(Texture1, 7); // Name of texture for 1st geoset with type 2 (see this). Texture must be in the same dir as M2 file of creature is.
__DBC_STRING(Texture2, 8); // Name of texture for 2nd geoset with type 2 (see this). Texture must be in the same dir as M2 file of creature is.
__DBC_STRING(Texture3, 9); // Name of texture for 3rd geoset with type 2 (see this). Texture must be in the same dir as M2 file of creature is.
__DBC_STRING(PortaitTexture, 10);
__DBC_TVALUE(uint32, UnitBloodLevelID, 11);
__DBC_TVALUE(uint32, UnitBloodID, 12);
__DBC_TVALUE(uint32, NPCSoundsID, 13);
__DBC_TVALUE(uint32, ParticlesID, 14);
__DBC_TVALUE(uint32, CreatureGeosetData, 15);
__DBC_TVALUE(uint32, <API key>, 16);
DBC_DEF_END
|
# ncurses, keep it simple for the moment
option(USE_BUNDLED_NCURSES "Enable building of the bundled ncurses" ${USE_BUNDLED_DEPS})
if(CURSES_INCLUDE_DIR)
# we already have ncurses
elseif(NOT USE_BUNDLED_NCURSES)
set(CURSES_NEED_NCURSES TRUE)
find_package(Curses REQUIRED)
message(STATUS "Found ncurses: include: ${CURSES_INCLUDE_DIR}, lib: ${CURSES_LIBRARIES}")
else()
set(CURSES_BUNDLE_DIR "${PROJECT_BINARY_DIR}/ncurses-prefix/src/ncurses")
set(CURSES_INCLUDE_DIR "${CURSES_BUNDLE_DIR}/include/")
set(CURSES_LIBRARIES "${CURSES_BUNDLE_DIR}/lib/libncurses.a")
if(NOT TARGET ncurses)
message(STATUS "Using bundled ncurses in '${CURSES_BUNDLE_DIR}'")
ExternalProject_Add(ncurses
PREFIX "${PROJECT_BINARY_DIR}/ncurses-prefix"
URL "http://download.draios.com/dependencies/ncurses-6.0-20150725.tgz"
URL_MD5 "<API key>"
CONFIGURE_COMMAND ./configure --without-cxx --without-cxx-binding --without-ada --without-manpages --without-progs --without-tests --with-terminfo-dirs=/etc/terminfo:/lib/terminfo:/usr/share/terminfo
BUILD_COMMAND ${CMD_MAKE}
BUILD_IN_SOURCE 1
BUILD_BYPRODUCTS ${CURSES_LIBRARIES}
INSTALL_COMMAND "")
endif()
endif()
include_directories("${CURSES_INCLUDE_DIR}")
|
{-# LANGUAGE ExplicitForAll, Rank2Types #-}
-- | An implementation of Reagents (http:
-- NOTE: currently this is just a very tiny core of the Reagent design. Needs
-- lots of work.
module Data.Concurrent.Internal.Reagent where
import Data.IORef
import Data.Atomics
import Prelude hiding (succ, fail)
type Reagent a = forall b. (a -> IO b) -> IO b -> IO b
-- | Execute a Reagent.
{-# INLINE react #-}
react :: Reagent a -> IO a
react r = try where
try = r finish try
finish x = return x
-- | Like atomicModifyIORef, but uses CAS and permits the update action to force
-- a retry by returning Nothing
{-# INLINE atomicUpdate #-}
atomicUpdate :: IORef a -> (a -> Maybe (a, b)) -> Reagent b
atomicUpdate r f succ fail = do
curTicket <- readForCAS r
let cur = peekTicket curTicket
case f cur of
Just (new, out) -> do
(done, _) <- casIORef r curTicket new
if done then succ out else fail
Nothing -> fail
atomicUpdate_ :: IORef a -> (a -> a) -> Reagent ()
atomicUpdate_ r f = atomicUpdate r (\x -> Just (f x, ()))
postCommit :: Reagent a -> (a -> IO b) -> Reagent b
postCommit r f succ fail = r (\x -> f x >>= succ) fail
choice :: Reagent a -> Reagent a -> Reagent a
choice _ _ = error "TODO"
|
using System;
using NDatabase.Api;
using NUnit.Framework;
using Test.NDatabase.Odb.Test.VO.Human;
namespace Test.NDatabase.Odb.Test.Query.Criteria
{
public class TestPolyMorphic : ODBTest
{
private const string DbName = "TestPolyMorphic.ndb";
[Test]
public void Test1()
{
DeleteBase(DbName);
using (var odb = Open(DbName))
{
odb.Store(new Animal("dog", "M", "my dog"));
odb.Store(new Animal("cat", "F", "my cat"));
odb.Store(new Man("Joe"));
odb.Store(new Woman("Karine"));
}
IObjectSet<object> os;
using (var odb = Open(DbName))
{
var q = odb.Query<object>();
os = q.Execute<object>();
Println(os);
}
AssertEquals(4, os.Count);
DeleteBase(DbName);
}
[Test]
public void Test2()
{
DeleteBase(DbName);
using (var odb = Open(DbName))
{
odb.Store(new Animal("dog", "M", "my dog"));
odb.Store(new Animal("cat", "F", "my cat"));
odb.Store(new Man("Joe"));
odb.Store(new Woman("Karine"));
}
IObjectSet<Human> os;
using (var odb = Open(DbName))
{
var q = odb.Query<Human>();
os = q.Execute<Human>();
Println(os);
}
AssertEquals(2, os.Count);
DeleteBase(DbName);
}
[Test]
public void Test3()
{
DeleteBase(DbName);
using (var odb = Open(DbName))
{
odb.Store(new Animal("dog", "M", "my dog"));
odb.Store(new Animal("cat", "F", "my cat"));
odb.Store(new Man("Joe"));
odb.Store(new Woman("Karine"));
}
IValues os;
using (var odb = Open(DbName))
{
var q = odb.ValuesQuery<object>().Field("specie");
os = q.Execute();
Println(os);
}
AssertEquals(4, os.Count);
DeleteBase(DbName);
}
[Test]
public void Test4()
{
DeleteBase(DbName);
using (var odb = Open(DbName))
{
odb.Store(new Animal("dog", "M", "my dog"));
odb.Store(new Animal("cat", "F", "my cat"));
odb.Store(new Man("Joe"));
odb.Store(new Woman("Karine"));
}
IValues os;
using (var odb = Open(DbName))
{
var q = odb.ValuesQuery<Human>().Field("specie");
os = q.Execute();
Println(os);
}
AssertEquals(2, os.Count);
DeleteBase(DbName);
}
[Test]
public void Test5()
{
DeleteBase(DbName);
using (var odb = Open(DbName))
{
odb.Store(new Animal("dog", "M", "my dog"));
odb.Store(new Animal("cat", "F", "my cat"));
odb.Store(new Man("Joe"));
odb.Store(new Woman("Karine"));
}
IValues os;
using (var odb = Open(DbName))
{
var q = odb.ValuesQuery<Man>().Field("specie");
os = q.Execute();
Println(os);
}
AssertEquals(1, os.Count);
DeleteBase(DbName);
}
[Test]
public void Test6()
{
DeleteBase(DbName);
using (var odb = Open(DbName))
{
odb.Store(new Animal("dog", "M", "my dog"));
odb.Store(new Animal("cat", "F", "my cat"));
odb.Store(new Man("Joe"));
odb.Store(new Woman("Karine"));
}
Decimal nb;
using (var odb = Open(DbName))
{
var q = odb.Query<object>();
nb = q.Count();
Println(nb);
}
AssertEquals(new Decimal(4), nb);
DeleteBase(DbName);
}
[Test]
public void Test7()
{
const int size = 3000;
var baseName = GetBaseName();
using (var odb = Open(baseName))
{
for (var i = 0; i < size; i++)
{
odb.Store(new Animal("dog", "M", "my dog"));
odb.Store(new Animal("cat", "F", "my cat"));
odb.Store(new Man("Joe" + i));
odb.Store(new Woman("Karine" + i));
}
}
Decimal nb;
using (var odb = Open(baseName))
{
var q = odb.Query<object>();
nb = q.Count();
Println(nb);
}
AssertEquals(new Decimal(4 * size), nb);
DeleteBase(baseName);
}
[Test]
public void Test8()
{
const int size = 3000;
var baseName = GetBaseName();
using (var odb = Open(baseName))
{
for (var i = 0; i < size; i++)
{
odb.Store(new Animal("dog" + i, "M", "my dog" + i));
odb.Store(new Animal("cat" + i, "F", "my cat" + i));
odb.Store(new Man("Joe" + i));
odb.Store(new Woman("Karine" + i));
}
}
Decimal nb;
using (var odb = Open(baseName))
{
var q = odb.Query<object>();
q.Descend("specie").Constrain("man").Equal();
nb = q.Count();
Println(nb);
}
AssertEquals(new Decimal(1 * size), nb);
DeleteBase(baseName);
}
}
}
|
package org.myrobotlab.framework;
import static org.myrobotlab.framework.StatusLevel.DEBUG;
import static org.myrobotlab.framework.StatusLevel.ERROR;
import static org.myrobotlab.framework.StatusLevel.INFO;
import static org.myrobotlab.framework.StatusLevel.SUCCESS;
import static org.myrobotlab.framework.StatusLevel.WARN;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.Objects;
import org.myrobotlab.codec.CodecUtils;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.slf4j.Logger;
/**
* Goal is to have a very simple Pojo with only a few (native Java helper
* methods) WARNING !!! - this class used to extend Exception or Throwable - but
* the gson serializer would stack overflow with self reference issue
*
* TODO - allow radix tree searches for "keys" ???
*
*/
public class Status implements Serializable {// extends Exception {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Status.class);
public String name; // service name ???
/**
* FIXME - should probably be an enum now that serialization mostly works now
* with enums [debug|info|warn|error|success] - yes the last part is different
* than "logging" but could still be a status...
*
*/
public String level;
/**
* The key is the non changing part and good identifier of what went on... For
* Exceptions I would recommend the Exception.class.getSimpleName() for the
* key, whilst the "detail" is for "changing" detail. This becomes important
* when Stati are aggregated - and humans are interested in "high" counts of
* specific Status while the details are not important unless diagnosing one.
*
* Violating Servo limits is a good example - "key" can be "Outside servo
* limits". The key can contain spaces and punctuation - the important part is
* that it is STATIC.
*
* "details" contain dynamic specifics - for example: "key":"Outside servo
* limits", "detail":"servo01 moveTo(75) limit is greater than 100"
*/
public String key;
/**
* Dynamic of verbose explanation of the status. e.g. "detail":"servo01
* moveTo(75) limit is greater than 100" or complete stack trace from an
* exception
*/
public String detail;
/**
* optional source of status
*/
public Object source;
public static Status debug(String format, Object... args) {
Status status = new Status(String.format(format, args));
status.level = DEBUG;
return status;
}
public static Status error(Exception e) {
Status s = new Status(e);
s.level = ERROR;
return s;
}
public static Status error(String msg) {
Status s = new Status(msg);
s.level = ERROR;
return s;
}
public static Status error(String format, Object... args) {
Status status = new Status(String.format(format, args));
status.level = ERROR;
return status;
}
public static Status warn(String msg) {
Status s = new Status(msg);
s.level = ERROR;
return s;
}
public static Status warn(String format, Object... args) {
Status status = new Status(String.format(format, args));
status.level = WARN;
return status;
}
public static Status info(String msg) {
Status s = new Status(msg);
s.level = INFO;
return s;
}
public static Status info(String format, Object... args) {
String formattedInfo = String.format(format, args);
Status status = new Status(formattedInfo);
status.level = INFO;
return status;
}
public final static String stackToString(final Throwable e) {
StringWriter sw;
try {
sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
} catch (Exception e2) {
return "bad stackToString";
}
return "
}
public Status(Exception e) {
this.level = ERROR;
StringWriter sw;
try {
sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
detail = sw.toString();
} catch (Exception e2) {
}
this.key = String.format("%s - %s", e.getClass().getSimpleName(), e.getMessage());
}
public Status(Status s) {
if (s == null) {
return;
}
this.name = s.name;
this.level = s.level;
this.key = s.key;
this.detail = s.detail;
}
/**
* for minimal amount of information error is assumed, and info is detail of
* an ERROR
*
* @param detail
* d
*/
public Status(String detail) {
this.level = ERROR;
this.detail = detail;
}
public Status(String name, String level, String key, String detail) {
this.name = name;
this.level = level;
this.key = key;
this.detail = detail;
}
public boolean isDebug() {
return DEBUG.equals(level);
}
public boolean isError() {
return ERROR.equals(level);
}
public boolean isInfo() {
return INFO.equals(level);
}
public boolean isWarn() {
return WARN.equals(level);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
if (name != null) {
sb.append(name);
sb.append(" ");
}
if (level != null) {
sb.append(level);
sb.append(" ");
}
if (key != null) {
sb.append(key);
sb.append(" ");
}
if (detail != null) {
sb.append(detail);
}
return sb.toString();
}
static public final Status newInstance(String name, String level, String key, String detail) {
Status s = new Status(name, level, key, detail);
return s;
}
@Override
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Status)) {
return false;
}
Status status = (Status) o;
return Objects.equals(name, status.name) && Objects.equals(level, status.level) && Objects.equals(key, status.key) && Objects.equals(detail, status.detail);
}
@Override
public int hashCode() {
return Objects.hash(name, level, key, detail);
}
public static void main(String[] args) throws IOException, <API key> {
LoggingFactory.init(Level.INFO);
Status test = new Status("i am pessimistic");
// Status subTest = new Status("i am sub pessimistic");
// test.add(subTest);
String json = CodecUtils.toJson(test);
Status z = CodecUtils.fromJson(json, Status.class);
log.info(json);
log.info(z.toString());
}
public static Status success() {
Status s = new Status(SUCCESS);
s.level = SUCCESS;
return s;
}
public boolean isSuccess() {
return SUCCESS.equals(level);
}
public static Status success(String detail) {
Status s = new Status(SUCCESS);
s.level = SUCCESS;
s.detail = detail;
return s;
}
}
|
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class <API key> : <API key><<API key>>
{
private static string GetBannerText(<API key> simpleDirective)
{
var kw = simpleDirective.DirectiveNameToken;
var prefixLength = kw.Span.End - simpleDirective.Span.Start;
var text = simpleDirective.ToString().Substring(prefixLength).Trim();
if (text.Length == 0)
{
return simpleDirective.HashToken.ToString() + kw.ToString();
}
else
{
return text;
}
}
protected override void CollectBlockSpans(
SyntaxToken previousToken,
<API key> regionDirective,
ref TemporaryArray<BlockSpan> spans,
<API key> optionProvider,
Cancellation<API key>)
{
var match = regionDirective.<API key>(cancellationToken);
if (match != null)
{
// Always auto-collapse regions for Metadata As Source. These generated files only have one region at
// the top of the file, which has content like the following:
// #region Assembly System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKey<API key>
// // C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\3.1.0\ref\netcoreapp3.1\System.Runtime.dll
// #endregion
// For other files, auto-collapse regions based on the user option.
var autoCollapse = optionProvider.IsMetadataAsSource || optionProvider.GetOption(
<API key>.<API key>, LanguageNames.CSharp);
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: TextSpan.FromBounds(regionDirective.SpanStart, match.Span.End),
type: BlockTypes.PreprocessorRegion,
bannerText: GetBannerText(regionDirective),
autoCollapse: autoCollapse,
isDefaultCollapsed: !optionProvider.IsMetadataAsSource));
}
}
}
}
|
// file at the top-level directory of this distribution and at
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Type resolution: the phase that finds all the types in the AST with
// unresolved type variables and replaces "ty_var" types with their
// substitutions.
use self::ResolveReason::*;
use astconv::AstConv;
use check::FnCtxt;
use middle::def;
use middle::pat_util;
use middle::ty::{mod, Ty, MethodCall, MethodCallee};
use middle::ty_fold::{TypeFolder,TypeFoldable};
use middle::infer::{force_all, resolve_all, resolve_region};
use middle::infer::resolve_type;
use middle::infer;
use write_substs_to_tcx;
use write_ty_to_tcx;
use util::ppaux::Repr;
use std::cell::Cell;
use syntax::ast;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::print::pprust::pat_to_string;
use syntax::visit;
use syntax::visit::Visitor;
// Entry point functions
pub fn <API key>(fcx: &FnCtxt, e: &ast::Expr) {
assert_eq!(fcx.writeback_errors.get(), false);
let mut wbcx = WritebackCx::new(fcx);
wbcx.visit_expr(e);
wbcx.<API key>();
wbcx.<API key>();
wbcx.<API key>();
}
pub fn <API key>(fcx: &FnCtxt,
decl: &ast::FnDecl,
blk: &ast::Block) {
assert_eq!(fcx.writeback_errors.get(), false);
let mut wbcx = WritebackCx::new(fcx);
wbcx.visit_block(blk);
for arg in decl.inputs.iter() {
wbcx.visit_node_id(ResolvingPattern(arg.pat.span), arg.id);
wbcx.visit_pat(&*arg.pat);
// Privacy needs the type for the whole pattern, not just each binding
if !pat_util::pat_is_binding(&fcx.tcx().def_map, &*arg.pat) {
wbcx.visit_node_id(ResolvingPattern(arg.pat.span),
arg.pat.id);
}
}
wbcx.<API key>();
wbcx.<API key>();
wbcx.<API key>();
}
// The Writerback context. This visitor walks the AST, checking the
// fn-specific tables to find references to types or regions. It
// resolves those regions to remove inference variables and writes the
// final result back into the master tables in the tcx. Here and
// there, it applies a few ad-hoc checks that were not convenient to
// do elsewhere.
struct WritebackCx<'cx, 'tcx: 'cx> {
fcx: &'cx FnCtxt<'cx, 'tcx>,
}
impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
fn new(fcx: &'cx FnCtxt<'cx, 'tcx>) -> WritebackCx<'cx, 'tcx> {
WritebackCx { fcx: fcx }
}
fn tcx(&self) -> &'cx ty::ctxt<'tcx> {
self.fcx.tcx()
}
}
// Impl of Visitor for Resolver
// This is the master code which walks the AST. It delegates most of
// the heavy lifting to the generic visit and resolve functions
// below. In general, a function is made into a `visitor` if it must
// traffic in node-ids or update tables in the type context etc.
impl<'cx, 'tcx, 'v> Visitor<'v> for WritebackCx<'cx, 'tcx> {
fn visit_item(&mut self, _: &ast::Item) {
// Ignore items
}
fn visit_stmt(&mut self, s: &ast::Stmt) {
if self.fcx.writeback_errors.get() {
return;
}
self.visit_node_id(ResolvingExpr(s.span), ty::stmt_node_id(s));
visit::walk_stmt(self, s);
}
fn visit_expr(&mut self, e: &ast::Expr) {
if self.fcx.writeback_errors.get() {
return;
}
self.visit_node_id(ResolvingExpr(e.span), e.id);
self.<API key>(ResolvingExpr(e.span),
MethodCall::expr(e.id));
match e.node {
ast::ExprClosure(_, _, ref decl, _) |
ast::ExprProc(ref decl, _) => {
for input in decl.inputs.iter() {
let _ = self.visit_node_id(ResolvingExpr(e.span),
input.id);
}
}
_ => {}
}
visit::walk_expr(self, e);
}
fn visit_block(&mut self, b: &ast::Block) {
if self.fcx.writeback_errors.get() {
return;
}
self.visit_node_id(ResolvingExpr(b.span), b.id);
visit::walk_block(self, b);
}
fn visit_pat(&mut self, p: &ast::Pat) {
if self.fcx.writeback_errors.get() {
return;
}
self.visit_node_id(ResolvingPattern(p.span), p.id);
debug!("Type for pattern binding {} (id {}) resolved to {}",
pat_to_string(p),
p.id,
ty::node_id_to_type(self.tcx(), p.id).repr(self.tcx()));
visit::walk_pat(self, p);
}
fn visit_local(&mut self, l: &ast::Local) {
if self.fcx.writeback_errors.get() {
return;
}
let var_ty = self.fcx.local_ty(l.span, l.id);
let var_ty = self.resolve(&var_ty, ResolvingLocal(l.span));
write_ty_to_tcx(self.tcx(), l.id, var_ty);
visit::walk_local(self, l);
}
fn visit_ty(&mut self, t: &ast::Ty) {
match t.node {
ast::TyFixedLengthVec(ref ty, ref count_expr) => {
self.visit_ty(&**ty);
write_ty_to_tcx(self.tcx(), count_expr.id, ty::mk_uint());
}
_ => visit::walk_ty(self, t)
}
}
}
impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
fn <API key>(&self) {
if self.fcx.writeback_errors.get() {
return;
}
for (upvar_id, upvar_borrow) in self.fcx.inh.upvar_borrow_map.borrow().iter() {
let r = upvar_borrow.region;
let r = self.resolve(&r, ResolvingUpvar(*upvar_id));
let new_upvar_borrow = ty::UpvarBorrow { kind: upvar_borrow.kind,
region: r };
debug!("Upvar borrow for {} resolved to {}",
upvar_id.repr(self.tcx()),
new_upvar_borrow.repr(self.tcx()));
self.fcx.tcx().upvar_borrow_map.borrow_mut().insert(
*upvar_id, new_upvar_borrow);
}
}
fn <API key>(&self) {
if self.fcx.writeback_errors.get() {
return
}
for (def_id, unboxed_closure) in self.fcx
.inh
.unboxed_closures
.borrow()
.iter() {
let closure_ty = self.resolve(&unboxed_closure.closure_type,
<API key>(*def_id));
let unboxed_closure = ty::UnboxedClosure {
closure_type: closure_ty,
kind: unboxed_closure.kind,
};
self.fcx
.tcx()
.unboxed_closures
.borrow_mut()
.insert(*def_id, unboxed_closure);
}
}
fn <API key>(&self) {
if self.fcx.writeback_errors.get() {
return
}
for (&node_id, trait_ref) in self.fcx
.inh
.object_cast_map
.borrow()
.iter()
{
let span = ty::expr_span(self.tcx(), node_id);
let reason = ResolvingExpr(span);
let closure_ty = self.resolve(trait_ref, reason);
self.tcx()
.object_cast_map
.borrow_mut()
.insert(node_id, closure_ty);
}
}
fn visit_node_id(&self, reason: ResolveReason, id: ast::NodeId) {
// Resolve any borrowings for the node with id `id`
self.visit_adjustments(reason, id);
// Resolve the type of the node with id `id`
let n_ty = self.fcx.node_ty(id);
let n_ty = self.resolve(&n_ty, reason);
write_ty_to_tcx(self.tcx(), id, n_ty);
debug!("Node {} has type {}", id, n_ty.repr(self.tcx()));
// Resolve any substitutions
self.fcx.opt_node_ty_substs(id, |item_substs| {
write_substs_to_tcx(self.tcx(), id,
self.resolve(item_substs, reason));
});
}
fn visit_adjustments(&self, reason: ResolveReason, id: ast::NodeId) {
match self.fcx.inh.adjustments.borrow_mut().remove(&id) {
None => {
debug!("No adjustments for node {}", id);
}
Some(adjustment) => {
let adj_object = ty::adjust_is_object(&adjustment);
let resolved_adjustment = match adjustment {
ty::AdjustAddEnv(store) => {
// FIXME(eddyb) #2190 Allow only statically resolved
// bare functions to coerce to a closure to avoid
// constructing (slower) indirect call wrappers.
match self.tcx().def_map.borrow().get(&id) {
Some(&def::DefFn(..)) |
Some(&def::DefStaticMethod(..)) |
Some(&def::DefVariant(..)) |
Some(&def::DefStruct(_)) => {
}
_ => {
span_err!(self.tcx().sess, reason.span(self.tcx()), E0100,
"cannot coerce non-statically resolved bare fn to closure");
span_help!(self.tcx().sess, reason.span(self.tcx()),
"consider embedding the function in a closure");
}
}
ty::AdjustAddEnv(self.resolve(&store, reason))
}
ty::AdjustDerefRef(adj) => {
for autoderef in range(0, adj.autoderefs) {
let method_call = MethodCall::autoderef(id, autoderef);
self.<API key>(reason, method_call);
}
if adj_object {
let method_call = MethodCall::autoobject(id);
self.<API key>(reason, method_call);
}
ty::AdjustDerefRef(ty::AutoDerefRef {
autoderefs: adj.autoderefs,
autoref: self.resolve(&adj.autoref, reason),
})
}
};
debug!("Adjustments for node {}: {}", id, resolved_adjustment);
self.tcx().adjustments.borrow_mut().insert(
id, resolved_adjustment);
}
}
}
fn <API key>(&self,
reason: ResolveReason,
method_call: MethodCall) {
// Resolve any method map entry
match self.fcx.inh.method_map.borrow_mut().remove(&method_call) {
Some(method) => {
debug!("writeback::<API key>(call={}, entry={})",
method_call,
method.repr(self.tcx()));
let new_method = MethodCallee {
origin: self.resolve(&method.origin, reason),
ty: self.resolve(&method.ty, reason),
substs: self.resolve(&method.substs, reason),
};
self.tcx().method_map.borrow_mut().insert(
method_call,
new_method);
}
None => {}
}
}
fn resolve<T:ResolveIn<'tcx>>(&self, t: &T, reason: ResolveReason) -> T {
t.resolve_in(&mut Resolver::new(self.fcx, reason))
}
}
// Resolution reason.
enum ResolveReason {
ResolvingExpr(Span),
ResolvingLocal(Span),
ResolvingPattern(Span),
ResolvingUpvar(ty::UpvarId),
<API key>(ast::DefId),
}
impl Copy for ResolveReason {}
impl ResolveReason {
fn span(&self, tcx: &ty::ctxt) -> Span {
match *self {
ResolvingExpr(s) => s,
ResolvingLocal(s) => s,
ResolvingPattern(s) => s,
ResolvingUpvar(upvar_id) => {
ty::expr_span(tcx, upvar_id.closure_expr_id)
}
<API key>(did) => {
if did.krate == ast::LOCAL_CRATE {
ty::expr_span(tcx, did.node)
} else {
DUMMY_SP
}
}
}
}
}
// Convenience methods for resolving different kinds of things.
trait ResolveIn<'tcx> {
fn resolve_in<'a>(&self, resolver: &mut Resolver<'a, 'tcx>) -> Self;
}
impl<'tcx, T: TypeFoldable<'tcx>> ResolveIn<'tcx> for T {
fn resolve_in<'a>(&self, resolver: &mut Resolver<'a, 'tcx>) -> T {
self.fold_with(resolver)
}
}
// The Resolver. This is the type folding engine that detects
// unresolved types and so forth.
struct Resolver<'cx, 'tcx: 'cx> {
tcx: &'cx ty::ctxt<'tcx>,
infcx: &'cx infer::InferCtxt<'cx, 'tcx>,
writeback_errors: &'cx Cell<bool>,
reason: ResolveReason,
}
impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
fn new(fcx: &'cx FnCtxt<'cx, 'tcx>,
reason: ResolveReason)
-> Resolver<'cx, 'tcx>
{
Resolver::from_infcx(fcx.infcx(), &fcx.writeback_errors, reason)
}
fn from_infcx(infcx: &'cx infer::InferCtxt<'cx, 'tcx>,
writeback_errors: &'cx Cell<bool>,
reason: ResolveReason)
-> Resolver<'cx, 'tcx>
{
Resolver { infcx: infcx,
tcx: infcx.tcx,
writeback_errors: writeback_errors,
reason: reason }
}
fn report_error(&self, e: infer::fixup_err) {
self.writeback_errors.set(true);
if !self.tcx.sess.has_errors() {
match self.reason {
ResolvingExpr(span) => {
span_err!(self.tcx.sess, span, E0101,
"cannot determine a type for this expression: {}",
infer::fixup_err_to_string(e));
}
ResolvingLocal(span) => {
span_err!(self.tcx.sess, span, E0102,
"cannot determine a type for this local variable: {}",
infer::fixup_err_to_string(e));
}
ResolvingPattern(span) => {
span_err!(self.tcx.sess, span, E0103,
"cannot determine a type for this pattern binding: {}",
infer::fixup_err_to_string(e));
}
ResolvingUpvar(upvar_id) => {
let span = self.reason.span(self.tcx);
span_err!(self.tcx.sess, span, E0104,
"cannot resolve lifetime for captured variable `{}`: {}",
ty::local_var_name_str(self.tcx, upvar_id.var_id).get().to_string(),
infer::fixup_err_to_string(e));
}
<API key>(_) => {
let span = self.reason.span(self.tcx);
self.tcx.sess.span_err(span,
"cannot determine a type for this \
unboxed closure")
}
}
}
}
}
impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> {
fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
self.tcx
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
if !ty::type_needs_infer(t) {
return t;
}
match resolve_type(self.infcx, None, t, resolve_all | force_all) {
Ok(t) => t,
Err(e) => {
self.report_error(e);
ty::mk_err()
}
}
}
fn fold_region(&mut self, r: ty::Region) -> ty::Region {
match resolve_region(self.infcx, r, resolve_all | force_all) {
Ok(r) => r,
Err(e) => {
self.report_error(e);
ty::ReStatic
}
}
}
}
// During type check, we store promises with the result of trait
// lookup rather than the actual results (because the results are not
// necessarily available immediately). These routines unwind the
// promises. It is expected that we will have already reported any
// errors that may be encountered, so if the promises store an error,
// a dummy result is returned.
|
'use strict';
module.exports = function (grunt) {
grunt.config(
'a11y', {
live: {
options: {
urls: ['www.google.com']
}
}
});
};
|
package org.lightadmin.core.view.preparer;
import org.apache.tiles.AttributeContext;
import org.apache.tiles.context.TilesRequestContext;
import org.lightadmin.core.config.domain.<API key>;
public class FormViewPreparer extends <API key> {
@Override
protected void execute(final TilesRequestContext tilesContext, final AttributeContext attributeContext, final <API key> configuration) {
super.execute(tilesContext, attributeContext, configuration);
addAttribute(attributeContext, "fields", configuration.getFormViewFragment().getFields());
}
}
|
import logging
from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_USERNAME,
CONF_PASSWORD,
CONF_NAME,
<API key>,
)
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
from homeassistant.exceptions import PlatformNotReady
_LOGGER = logging.getLogger(__name__)
GIGABITS = "Gb"
PRICE = "CAD"
DAYS = "days"
PERCENT = "%"
DEFAULT_NAME = "EBox"
REQUESTS_TIMEOUT = 15
SCAN_INTERVAL = timedelta(minutes=15)
<API key> = timedelta(minutes=15)
SENSOR_TYPES = {
"usage": ["Usage", PERCENT, "mdi:percent"],
"balance": ["Balance", PRICE, "mdi:square-inc-cash"],
"limit": ["Data limit", GIGABITS, "mdi:download"],
"days_left": ["Days left", DAYS, "mdi:calendar-today"],
"<API key>": ["Download before offpeak", GIGABITS, "mdi:download"],
"<API key>": ["Upload before offpeak", GIGABITS, "mdi:upload"],
"<API key>": ["Total before offpeak", GIGABITS, "mdi:download"],
"offpeak_download": ["Offpeak download", GIGABITS, "mdi:download"],
"offpeak_upload": ["Offpeak Upload", GIGABITS, "mdi:upload"],
"offpeak_total": ["Offpeak Total", GIGABITS, "mdi:download"],
"download": ["Download", GIGABITS, "mdi:download"],
"upload": ["Upload", GIGABITS, "mdi:upload"],
"total": ["Total", GIGABITS, "mdi:download"],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(<API key>): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]
),
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
async def <API key>(hass, config, async_add_entities, discovery_info=None):
"""Set up the EBox sensor."""
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
httpsession = hass.helpers.aiohttp_client.<API key>()
ebox_data = EBoxData(username, password, httpsession)
name = config.get(CONF_NAME)
from pyebox.client import PyEboxError
try:
await ebox_data.async_update()
except PyEboxError as exp:
_LOGGER.error("Failed login: %s", exp)
raise PlatformNotReady
sensors = []
for variable in config[<API key>]:
sensors.append(EBoxSensor(ebox_data, variable, name))
async_add_entities(sensors, True)
class EBoxSensor(Entity):
"""Implementation of a EBox sensor."""
def __init__(self, ebox_data, sensor_type, name):
"""Initialize the sensor."""
self.client_name = name
self.type = sensor_type
self._name = SENSOR_TYPES[sensor_type][0]
self.<API key> = SENSOR_TYPES[sensor_type][1]
self._icon = SENSOR_TYPES[sensor_type][2]
self.ebox_data = ebox_data
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return f"{self.client_name} {self._name}"
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self.<API key>
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return self._icon
async def async_update(self):
"""Get the latest data from EBox and update the state."""
await self.ebox_data.async_update()
if self.type in self.ebox_data.data:
self._state = round(self.ebox_data.data[self.type], 2)
class EBoxData:
"""Get data from Ebox."""
def __init__(self, username, password, httpsession):
"""Initialize the data object."""
from pyebox import EboxClient
self.client = EboxClient(username, password, REQUESTS_TIMEOUT, httpsession)
self.data = {}
@Throttle(<API key>)
async def async_update(self):
"""Get the latest data from Ebox."""
from pyebox.client import PyEboxError
try:
await self.client.fetch_data()
except PyEboxError as exp:
_LOGGER.error("Error on receive last EBox data: %s", exp)
return
# Update data
self.data = self.client.get_data()
|
#ifndef _CUFTPD_H
#define _CUFTPD_H
#define CUFTPD_DEBUG(fmt, ...) cuftpd_debug(__FILE__, __LINE__, fmt, __VA_ARGS__)
#define CUFTPD_ARR_LEN(arr) (sizeof(arr)/sizeof(arr[0]))
#define CUFTPD_VER "1.0"
#define CUFTPD_DEF_SRV_PORT 21
#define <API key> 8
#define CUFTPD_LINE_END "\r\n"
#define CUFTPD_OK 0
#define CUFTPD_ERR (-1)
#define CUFTPD_CHECK_LOGIN() \
do { \
if (!cuftpd_cur_user) { \
cuftpd_send_resp(ctrlfd, 530, "first please"); \
return CUFTPD_ERR; \
} \
} while(0)
struct cuftpd_cmd_struct {
char *cmd_name;
int (*cmd_handler)(int ctrlfd, char *cmd_line);
};
struct cuftpd_user_struct {
char user[128];
char pass[128];
};
#endif
|
package no.nb.nna.veidemann.chrome.client.ws;
import no.nb.nna.veidemann.chrome.client.ws.<API key>.Response;
public class <API key> extends Command<Response> {
public <API key>(Cdp client) {
super(client, "Browser", "getVersion", Response.class);
}
public static class Response {
private String protocolVersion;
private String product;
private String revision;
private String userAgent;
private String jsVersion;
/**
* Protocol version.
*/
public String protocolVersion() {
return protocolVersion;
}
/**
* Product name.
*/
public String product() {
return product;
}
/**
* Product revision.
*/
public String revision() {
return revision;
}
/**
* User-Agent.
*/
public String userAgent() {
return userAgent;
}
/**
* V8 version.
*/
public String jsVersion() {
return jsVersion;
}
public String toString() {
return "Version{protocolVersion=" + protocolVersion + ", product=" + product + ", revision=" + revision + ", userAgent=" + userAgent + ", jsVersion=" + jsVersion + "}";
}
}
}
|
package fr.javatronic.blog.massive.annotation1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_914 {
}
|
// +build integration,ethereum
package ethclient
import (
"encoding/json"
"fmt"
"testing"
"github.com/hyperledger/burrow/crypto"
"github.com/hyperledger/burrow/encoding/web3hex"
"github.com/hyperledger/burrow/execution/solidity"
"github.com/hyperledger/burrow/rpc/rpcevents"
"github.com/hyperledger/burrow/tests/web3/web3test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var client = NewEthClient(web3test.GetChainRPCClient())
func TestEthAccounts(t *testing.T) {
accounts, err := client.Accounts()
require.NoError(t, err)
fmt.Println(accounts)
}
func <API key>(t *testing.T) {
pk := web3test.GetPrivateKey(t)
d := new(web3hex.Decoder)
param := &<API key>{
From: web3hex.Encoder.Address(pk.GetAddress()),
Gas: web3hex.Encoder.Uint64(999999),
Data: web3hex.Encoder.BytesTrim(solidity.<API key>),
}
txHash, err := client.SendTransaction(param)
require.NoError(t, err)
require.NotEmpty(t, txHash)
tx, err := client.<API key>(txHash)
require.NoError(t, err)
assert.Greater(t, d.Uint64(tx.BlockNumber), uint64(0))
receipt, err := client.<API key>(txHash)
require.NoError(t, err)
assert.Equal(t, txHash, receipt.TransactionHash)
require.NoError(t, d.Err())
}
func <API key>(t *testing.T) {
txHash := "<API key>"
receipt, err := client.<API key>(txHash)
require.NoError(t, err)
require.Equal(t, "", receipt.TransactionHash)
require.Equal(t, "", receipt.BlockNumber)
require.Equal(t, "", receipt.BlockHash)
tx, err := client.<API key>(txHash)
require.NoError(t, err)
require.Equal(t, "", tx.Hash)
require.Equal(t, "", tx.BlockNumber)
require.Equal(t, "", tx.BlockHash)
}
func <API key>(t *testing.T) {
// TODO: make this test generate its own fixutres
filter := &Filter{
BlockRange: rpcevents.AbsoluteRange(1, 34340),
Addresses: []crypto.Address{
crypto.<API key>("<SHA1-like>"),
crypto.<API key>("<SHA1-like>"),
},
}
result, err := client.GetLogs(filter)
require.NoError(t, err)
bs, err := json.Marshal(result)
require.NoError(t, err)
fmt.Printf("%s\n", string(bs))
}
func <API key>(t *testing.T) {
block, err := client.GetBlockByNumber("latest")
require.NoError(t, err)
d := new(web3hex.Decoder)
assert.Greater(t, d.Uint64(block.Number), uint64(0))
require.NoError(t, d.Err())
}
func TestNetVersion(t *testing.T) {
chainID, err := client.NetVersion()
require.NoError(t, err)
require.NotEmpty(t, chainID)
}
func <API key>(t *testing.T) {
version, err := client.Web3ClientVersion()
require.NoError(t, err)
require.NotEmpty(t, version)
}
func TestEthSyncing(t *testing.T) {
result, err := client.Syncing()
require.NoError(t, err)
fmt.Printf("%#v\n", result)
}
func TestEthBlockNumber(t *testing.T) {
height, err := client.BlockNumber()
require.NoError(t, err)
require.Greater(t, height, uint64(0))
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the output module field formatting helper."""
import unittest
from dfdatetime import semantic_time as <API key>
from dfvfs.path import fake_path_spec
from plaso.containers import events
from plaso.lib import definitions
from plaso.output import formatting_helper
from tests.containers import test_lib as containers_test_lib
from tests.output import test_lib
class <API key>(formatting_helper.<API key>):
"""Field formatter helper for testing purposes."""
<API key> = {'zone': '_FormatTimeZone'}
class <API key>(test_lib.<API key>):
"""Test the output module field formatting helper."""
# pylint: disable=protected-access
_TEST_EVENTS = [
{'data_type': 'test:event',
'filename': 'log/syslog.1',
'hostname': 'ubuntu',
'path_spec': fake_path_spec.FakePathSpec(
location='log/syslog.1'),
'text': (
'Reporter <CRON> PID: 8442 (pam_unix(cron:session): session\n '
'closed for user root)'),
'timestamp': '2012-06-27 18:17:01',
'timestamp_desc': definitions.<API key>}]
def testFormatDateTime(self):
"""Tests the _FormatDateTime function with dynamic time."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T18:17:01.000000+00:00')
output_mediator.SetTimezone('Europe/Amsterdam')
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T20:17:01.000000+02:00')
output_mediator.SetTimezone('UTC')
event.date_time = <API key>.InvalidTime()
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, 'Invalid')
def <API key>(self):
"""Tests the _FormatDateTime function without dynamic time."""
output_mediator = self.<API key>(dynamic_time=False)
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
# Test with event.date_time
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T18:17:01.000000+00:00')
output_mediator.SetTimezone('Europe/Amsterdam')
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T20:17:01.000000+02:00')
output_mediator.SetTimezone('UTC')
event.date_time = <API key>.InvalidTime()
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '0000-00-00T00:00:00.000000+00:00')
# Test with event.timestamp
event.date_time = None
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T18:17:01.000000+00:00')
event.timestamp = 0
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '0000-00-00T00:00:00.000000+00:00')
event.timestamp = -9223372036854775808
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '0000-00-00T00:00:00.000000+00:00')
def <API key>(self):
"""Tests the _FormatDisplayName function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
display_name_string = test_helper._FormatDisplayName(
event, event_data, event_data_stream)
self.assertEqual(display_name_string, 'FAKE:log/syslog.1')
def testFormatFilename(self):
"""Tests the _FormatFilename function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
filename_string = test_helper._FormatFilename(
event, event_data, event_data_stream)
self.assertEqual(filename_string, 'log/syslog.1')
def testFormatHostname(self):
"""Tests the _FormatHostname function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
hostname_string = test_helper._FormatHostname(
event, event_data, event_data_stream)
self.assertEqual(hostname_string, 'ubuntu')
def testFormatInode(self):
"""Tests the _FormatInode function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
inode_string = test_helper._FormatInode(
event, event_data, event_data_stream)
self.assertEqual(inode_string, '-')
def testFormatMACB(self):
"""Tests the _FormatMACB function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
macb_string = test_helper._FormatMACB(event, event_data, event_data_stream)
self.assertEqual(macb_string, '..C.')
def testFormatMessage(self):
"""Tests the _FormatMessage function."""
output_mediator = self.<API key>()
<API key> = self._GetTestFilePath(['formatters'])
output_mediator.<API key>(
<API key>)
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
message_string = test_helper._FormatMessage(
event, event_data, event_data_stream)
<API key> = (
'Reporter <CRON> PID: 8442 (pam_unix(cron:session): session closed '
'for user root)')
self.assertEqual(message_string, <API key>)
def <API key>(self):
"""Tests the _FormatMessageShort function."""
output_mediator = self.<API key>()
<API key> = self._GetTestFilePath(['formatters'])
output_mediator.<API key>(
<API key>)
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
<API key> = test_helper._FormatMessageShort(
event, event_data, event_data_stream)
<API key> = (
'Reporter <CRON> PID: 8442 (pam_unix(cron:session): session closed '
'for user root)')
self.assertEqual(<API key>, <API key>)
def testFormatSource(self):
"""Tests the _FormatSource function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
source_string = test_helper._FormatSource(
event, event_data, event_data_stream)
self.assertEqual(source_string, 'Test log file')
def <API key>(self):
"""Tests the _FormatSourceShort function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
source_short_string = test_helper._FormatSourceShort(
event, event_data, event_data_stream)
self.assertEqual(source_short_string, 'FILE')
def testFormatTag(self):
"""Tests the _FormatTag function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
tag_string = test_helper._FormatTag(None)
self.assertEqual(tag_string, '-')
event_tag = events.EventTag()
event_tag.AddLabel('one')
event_tag.AddLabel('two')
tag_string = test_helper._FormatTag(event_tag)
self.assertEqual(tag_string, 'one two')
def testFormatTime(self):
"""Tests the _FormatTime function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
# Test with event.date_time
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '18:17:01')
output_mediator.SetTimezone('Europe/Amsterdam')
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '20:17:01')
output_mediator.SetTimezone('UTC')
# Test with event.timestamp
event.date_time = None
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '18:17:01')
event.timestamp = 0
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '
event.timestamp = -9223372036854775808
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '
def testFormatTimeZone(self):
"""Tests the _FormatTimeZone function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
zone_string = test_helper._FormatTimeZone(
event, event_data, event_data_stream)
self.assertEqual(zone_string, 'UTC')
def testFormatUsername(self):
"""Tests the _FormatUsername function."""
output_mediator = self.<API key>()
test_helper = formatting_helper.<API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
username_string = test_helper._FormatUsername(
event, event_data, event_data_stream)
self.assertEqual(username_string, '-')
# TODO: add coverage for _ReportEventError
def <API key>(self):
"""Tests the GetFormattedField function."""
output_mediator = self.<API key>()
test_helper = <API key>(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.<API key>(self._TEST_EVENTS[0]))
zone_string = test_helper.GetFormattedField(
'zone', event, event_data, event_data_stream, None)
self.assertEqual(zone_string, 'UTC')
if __name__ == '__main__':
unittest.main()
|
package de.tototec.sbuild.internal
import de.tototec.sbuild.TargetContext
import de.tototec.sbuild.<API key>
import de.tototec.sbuild.Project
trait <API key> {
def targetContext: TargetContext
protected[sbuild] def <API key>: Seq[TargetContext]
}
object <API key> extends ThreadLocal[<API key>] {
private[sbuild] override def remove: Unit = super.remove
private[sbuild] override def set(<API key>: <API key>): Unit = super.set(<API key>)
/**
* To use a <API key>, one should use this method.
*/
private[sbuild] def <API key>[T](callingMethodName: String, project: Option[Project] = None)(doWith: <API key> => T): T =
get match {
case null =>
val msg = I18n.marktr("'{0}' can only be used inside an exec block of a target.")
val ex = new <API key>(I18n.notr(msg, callingMethodName), null, I18n[<API key>.type].tr(msg, callingMethodName))
ex.buildScript = project.map(_.projectFile)
throw ex
case withinExecution => doWith(withinExecution)
}
// private[sbuild] def safeTargetContext(callingMethodName: String, project: Option[Project] = None): TargetContext =
// <API key>(callingMethodName, project)(_.targetContext)
}
|
package cn.edu.hhu.reg.vo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="doctor_login")
public class DoctorLogin {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(length = 16)
private Integer id;
@Column(name="doctor_id",length=16)
private Integer doctorId;
@Column(name="login_name",length=50)
private String loginName;
@Column(name="password",length=50)
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getDoctorId() {
return doctorId;
}
public void setDoctorId(Integer doctorId) {
this.doctorId = doctorId;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public DoctorLogin() {
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Tue Oct 08 12:24:28 JST 2013 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class twitter4j.examples.geo.CreatePlace (<TwitterConsumerkey> 3.0.4 API)</title>
<meta name="date" content="2013-10-08">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class twitter4j.examples.geo.CreatePlace (<TwitterConsumerkey> 3.0.4 API)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../twitter4j/examples/geo/CreatePlace.html" title="class in twitter4j.examples.geo">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?twitter4j/examples/geo/class-use/CreatePlace.html" target="_top">Frames</a></li>
<li><a href="CreatePlace.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h2 title="Uses of Class twitter4j.examples.geo.CreatePlace" class="title">Uses of Class<br>twitter4j.examples.geo.CreatePlace</h2>
</div>
<div class="classUseContainer">No usage of twitter4j.examples.geo.CreatePlace</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../twitter4j/examples/geo/CreatePlace.html" title="class in twitter4j.examples.geo">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?twitter4j/examples/geo/class-use/CreatePlace.html" target="_top">Frames</a></li>
<li><a href="CreatePlace.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small>Copyright &
</body>
</html>
|
package problems;
import java.util.Arrays;
import java.util.PriorityQueue;
public class SuperUglyNumber {
class Node implements Comparable<Node> {
int val;
final int prime_index;
public Node(int value, int prime_idx) {
this.val = value;
this.prime_index = prime_idx;
}
public int compareTo(Node a) {
return this.val - a.val;
}
}
public int[] nthSuperUglyNumber(int n, int[] primes) {
int[] nums = new int[n];
nums[0] = 1;
int[] index = new int[primes.length];
PriorityQueue<Node> pq = new PriorityQueue<>();
for (int i = 0; i < primes.length; i++)
pq.add(new Node(primes[i], i));
for (int i = 1; i < n; i++) {
Node node = pq.poll();
while (node.val == nums[i - 1]) {
node.val = nums[++index[node.prime_index]] * primes[node.prime_index];
pq.add(node);
node = pq.poll();
}
nums[i] = node.val;
node.val = nums[++index[node.prime_index]] * primes[node.prime_index];
pq.add(node);
}
return nums;
}
public static void main(String[] args) {
SuperUglyNumber sn = new SuperUglyNumber();
int[] primes = {2, 7, 13, 19};
System.out.println(Arrays.toString(primes));
System.out.println(Arrays.toString(sn.nthSuperUglyNumber(12, primes)));
}
}
|
package yuku.alkitab.base.util;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Xml;
import com.afollestad.materialdialogs.MaterialDialog;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.hash.TIntLongHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.ext.DefaultHandler2;
import yuku.alkitab.base.App;
import yuku.alkitab.base.IsiActivity;
import yuku.alkitab.base.S;
import yuku.alkitab.base.storage.Db;
import yuku.alkitab.base.storage.InternalDb;
import yuku.alkitab.debug.R;
import yuku.alkitab.model.Label;
import yuku.alkitab.model.Marker;
import yuku.alkitab.model.Marker_Label;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static yuku.alkitab.base.util.Literals.ToStringArray;
// Imported from v3. Used for once-only migration from v3 to v4.
public class BookmarkImporter {
static final String TAG = BookmarkImporter.class.getSimpleName();
// constants
static class Bookmark2_Label { // DO NOT CHANGE CONSTANT VALUES!
public static final String <API key> = "Bukmak2_Label";
public static final String <API key> = "bukmak2_relId";
public static final String XMLATTR_label_relId = "label_relId";
}
// constants
static class BackupManager {
public static final String XMLTAG_Bukmak2 = "Bukmak2";
private static final String XMLATTR_ari = "ari";
private static final String XMLATTR_kind = "jenis";
private static final String XMLATTR_caption = "tulisan";
private static final String XMLATTR_addTime = "waktuTambah";
private static final String XMLATTR_modifyTime = "waktuUbah";
private static final String XMLATTR_relId = "relId";
private static final String XMLVAL_bookmark = "bukmak";
private static final String XMLVAL_note = "catatan";
private static final String XMLVAL_highlight = "stabilo";
public static final String XMLTAG_Label = "Label";
private static final String XMLATTR_title = "judul";
private static final String XMLATTR_bgColor = "warnaLatar";
@Nullable
public static Marker <API key>(Attributes attributes) {
int ari = Integer.parseInt(attributes.getValue("", XMLATTR_ari));
String kind_s = attributes.getValue("", XMLATTR_kind);
Marker.Kind kind = kind_s.equals(XMLVAL_bookmark) ? Marker.Kind.bookmark : kind_s.equals(XMLVAL_note) ? Marker.Kind.note : kind_s.equals(XMLVAL_highlight) ? Marker.Kind.highlight : null;
String caption = unescapeHighUnicode(attributes.getValue("", XMLATTR_caption));
Date addTime = Sqlitil.toDate(Integer.parseInt(attributes.getValue("", XMLATTR_addTime)));
Date modifyTime = Sqlitil.toDate(Integer.parseInt(attributes.getValue("", XMLATTR_modifyTime)));
if (kind == null) { // invalid
return null;
}
return Marker.createNewMarker(ari, kind, caption, 1, addTime, modifyTime);
}
public static int getRelId(Attributes attributes) {
String s = attributes.getValue("", XMLATTR_relId);
return s == null ? 0 : Integer.parseInt(s);
}
public static Label labelFromAttributes(Attributes attributes) {
String title = unescapeHighUnicode(attributes.getValue("", XMLATTR_title));
String bgColor = attributes.getValue("", XMLATTR_bgColor);
return Label.createNewLabel(title, 0, bgColor);
}
static ThreadLocal<Matcher> highUnicodeMatcher = new ThreadLocal<Matcher>() {
@Override
protected Matcher initialValue() {
return Pattern.compile("\\[\\[~U([0-9A-Fa-f]{6})~\\]\\]").matcher("");
}
};
public static String unescapeHighUnicode(String input) {
if (input == null) return null;
final Matcher m = highUnicodeMatcher.get();
m.reset(input);
StringBuffer res = new StringBuffer();
while (m.find()) {
String s = m.group(1);
final int cp = Integer.parseInt(s, 16);
m.appendReplacement(res, new String(new int[]{cp}, 0, 1));
}
m.appendTail(res);
return res.toString();
}
}
public static void importBookmarks(final Activity activity, @NonNull final InputStream fis, final boolean <API key>, final Runnable runWhenDone) {
final MaterialDialog pd = new MaterialDialog.Builder(activity)
.content(R.string.mengimpor_titiktiga)
.cancelable(false)
.progress(true, 0)
.show();
new AsyncTask<Boolean, Integer, Object>() {
int count_bookmark = 0;
int count_label = 0;
@Override
protected Object doInBackground(Boolean... params) {
final List<Marker> markers = new ArrayList<>();
final TObjectIntHashMap<Marker> markerToRelIdMap = new TObjectIntHashMap<>();
final List<Label> labels = new ArrayList<>();
final TObjectIntHashMap<Label> labelToRelIdMap = new TObjectIntHashMap<>();
final TIntLongHashMap <API key> = new TIntLongHashMap();
final TIntObjectHashMap<TIntList> <API key> = new TIntObjectHashMap<>();
try {
Xml.parse(fis, Xml.Encoding.UTF_8, new DefaultHandler2() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch (localName) {
case BackupManager.XMLTAG_Bukmak2:
final Marker marker = BackupManager.<API key>(attributes);
if (marker != null) {
markers.add(marker);
final int bookmark2_relId = BackupManager.getRelId(attributes);
markerToRelIdMap.put(marker, bookmark2_relId);
count_bookmark++;
}
break;
case BackupManager.XMLTAG_Label: {
final Label label = BackupManager.labelFromAttributes(attributes);
int label_relId = BackupManager.getRelId(attributes);
labels.add(label);
labelToRelIdMap.put(label, label_relId);
count_label++;
break;
}
case Bookmark2_Label.<API key>: {
final int bookmark2_relId = Integer.parseInt(attributes.getValue("", Bookmark2_Label.<API key>));
final int label_relId = Integer.parseInt(attributes.getValue("", Bookmark2_Label.XMLATTR_label_relId));
TIntList labelRelIds = <API key>.get(bookmark2_relId);
if (labelRelIds == null) {
labelRelIds = new TIntArrayList();
<API key>.put(bookmark2_relId, labelRelIds);
}
labelRelIds.add(label_relId);
break;
}
}
}
});
fis.close();
} catch (Exception e) {
return e;
}
{ // bikin label-label yang diperlukan, juga map relId dengan id dari label.
final HashMap<String, Label> judulMap = new HashMap<>();
final List<Label> xlabelLama = S.getDb().listAllLabels();
for (Label labelLama : xlabelLama) {
judulMap.put(labelLama.title, labelLama);
}
for (Label label : labels) {
// cari apakah label yang judulnya persis sama udah ada
Label labelLama = judulMap.get(label.title);
final int labelRelId = labelToRelIdMap.get(label);
if (labelLama != null) {
// removed from v3: update warna label lama
<API key>.put(labelRelId, labelLama._id);
AppLog.d(TAG, "label (lama) r->a : " + labelRelId + "->" + labelLama._id);
} else { // belum ada, harus bikin baru
Label labelBaru = S.getDb().insertLabel(label.title, label.backgroundColor);
<API key>.put(labelRelId, labelBaru._id);
AppLog.d(TAG, "label (baru) r->a : " + labelRelId + "->" + labelBaru._id);
}
}
}
importBookmarks(markers, markerToRelIdMap, <API key>, <API key>);
return null;
}
@Override
protected void onPostExecute(@NonNull Object result) {
pd.dismiss();
if (result instanceof Exception) {
AppLog.e(TAG, "Error when importing markers", (Throwable) result);
new MaterialDialog.Builder(activity)
.content(activity.getString(R.string.<API key>, ((Exception) result).getMessage()))
.positiveText(R.string.ok)
.show();
} else {
final Dialog dialog = new MaterialDialog.Builder(activity)
.content(activity.getString(R.string.<API key>, count_bookmark, count_label))
.positiveText(R.string.ok)
.show();
if (<API key>) {
dialog.<API key>(dialog1 -> activity.finish());
}
}
if (runWhenDone != null) runWhenDone.run();
}
}.execute();
}
public static void importBookmarks(List<Marker> markers, TObjectIntHashMap<Marker> markerToRelIdMap, TIntLongHashMap <API key>, TIntObjectHashMap<TIntList> <API key>) {
SQLiteDatabase db = S.getDb().getWritableDatabase();
db.beginTransaction();
try {
final TIntObjectHashMap<Marker> markerRelIdToMarker = new TIntObjectHashMap<>();
{ // write new markers (if not available yet)
for (int i = 0; i < markers.size(); i++) {
Marker marker = markers.get(i);
final int marker_relId = markerToRelIdMap.get(marker);
// migrate: look for existing marker with same kind, ari, and content
try (Cursor cursor = db.query(
Db.TABLE_Marker,
null,
Db.Marker.ari + "=? and " + Db.Marker.kind + "=? and " + Db.Marker.caption + "=?",
ToStringArray(marker.ari, marker.kind.code, marker.caption),
null, null, null
)) {
if (cursor.moveToNext()) {
marker = InternalDb.markerFromCursor(cursor);
markers.set(i, marker);
} else {
InternalDb.insertMarker(db, marker);
}
// map it
markerRelIdToMarker.put(marker_relId, marker);
}
}
}
{ // now is marker-label assignments
for (final int marker_relId : <API key>.keys()) {
final TIntList label_relIds = <API key>.get(marker_relId);
final Marker marker = markerRelIdToMarker.get(marker_relId);
if (marker != null) {
// existing labels > 0: ignore
// existing labels == 0: insert
final int <API key> = (int) DatabaseUtils.queryNumEntries(db, Db.TABLE_Marker_Label, Db.Marker_Label.marker_gid + "=?", ToStringArray(marker.gid));
if (<API key> == 0) {
for (int label_relId : label_relIds.toArray()) {
final long label_id = <API key>.get(label_relId);
if (label_id > 0) {
final Label label = S.getDb().getLabelById(label_id);
final Marker_Label marker_label = Marker_Label.<API key>(marker.gid, label.gid);
InternalDb.<API key>(db, marker_label);
} else {
AppLog.w(TAG, "label_id is invalid!: " + label_id);
}
}
}
} else {
AppLog.w(TAG, "wrong marker_relId: " + marker_relId);
}
}
}
db.<API key>();
} finally {
db.endTransaction();
}
App.getLbm().sendBroadcast(new Intent(IsiActivity.<API key>));
}
}
|
package com.opengamma.core.region;
import java.util.Set;
import org.joda.beans.impl.flexi.FlexiBean;
import org.threeten.bp.ZoneId;
import com.opengamma.id.<API key>;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.id.UniqueId;
import com.opengamma.id.UniqueIdentifiable;
import com.opengamma.util.PublicAPI;
import com.opengamma.util.i18n.Country;
import com.opengamma.util.money.Currency;
/**
* A region of the world.
* <p>
* Many aspects of business, algorithms and contracts are specific to a region. The region may be of any size, from a municipality to a super-national group.
* <p>
* This interface is read-only. Implementations may be mutable.
*/
@PublicAPI
public interface Region extends UniqueIdentifiable, <API key> {
/**
* Gets the unique identifier of the region.
* <p>
* This specifies a single version-correction of the region.
*
* @return the unique identifier for this region, not null within the engine
*/
@Override
UniqueId getUniqueId();
/**
* Gets the external identifier bundle that defines the region.
* <p>
* Each external system has one or more identifiers by which they refer to the region.
* Some of these may be unique within that system, while others may be more descriptive.
* This bundle stores the set of these external identifiers.
* <p>
* This will include the country, currency and time-zone.
*
* @return the bundle defining the region, not null
*/
@Override // override for Javadoc
ExternalIdBundle getExternalIdBundle();
/**
* Gets the classification of the region.
*
* @return the classification of region, such as SUPER_NATIONAL or INDEPENDENT_STATE, not null
*/
<API key> getClassification();
/**
* Gets the unique identifiers of the regions that this region is a member of. For example, a country might be a member
* of the World, UN, European Union and NATO.
*
* @return the parent unique identifiers, null if this is the root entry
*/
Set<UniqueId> getParentRegionIds();
/**
* Gets the country.
*
* @return the country, null if not applicable
*/
Country getCountry();
/**
* Gets the currency.
*
* @return the currency, null if not applicable
*/
Currency getCurrency();
/**
* Gets the time-zone. For larger regions, there can be multiple time-zones, so this is only reliable for municipalities.
*
* @return the time-zone, null if not applicable
*/
ZoneId getTimeZone();
/**
* Gets the short descriptive name of the region.
*
* @return the name of the region, not null
*/
String getName();
/**
* Gets the full descriptive name of the region.
*
* @return the full name of the region, not null
*/
String getFullName();
/**
* Gets the extensible data store for additional information. Applications may store additional region based information here.
*
* @return the additional data, not null
*/
FlexiBean getData();
}
|
var config = require('./lib/config');
var FaceRec = require('./lib/facerec').FaceRec;
var hfr = new FaceRec(config);
// constant
var threshold = 20;
var prevX;
var prevY;
setInterval(function() {
var result = hfr.detect();
console.log('result:' + JSON.stringify(result));
if (result && result.pos_x && result.pos_y) {
var newX = result.pos_x;
var newY = result.pos_y;
var deltaX = newX - prevX;
var deltaY = newY - prevY;
if (Math.abs(deltaX) > threshold) {
var direction = deltaX > 0 ? "right" : "left";
console.log("moving head to " + direction + " , distance" + Math.abs(deltaX));
}
if (Math.abs(deltaY) > threshold) {
var direction = deltaY > 0 ? "down" : "up";
console.log("moving head to " + direction + " , distance" + Math.abs(deltaY));
}
console.log('updating x and y');
prevX = newX;
prevY = newY;
}
}, 5000);
|
package cat.ereza.<API key>.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import cat.ereza.<API key>.<API key>;
public class ClearStack extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = getIntent().getParcelableExtra(<API key>.KEY_CURRENT_INTENT);
startActivity(intent);
finish();
Runtime.getRuntime().exit(0);
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Services.Common;
using System.IO;
using System.Linq;
using NuGet.Resources;
namespace NuGet {
[DataServiceKey("Id", "Version")]
[<API key>("LastUpdated", <API key>.Updated, <API key>.Plaintext, keepInContent: false)]
[<API key>("Id", <API key>.Title, <API key>.Plaintext, keepInContent: false)]
[<API key>("Authors", <API key>.AuthorName, <API key>.Plaintext, keepInContent: false)]
[<API key>("Summary", <API key>.Summary, <API key>.Plaintext, keepInContent: false)]
[CLSCompliant(false)]
public class DataServicePackage : IPackage {
private readonly LazyWithRecreate<IPackage> _package;
public DataServicePackage() {
_package = new LazyWithRecreate<IPackage>(<API key>, ShouldUpdatePackage);
}
public string Id {
get;
set;
}
public string Version {
get;
set;
}
public string Title {
get;
set;
}
public string Authors {
get;
set;
}
public string Owners {
get;
set;
}
public Uri IconUrl {
get;
set;
}
public Uri LicenseUrl {
get;
set;
}
public Uri ProjectUrl {
get;
set;
}
public Uri ReportAbuseUrl {
get;
set;
}
public Uri GalleryDetailsUrl {
get;
set;
}
public Uri DownloadUrl {
get {
return Context.GetReadStreamUri(this);
}
}
public DateTimeOffset Published {
get;
set;
}
public DateTimeOffset LastUpdated {
get;
set;
}
public int DownloadCount {
get;
set;
}
public double Rating {
get;
set;
}
public int RatingsCount {
get;
set;
}
public bool <API key> {
get;
set;
}
public string Description {
get;
set;
}
public string Summary {
get;
set;
}
public string Language {
get;
set;
}
public string Tags {
get;
set;
}
public string Dependencies {
get;
set;
}
public string PackageHash {
get;
set;
}
internal string OldHash {
get;
set;
}
internal IDataServiceContext Context {
get;
set;
}
internal PackageDownloader Downloader { get; set; }
IEnumerable<string> IPackageMetadata.Authors {
get {
if (String.IsNullOrEmpty(Authors)) {
return Enumerable.Empty<string>();
}
return Authors.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
}
IEnumerable<string> IPackageMetadata.Owners {
get {
if (String.IsNullOrEmpty(Owners)) {
return Enumerable.Empty<string>();
}
return Owners.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
}
}
IEnumerable<PackageDependency> IPackageMetadata.Dependencies {
get {
if (String.IsNullOrEmpty(Dependencies)) {
return Enumerable.Empty<PackageDependency>();
}
return from d in Dependencies.Split('|')
let dependency = ParseDependency(d)
where dependency != null
select dependency;
}
}
Version IPackageMetadata.Version {
get {
if (Version != null) {
return new Version(Version);
}
return null;
}
}
public IEnumerable<<API key>> AssemblyReferences {
get {
return _package.Value.AssemblyReferences;
}
}
public IEnumerable<<API key>> FrameworkAssemblies {
get {
return _package.Value.FrameworkAssemblies;
}
}
public IEnumerable<IPackageFile> GetFiles() {
return _package.Value.GetFiles();
}
public Stream GetStream() {
return _package.Value.GetStream();
}
public override string ToString() {
return this.GetFullName();
}
private bool ShouldUpdatePackage() {
return ShouldUpdatePackage(MachineCache.Default);
}
internal bool ShouldUpdatePackage(IPackageRepository repository) {
// If the hash changed re-download the package.
if (OldHash != PackageHash) {
return true;
}
// If the package hasn't been cached, then re-download the package.
IPackage package = GetPackage(repository);
if (package == null) {
return true;
}
// If the cached package hash isn't the same as incoming package hash
// then re-download the package.
string cachedHash = package.GetHash();
if (cachedHash != PackageHash) {
return true;
}
return false;
}
private IPackage <API key>() {
return <API key>(MachineCache.Default);
}
internal IPackage <API key>(IPackageRepository repository) {
if (String.IsNullOrEmpty(PackageHash)) {
throw new <API key>(NuGetResources.<API key>);
}
IPackage package = null;
// If OldHash is null, we're looking at a new instance of the data service package.
// The package might be stored in the cache so we're going to try the looking there before attempting a download.
if (OldHash == null) {
package = GetPackage(repository);
}
if (package == null) {
byte[] hashBytes = Convert.FromBase64String(PackageHash);
package = Downloader.DownloadPackage(DownloadUrl, hashBytes, this);
// Add the package to the cache
repository.AddPackage(package);
// Clear the cache for this package
ZipPackage.ClearCache(package);
}
// Update the hash
OldHash = PackageHash;
return package;
}
<summary>
Parses a dependency from the feed in the format:
id:versionSpec or id
</summary>
private static PackageDependency ParseDependency(string value) {
if (String.IsNullOrWhiteSpace(value)) {
return null;
}
string[] tokens = value.Trim().Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length == 0) {
return null;
}
// Trim the id
string id = tokens[0].Trim();
IVersionSpec versionSpec = null;
if (tokens.Length > 1) {
// Attempt to parse the version
VersionUtility.TryParseVersionSpec(tokens[1], out versionSpec);
}
return new PackageDependency(id, versionSpec);
}
private IPackage GetPackage(IPackageRepository repository) {
return repository.FindPackage(Id, ((IPackageMetadata)this).Version);
}
<summary>
We can't use the built in Lazy for 2 reasons:
1. It caches the exception if any is thrown from the creator func (this means it won't retry calling the function).
2. There's no way to force a retry or expiration of the cache.
</summary>
private class LazyWithRecreate<T> {
private readonly Func<T> _creator;
private readonly Func<bool> _shouldRecreate;
private T _value;
private bool _isValueCreated;
public LazyWithRecreate(Func<T> creator, Func<bool> shouldRecreate) {
_creator = creator;
_shouldRecreate = shouldRecreate;
}
public T Value {
get {
if (_shouldRecreate() || !_isValueCreated) {
_value = _creator();
_isValueCreated = true;
}
return _value;
}
}
}
}
}
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_75) on Tue May 19 17:15:49 PDT 2015 -->
<title>Uses of Class org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter (Hadoop 2.6.0-mr1-cdh5.4.2 API)</title>
<meta name="date" content="2015-05-19">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter (Hadoop 2.6.0-mr1-cdh5.4.2 API)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/hadoop/mapred/lib/db/DBOutputFormat.DBRecordWriter.html" title="class in org.apache.hadoop.mapred.lib.db">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/hadoop/mapred/lib/db/class-use/DBOutputFormat.DBRecordWriter.html" target="_top">Frames</a></li>
<li><a href="DBOutputFormat.DBRecordWriter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h2 title="Uses of Class org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter" class="title">Uses of Class<br>org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter</h2>
</div>
<div class="classUseContainer">No usage of org.apache.hadoop.mapred.lib.db.DBOutputFormat.DBRecordWriter</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/hadoop/mapred/lib/db/DBOutputFormat.DBRecordWriter.html" title="class in org.apache.hadoop.mapred.lib.db">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/hadoop/mapred/lib/db/class-use/DBOutputFormat.DBRecordWriter.html" target="_top">Frames</a></li>
<li><a href="DBOutputFormat.DBRecordWriter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small>Copyright © 2009 The Apache Software Foundation</small></p>
</body>
</html>
|
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>PriceComparable | GDAX Trading Toolkit API Reference</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">GDAX Trading Toolkit API Reference</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="<API key>">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="<API key>" checked />
<label class="tsd-widget" for="<API key>">Inherited</label>
<input type="checkbox" id="<API key>" checked />
<label class="tsd-widget" for="<API key>">Externals</label>
<input type="checkbox" id="<API key>" />
<label class="tsd-widget" for="<API key>">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="../modules/_src_lib_orderbook_.html">"src/lib/Orderbook"</a>
</li>
<li>
<a href="_src_lib_orderbook_.pricecomparable.html">PriceComparable</a>
</li>
</ul>
<h1>Interface PriceComparable</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">PriceComparable</span>
<ul class="tsd-hierarchy">
<li>
<a href="_src_lib_orderbook_.pricelevel.html" class="tsd-signature-type">PriceLevel</a>
</li>
</ul>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section ">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property <API key>"><a href="_src_lib_orderbook_.pricecomparable.html#price" class="tsd-kind-icon">price</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group ">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property <API key>">
<a name="price" class="tsd-anchor"></a>
<h3>price</h3>
<div class="tsd-signature tsd-kind-icon">price<span class="<API key>">:</span> <a href="../modules/_src_lib_types_.html#bigjs" class="tsd-signature-type">BigJS</a></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/coinbase/gdax-tt/blob/a3d18bb/src/lib/Orderbook.ts#L29">src/lib/Orderbook.ts:29</a></li>
</ul>
</aside>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class="current <API key>">
<a href="../modules/_src_lib_orderbook_.html">"src/lib/<wbr>Orderbook"</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-interface <API key>">
<a href="_src_lib_orderbook_.basicorder.html" class="tsd-kind-icon">Basic<wbr>Order</a>
</li>
<li class=" tsd-kind-interface <API key>">
<a href="_src_lib_orderbook_.<API key>.html" class="tsd-kind-icon">Cumulative<wbr>Price<wbr>Level</a>
</li>
<li class=" tsd-kind-interface <API key>">
<a href="_src_lib_orderbook_.level3order.html" class="tsd-kind-icon">Level3<wbr>Order</a>
</li>
<li class=" tsd-kind-interface <API key>">
<a href="_src_lib_orderbook_.liveorder.html" class="tsd-kind-icon">Live<wbr>Order</a>
</li>
<li class=" tsd-kind-interface <API key>">
<a href="_src_lib_orderbook_.orderbook.html" class="tsd-kind-icon">Orderbook</a>
</li>
<li class=" tsd-kind-interface <API key>">
<a href="_src_lib_orderbook_.orderbookstate.html" class="tsd-kind-icon">Orderbook<wbr>State</a>
</li>
</ul>
<ul class="current">
<li class="current tsd-kind-interface <API key>">
<a href="_src_lib_orderbook_.pricecomparable.html" class="tsd-kind-icon">Price<wbr>Comparable</a>
<ul>
<li class=" tsd-kind-property <API key>">
<a href="_src_lib_orderbook_.pricecomparable.html#price" class="tsd-kind-icon">price</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
<li class=" tsd-kind-interface <API key>">
<a href="_src_lib_orderbook_.pricelevel.html" class="tsd-kind-icon">Price<wbr>Level</a>
</li>
<li class=" tsd-kind-interface <API key>">
<a href="_src_lib_orderbook_.<API key>.html" class="tsd-kind-icon">Price<wbr>Level<wbr>With<wbr>Orders</a>
</li>
<li class=" tsd-kind-function <API key>">
<a href="../modules/_src_lib_orderbook_.html#pricelevelfactory" class="tsd-kind-icon">Price<wbr>Level<wbr>Factory</a>
</li>
<li class=" tsd-kind-function <API key> <API key>">
<a href="../modules/_src_lib_orderbook_.html#pricetreefactory" class="tsd-kind-icon">Price<wbr>Tree<wbr>Factory</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="<API key>"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function <API key>"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="<API key>"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="<API key>"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property <API key>"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method <API key>"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface <API key>"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="<API key> <API key>"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property <API key>"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method <API key>"><span class="tsd-kind-icon">Method</span></li>
<li class="<API key> <API key>"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class <API key>"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="<API key> <API key>"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property <API key>"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method <API key>"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor <API key>"><span class="tsd-kind-icon">Accessor</span></li>
<li class="<API key> <API key>"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="<API key> <API key> tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property <API key> tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method <API key> tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor <API key> tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property <API key> tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method <API key> tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor <API key> tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property <API key> tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method <API key> tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor <API key> tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property <API key> tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="<API key> <API key> tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.org/" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html>
|
#define DEBUG_TYPE "sil-simplify-cfg"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h"
#include "swift/SILOptimizer/Utils/CFG.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SILOptimizer/Utils/SILInliner.h"
using namespace swift;
namespace {
This is a class implementing a dominator-based jump-threading
for checked_cast_br [exact].
class <API key> {
// The checked_cast_br instruction, which
// we try to jump-thread
<API key> *CCBI;
// Basic block of the current checked_cast_br instruction.
SILBasicBlock *BB;
// Condition used by the current checked_cast_br instruction.
SILValue Condition;
// Success branch of the current checked_cast_br instruction.
SILBasicBlock *SuccessBB;
// Failure branch of the current checked_cast_br instruction.
SILBasicBlock *FailureBB;
// Current dominating checked_cast_br instruction.
<API key> *DomCCBI;
// Basic block of the dominating checked_cast_br instruction.
SILBasicBlock *DomBB;
// Condition used by the dominating checked_cast_br instruction.
SILValue DomCondition;
// Success branch of the dominating checked_cast_br instruction.
SILBasicBlock *DomSuccessBB;
// Failure branch of the dominating checked_cast_br instruction.
SILBasicBlock *DomFailureBB;
// Current dominator tree node where we look for a dominating
// checked_cast_br instruction.
llvm::DomTreeNodeBase<SILBasicBlock> *Node;
SILBasicBlock *ArgBB;
// Dominator information to be used.
DominanceInfo *DT;
// Basic block created as a landing BB for all failure predecessors.
SILBasicBlock *TargetFailureBB;
// Basic block created as a landing BB for all success predecessors.
SILBasicBlock *TargetSuccessBB;
// Cloner used to clone the BB to FailureSuccessBB.
Optional<BasicBlockCloner> FailureBBCloner;
// Cloner used to clone the BB to TargetSuccessBB.
Optional<BasicBlockCloner> SuccessBBCloner;
// Predecessors reached only via a path along the
// success branch of the dominating checked_cast_br.
SmallVector<SILBasicBlock *, 8> SuccessPreds;
// Predecessors reached only via a path along the
// failure branch of the dominating checked_cast_br.
SmallVector<SILBasicBlock *, 8> FailurePreds;
// All other predecessors, where the outcome of the
// checked_cast_br along the path is not known.
SmallVector<SILBasicBlock *, 8> UnknownPreds;
// Basic blocks to be added to for reprocessing
// after jump-threading is done.
SmallVectorImpl<SILBasicBlock *> &BlocksForWorklist;
bool <API key>();
bool <API key>();
bool <API key>(SILBasicBlock *ArgBB);
bool <API key>();
void <API key>();
void <API key>();
void <API key>();
void updateDominatorTree();
void updateSSA();
void <API key>(SILBasicBlock *BB);
void addBlocksToWorklist();
void classifyPredecessor(
SILBasicBlock *Pred,
SmallVectorImpl<SILBasicBlock *> &SuccessPreds,
SmallVectorImpl<SILBasicBlock *> &FailurePreds,
SmallVectorImpl<SILBasicBlock *> &UnknownPreds,
bool SuccessDominates,
bool FailureDominates);
SILValue <API key>(SILValue Value,
SILBasicBlock *DomBB,
SILValue DomValue,
DominanceInfo *DT);
public:
<API key>(DominanceInfo *DT,
SmallVectorImpl<SILBasicBlock *> &BBs)
: DT(DT), BlocksForWorklist(BBs) { }
bool trySimplify(TermInst *Term);
ArrayRef<SILBasicBlock*> <API key>() {
return BlocksForWorklist;
}
};
} // end anonymous namespace
Find a nearest common dominator for a given set of basic blocks.
static DominanceInfoNode *findCommonDominator(ArrayRef<SILBasicBlock *> BBs,
DominanceInfo *DT) {
DominanceInfoNode *CommonDom = nullptr;
for (auto *BB : BBs) {
if (!CommonDom) {
CommonDom = DT->getNode(BB);
} else {
CommonDom = DT->getNode(
DT-><API key>(CommonDom->getBlock(), BB));
}
}
return CommonDom;
}
Find a nearest common dominator for all predecessors of
a given basic block.
static DominanceInfoNode *findCommonDominator(SILBasicBlock *BB,
DominanceInfo *DT) {
SmallVector<SILBasicBlock *, 8> Preds;
for (auto *Pred: BB->getPreds())
Preds.push_back(Pred);
return findCommonDominator(Preds, DT);
}
Estimate the cost of inlining a given basic block.
static unsigned <API key>(SILBasicBlock *BB, unsigned Cutoff) {
unsigned Cost = 0;
for (auto &I : *BB) {
auto ICost = <API key>(I);
Cost += unsigned(ICost);
if (Cost > Cutoff)
return Cost;
}
return Cost;
}
We cannot duplicate blocks with AllocStack instructions (they need to be
FIFO). Other instructions can be duplicated.
static bool canDuplicateBlock(SILBasicBlock *BB) {
for (auto &I : *BB) {
if (!I.<API key>())
return false;
}
return true;
}
void <API key>::<API key>(SILBasicBlock *BB) {
BlocksForWorklist.push_back(BB);
}
Add affected blocks for re-processing by simplifyCFG
void <API key>::addBlocksToWorklist() {
if (TargetFailureBB) {
if (!TargetFailureBB->pred_empty())
<API key>(TargetFailureBB);
}
if (TargetSuccessBB) {
if (!TargetSuccessBB->pred_empty())
<API key>(TargetSuccessBB);
}
if (!BB->pred_empty())
<API key>(BB);
}
Classify a predecessor of a BB containing checked_cast_br as being
reachable via success or failure branches of a dominating checked_cast_br
or as unknown if it can be reached via success or failure branches
at the same time.
void <API key>::classifyPredecessor(
SILBasicBlock *Pred,
SmallVectorImpl<SILBasicBlock *> &SuccessPreds,
SmallVectorImpl<SILBasicBlock *> &FailurePreds,
SmallVectorImpl<SILBasicBlock *> &UnknownPreds,
bool SuccessDominates,
bool FailureDominates) {
if (SuccessDominates && FailureDominates) {
UnknownPreds.push_back(Pred);
return;
}
if (SuccessDominates) {
SuccessPreds.push_back(Pred);
return;
}
if (FailureDominates) {
FailurePreds.push_back(Pred);
return;
}
UnknownPreds.push_back(Pred);
}
Check if the root value for Value that comes
along the path from DomBB is equivalent to the
DomCondition.
SILValue <API key>::<API key>(
SILValue Value, SILBasicBlock *DomBB, SILValue DomValue,
DominanceInfo *DT) {
SmallPtrSet<ValueBase *, 16> SeenValues;
DomValue = DomValue.stripClassCasts();
while (true) {
Value = Value.stripClassCasts();
if (Value == DomValue)
return Value;
// We know how to propagate through BBArgs only.
auto *V = dyn_cast<SILArgument>(Value);
if (!V)
return SILValue();
// Have we visited this BB already?
if (!SeenValues.insert(Value.getDef()).second)
return SILValue();
if (SeenValues.size() > 10)
return SILValue();
SmallVector<SILValue, 4> IncomingValues;
if (!V->getIncomingValues(IncomingValues) || IncomingValues.empty())
return SILValue();
ValueBase *Def = nullptr;
for (auto IncomingValue : IncomingValues) {
// Each incoming value should be either from a block
// dominated by DomBB or it should be the value used in
// condition in DomBB
Value = IncomingValue.stripClassCasts();
if (Value == DomValue)
continue;
// Values should be the same
if (!Def)
Def = Value.getDef();
if (Def != Value.getDef())
return SILValue();
if (!DT->dominates(DomBB, Value.getDef()->getParentBB()))
return SILValue();
// OK, this value is a potential candidate
}
Value = IncomingValues[0];
}
}
Update the SSA form after all changes.
void <API key>::updateSSA() {
assert(!(SuccessBBCloner.hasValue() && FailureBBCloner.hasValue()) &&
"Both cloners cannot be used at the same time yet");
// Now update the SSA form.
if (!FailurePreds.empty() && FailureBBCloner.hasValue() &&
!SuccessBBCloner.hasValue())
<API key>(*FailureBBCloner.getPointer(), TargetFailureBB, BB);
if (SuccessBBCloner.hasValue() && !FailureBBCloner.hasValue()) {
<API key>(*SuccessBBCloner.getPointer(), TargetSuccessBB, BB);
}
}
Update the SSA form after all changes.
void <API key>::updateDominatorTree() {
// Update the dominator tree.
// If BB was IDom of something, then PredCBBI becomes the IDOM
// of this after jump-threading.
auto *BBDomNode = DT->getNode(BB);
auto &Children = BBDomNode->getChildren();
if (Children.size() > 1) {
SmallVector<DominanceInfoNode *, 16> ChildrenCopy;
std::copy(Children.begin(), Children.end(),
std::back_inserter(ChildrenCopy));
for (auto *Child : ChildrenCopy) {
DT-><API key>(Child, Node);
}
}
DominanceInfoNode *CommonDom;
// Find a common dominator for all unknown preds.
if (!UnknownPreds.empty()) {
// Find a new IDom for FailureBB
CommonDom = findCommonDominator(FailureBB, DT);
if (CommonDom)
DT-><API key>(FailureBB, CommonDom->getBlock());
CommonDom = findCommonDominator(UnknownPreds, DT);
// This common dominator dominates the BB now.
if (CommonDom) {
DT-><API key>(BB, CommonDom->getBlock());
}
}
// Find a common dominator for all failure preds.
CommonDom = findCommonDominator(FailurePreds, DT);
// This common dominator dominates the TargetFailureBB now.
if (CommonDom) {
DT->addNewBlock(TargetFailureBB, CommonDom->getBlock());
// Find a new IDom for FailureBB
CommonDom = findCommonDominator(FailureBB, DT);
if (CommonDom)
DT-><API key>(FailureBB, CommonDom->getBlock());
}
// Find a common dominator for all success preds.
CommonDom = findCommonDominator(SuccessPreds, DT);
// This common dominator of all success preds dominates the BB now.
if (CommonDom) {
if (TargetSuccessBB) {
DT->addNewBlock(TargetSuccessBB, CommonDom->getBlock());
} else {
DT-><API key>(BB, CommonDom->getBlock());
}
CommonDom = findCommonDominator(SuccessBB, DT);
if (CommonDom)
DT-><API key>(SuccessBB, CommonDom->getBlock());
}
// End of dominator tree update.
}
void <API key>::<API key>() {
if (UnknownPreds.empty())
return;
// Check the FailureBB if it is a BB that contains a class_method
// referring to the same value as a condition. This pattern is typical
// for method chaining code like obj.method1().method2().etc()
SILInstruction *Inst = &*FailureBB->begin();
if (ClassMethodInst *CMI = dyn_cast<ClassMethodInst>(Inst)) {
if (CMI->getOperand() == Condition) {
// Replace checked_cast_br by branch to FailureBB.
SILBuilder(BB).createBranch(CCBI->getLoc(), FailureBB);
CCBI->eraseFromParent();
}
}
}
Create a copy of the BB as a landing BB
for all FailurePreds.
void <API key>::<API key>() {
if (FailurePreds.empty())
return;
FailureBBCloner.emplace(BasicBlockCloner(BB));
FailureBBCloner->clone();
TargetFailureBB = FailureBBCloner->getDestBB();
auto *TI = TargetFailureBB->getTerminator();
SILBuilderWithScope Builder(TI);
// This BB copy branches to a FailureBB.
Builder.createBranch(TI->getLoc(), FailureBB);
TI->eraseFromParent();
// Redirect all FailurePreds to the copy of BB.
for (auto *Pred : FailurePreds) {
TermInst *TI = Pred->getTerminator();
// Replace branch to BB by branch to TargetFailureBB.
replaceBranchTarget(TI, BB, TargetFailureBB, /*PreserveArgs=*/true);
Pred = nullptr;
}
}
Create a copy of the BB or reuse BB as
a landing basic block for all FailurePreds.
void <API key>::<API key>() {
if (!UnknownPreds.empty()) {
if (!SuccessPreds.empty()) {
// Create a copy of the BB as a landing BB.
// for all SuccessPreds.
SuccessBBCloner.emplace(BasicBlockCloner(BB));
SuccessBBCloner->clone();
TargetSuccessBB = SuccessBBCloner->getDestBB();
auto *TI = TargetSuccessBB->getTerminator();
SILBuilderWithScope Builder(TI);
SmallVector<SILValue, 8> SuccessBBArgs;
// Take argument value from the dominating BB.
SuccessBBArgs.push_back(DomSuccessBB->getBBArg(0));
// This BB copy branches to SuccessBB.
Builder.createBranch(TI->getLoc(), SuccessBB, SuccessBBArgs);
TI->eraseFromParent();
// Redirect all SuccessPreds to the copy of BB.
for (auto *Pred : SuccessPreds) {
TermInst *TI = Pred->getTerminator();
// Replace branch to BB by branch to TargetSuccessBB.
replaceBranchTarget(TI, BB, TargetSuccessBB, /*PreserveArgs=*/true);
SuccessBBArgs.push_back(DomSuccessBB->getBBArg(0));
Pred = nullptr;
}
}
} else {
// There are no predecessors where it is not clear
// if they are dominated by a success or failure branch
// of DomBB. Therefore, there is no need to clone
// the BB for SuccessPreds. Current BB can be re-used
// instead as their target.
// Add an unconditional jump at the end of the block.
SmallVector<SILValue, 1> SuccessBBArgs;
// Take argument value from the dominating BB
SuccessBBArgs.push_back(DomSuccessBB->getBBArg(0));
SILBuilder(BB).createBranch(CCBI->getLoc(), SuccessBB, SuccessBBArgs);
CCBI->eraseFromParent();
}
}
Handle a special case, where ArgBB is the entry block.
bool <API key>::<API key>(SILBasicBlock *ArgBB) {
if (ArgBB->getPreds().begin() == ArgBB->getPreds().end()) {
// It must be the entry block
// See if it is reached over Success or Failure path.
bool SuccessDominates = DomSuccessBB == BB;
bool FailureDominates = DomFailureBB == BB;
classifyPredecessor(ArgBB, SuccessPreds, FailurePreds, UnknownPreds,
SuccessDominates, FailureDominates);
return true;
}
return false;
}
// Returns false if cloning required by jump threading cannot
// be performed, because some of the constraints are violated.
bool <API key>::<API key>() {
// Check some cloning related constraints.
// If this argument from a different BB, then jump-threading
// may require too much code duplication.
if (ArgBB && ArgBB != BB)
return false;
// Bail out if current BB cannot be duplicated.
if (!canDuplicateBlock(BB))
return false;
// Check if code-bloat would be too big when this BB
// is jump-threaded.
// TODO: Make InlineCostCutoff parameter configurable?
// Dec 1, 2014:
// We looked at the inline costs of BBs from our benchmark suite
// and found that currently the highest inline cost for the
// whole benchmark suite is 12. In 95% of all cases it is <=3.
const unsigned InlineCostCutoff = 20;
if (<API key>(BB, InlineCostCutoff) >= InlineCostCutoff)
return false;
return true;
}
If conditions are not equivalent along all paths, try harder
to check if they are actually equivalent along a subset of paths.
To do it, try to back-propagate the Condition
backwards and see if it is actually equivalent to DomCondition.
along some of the paths.
bool <API key>::<API key>() {
auto *Arg = dyn_cast<SILArgument>(Condition);
if (!Arg)
return false;
ArgBB = Arg->getParent();
if (!DT->dominates(DomBB, ArgBB))
return false;
// Incoming values for the BBArg.
SmallVector<SILValue, 4> IncomingValues;
if (ArgBB != ArgBB->getParent()->begin() &&
(!Arg->getIncomingValues(IncomingValues) || IncomingValues.empty()))
return false;
// Check for each predecessor, if the incoming value coming from it
// is equivalent to the DomCondition. If this is the case, it is
// possible to try jump-threading along this path.
if (!<API key>(ArgBB)) {
// ArgBB is not the entry block and has predecessors.
unsigned idx = 0;
for (auto *PredBB : ArgBB->getPreds()) {
auto IncomingValue = IncomingValues[idx];
SILValue ReachingValue = <API key>(
IncomingValue, DomBB, DomCondition, DT);
if (ReachingValue == SILValue()) {
UnknownPreds.push_back(PredBB);
idx++;
continue;
}
// Condition is the same if BB is reached over a pass through Pred.
DEBUG(llvm::dbgs() << "Condition is the same if reached over ");
DEBUG(PredBB->print(llvm::dbgs()));
// See if it is reached over Success or Failure path.
bool SuccessDominates = DT->dominates(DomSuccessBB, PredBB) ||
DT->dominates(DomSuccessBB, BB) ||
DomSuccessBB == BB;
bool FailureDominates = DT->dominates(DomFailureBB, PredBB) ||
DT->dominates(DomFailureBB, BB) ||
DomFailureBB == BB;
classifyPredecessor(
PredBB, SuccessPreds, FailurePreds, UnknownPreds,
SuccessDominates, FailureDominates);
idx++;
}
} else {
// ArgBB is the entry block. Check that conditions are the equivalent in this
// case as well.
if (!<API key>(Condition, DomBB, DomCondition, DT))
return false;
}
// At this point we know for each predecessor of ArgBB if its reached
// over the success, failure or unknown path from DomBB.
// Now we can generate a new BB for preds reaching BB over the success
// path and a new BB for preds reaching BB over the failure path.
// Then we redirect those preds to those new basic blocks.
return true;
}
Check if conditions of CCBI and DomCCBI are equivalent along
all or at least some paths.
bool <API key>::<API key>() {
// Are conditions equivalent along all paths?
if (DomCondition == Condition) {
// Conditions are exactly the same, without any restrictions.
// They are equivalent along all paths.
// Figure out for each predecessor which branch of
// the dominating checked_cast_br is used to reach it.
for (auto *PredBB : BB->getPreds()) {
// All predecessors should either unconditionally branch
// to the current BB or be another checked_cast_br instruction.
if (!dyn_cast<<API key>>(PredBB->getTerminator()) &&
!dyn_cast<BranchInst>(PredBB->getTerminator()))
return false;
bool SuccessDominates =
DT->dominates(DomSuccessBB, PredBB) || DomSuccessBB == BB;
bool FailureDominates =
DT->dominates(DomFailureBB, PredBB) || DomFailureBB == BB;
classifyPredecessor(PredBB, SuccessPreds, FailurePreds, UnknownPreds,
SuccessDominates, FailureDominates);
}
return true;
}
// Check if conditions are equivalent along a subset of reaching paths.
return <API key>();
}
Try performing a dominator-based jump-threading for
checked_cast_br instructions.
bool <API key>::trySimplify(TermInst *Term) {
CCBI = cast<<API key>>(Term);
if (!CCBI)
return false;
// Init information about the checked_cast_br we try to
// jump-thread.
BB = Term->getParent();
Condition = Term->getOperand(0).stripClassCasts();
SuccessBB = CCBI->getSuccessBB();
FailureBB = CCBI->getFailureBB();
// Find a dominating checked_cast_br, which performs the same check.
for (Node = DT->getNode(BB)->getIDom(); Node; Node = Node->getIDom()) {
// Get current dominating block.
DomBB = Node->getBlock();
auto *DomTerm = DomBB->getTerminator();
if (!DomTerm->getNumOperands())
continue;
// Check that it is a dominating checked_cast_br.
DomCCBI = dyn_cast<<API key>>(DomTerm);
if (!DomCCBI)
continue;
// We need to verify that the result type is the same in the
// dominating checked_cast_br, but only for non-exact casts.
// For exact casts, we are interested only in the
// fact that the source operand is the same for
// both instructions.
if (!CCBI->isExact() && !DomCCBI->isExact()) {
if (DomCCBI->getCastType() != CCBI->getCastType())
continue;
}
// Conservatively check that both checked_cast_br instructions
// are either exact or non-exact. This is very conservative,
// but safe.
// TODO:
// If the dominating checked_cast_br is non-exact, then
// it is in general not safe to assume that current exact cast
// would have the same outcome. But if the dominating non-exact
// checked_cast_br fails, then the current exact cast would
// always fail as well.
// If the dominating checked_cast_br is exact then then
// it is in general not safe to assume that the current non-exact
// cast would have the same outcome. But if the dominating exact
// checked_cast_br succeeds, then the current non-exact cast
// would always succeed as well.
// TODO: In some specific cases, it is possible to prove that
// success or failure of the dominating cast is equivalent to
// the success or failure of the current cast, even if one
// of them is exact and the other not. This is the case
// e.g. if the class has no subclasses.
if (DomCCBI->isExact() != CCBI->isExact())
continue;
// Initialize state variables for the current round of checks
// based on the found dominating checked_cast_br.
DomSuccessBB = DomCCBI->getSuccessBB();
DomFailureBB = DomCCBI->getFailureBB();
DomCondition = DomTerm->getOperand(0).stripClassCasts();
// Init state variables for paths analysis
SuccessPreds.clear();
FailurePreds.clear();
UnknownPreds.clear();
ArgBB = nullptr;
// Init state variables for jump-threading transformation.
TargetFailureBB = nullptr;
TargetSuccessBB = nullptr;
// Are conditions of CCBI and DomCCBI equivalent along (some) paths?
// If this is the case, classify all incoming paths into SuccessPreds,
// FailurePreds or UnknownPreds depending on how they reach CCBI.
if (!<API key>())
continue;
// Check if any jump-threading is required and possible.
if (SuccessPreds.empty() && FailurePreds.empty())
return false;
// If this check is reachable via success, failure and unknown
// at the same time, then we don't know the outcome of the
// dominating check. No jump-threading is possible in this case.
if (!SuccessPreds.empty() && !FailurePreds.empty() &&
!UnknownPreds.empty()) {
return false;
}
unsigned TotalPreds =
SuccessPreds.size() + FailurePreds.size() + UnknownPreds.size();
// We only need to clone the BB if not all of its
// predecessors are in the same group.
if (TotalPreds != SuccessPreds.size() &&
TotalPreds != UnknownPreds.size()) {
// Check some cloning related constraints.
if (!<API key>())
return false;
}
bool InvertSuccess = false;
if (DomCCBI->isExact() && CCBI->isExact() &&
DomCCBI->getCastType() != CCBI->getCastType()) {
if (TotalPreds == SuccessPreds.size()) {
// The dominating exact cast was successful, but it casted to a
// different type. Therefore, the current cast fails for sure.
// Since we are going to change the BB,
// add its successors and predecessors
// for re-processing.
InvertSuccess = true;
} else {
// Otherwise, we don't know if the current cast will succeed or
// fail.
return false;
}
}
// If we have predecessors, where it is not known if they are reached over
// success or failure path, we cannot eliminate a checked_cast_br.
// We have to generate new dedicated BBs as landing BBs for all
// FailurePreds and all SuccessPreds.
// Since we are going to change the BB,
// add its successors and predecessors
// for re-processing.
for (auto *B : BB->getPreds()) {
<API key>(B);
}
for (auto *B : BB->getSuccessorBlocks()) {
<API key>(B);
}
// Create a copy of the BB as a landing BB
// for all FailurePreds.
<API key>();
if (InvertSuccess) {
SILBuilder(BB).createBranch(CCBI->getLoc(), FailureBB);
CCBI->eraseFromParent();
SuccessPreds.clear();
} else {
// Create a copy of the BB or reuse BB as
// a landing basic block for all SuccessPreds.
<API key>();
}
// Handle unknown preds.
<API key>();
// Update the dominator tree after all changes.
updateDominatorTree();
// Update the SSA form after all changes.
updateSSA();
// Since a few BBs were changed now, add them for re-processing.
addBlocksToWorklist();
return true;
}
// Jump-threading was not possible.
return false;
}
namespace swift {
bool <API key>(TermInst *Term, DominanceInfo *DT,
SmallVectorImpl<SILBasicBlock *> &BBs) {
<API key> CCBJumpThreading(DT, BBs);
return CCBJumpThreading.trySimplify(Term);
}
} // end namespace swift
|
package jp.co.omana.action;
import org.seasar.struts.annotation.Execute;
public class ServiceAction {
@Execute(validator = false)
public String index() {
return "board.jsp";
}
@Execute(validator = false)
public String confirm() {
return "index.jsp";
}
@Execute(validator = false)
public String finish() {
return "index.jsp";
}
}
|
from turbo.flux import Mutation, register, dispatch, register_dispatch
import mutation_types
@register_dispatch('user', mutation_types.INCREASE)
def increase(rank):
pass
def decrease(rank):
return dispatch('user', mutation_types.DECREASE, rank)
@register_dispatch('metric', 'inc_qps')
def inc_qps():
pass
|
package com.sivalabs.demo.orders.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.sivalabs.demo.orders.entities.Order;
/**
* @author Siva
*
*/
public interface OrderRepository extends JpaRepository<Order, Integer>{
}
|
var structCO__config__t =
[
[ "CNT_NMT", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1017", "structCO__config__t.html#<API key>", null ],
[ "CNT_HB_CONS", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1016", "structCO__config__t.html#<API key>", null ],
[ "CNT_EM", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1001", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1014", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1015", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1003", "structCO__config__t.html#<API key>", null ],
[ "CNT_SDO_SRV", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1200", "structCO__config__t.html#<API key>", null ],
[ "CNT_SDO_CLI", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1280", "structCO__config__t.html#<API key>", null ],
[ "CNT_TIME", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1012", "structCO__config__t.html#<API key>", null ],
[ "CNT_SYNC", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1005", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1006", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1007", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1019", "structCO__config__t.html#<API key>", null ],
[ "CNT_RPDO", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1400", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1600", "structCO__config__t.html#<API key>", null ],
[ "CNT_TPDO", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1800", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1A00", "structCO__config__t.html#<API key>", null ],
[ "CNT_LEDS", "structCO__config__t.html#<API key>", null ],
[ "CNT_GFC", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1300", "structCO__config__t.html#<API key>", null ],
[ "CNT_SRDO", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1301", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H1381", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H13FE", "structCO__config__t.html#<API key>", null ],
[ "ENTRY_H13FF", "structCO__config__t.html#<API key>", null ],
[ "CNT_LSS_SLV", "structCO__config__t.html#<API key>", null ],
[ "CNT_LSS_MST", "structCO__config__t.html#<API key>", null ],
[ "CNT_GTWA", "structCO__config__t.html#<API key>", null ],
[ "CNT_TRACE", "structCO__config__t.html#<API key>", null ]
];
|
#include <tuple>
#include "Vector2.h"
Vector2::Vector2(void)
{
}
Vector2::Vector2(float X, float Y)
{
this->X = X;
this->Y = Y;
}
// Returns the length of the vector
float Vector2::Magnitude()
{
return sqrt(X * X + Y * Y);
}
// Returns the length of the vector squared
// Used for length comparisons without needing roots
float Vector2::MagnitudeSquared()
{
return X * X + Y * Y;
}
// Normalizes the vector
Vector2 Vector2::Normal()
{
float length = this->Magnitude();
if (length != 0)
return Vector2(X / length, Y / length);
return Vector2();
}
// Sets the magnitude of the vector
void Vector2::SetMagnitude(float mag)
{
Vector2 v = this->Normal();
X = v.X*mag;
Y = v.Y*mag;
}
float Vector2::Dot(Vector2 other)
{
return X * other.X + Y * other.Y;
}
float Vector2::Cross(Vector2 other)
{
return X * other.Y - Y * other.X;
}
Vector2 Vector2::operator+(Vector2 other)
{
return Vector2(X + other.X, Y + other.Y);
}
Vector2 Vector2::operator-(Vector2 other)
{
return Vector2(X - other.X, Y - other.Y);
}
Vector2 Vector2::operator*(float scalar)
{
return Vector2(X * scalar, Y * scalar);
}
Vector2 Vector2::operator-()
{
return Vector2(-X, -Y);
}
Vector2& Vector2::operator+=(const Vector2& other)
{
X += other.X;
Y += other.Y;
return *this;
}
Vector2& Vector2::operator-=(const Vector2& other)
{
X -= other.X;
Y -= other.Y;
return *this;
}
Vector2& Vector2::operator*=(const Vector2& other)
{
X *= other.X;
Y *= other.Y;
return *this;
}
Vector2& Vector2::operator/=(const Vector2& other)
{
X /= other.X;
Y /= other.Y;
return *this;
}
bool operator==(const Vector2& L, const Vector2& R)
{
return std::tie(L.X, L.Y) == std::tie(R.X, R.Y);
}
|
package com.easemob.chatuidemo.activity;
import java.io.<API key>;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.media.<API key>;
import android.media.<API key>.<API key>;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
import com.easemob.chatuidemo.utils.CommonUtils;
import com.easemob.chatuidemo.video.util.Utils;
import com.easemob.qixin.R;
import com.easemob.util.EMLog;
import com.easemob.util.PathUtil;
public class <API key> extends BaseActivity implements
OnClickListener, SurfaceHolder.Callback, OnErrorListener,
OnInfoListener {
private static final String TAG = "<API key>";
private final static String CLASS_LABEL = "RecordActivity";
private PowerManager.WakeLock mWakeLock;
private ImageView btnStart;
private ImageView btnStop;
private MediaRecorder mediaRecorder;
private VideoView mVideoView;
String localPath = "";
private Camera mCamera;
private int previewWidth = 480;
private int previewHeight = 480;
private Chronometer chronometer;
private int frontCamera = 0;
private Button btn_switch;
Parameters cameraParameters = null;
private SurfaceHolder mSurfaceHolder;
int <API key> = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
<API key>(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// surfaceviewactivity
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.recorder_activity);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.<API key>,
CLASS_LABEL);
mWakeLock.acquire();
initViews();
}
private void initViews() {
btn_switch = (Button) findViewById(R.id.switch_btn);
btn_switch.setOnClickListener(this);
btn_switch.setVisibility(View.VISIBLE);
mVideoView = (VideoView) findViewById(R.id.mVideoView);
btnStart = (ImageView) findViewById(R.id.recorder_start);
btnStop = (ImageView) findViewById(R.id.recorder_stop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
mSurfaceHolder = mVideoView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.<API key>);
chronometer = (Chronometer) findViewById(R.id.chronometer);
}
public void back(View view) {
releaseRecorder();
releaseCamera();
finish();
}
@Override
protected void onResume() {
super.onResume();
if (mWakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.<API key>,
CLASS_LABEL);
mWakeLock.acquire();
}
// if (!initCamera()) {
// showFailDialog();
}
@SuppressLint("NewApi")
private boolean initCamera() {
try {
if (frontCamera == 0) {
mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
} else {
mCamera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);
}
Camera.Parameters camParams = mCamera.getParameters();
mCamera.lock();
mSurfaceHolder = mVideoView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.<API key>);
mCamera.<API key>(90);
} catch (RuntimeException ex) {
EMLog.e("video", "init Camera fail " + ex.getMessage());
return false;
}
return true;
}
private void <API key>() {
if (mCamera == null) {
finish();
return;
}
boolean hasSupportRate = false;
List<Integer> <API key> = mCamera.getParameters()
.<API key>();
if (<API key> != null
&& <API key>.size() > 0) {
Collections.sort(<API key>);
for (int i = 0; i < <API key>.size(); i++) {
int supportRate = <API key>.get(i);
if (supportRate == 15) {
hasSupportRate = true;
}
}
if (hasSupportRate) {
<API key> = 15;
} else {
<API key> = <API key>.get(0);
}
}
List<Camera.Size> resolutionList = Utils.getResolutionList(mCamera);
if (resolutionList != null && resolutionList.size() > 0) {
Collections.sort(resolutionList, new Utils.<API key>());
Camera.Size previewSize = null;
boolean hasSize = false;
// 640*480640*480
for (int i = 0; i < resolutionList.size(); i++) {
Size size = resolutionList.get(i);
if (size != null && size.width == 640 && size.height == 480) {
previewSize = size;
previewWidth = previewSize.width;
previewHeight = previewSize.height;
hasSize = true;
break;
}
}
if (!hasSize) {
int mediumResolution = resolutionList.size() / 2;
if (mediumResolution >= resolutionList.size())
mediumResolution = resolutionList.size() - 1;
previewSize = resolutionList.get(mediumResolution);
previewWidth = previewSize.width;
previewHeight = previewSize.height;
}
}
}
@Override
protected void onPause() {
super.onPause();
if (mWakeLock != null) {
mWakeLock.release();
mWakeLock = null;
}
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.switch_btn:
switchCamera();
break;
case R.id.recorder_start:
// start recording
if(!startRecording())
return;
Toast.makeText(this, R.string.The_video_to_start, Toast.LENGTH_SHORT).show();
btn_switch.setVisibility(View.INVISIBLE);
btnStart.setVisibility(View.INVISIBLE);
btnStart.setEnabled(false);
btnStop.setVisibility(View.VISIBLE);
chronometer.setBase(SystemClock.elapsedRealtime());
chronometer.start();
break;
case R.id.recorder_stop:
btnStop.setEnabled(false);
stopRecording();
btn_switch.setVisibility(View.VISIBLE);
chronometer.stop();
btnStart.setVisibility(View.VISIBLE);
btnStop.setVisibility(View.INVISIBLE);
new AlertDialog.Builder(this)
.setMessage(R.string.Whether_to_send)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
sendVideo(null);
}
})
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
if(localPath != null){
File file = new File(localPath);
if(file.exists())
file.delete();
}
finish();
}
}).setCancelable(false).show();
break;
default:
break;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// holderholderoncreatholdersurfaceHolder
mSurfaceHolder = holder;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (mCamera == null){
if(!initCamera()){
showFailDialog();
return;
}
}
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.startPreview();
<API key>();
} catch (Exception e1) {
EMLog.e("video", "start preview fail " + e1.getMessage());
showFailDialog();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
EMLog.v("video", "surfaceDestroyed");
}
public boolean startRecording(){
if (mediaRecorder == null){
if(!initRecorder())
return false;
}
mediaRecorder.setOnInfoListener(this);
mediaRecorder.setOnErrorListener(this);
mediaRecorder.start();
return true;
}
@SuppressLint("NewApi")
private boolean initRecorder(){
if(!CommonUtils.isExitsSdcard()){
showNoSDCardDialog();
return false;
}
if (mCamera == null) {
if(!initCamera()){
showFailDialog();
return false;
}
}
mVideoView.setVisibility(View.VISIBLE);
// TODO init button
mCamera.stopPreview();
mediaRecorder = new MediaRecorder();
mCamera.unlock();
mediaRecorder.setCamera(mCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
// Camera
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
if (frontCamera == 1) {
mediaRecorder.setOrientationHint(270);
} else {
mediaRecorder.setOrientationHint(90);
}
// THREE_GPP3gp.MPEG_4mp4
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
// h263 h264
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
mediaRecorder.setVideoSize(previewWidth, previewHeight);
mediaRecorder.<API key>(384 * 1024);
if (<API key> != -1) {
mediaRecorder.setVideoFrameRate(<API key>);
}
localPath = PathUtil.getInstance().getVideoPath() + "/"
+ System.currentTimeMillis() + ".mp4";
mediaRecorder.setOutputFile(localPath);
mediaRecorder.setMaxDuration(30000);
mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
try {
mediaRecorder.prepare();
} catch (<API key> e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public void stopRecording() {
if (mediaRecorder != null) {
mediaRecorder.setOnErrorListener(null);
mediaRecorder.setOnInfoListener(null);
try {
mediaRecorder.stop();
} catch (<API key> e) {
EMLog.e("video", "stopRecording error:" + e.getMessage());
}
}
releaseRecorder();
if (mCamera != null) {
mCamera.stopPreview();
releaseCamera();
}
}
private void releaseRecorder() {
if (mediaRecorder != null) {
mediaRecorder.release();
mediaRecorder = null;
}
}
protected void releaseCamera() {
try {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
} catch (Exception e) {
}
}
@SuppressLint("NewApi")
public void switchCamera() {
if (mCamera == null) {
return;
}
if (Camera.getNumberOfCameras() >= 2) {
btn_switch.setEnabled(false);
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
switch (frontCamera) {
case 0:
mCamera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);
frontCamera = 1;
break;
case 1:
mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
frontCamera = 0;
break;
}
try {
mCamera.lock();
mCamera.<API key>(90);
mCamera.setPreviewDisplay(mVideoView.getHolder());
mCamera.startPreview();
} catch (IOException e) {
mCamera.release();
mCamera = null;
}
btn_switch.setEnabled(true);
}
}
<API key> msc = null;
ProgressDialog progressDialog = null;
public void sendVideo(View view) {
if (TextUtils.isEmpty(localPath)) {
EMLog.e("Recorder", "recorder fail please try again!");
return;
}
if(msc == null)
msc = new <API key>(this,
new <API key>() {
@Override
public void onScanCompleted(String path, Uri uri) {
EMLog.d(TAG, "scanner completed");
msc.disconnect();
progressDialog.dismiss();
setResult(RESULT_OK, getIntent().putExtra("uri", uri));
finish();
}
@Override
public void <API key>() {
|
@font-face {
font-family: 'Braille';
src: url(http://tjb0607.me/i3_tumblr_theme/font/Braille.woff);
}
html {
background-color: #7C8491;
background-image: url(http://static.tumblr.com/bwey4ra/Gzwno4oq5/sunset.jpg);
background-position: bottom;
<API key>: fixed;
height: 100%;
margin: 0px;
-<API key>: cover;
background-size: cover;
font-family: Inconsolata, monospace;
font-size: 11px;
color: #fff;
}
#tumblr_controls {
margin-top: 18px;
}
p, code {
line-height: 11px;
margin: 0px;
}
a, #sidebar .blogdescription a, .jslink {
color: #5FD7FF;
text-decoration: underline;
cursor: pointer;
}
ul {
padding-left: 11px;
}
#i3bar {
overflow: hidden;
color: #dedede;
position: fixed;
z-index: 1;
top: 0px;
left: 0px;
right: 0px;
height: 18px;
background-color: #2d2d2d;
}
#i3bar p {
margin: 3px 8px;
}
#sidebar {
position: fixed;
top: 47px;
left: 35px;
bottom: 35px;
width: 450px;
}
.short-info .separator {
color: #808080;
}
.window {
overflow: auto;
position: relative;
margin: 10px;
border: 2px solid #2d2d2d;
box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.75);
}
.window:hover, html:hover #active-window {
border-color: #D64937;
}
.window:hover .cursor, html:hover #active-window .cursor {
background-color: #fff;
}
.urxvt {
background-color: rgba(28, 28, 28, 0.9);
cursor: text;
padding: 2px;
max-width: 100%;
min-height: 100%;
}
#i3-gaps-tumblr a .blog-title {
cursor: pointer;
}
#i3-gaps-tumblr .blog-title p {
text-align: center;
}
#i3-gaps-tumblr .blog-title p.small, #i3-gaps-tumblr .blog-title a {
font-weight: 700;
background-color: #107bcc;
color: #fff;
text-decoration: none;
}
#content {
position: absolute;
top: 47px;
right: 35px;
left: 475px;
padding-bottom: 35px;
}
.post-header, .post-footer {
overflow: hidden;
position: relative;
width: 100%;
background-color: #303030;
}
.left {
float: left;
}
.tags {
padding-right: 60px;
}
.right {
float: right;
}
.post-body {
padding: 1em;
max-width: 100%;
}
.post-body .title, .post-body .title a {
text-decoration: none;
color: #fff;
font-size: 1.5em;
}
.post-body .link {
font-size: 1.5em;
}
.post-body img {
max-width: 100%;
width: auto;
height: auto;
max-height: 95vh;
}
.post-body figure {
margin: 0px;
}
.post-body p, .post-body blockquote {
margin-top: 4px;
margin-bottom: 4px;
}
.post-body blockquote {
margin-left: 4px;
border-left: 2px solid #5f5f5f;
padding-left: 6px;
margin-right: 0px;
}
.post-header, .post-header a, .post-footer, .post-footer a {
color: #808080;
}
.footer-left {
display: inline-block;
}
.post-footer {
min-height: 22px;
}
.buttons {
position: absolute;
width: 50px;
text-align: right;
display: inline-block;
right: 0px;
padding: 2px 4px 2px 0px;
}
.buttons .reblogbutton {
margin-bottom: -20px;
}
#i3bar .left .page-button {
padding: 3px 5px 2px 5px;
margin-bottom: 1px;
color: #808080;
float: left;
}
#i3bar .left .page-button-active {
color: #dedede;
background-color: #D64937;
}
#i3status {
padding: 3px 5px 2px 5px;
}
#i3status > span a, #sidebar a {
color: inherit;
text-decoration: none;
}
#i3status span.i3status-separator {
color: #808080;
}
#nav {
text-align: center;
overflow: hidden;
width: 100%;
margin-top: -10px;
}
#nav .prev-page-window {
float: left;
}
#nav .next-page-window {
float: right;
}
#nav .current-page-window {
display: inline-block;
margin-left: auto;
margin-right: auto;
}
#nav .prev-page-window .urxvt, #nav .next-page-window .urxvt {
cursor: pointer;
}
#nav a, #sidebar a, #sidebar .jslink {
text-decoration: inherit;
color: inherit;
}
#nav .prev-page-window .urxvt p, #nav .next-page-window .urxvt p {
text-decoration: none;
background-color: #107BCC;
padding: 0px 5px;
}
.mobile-info {
display: none;
}
#confirm {
display: none;
}
#confirm-window {
z-index: 2;
position: fixed;
left: 50%;
top: 50%;
width: 200px;
margin-left: -100px;
transform: translateY(-50%);
border-color: #fff;
text-align: center;
}
#confirm-bg {
position: fixed;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1;
}
|
# This code was automatically generated using xdrgen
# DO NOT EDIT or your changes may be overwritten
require 'xdr'
# enum PublicKeyType
# <API key> = KEY_TYPE_ED25519
module Stellar
class PublicKeyType < XDR::Enum
member :<API key>, 0
seal
end
end
|
@CHARSET "UTF-8";
/*PRINCIPAL*/
body{
margin:0px;
padding:0;
font-family:verdana;
font-size: 10px;
height:100%;
width: 100%;
}
img {
border:0;
}
em {
color: #b1b1b1;
font-style: italic;
}
a {
color:#333333;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
h1, h2, h3, h4, h5, h6 {
font-family: Arial;
color:#333;
}
h1 {
font-size:2em;
}
h2 {
clear:both;
margin-top: 22px;
}
#principal {
background-image:url(../imagens/bg-topo.png);
background-repeat:repeat-x;
background-position:top;
}
#topo{
height: 110px; /*Height of top section*/
background-image:url("../imagens/topo.png");
background-position:bottom left;
background-repeat:no-repeat;
}
#logo {
width:150px;
height:70px;
float:left;
}
#logon {
width:254px;
height:25px;
float:right;
padding-left:10px;
margin: 10px 30px 0 30px;
}
#logon img{
margin-top:5px;
}
#logo-sistema {
height: 30px;
position: absolute;
right: 82px;
top: 43px;
width: 127px;
}
#topo h1{
margin: 0;
padding-top: 15px;
}
#barra-1 {
width:100%;
background-color: #cc0001;
}
#barra-2 {
width:100%;
background-color: #c8fc98;
}
#conteudo-col{
margin-left: 193px; /*Set left margin to LeftColumnWidth*/
}
#cabecalho-div-1 {
background-image:url(../imagens/bg-cabecalho-1.png);
width:394px;
width : 393px;
height:29px;
float:left;
background-repeat:repeat-x;
background-position:left bottom;
margin-bottom:5px;
}
:root #cabecalho-div-1 {
width:375px\0/IE9; /* IE9 */
}
#cabecalho-div-2 {
background-image:url(../imagens/bg-cabecalho-2.png);
width:165px;
width : 166px;
height:29px;
float:left;
background-repeat:repeat-x;
background-position:left bottom;
margin-bottom:5px;
}
:root #cabecalho-div-2 {
width:158px\0/IE9; /* IE9 */
}
#miolo{
float: left;
width: 100%;
}
.principal {
background: none repeat scroll 0 0 #FFFFFF;
border-bottom: 4px solid #B31419;
clear: both;
float: left;
overflow: hidden;
padding-bottom: 20px;
width: 100%;
}
#col-esquerda{
float: left;
width: 175px; /*Width of left column*/
height: 100%;
margin-left: -100%;
background: #efefef;
margin-top:3px;
}
#titulo-pag{
margin-left:193px;
width:57%;
float:left;
}
#ico-internos{
float:right;
text-align:right;
margin:10px 20px 0 0;
}
#ico-internos img {
}
.alerta {
margin-left:193px;
width:100%;
float:left;
}
#parametros {
width:100%;
margin-bottom:20px;
}
#menu {
}
#smoothmenu2 {
height:400px;
}
#rodape{
clear: left;
width: 100%;
background: #d9d9d9;
color: #333333;
text-align: center;
padding: 4px 0;
text-align:center;
}
#rodape a{
color: #FFFF80;
}
/*FORMULARIO*/
.label-inter {
position:absolute;
top:0;
left:5px;
margin-right: 3px;
text-align: right;
width:80px;
font-size:11px;
z-index:1;
}
.obs {
color: #b1b1b1;
font-size: 11px;
margin-left:5px;
float:left;
}
div.form-divisoria {
margin:-10px 0 5px 0px;
width:100%;
height:1px;
background-color:#fff;
clear:both;
}
div.field {
}
.field-busca {
margin-bottom: 7px;
margin-top: 7px;
position: relative;
text-align: right;
}
.buscar {
height: 27px;
width: 32px;
float: left;
}
.buttonSubmit {
clear:both;
}
#bt-submit {
border: none;
text-indent:-9999px;
}
.bt-salvar {
background-image: url("../imagens/bt-salvar.png");
height: 30px;
width: 63px;
}
.bt-cancelar {
background-image:url(../imagens/bt-cancelar.png);
width:30px;
height:25px;
}
#bt-submit:hover{
border: none;
}
.botoes-internos {
width:98.5%;
text-align:right;
margin-top:17px;
}
#voltar, #buscar-modal, #alteraplano-modal, #alteraextrato-modal, #desativaplano-modal, #novo-plano-modal, #pesquisar, #<API key> {
display: inline;
float: left;
margin-left: 2px;
}
div.field input.error, div.field select.error, tr.errorRow div.field input, tr.errorRow div.field select {
border: 1px solid #b31419;
background-color: #FAFFD6;
color: #b31419;
}
div.field div.formError {
display: none;
color: #FF0000;
}
div.field div.formError {
font-weight: normal;
}
div.error {
margin: 5px 0 23px 0;
color: #b31419 !important;
width:400px;
padding:10px 0px 5px 3px;
border:1px solid #b31419;
}
div.error a {
color: #336699;
font-size: 12px;
text-decoration: underline;
}
label.error {
color: #b31419;
}
.error span {
margin-top:10px;
}
.botoes-externos {
float:right;
margin: -14px 30px 10px 0;
}
#caixa-pesquisa {
background-color: #F5F5F5;
background-image: url("../imagens/bg-pesquisa-lupa.gif");
background-position: right top;
background-repeat: no-repeat;
border: 1px solid #999999;
display: block;
min-width: 575px;
padding: 0 15px 15px;
position: relative;
width: 65%;
}
.clear {
clear:both;
}
.linha-form {
line-height: 1.5em;
}
div.field-form-1 {
width:48%;
float:left;
margin-right:2%;
position:relative;
}
div.field-form-2 {
float: left;
margin-right: 2%;
position: relative;
width: 23%;
}
div.field-form-3 {
width:14.65%;
float:left;
margin-right:2%;
position:relative;
}
.textarea-form-1 {
width:100%;
}
.textarea-form-2 {
width:100%;
}
div.tabela-form-2 {
height:91px;
overflow:auto;
background-color:#f5f5f5;
border: 1px solid #999999;
width:48%;
float:left;
}
div.tabela-form-1 {
height:99px;
overflow:auto;
background-color:#f5f5f5;
border: 1px solid #999999;
width:100%;
float:left;
min-width:200px;
}
div.tabela-form-1-menor {
height:68px;
overflow:auto;
background-color:#f5f5f5;
border: 1px solid #999999;
width:100%;
float:left;
}
div.ico-planos{
height:68px;
width:100%;
float:left;
}
div.ico-reneg{
height:49px;
width:100%;
float:left;
}
div.tabela-form-2 a{
font-weight:900;
}
div.add-contrato-tabela {
float:left;
color:#b31419;
margin-left:7px;
}
div.field-com-busca {
width:23%;
float:left;
margin-right:2%;
position:relative;
}
div.ico-busca {
position:absolute;
z-index:500;
right:0;
}
.<API key> textarea {
width:98%;
min-width:136px;
border:1px solid #999999;
height: 62px;
}
.<API key> textarea {
width:100%;
min-width:136px;
border:1px solid #999999;
}
div.label-form {
color:#666;
margin-top:7px;
}
div.input-form {
width:100%;
}
div.input-form input {
width:100%;
min-width:100px;
border:1px solid #999999;
}
div.input-form select {
width:100%;
min-width:100px;
border:1px solid #999999;
}
div.<API key> input {
width:100%;
min-width:100px;
border:1px solid #999999;
background-image:url(../imagens/bt-calendar-18x17.png);
background-repeat:no-repeat;
background-position:center right;
cursor:pointer;
}
div.input-form-busca input {
width:87%;
min-width:100px;
border:1px solid #999999;
position:relative;
}
div.input-form-menor input {
width:100%;
min-width:50px;
border:1px solid #999999;
}
div.input-form-menor select {
width:100%;
min-width:50px;
border:1px solid #999999;
}
/* TABS */
ul.tabs {
margin: 0;
padding: 0;
float: left;
list-style: none;
height: 32px; /*--Set height of tabs--*/
border-bottom: 1px solid #999;
border-left: 1px solid #999;
width: 98%;
}
ul.tabs li {
float: left;
margin: 0;
padding: 0;
height: 31px; /*--Subtract 1px from the height of the unordered list--*/
line-height: 31px; /*--Vertically aligns the text within the tab--*/
border: 1px solid #999;
border-left: none;
margin-bottom: -1px; /*--Pull the list item down 1px--*/
overflow: hidden;
position: relative;
background: #e0e0e0;
}
ul.tabs li a {
text-decoration: none;
color: #000;
display: block;
font-size: 1.2em;
padding: 0 10px;
border: 1px solid #fff; /*--Gives the bevel look with a 1px white border inside the list item--*/
outline: none;
}
ul.tabs li a:hover {
background: #ccc;
}
html ul.tabs li.active, html ul.tabs li.active a:hover { /*--Makes sure that the active tab does not listen to the hover properties--*/
background: #fff;
border-bottom: 1px solid #fff; /*--Makes the active tab look like it's connected with its content--*/
}
ul.tabs li .reneg-tab {
background-color:#b2b2b2;
}
ul.tabs li .reneg-tab:hover {
background-color:#949494;
}
html ul.tabs li.active .reneg-tab, html ul.tabs li.active .reneg-tab:hover { /*--Makes sure that the active tab does not listen to the hover properties--*/
background: #fafce8;
border-bottom: 1px solid #fafce8; /*--Makes the active tab look like it's connected with its content--*/
}
.reneg-tb-bg {
background-color:#fafce8;
}
.tab_container {
border: 1px solid #999;
border-top: none;
border-bottom: 4px solid #ab1f23;
overflow: hidden;
clear: both;
float: left;
width: 98%;
background: #fff;
}
.tab_content {
padding: 10px;
overflow:auto;
}
.grid td{
border-bottom:1px solid #e1e1e1;
font-size:10px;
line-height:2em;
}
table.nivel-1 {
border-collapse:collapse;
}
table.nivel-1 tr {
border-bottom:1px solid #E1E1E1;
}
.detalhes-contrato{
background-color:#efefef;
width:100%;
margin-top: -1px;
padding-top: 11px;
margin-bottom:20px;
}
.detalhes-contrato table {
width:100%;
background-color:#efefef;
}
/* FIM - TABELA*/
.principal td {
border-bottom:1px solid #e1e1e1;
font-size:10px;
}
.principal td a {
font-weight: bold;
}
.link-pesquisa a{
border: 1px solid #999999;
padding: 4px;
background-color: #efefef;
text-decoration:none;
}
.<API key> a {
background-color: #EFEFEF;
border: 1px solid #999999;
padding: 4px;
position: absolute;
right: 34px;
text-decoration: none;
top: 216px;
}
#nav-planos {
height: 30px;
margin: 20px 0;
width: 100%;
}
#nav-icons-tabela {
height: 30px;
margin: 0;
width: 100%;
}
#nav-planos h3{
float:left;
margin-top: 4px;
}
#paginacao {
float:left;
}
#paginacao ul{
padding:0px;
margin-top: 5px;
float: left;
list-style:none;
}
#paginacao ul li {
display: inline;
}
#paginacao ul li a{
background-image: url("../imagens/nav-bg.png");
background-repeat: no-repeat;
height: 22px;
padding: 5px 8px;
margin-top:3px;
}
#paginacao ul li a:hover{
background-image: url("../imagens/nav-bg-hover.png");
text-decoration:none;
}
.seta-navega {
float:left;
}
.ico-plano img{
margin-left:5px;
}
.ico-plano img{
margin-left:1px;
}
|
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
import { Merch } from '../data/merch';
import { MerchService } from '../data/merch.service';
@Component({
selector: 'app-merch-display',
templateUrl: './merch-display.component.html',
styleUrls: ['./merch-display.component.scss'],
})
export class <API key> implements OnInit {
merch: Merch[] = [];
private _serviceWorker: ServiceWorker|null = null;
constructor(
private route: ActivatedRoute,
private merchService: MerchService,
private location: Location
) {}
ngOnInit(): void {
navigator.serviceWorker.ready.then( registration => {
this._serviceWorker = registration.active;
});
this.route.params.subscribe((routeParams) => {
this.getMerch(routeParams.category);
if (this._serviceWorker) {
this._serviceWorker.postMessage({ page: routeParams.category });
}
});
}
getMerch(category: string): void {
this.merchService
.getMerchList(category)
.then((merch) => (this.merch = merch));
}
goBack(): void {
this.location.back();
}
}
|
package com.github.sergejsamsonow.codegenerator.producer.pojo.renderer;
import com.github.sergejsamsonow.codegenerator.api.producer.sc.<API key>;
import com.github.sergejsamsonow.codegenerator.api.producer.sc.<API key>;
import com.github.sergejsamsonow.codegenerator.producer.pojo.model.PojoProperty;
import com.github.sergejsamsonow.codegenerator.producer.pojo.renderer.javalang.BeanModifier;
public class JavaLangToString extends BeanModifier {
public JavaLangToString(<API key> format) {
super(format);
}
@Override
protected void <API key>() {
<API key> writer = getMethodCodeWriter();
writer.annotation("@Override");
writer.start("public String toString() {");
writer.code("StringBuilder builder = new StringBuilder();");
writer.code("builder.append(\"%s (\");", getData().getClassName());
}
@Override
protected void writePropertyCode(PojoProperty property) {
<API key> writer = getMethodCodeWriter();
String end = isLast() ? ");" : " + \", \");";
writer.code("builder.append(\"%s: \" + Objects.toString(%s())%s",
property.getFieldName(), property.getGetterName(), end);
}
@Override
protected void <API key>() {
<API key> writer = getMethodCodeWriter();
writer.code("builder.append(\")\");");
writer.code("return builder.toString();");
writer.end();
writer.emptyNewLine();
}
}
|
from functools import wraps
import json
import os
import traceback
import validators
from jinja2 import Environment, PackageLoader
from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler
import requests
from requests.auth import HTTPBasicAuth
env = Environment(
loader=PackageLoader('saagie', 'jinja2'),
)
SAAGIE_ROOT_URL = os.environ.get("SAAGIE_ROOT_URL", None)
SAAGIE_USERNAME = None
PLATFORMS_URL = None
<API key> = None
JOBS_URL_PATTERN = None
JOB_URL_PATTERN = None
<API key> = None
<API key> = None
def <API key>(saagie_url):
if saagie_url.startswith('/'):
return SAAGIE_ROOT_URL + saagie_url
return saagie_url
class ResponseError(Exception):
def __init__(self, status_code):
self.status_code = status_code
super(ResponseError, self).__init__(status_code)
class SaagieHandler(IPythonHandler):
def handle_request(self, method):
data = {k: v[0].decode() for k, v in self.request.arguments.items()}
if 'view' not in data:
self.send_error(404)
return
view_name = data.pop('view')
notebook_path = data.pop('notebook_path', None)
notebook_json = data.pop('notebook_json', None)
notebook = Notebook(notebook_path, notebook_json)
try:
template_name, template_data = views.render(
view_name, notebook=notebook, data=data, method=method)
except ResponseError as e:
self.send_error(e.status_code)
return
except:
template_name = 'internal_error.html'
template_data = {'error': traceback.format_exc()}
self.set_status(500)
template_data.update(
notebook=notebook,
)
template = env.get_template(template_name)
self.finish(template.render(template_data))
def get(self):
self.handle_request('GET')
def post(self):
self.handle_request('POST')
def check_xsrf_cookie(self):
return
class SaagieCheckHandler(IPythonHandler):
def get(self):
self.finish()
class SaagieJobRun:
def __init__(self, job, run_data):
self.job = job
self.id = run_data['id']
self.status = run_data['status']
self.stderr = run_data.get('logs_err', '')
self.stdout = run_data.get('logs_out', '')
class SaagieJob:
@classmethod
def from_id(cls, notebook, platform_id, job_id):
return SaagieJob(
notebook,
requests.get(JOB_URL_PATTERN % (platform_id, job_id), <API key>).json())
def __init__(self, notebook, job_data):
self.notebook = notebook
self.data = job_data
self.platform_id = job_data['platform_id']
self.capsule_type = job_data['capsule_code']
self.id = job_data['id']
self.name = job_data['name']
self.last_run = None
def set_as_current(self):
self.notebook.current_job = self
@property
def url(self):
return (JOBS_URL_PATTERN + '/%s') % (self.platform_id, self.id)
@property
def admin_url(self):
return <API key>('/#/manager/%s/job/%s'
% (self.platform_id, self.id))
@property
def logs_url(self):
return self.admin_url + '/logs'
@property
def is_started(self):
return self.last_run is not None
def fetch_logs(self):
job_data = requests.get(self.url, <API key>).json()
run_data = job_data.get('last_instance')
if run_data is None or run_data['status'] not in ('SUCCESS', 'FAILED'):
return
run_data = requests.get(
<API key>('/api/v1/jobtask/%s'
% run_data['id']), <API key>).json()
self.last_run = SaagieJobRun(self, run_data)
@property
def <API key>(self):
return 'include/python_job_details.html'
def __str__(self):
return self.name
def __eq__(self, other):
if other is None:
return False
return self.platform_id == other.platform_id and self.id == other.id
def __lt__(self, other):
if other is None:
return False
return self.id < other.id
class SaagiePlatform:
<API key> = {'python'}
def __init__(self, notebook, platform_data):
self.notebook = notebook
self.id = platform_data['id']
self.name = platform_data['name']
self.capsule_types = {c['code'] for c in platform_data['capsules']}
@property
def is_supported(self):
return not self.capsule_types.isdisjoint(self.<API key>)
def get_jobs(self):
if not self.is_supported:
return []
jobs_data = requests.get(JOBS_URL_PATTERN % self.id, <API key>).json()
return [SaagieJob(self.notebook, job_data) for job_data in jobs_data
if job_data['category'] == 'processing' and
job_data['capsule_code'] in self.<API key>]
def __eq__(self, other):
return self.id == other.id
class Notebook:
CACHE = {}
def __new__(cls, path, json):
if path in cls.CACHE:
return cls.CACHE[path]
cls.CACHE[path] = new = super(Notebook, cls).__new__(cls)
return new
def __init__(self, path, json_data):
if path is None:
path = 'Untitled.ipynb'
if json_data is None:
json_data = json.dumps({
'cells': [],
'metadata': {'kernelspec': {'name': 'python3'}}})
self.path = path
self.json = json.loads(json_data)
# In cached instances, current_job is already defined.
if not hasattr(self, 'current_job'):
self.current_job = None
@property
def name(self):
return os.path.splitext(os.path.basename(self.path))[0]
@property
def kernel_name(self):
return self.json['metadata']['kernelspec']['name']
@property
def kernel_display_name(self):
return self.json['metadata']['kernelspec']['display_name']
def get_code_cells(self):
return [cell['source'] for cell in self.json['cells']
if cell['cell_type'] == 'code']
def get_code(self, indices=None):
cells = self.get_code_cells()
if indices is None:
indices = list(range(len(cells)))
return '\n\n\n'.join([cells[i] for i in indices])
def get_platforms(self):
return [SaagiePlatform(self, platform_data)
for platform_data in requests.get(PLATFORMS_URL, <API key>).json()]
class ViewsCollection(dict):
def add(self, func):
self[func.__name__] = func
return func
def render(self, view_name, notebook, data=None, method='GET', **kwargs):
if data is None:
data = {}
try:
view = views[view_name]
except KeyError:
raise ResponseError(404)
template_data = view(method, notebook, data, **kwargs)
if isinstance(template_data, tuple):
template_name, template_data = template_data
else:
template_name = view.__name__ + '.html'
return template_name, template_data
views = ViewsCollection()
@views.add
def modal(method, notebook, data):
return {}
def <API key>():
global SAAGIE_BASIC_AUTH_<API key> = None
# Init an empty Basic Auth token on first launch
<API key>()
def is_logged():
if SAAGIE_ROOT_URL is None or <API key> is None:
return False
else:
# Check if Basic token is still valid
is_logged_in = False
try:
response = requests.get(SAAGIE_ROOT_URL + '/api/v1/user-current', <API key>, allow_redirects=False)
is_logged_in = response.ok
except (requests.ConnectionError, requests.RequestException, requests.HTTPError, requests.Timeout) as err:
print ('Error while trying to connect to Saagie: ', err)
if is_logged_in is not True:
# Remove Basic Auth token from globals. It will force a new login phase.
<API key>()
return is_logged_in
def define_globals(saagie_root_url, saagie_username):
if saagie_root_url is not None:
global SAAGIE_ROOT_URL
global SAAGIE_USERNAME
global PLATFORMS_URL
global JOBS_URL_PATTERN
global JOB_URL_PATTERN
global <API key>
global <API key>
SAAGIE_USERNAME = saagie_username
SAAGIE_ROOT_URL = saagie_root_url.strip("/")
PLATFORMS_URL = SAAGIE_ROOT_URL + '/api/v1/platform'
JOBS_URL_PATTERN = PLATFORMS_URL + '/%s/job'
JOB_URL_PATTERN = JOBS_URL_PATTERN + '/%s'
<API key> = JOBS_URL_PATTERN + '/%s/version'
<API key> = JOBS_URL_PATTERN + '/upload'
@views.add
def login_form(method, notebook, data):
if method == 'POST':
# check if the given Saagie URL is well formed
if not validators.url(data['saagie_root_url']):
return {'error': 'Invalid URL', 'saagie_root_url': data['saagie_root_url'] or '', 'username': data['username'] or ''}
define_globals(data['saagie_root_url'], data['username'])
try:
basic_token = HTTPBasicAuth(data['username'], data['password'])
<API key> = requests.get(SAAGIE_ROOT_URL + '/api/v1/user-current', auth=basic_token, allow_redirects=False)
if <API key>.ok:
# Login succeeded, keep the basic token for future API calls
global <API key>
<API key> = basic_token
except (requests.ConnectionError, requests.RequestException, requests.HTTPError, requests.Timeout) as err:
print ('Error while trying to connect to Saagie: ', err)
return {'error': 'Connection error', 'saagie_root_url': SAAGIE_ROOT_URL, 'username': SAAGIE_USERNAME or ''}
if <API key> is not None:
return views.render('<API key>', notebook)
return {'error': 'Invalid URL, username or password.', 'saagie_root_url': SAAGIE_ROOT_URL, 'username': SAAGIE_USERNAME or ''}
if is_logged():
return views.render('<API key>', notebook)
return {'error': None, 'saagie_root_url': SAAGIE_ROOT_URL or '', 'username': SAAGIE_USERNAME or ''}
def login_required(view):
@wraps(view)
def inner(method, notebook, data, *args, **kwargs):
if not is_logged():
return views.render('login_form', notebook)
return view(method, notebook, data, *args, **kwargs)
return inner
@views.add
@login_required
def <API key>(method, notebook, data):
return {'username': SAAGIE_USERNAME}
def get_job_form(method, notebook, data):
context = {'platforms': notebook.get_platforms()}
context['values'] = ({'current': {'options': {}}} if notebook.current_job is None
else notebook.current_job.data)
return context
def <API key>(data):
return {
'platform_id': data['saagie-platform'],
'category': 'processing',
'name': data['job-name'],
'description': data['description'],
'current': {
'cpu': data['cpu'],
'disk': data['disk'],
'memory': data['ram'],
'isInternalSubDomain': False,
'isInternalPort': False,
'options': {}
}
}
def <API key>(notebook, data):
code = notebook.get_code(map(int, data.get('code-lines', '').split('|')))
files = {'file': (data['job-name'] + '.py', code)}
return requests.post(
<API key> % data['saagie-platform'],
files=files, <API key>).json()['fileName']
@views.add
@login_required
def python_job_form(method, notebook, data):
if method == 'POST':
platform_id = data['saagie-platform']
job_data = <API key>(data)
job_data['capsule_code'] = 'python'
job_data['always_email'] = False
job_data['manual'] = True
job_data['retry'] = ''
current = job_data['current']
current['options']['language_version'] = data['language-version']
current['releaseNote'] = data['release-note']
current['template'] = data['shell-command']
current['file'] = <API key>(notebook, data)
new_job_data = requests.post(JOBS_URL_PATTERN % platform_id,
json=job_data, <API key>).json()
job = SaagieJob(notebook, new_job_data)
job.set_as_current()
return views.render('starting_job', notebook, {'job': job})
context = get_job_form(method, notebook, data)
context['action'] = '/saagie?view=python_job_form'
context['username'] = SAAGIE_USERNAME
return context
@views.add
@login_required
def update_python_job(method, notebook, data):
if method == 'POST':
job = notebook.current_job
platform_id = job.platform_id
data['saagie-platform'] = platform_id
data['job-name'] = job.name
data['description'] = ''
current = <API key>(data)['current']
current['options']['language_version'] = data['language-version']
current['releaseNote'] = data['release-note']
current['template'] = data['shell-command']
current['file'] = <API key>(notebook, data)
requests.post(<API key> % (platform_id, job.id),
json={'current': current}, <API key>)
job.last_run = None
return views.render('starting_job', notebook, {'job': job})
context = get_job_form(method, notebook, data)
context['action'] = '/saagie?view=update_python_job'
context['username'] = SAAGIE_USERNAME
return context
@views.add
@login_required
def select_python_job(method, notebook, data):
if method == 'POST':
platform_id, job_id = data['job'].split('-')
notebook.current_job = SaagieJob.from_id(notebook, platform_id, job_id)
return views.render('update_python_job', notebook, data)
jobs_by_platform = []
for platform in notebook.get_platforms():
jobs = platform.get_jobs()
if jobs:
jobs_by_platform.append((platform,
list(sorted(jobs, reverse=True))))
return {'jobs_by_platform': jobs_by_platform,
'action': '/saagie?view=select_python_job', 'username': SAAGIE_USERNAME}
@views.add
@login_required
def unsupported_kernel(method, notebook, data):
return {'username': SAAGIE_USERNAME}
@views.add
@login_required
def starting_job(method, notebook, data):
job = notebook.current_job
job.fetch_logs()
if job.is_started:
return views.render('started_job', notebook, {'job': job})
return {'job': job, 'username': SAAGIE_USERNAME}
@views.add
@login_required
def started_job(method, notebook, data):
return {'job': notebook.current_job, 'username': SAAGIE_USERNAME}
@views.add
def logout(method, notebook, data):
global <API key>
global SAAGIE_ROOT_URL
global SAAGIE_USERNAME
<API key> = None
SAAGIE_ROOT_URL = None
SAAGIE_USERNAME = None
return {}
def <API key>(nb_app):
web_app = nb_app.web_app
base_url = web_app.settings['base_url']
route_pattern = url_path_join(base_url, '/saagie')
web_app.add_handlers('.*$', [(route_pattern, SaagieHandler)])
route_pattern = url_path_join(base_url, '/saagie/check')
web_app.add_handlers('.*$', [(route_pattern, SaagieCheckHandler)])
|
/ [<API key>.ts]
//When used as a contextual type, a union type U has those members that are present in any of
// its constituent types, with types that are unions of the respective members in the constituent types.
interface I1<T> {
commonMethodType(a: string): string;
commonPropertyType: string;
<API key>(a: T): T;
methodOnlyInI1(a: string): string;
propertyOnlyInI1: string;
}
interface I2<T> {
commonMethodType(a: string): string;
commonPropertyType: string;
<API key>(a: T): T;
methodOnlyInI2(a: string): string;
propertyOnlyInI2: string;
}
// Let S be the set of types in U that has a property P.
// If S is not empty, U has a property P of a union type of the types of P from each type in S.
var i1: I1<number>;
var i2: I2<number>;
var i1Ori2: I1<number> | I2<number> = i1;
var i1Ori2: I1<number> | I2<number> = i2;
var i1Ori2: I1<number> | I2<number> = { // Like i1
commonPropertyType: "hello",
commonMethodType: a=> a,
<API key>: a => a,
methodOnlyInI1: a => a,
propertyOnlyInI1: "Hello",
};
var i1Ori2: I1<number> | I2<number> = { // Like i2
commonPropertyType: "hello",
commonMethodType: a=> a,
<API key>: a => a,
methodOnlyInI2: a => a,
propertyOnlyInI2: "Hello",
};
var i1Ori2: I1<number> | I2<number> = { // Like i1 and i2 both
commonPropertyType: "hello",
commonMethodType: a=> a,
<API key>: a => a,
methodOnlyInI1: a => a,
propertyOnlyInI1: "Hello",
methodOnlyInI2: a => a,
propertyOnlyInI2: "Hello",
};
var arrayI1OrI2: Array<I1<number> | I2<number>> = [i1, i2, { // Like i1
commonPropertyType: "hello",
commonMethodType: a=> a,
<API key>: a => a,
methodOnlyInI1: a => a,
propertyOnlyInI1: "Hello",
},
{ // Like i2
commonPropertyType: "hello",
commonMethodType: a=> a,
<API key>: a => a,
methodOnlyInI2: a => a,
propertyOnlyInI2: "Hello",
}, { // Like i1 and i2 both
commonPropertyType: "hello",
commonMethodType: a=> a,
<API key>: a => a,
methodOnlyInI1: a => a,
propertyOnlyInI1: "Hello",
methodOnlyInI2: a => a,
propertyOnlyInI2: "Hello",
}];
interface I11 {
<API key>(a: string, b: number): string;
<API key>: string;
}
interface I21 {
<API key>(a: string, b: number): number;
<API key>: number;
}
var i11: I11;
var i21: I21;
var i11Ori21: I11 | I21 = i11;
var i11Ori21: I11 | I21 = i21;
var i11Ori21: I11 | I21 = {
// Like i1
<API key>: (a, b) => {
var z = a.charAt(b);
return z;
},
<API key>: "hello",
};
var i11Ori21: I11 | I21 = {
// Like i2
<API key>: (a, b) => {
var z = a.charCodeAt(b);
return z;
},
<API key>: 10,
};
var arrayOrI11OrI21: Array<I11 | I21> = [i11, i21, i11 || i21, {
// Like i1
<API key>: (a, b) => {
var z = a.charAt(b);
return z;
},
<API key>: "hello",
}, {
// Like i2
<API key>: (a, b) => {
var z = a.charCodeAt(b);
return z;
},
<API key>: 10,
}];
/ [<API key>.js]
// Let S be the set of types in U that has a property P.
// If S is not empty, U has a property P of a union type of the types of P from each type in S.
var i1;
var i2;
var i1Ori2 = i1;
var i1Ori2 = i2;
var i1Ori2 = {
commonPropertyType: "hello",
commonMethodType: function (a) { return a; },
<API key>: function (a) { return a; },
methodOnlyInI1: function (a) { return a; },
propertyOnlyInI1: "Hello"
};
var i1Ori2 = {
commonPropertyType: "hello",
commonMethodType: function (a) { return a; },
<API key>: function (a) { return a; },
methodOnlyInI2: function (a) { return a; },
propertyOnlyInI2: "Hello"
};
var i1Ori2 = {
commonPropertyType: "hello",
commonMethodType: function (a) { return a; },
<API key>: function (a) { return a; },
methodOnlyInI1: function (a) { return a; },
propertyOnlyInI1: "Hello",
methodOnlyInI2: function (a) { return a; },
propertyOnlyInI2: "Hello"
};
var arrayI1OrI2 = [i1, i2, {
commonPropertyType: "hello",
commonMethodType: function (a) { return a; },
<API key>: function (a) { return a; },
methodOnlyInI1: function (a) { return a; },
propertyOnlyInI1: "Hello"
},
{
commonPropertyType: "hello",
commonMethodType: function (a) { return a; },
<API key>: function (a) { return a; },
methodOnlyInI2: function (a) { return a; },
propertyOnlyInI2: "Hello"
}, {
commonPropertyType: "hello",
commonMethodType: function (a) { return a; },
<API key>: function (a) { return a; },
methodOnlyInI1: function (a) { return a; },
propertyOnlyInI1: "Hello",
methodOnlyInI2: function (a) { return a; },
propertyOnlyInI2: "Hello"
}];
var i11;
var i21;
var i11Ori21 = i11;
var i11Ori21 = i21;
var i11Ori21 = {
// Like i1
<API key>: function (a, b) {
var z = a.charAt(b);
return z;
},
<API key>: "hello"
};
var i11Ori21 = {
// Like i2
<API key>: function (a, b) {
var z = a.charCodeAt(b);
return z;
},
<API key>: 10
};
var arrayOrI11OrI21 = [i11, i21, i11 || i21, {
// Like i1
<API key>: function (a, b) {
var z = a.charAt(b);
return z;
},
<API key>: "hello"
}, {
// Like i2
<API key>: function (a, b) {
var z = a.charCodeAt(b);
return z;
},
<API key>: 10
}];
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperMap.WinRT.Core;
using SuperMap.WinRT.Utilities;
using Windows.Data.Json;
using Windows.UI;
namespace SuperMap.WinRT.REST
{
<summary>
<para>${<API key>}</para>
<para>${<API key>}</para>
</summary>
public class ServerLayer
{
<summary>${<API key>}</summary>
public ServerLayer()
{ }
//Property
<summary>${<API key>}</summary>
public Rectangle2D Bounds
{
get;
internal set;
}
//Layer
<summary>${<API key>}</summary>
public string Caption { get; internal set; }
<summary>${<API key>}</summary>
public string Description { get; internal set; }
<summary>${<API key>}</summary>
public string Name { get; internal set; }
<summary>${<API key>}</summary>
public bool IsQueryable { get; internal set; }
//public System.Collections.Generic.List<LayerInfo> SubLayers { get; internal set; }
//UGC
//private string LayerType = "UGC";
<summary>${<API key>}</summary>
public bool IsVisible { get; internal set; }
//UGCMapLayer
<summary>${<API key>}</summary>
public bool <API key> { get; internal set; }
<summary>${<API key>}</summary>
public double MaxScale { get; internal set; }
<summary>${<API key>}</summary>
public double MinScale { get; internal set; }
<summary>${<API key>}</summary>
public double <API key> { get; internal set; }
<summary>${<API key>}</summary>
public int OpaqueRate { get; internal set; }
<summary>${<API key>}</summary>
public bool IsSymbolScalable { get; internal set; }
<summary>${<API key>}</summary>
public double SymbolScale { get; internal set; }
//UGCLayer
<summary>${<API key>}</summary>
public DatasetInfo DatasetInfo { get; internal set; }
<summary>${<API key>}</summary>
public string DisplayFilter { get; internal set; }
<summary>${<API key>}</summary>
public System.Collections.Generic.List<JoinItem> JoinItems { get; internal set; }
<summary>${<API key>}</summary>
public string RepresentationField { get; internal set; }
<summary>${<API key>}</summary>
public SuperMapLayerType UGCLayerType { get; internal set; }
<summary>${<API key>}</summary>
public UGCLayer UGCLayer { get; internal set; }
<summary>${<API key>}</summary>
<returns>${<API key>}</returns>
<param name="json">${<API key>}</param>
internal static ServerLayer FromJson(JsonObject json)
{
var serverLayer = new ServerLayer();
if (json["bounds"].ValueType != JsonValueType.Null)
{
serverLayer.Bounds = JsonHelper.ToRectangle2D(json["bounds"].GetObjectEx());
}
else
{
//null
}
serverLayer.Caption = json["caption"].GetStringEx();
serverLayer.Description = json["description"].GetStringEx();
serverLayer.Name = json["name"].GetStringEx();
serverLayer.IsQueryable = json["queryable"].GetBooleanEx();
serverLayer.IsVisible = json["visible"].GetBooleanEx();
serverLayer.<API key> = json["<API key>"].GetBooleanEx();
serverLayer.MaxScale = json["maxScale"].GetNumberEx();
serverLayer.MinScale = json["minScale"].GetNumberEx();
serverLayer.<API key> = json["<API key>"].GetNumberEx();
serverLayer.OpaqueRate = (int)json["opaqueRate"].GetNumberEx();
serverLayer.IsSymbolScalable = json["symbolScalable"].GetBooleanEx();
serverLayer.SymbolScale = json["symbolScale"].GetNumberEx();
serverLayer.DatasetInfo = DatasetInfo.FromJson(json["datasetInfo"].GetObjectEx());
serverLayer.DisplayFilter = json["displayFilter"].GetStringEx();
if (json["joinItems"].ValueType != JsonValueType.Null)
{
List<JoinItem> joinItems = new List<JoinItem>();
foreach (JsonValue item in json["joinItems"].GetArray())
{
joinItems.Add(JoinItem.FromJson(item.GetObjectEx()));
}
serverLayer.JoinItems = joinItems;
}
serverLayer.RepresentationField = json["representationField"].GetStringEx();
if (json["ugcLayerType"].GetStringEx() == SuperMapLayerType.GRID.ToString())
{
UGCGridLayer ugcGridLayer = new UGCGridLayer();
List<Color> colors = new List<Color>();
foreach (JsonValue colorItem in json["colors"].GetArray())
{
colors.Add(ServerColor.FromJson(colorItem.GetObjectEx()).ToColor());
}
ugcGridLayer.Colors = colors;
if (json["dashStyle"].ValueType != JsonValueType.Null)
{
ugcGridLayer.DashStyle = ServerStyle.FromJson(json["dashStyle"].GetObjectEx());
}
if (json["gridType"].ValueType != JsonValueType.Null)
{
ugcGridLayer.GridType = (GridType)Enum.Parse(typeof(GridType), json["gridType"].GetStringEx(), true);
}
else
{
}
ugcGridLayer.HorizontalSpacing = json["horizontalSpacing"].GetNumberEx();
ugcGridLayer.SizeFixed = json["sizeFixed"].GetBooleanEx();
if (json["solidStyle"].ValueType != JsonValueType.Null)
{
ugcGridLayer.SolidStyle = ServerStyle.FromJson(json["solidStyle"].GetObjectEx());
}
if (json["specialColor"].ValueType != JsonValueType.Null)
{
ugcGridLayer.SpecialColor = ServerColor.FromJson(json["specialColor"].GetObjectEx()).ToColor();
}
ugcGridLayer.SpecialValue = json["specialValue"].GetNumberEx();
ugcGridLayer.VerticalSpacing = json["verticalSpacing"].GetNumberEx();
serverLayer.UGCLayer = ugcGridLayer;
}
else if (json["ugcLayerType"].GetStringEx() == SuperMapLayerType.IMAGE.ToString())
{
UGCImageLayer ugcImageLayer = new UGCImageLayer();
ugcImageLayer.Brightness = (int)json["brightness"].GetNumberEx();
if (json["colorSpaceType"].ValueType != JsonValueType.Null)
{
ugcImageLayer.ColorSpaceType = (ColorSpaceType)Enum.Parse(typeof(ColorSpaceType), json["colorSpaceType"].GetStringEx(), true);
}
else
{
}
ugcImageLayer.Contrast = (int)json["contrast"].GetNumberEx();
List<int> bandIndexes = new List<int>();
if (json["displayBandIndexes"].ValueType != JsonValueType.Null && (json["displayBandIndexes"].GetArray()).Count > 0)
{
foreach (JsonObject item in json["displayBandIndexes"].GetArray())
{
bandIndexes.Add((int)item.GetNumber());
}
ugcImageLayer.DisplayBandIndexes = bandIndexes;
}
ugcImageLayer.Transparent = json["transparent"].GetBooleanEx();
ugcImageLayer.TransparentColor = ServerColor.FromJson(json["transparentColor"].GetObjectEx()).ToColor();
serverLayer.UGCLayer = ugcImageLayer;
}
else if (json["ugcLayerType"].GetStringEx() == SuperMapLayerType.THEME.ToString())
{
UGCThemeLayer ugcThemeLayer = new UGCThemeLayer();
if (json["theme"].ValueType != JsonValueType.Null)
{
if (json["theme"].GetObjectEx()["type"].GetStringEx() == "UNIQUE")
{
ugcThemeLayer.Theme = ThemeUnique.FromJson(json["theme"].GetObjectEx());
}
else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "RANGE")
{
ugcThemeLayer.Theme = ThemeRange.FromJson(json["theme"].GetObjectEx());
}
else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "LABEL")
{
ugcThemeLayer.Theme = ThemeLabel.FromJson(json["theme"].GetObjectEx());
}
else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "GRAPH")
{
ugcThemeLayer.Theme = ThemeGraph.FromJson(json["theme"].GetObjectEx());
}
else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "DOTDENSITY")
{
ugcThemeLayer.Theme = ThemeDotDensity.FromJson(json["theme"].GetObjectEx());
}
else if (json["theme"].GetObjectEx()["type"].GetStringEx() == "GRADUATEDSYMBOL")
{
ugcThemeLayer.Theme = <API key>.FromJson(json["theme"].GetObjectEx());
}
else
{
}
}
if (json["theme"].GetObjectEx()["type"].ValueType != JsonValueType.Null)
{
ugcThemeLayer.ThemeType = (ThemeType)Enum.Parse(typeof(ThemeType), json["theme"].GetObjectEx()["type"].GetStringEx(), true);
}
serverLayer.UGCLayer = ugcThemeLayer;
//ugcThemeLayer.Theme
}
else if (json["ugcLayerType"].GetStringEx() == SuperMapLayerType.VECTOR.ToString() && json.ContainsKey("style"))
{
serverLayer.UGCLayer = UGCVectorLayer.FromJson(json["style"].GetObjectEx());
}
else
{
serverLayer.UGCLayer = new UGCLayer();
}
if (json["ugcLayerType"].ValueType != JsonValueType.Null)
{
serverLayer.UGCLayerType = (SuperMapLayerType)Enum.Parse(typeof(SuperMapLayerType), json["ugcLayerType"].GetStringEx(), true);
}
else
{
}
//WMSWFS
//else if (json["ugcLayerType"] == SuperMapLayerType.WMS.ToString())
return serverLayer;
}
}
}
|
.tobox{
float: left;
padding: 10px;
background-color: #eee;
width:120px;
margin:0 10px 10px 0px;
text-align:center;
border-radius: 3px;
}
.tobox.two{
width: 180px;
}
.tobox.fixed-box{
position:fixed;
right:50px;
top:50px;
}
.dark-tooltip{ display:none; position:absolute; z-index:99; text-decoration:none; font-weight:normal; height:auto; top:0; left:0;}
.dark-tooltip.small{ padding:4px; font-size:12px; max-width:150px; -<API key>: 2px; -moz-border-radius: 2px; border-radius: 2px; }
.dark-tooltip.medium{ padding:10px; font-size:14px; max-width:200px; -<API key>: 4px; -moz-border-radius: 4px; border-radius: 4px;}
.dark-tooltip.large{ padding:16px; font-size:16px; max-width:250px; -<API key>: 6px; -moz-border-radius: 6px; border-radius: 6px; }
/* Tips */
.dark-tooltip .tip{ transform: scale(1.01); -webkit-transform: scale(1.01); transform: scale(1.01); content: ""; position: absolute; width:0; height:0; border-style: solid; line-height: 0px; }
.dark-tooltip.south .tip{ left:50%; top:100%;}
.dark-tooltip.west .tip{ left:0; top:50%;}
.dark-tooltip.north .tip{ left:50%; top:0; }
.dark-tooltip.east .tip{ left:100%; top:50%;}
.dark-tooltip.south.small .tip{ border-width: 7px 5px 0 5px; margin-left:-5px;}
.dark-tooltip.south.medium .tip{ border-width: 8px 6px 0 6px; margin-left:-6px;}
.dark-tooltip.south.large .tip{ border-width: 14px 12px 0 12px; margin-left:-12px;}
.dark-tooltip.west.small .tip{ border-width: 5px 7px 5px 0; margin-left:-7px; margin-top:-5px;}
.dark-tooltip.west.medium .tip{ border-width: 6px 8px 6px 0; margin-left:-8px; margin-top:-6px;}
.dark-tooltip.west.large .tip{ border-width: 12px 14px 12px 0; margin-left:-14px; margin-top:-12px;}
.dark-tooltip.north.small .tip{ border-width: 0 5px 7px 5px; margin-left:-5px; margin-top:-7px;}
.dark-tooltip.north.medium .tip{ border-width: 0 6px 8px 6px; margin-left:-6px; margin-top:-8px;}
.dark-tooltip.north.large .tip{ border-width: 0 12px 14px 12px; margin-left:-12px; margin-top:-14px;}
.dark-tooltip.east.small .tip{ border-width: 5px 0 5px 7px; margin-top:-5px;}
.dark-tooltip.east.medium .tip{ border-width: 6px 0 6px 8px; margin-top:-6px;}
.dark-tooltip.east.large .tip{ border-width: 12px 0 12px 14px; margin-top:-12px;}
/* confirm */
.dark-tooltip ul.confirm{ list-style-type:none;margin-top:5px;display:inline-block;margin:0 auto; }
.dark-tooltip ul.confirm li{ padding:10px;float:left;margin:5px;min-width:25px;-<API key>:3px;-moz-border-radius:3px;-o-border-radius:3px;border-radius:3px;}
/* themes */
.dark-tooltip.dark{ background-color:#1e1e1e; color:#fff; }
.dark-tooltip.light{ background-color:#ebedf3; color:#1e1e1e; }
.dark-tooltip.dark.south .tip{ border-color: #1e1e1e transparent transparent transparent; _border-color: #1e1e1e #000000 #000000 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); }
.dark-tooltip.dark.west .tip{ border-color: transparent #1e1e1e transparent transparent; _border-color: #000000 #1e1e1e #000000 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); }
.dark-tooltip.dark.north .tip{ border-color: transparent transparent #1e1e1e transparent; _border-color: #000000 #000000 #1e1e1e #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); }
.dark-tooltip.dark.east .tip{ border-color: transparent transparent transparent #1e1e1e; _border-color: #000000 #000000 #000000 #1e1e1e; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); }
.dark-tooltip.light.south .tip{ border-color: #ebedf3 transparent transparent transparent; _border-color: #ebedf3 #000000 #000000 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); }
.dark-tooltip.light.west .tip{ border-color: transparent #ebedf3 transparent transparent; _border-color: #000000 #ebedf3 #000000 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); }
.dark-tooltip.light.north .tip{ border-color: transparent transparent #ebedf3 transparent; _border-color: #000000 #000000 #ebedf3 #000000; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); }
.dark-tooltip.light.east .tip{ border-color: transparent transparent transparent #ebedf3; _border-color:#000000 #000000 #000000 #ebedf3 ; _filter: progid:DXImageTransform.Microsoft.Chroma(color='#000000'); }
.dark-tooltip.dark ul.confirm li{ background-color:#416E85;}
.dark-tooltip.dark ul.confirm li:hover{ background-color:#417E85;}
.dark-tooltip.light ul.confirm li{ background-color:#C1DBDB;}
.dark-tooltip.light ul.confirm li:hover{ background-color:#DCE8E8;}
/* Animations */
.animated{
-<API key>:both;-<API key>:both;-<API key>:both;-<API key>:both;animation-fill-mode:both;
-<API key>:.5s;-<API key>:.5s;-<API key>:.5s;-<API key>:.5s;animation-duration:.5s;
}
@-webkit-keyframes flipInUp {
0% { -webkit-transform: perspective(400px) rotateX(-90deg); opacity: 0;}
40% { -webkit-transform: perspective(400px) rotateX(5deg);}
70% { -webkit-transform: perspective(400px) rotateX(-5deg);}
100% { -webkit-transform: perspective(400px) rotateX(0deg); opacity: 1;}
}
@-moz-keyframes flipInUp {
0% {transform: perspective(400px) rotateX(-90deg);opacity: 0;}
40% {transform: perspective(400px) rotateX(5deg);}
70% {transform: perspective(400px) rotateX(-5deg);}
100% {transform: perspective(400px) rotateX(0deg);opacity: 1;}
}
@-o-keyframes flipInUp {
0% {-o-transform: perspective(400px) rotateX(-90deg);opacity: 0;}
40% {-o-transform: perspective(400px) rotateX(5deg);}
70% {-o-transform: perspective(400px) rotateX(-5deg);}
100% {-o-transform: perspective(400px) rotateX(0deg);opacity: 1;}
}
@keyframes flipInUp {
0% {transform: perspective(400px) rotateX(-90deg);opacity: 0;}
40% {transform: perspective(400px) rotateX(5deg);}
70% {transform: perspective(400px) rotateX(-5deg);}
100% {transform: perspective(400px) rotateX(0deg);opacity: 1;}
}
@-webkit-keyframes flipInRight {
0% { -webkit-transform: perspective(400px) rotateY(-90deg); opacity: 0;}
40% { -webkit-transform: perspective(400px) rotateY(5deg);}
70% { -webkit-transform: perspective(400px) rotateY(-5deg);}
100% { -webkit-transform: perspective(400px) rotateY(0deg); opacity: 1;}
}
@-moz-keyframes flipInRight {
0% {transform: perspective(400px) rotateY(-90deg);opacity: 0;}
40% {transform: perspective(400px) rotateY(5deg);}
70% {transform: perspective(400px) rotateY(-5deg);}
100% {transform: perspective(400px) rotateY(0deg);opacity: 1;}
}
@-o-keyframes flipInRight {
0% {-o-transform: perspective(400px) rotateY(-90deg);opacity: 0;}
40% {-o-transform: perspective(400px) rotateY(5deg);}
70% {-o-transform: perspective(400px) rotateY(-5deg);}
100% {-o-transform: perspective(400px) rotateY(0deg);opacity: 1;}
}
@keyframes flipInRight {
0% {transform: perspective(400px) rotateY(-90deg);opacity: 0;}
40% {transform: perspective(400px) rotateY(5deg);}
70% {transform: perspective(400px) rotateY(-5deg);}
100% {transform: perspective(400px) rotateY(0deg);opacity: 1;}
}
.flipIn { -<API key>: visible !important; -<API key>: visible !important; -<API key>: visible !important; backface-visibility: visible !important}
.flipIn.south, .flipIn.north { -<API key>: flipInUp; -moz-animation-name: flipInUp; -o-animation-name: flipInUp; animation-name: flipInUp; }
.flipIn.west, .flipIn.east { -<API key>: flipInRight; -moz-animation-name: flipInRight; -o-animation-name: flipInRight; animation-name: flipInRight; }
@-webkit-keyframes fadeIn { 0% {opacity: 0;} 100% {opacity: 1;}}
@-moz-keyframes fadeIn { 0% {opacity: 0;} 100% {opacity: 1;}}
@-o-keyframes fadeIn {0% {opacity: 0;}100% {opacity: 1;}}
@keyframes fadeIn {0% {opacity: 0;}100% {opacity: 1;}}
.fadeIn{-<API key>: fadeIn; -moz-animation-name: fadeIn; -o-animation-name: fadeIn; animation-name: fadeIn;}
/* Modal */
.<API key>{
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('http://gsrthemes.com/aaika/fullwidth/js/img/modal-bg.png');
opacity: .7;
display: none;
}
|
<!doctype html public "-
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $object1</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('object1');
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#object1">$object1</a></h2>
<b>Defined at:</b><ul>
<li><a href="../tests/simpletest/test/compatibility_test.php.html">/tests/simpletest/test/compatibility_test.php</A> -> <a href="../tests/simpletest/test/compatibility_test.php.source.html#l32"> line 32</A></li>
</ul>
<br><b>Referenced 2 times:</b><ul>
<li><a href="../tests/simpletest/test/compatibility_test.php.html">/tests/simpletest/test/compatibility_test.php</a> -> <a href="../tests/simpletest/test/compatibility_test.php.source.html#l32"> line 32</a></li>
<li><a href="../tests/simpletest/test/compatibility_test.php.html">/tests/simpletest/test/compatibility_test.php</a> -> <a href="../tests/simpletest/test/compatibility_test.php.source.html#l34"> line 34</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
|
#include <iostream>
#include "SParser.hpp"
#pragma once
namespace Silent
{
/*static class SymTablePrinter
{
public:
static void Out(std::string str, uint64_t currentTab)
{
std::string tabs = "";
for (uint64_t i = 0; i < currentTab; i++) tabs += "\t";
std::cout << tabs << str << std::endl;
}
SymTablePrinter()
{
}
static void PrintSymTable(SymbolTable* symTable)
{
PrintNode(symTable->self, 0);
}
static void PrintNode(TableNode node, uint64_t currentTab)
{
switch (node.nodeType)
{
case TableNode::Type::Program:
{
Program* p = (Program*)node.GetNode();
Out("Program", currentTab);
currentTab++;
for(TableNode node : p->table->GetItems())
PrintNode(node, currentTab);
currentTab--;
}
break;
case TableNode::Type::Namespace:
{
Namespace* n = (Namespace*)node.GetNode();
Out("Namespace " + n->GetId(), currentTab);
currentTab++;
for (TableNode node : n->GetTable()->GetItems())
PrintNode(node, currentTab);
currentTab--;
}
break;
case TableNode::Type::Subroutine:
{
Subroutine* s = (Subroutine*)node.GetNode();
Out("Subroutine " + s->GetId(), currentTab);
currentTab++;
for (TableNode node : s->GetTable()->GetItems())
PrintNode(node, currentTab);
currentTab--;
}
break;
case TableNode::Type::Variable:
{
Variable* v = (Variable*)node.GetNode();
Out("Variable " + v->GetId(), currentTab);
}
break;
case TableNode::Type::Structure:
{
Type* t = (Type*)node.GetNode();
Out("Type " + t->GetId(), currentTab);
currentTab++;
for (TableNode node : t->GetTable()->GetItems())
PrintNode(node, currentTab);
currentTab--;
}
break;
}
}
};*/
}
|
package net.sf.mmm.util.io.base;
import net.sf.mmm.util.exception.api.<API key>;
/**
* This class is similar to {@link java.nio.ByteBuffer} but a lot simpler.
*
* @see java.nio.ByteBuffer#wrap(byte[], int, int)
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.1.0
*/
public class ByteArrayImpl extends AbstractByteArray {
private final byte[] buffer;
private int minimumIndex;
private int maximumIndex;
/**
* The constructor.
*
* @param capacity is the {@code length} of the internal {@link #getBytes() buffer}.
*/
public ByteArrayImpl(int capacity) {
this(new byte[capacity], 0, -1);
}
/**
* The constructor.
*
* @param buffer is the internal {@link #getBytes() buffer}.
*/
public ByteArrayImpl(byte[] buffer) {
this(buffer, 0, buffer.length - 1);
}
/**
* The constructor.
*
* @param buffer is the internal {@link #getBytes() buffer}.
* @param startIndex is the {@link #getCurrentIndex() current index} as well as the {@link #getMinimumIndex() minimum
* index}.
* @param maximumIndex is the {@link #getMaximumIndex() maximum index}.
*/
public ByteArrayImpl(byte[] buffer, int startIndex, int maximumIndex) {
super();
if (buffer == null) {
throw new <API key>("buffer");
}
this.buffer = buffer;
this.minimumIndex = startIndex;
this.maximumIndex = maximumIndex;
}
@Override
public byte[] getBytes() {
return this.buffer;
}
@Override
public int getCurrentIndex() {
return this.minimumIndex;
}
@Override
public int getMinimumIndex() {
return this.minimumIndex;
}
@Override
public int getMaximumIndex() {
return this.maximumIndex;
}
/**
* This method sets the {@link #getMaximumIndex() maximumIndex}. This may be useful if the buffer should be reused.
* <br>
* <b>ATTENTION:</b><br>
* Be very careful and only use this method if you know what you are doing!
*
* @param maximumIndex is the {@link #getMaximumIndex() maximumIndex} to set. It has to be in the range from {@code 0}
* ( <code>{@link #getCurrentIndex() currentIndex} - 1</code>) to <code>{@link #getBytes()}.length</code>.
*/
protected void setMaximumIndex(int maximumIndex) {
this.maximumIndex = maximumIndex;
}
@Override
public ByteArrayImpl createSubArray(int minimum, int maximum) {
checkSubArray(minimum, maximum);
return new ByteArrayImpl(this.buffer, minimum, maximum);
}
@Override
public String toString() {
return new String(this.buffer, this.minimumIndex, getBytesAvailable());
}
}
|
package com.yahoo.vespaclient;
public class ClusterDef {
private final String name;
public ClusterDef(String name) { this.name = name; }
public String getName() { return name; }
public String getRoute() { return "[Content:cluster=" + name + "]"; }
}
|
import numpy as np
class WordClusters(object):
def __init__(self, vocab, clusters):
self.vocab = vocab
self.clusters = clusters
def ix(self, word):
"""
Returns the index on self.vocab and self.clusters for 'word'
"""
temp = np.where(self.vocab == word)[0]
if temp.size == 0:
raise KeyError("Word not in vocabulary")
else:
return temp[0]
def __getitem__(self, word):
return self.get_cluster(word)
def get_cluster(self, word):
"""
Returns the cluster number for a word in the vocabulary
"""
idx = self.ix(word)
return self.clusters[idx]
def <API key>(self, cluster):
return self.vocab[self.clusters == cluster]
@classmethod
def from_text(cls, fname):
vocab = np.genfromtxt(fname, dtype=str, delimiter=" ", usecols=0)
clusters = np.genfromtxt(fname, dtype=int, delimiter=" ", usecols=1)
return cls(vocab=vocab, clusters=clusters)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.