repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
avanov/type
|
tests/unions/test_unions.py
|
import json
from typing import NamedTuple, Union, Any, Dict, Optional, Mapping
import pytest
from inflection import camelize
import typeit
from ..paths import PETSTORE_SPEC
from typeit import TypeConstructor, flags, Error
from openapi_type import OpenAPI, OperationParameter, Reference, PathItem
def test_type_with_unions():
class VariantA(NamedTuple):
variant_a: int
class VariantB(NamedTuple):
variant_b: int
variant_b_attr: int
class X(NamedTuple):
x: Union[None, VariantA, VariantB]
y: Union[str, VariantA]
mk_x, serialize_x = typeit.TypeConstructor(X)
x = mk_x({'x': {'variant_a': 1}, 'y': 'y'})
assert isinstance(x.x, VariantA)
data = {'x': {'variant_b': 1, 'variant_b_attr': 1}, 'y': 'y'}
x = mk_x(data)
assert isinstance(x.x, VariantB)
assert data == serialize_x(x)
assert mk_x({'x': None, 'y': 'y'}) == mk_x({'y': 'y'})
with pytest.raises(typeit.Error):
# this is not the same as mk_x({}),
# the empty structure is passed as attribute x,
# which should match with only an empty named tuple definition,
# which is not the same as None.
mk_x({'x': {}})
def test_type_with_primitive_union():
class X(NamedTuple):
x: Union[None, str]
mk_x, serialize_x = TypeConstructor(X)
x = mk_x({'x': None})
assert x.x is None
data = {'x': 'test'}
x = mk_x(data)
assert x.x == 'test'
assert data == serialize_x(x)
def test_union_primitive_match():
class X(NamedTuple):
# here, str() accepts everything that could be passed to int(),
# and int() accepts everything that could be passed to float(),
# and we still want to get int values instead of string values,
# and float values instead of rounded int values.
x: Union[str, int, float, bool]
mk_x, serializer = TypeConstructor(X)
x = mk_x({'x': 1})
assert isinstance(x.x, int)
x = mk_x({'x': 1.0})
assert isinstance(x.x, float)
x = mk_x({'x': True})
assert isinstance(x.x, bool)
data = {'x': '1'}
x = mk_x(data)
assert isinstance(x.x, str)
assert serializer(x) == data
def test_test_union_primitive_and_compound_types():
class X(NamedTuple):
x: Union[str, Dict[str, Any]]
mk_x, serialize_x = TypeConstructor(X)
mk_x_nonstrict, serialize_x_nonstrict = TypeConstructor & flags.NonStrictPrimitives ^ X
data = {'x': {'key': 'value'}}
x = mk_x(data)
assert serialize_x(x) == data
x = mk_x_nonstrict(data)
assert serialize_x_nonstrict(x) == data
def test_union_mappings():
class X(NamedTuple):
x: Optional[Mapping[Any, Any]] = None
mk_x, serialize_x = typeit.TypeConstructor ^ X
serialize_x(mk_x({'x': None}))
serialize_x(mk_x({'x': {'y': None}}))
def test_union_errors():
class X(NamedTuple):
x: Optional[int]
mk_x, serialize_x = typeit.TypeConstructor ^ X
with pytest.raises(Error):
mk_x({'x': '1'})
with pytest.raises(Error):
serialize_x(X(x="5"))
# def test_nested_unions_openapi():
# overrides = {
# OperationParameter.in_: 'in',
# Reference.ref: '$ref',
# PathItem.ref: '$ref',
# }
# _camelcase_attribute_names = flags.GlobalNameOverride(lambda x: camelize(x, uppercase_first_letter=False))
#
# parse_spec, serialize_spec = TypeConstructor & overrides & _camelcase_attribute_names ^ OpenAPI
#
# with PETSTORE_SPEC.open('r') as f:
# spec_dict = json.load(f)
#
# spec = parse_spec(spec_dict)
# assert spec
|
xlhj/SpringBoot-Integration
|
springboot-security/src/main/java/com/xlhj/security/handler/SecurityAuthenticationFailureHandler.java
|
package com.xlhj.security.handler;
import com.alibaba.fastjson.JSON;
import com.xlhj.security.common.ResultCode;
import com.xlhj.security.common.ResultData;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @Author: lcj
* @Date: 2020/10/27 10:10
* @Description: 认证失败处理类
* @Version: 0.0.1
*/
@Component
public class SecurityAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
response.setContentType("application/json;charset=UTF-8");
PrintWriter writer = response.getWriter();
writer.write(JSON.toJSONString(ResultData.error(ResultCode.ERROR, "登录失败!")));
}
}
|
grgrzybek/camel
|
components/camel-gae/src/test/java/org/apache/camel/component/gae/http/GHttpTestUtils.java
|
<reponame>grgrzybek/camel<gh_stars>1-10
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.gae.http;
import java.net.URL;
import com.google.appengine.api.urlfetch.HTTPRequest;
import org.apache.camel.CamelContext;
import org.apache.camel.component.gae.TestConfig;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.SimpleRegistry;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
public final class GHttpTestUtils {
private static CamelContext context;
private static GHttpComponent component;
static {
SimpleRegistry registry = new SimpleRegistry();
registry.put("customBinding", new GHttpBinding() { }); // subclass
context = new DefaultCamelContext(registry);
component = new GHttpComponent();
component.setCamelContext(context);
}
private GHttpTestUtils() {
}
public static CamelContext getCamelContext() {
return context;
}
public static Server createTestServer() {
ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
handler.addServlet(new ServletHolder(new GHttpTestServlet()), "/*");
handler.setContextPath("/");
Server server = new Server(TestConfig.getPort());
server.setHandler(handler);
return server;
}
public static GHttpEndpoint createEndpoint(String endpointUri) throws Exception {
return (GHttpEndpoint)component.createEndpoint(endpointUri);
}
public static HTTPRequest createRequest() throws Exception {
return createRequest("http://localhost:8080");
}
public static HTTPRequest createRequest(String url) throws Exception {
return new HTTPRequest(new URL(url));
}
}
|
seleuco/MAME4droid_Native
|
src/emu/emucore.h
|
<filename>src/emu/emucore.h
/***************************************************************************
emucore.h
General core utilities and macros used throughout the emulator.
Copyright <NAME> and the MAME Team.
Visit http://mamedev.org for licensing and usage restrictions.
***************************************************************************/
#pragma once
#ifndef __EMUCORE_H__
#define __EMUCORE_H__
// standard C includes
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdarg.h>
// some cleanups for Solaris for things defined in stdlib.h
#ifdef SDLMAME_SOLARIS
#undef si_status
#undef WWORD
#endif
// standard C++ includes
#include <exception>
#include <typeinfo>
// core system includes
#include "osdcomm.h"
#include "emualloc.h"
#include "corestr.h"
#include "astring.h"
#include "bitmap.h"
#include "tagmap.h"
//**************************************************************************
// COMPILER-SPECIFIC NASTINESS
//**************************************************************************
// Suppress warnings about redefining the macro 'PPC' on LinuxPPC.
#undef PPC
// Suppress warnings about redefining the macro 'ARM' on ARM.
#undef ARM
//**************************************************************************
// FUNDAMENTAL TYPES
//**************************************************************************
// genf is a generic function pointer; cast function pointers to this instead of void *
typedef void genf(void);
// FPTR is used to cast a pointer to a scalar
#ifdef PTR64
typedef UINT64 FPTR;
#else
typedef UINT32 FPTR;
#endif
// pen_t is used to represent pixel values in bitmaps
typedef UINT32 pen_t;
// stream_sample_t is used to represent a single sample in a sound stream
typedef INT32 stream_sample_t;
// running_machine is core to pretty much everything
class running_machine;
//**************************************************************************
// USEFUL COMPOSITE TYPES
//**************************************************************************
// generic_ptr is a union of pointers to various sizes
union generic_ptr
{
void * v;
INT8 * i8;
UINT8 * u8;
INT16 * i16;
UINT16 * u16;
INT32 * i32;
UINT32 * u32;
INT64 * i64;
UINT64 * u64;
};
// PAIR is an endian-safe union useful for representing 32-bit CPU registers
union PAIR
{
#ifdef LSB_FIRST
struct { UINT8 l,h,h2,h3; } b;
struct { UINT16 l,h; } w;
struct { INT8 l,h,h2,h3; } sb;
struct { INT16 l,h; } sw;
#else
struct { UINT8 h3,h2,h,l; } b;
struct { INT8 h3,h2,h,l; } sb;
struct { UINT16 h,l; } w;
struct { INT16 h,l; } sw;
#endif
UINT32 d;
INT32 sd;
};
// PAIR64 is a 64-bit extension of a PAIR
union PAIR64
{
#ifdef LSB_FIRST
struct { UINT8 l,h,h2,h3,h4,h5,h6,h7; } b;
struct { UINT16 l,h,h2,h3; } w;
struct { UINT32 l,h; } d;
struct { INT8 l,h,h2,h3,h4,h5,h6,h7; } sb;
struct { INT16 l,h,h2,h3; } sw;
struct { INT32 l,h; } sd;
#else
struct { UINT8 h7,h6,h5,h4,h3,h2,h,l; } b;
struct { UINT16 h3,h2,h,l; } w;
struct { UINT32 h,l; } d;
struct { INT8 h7,h6,h5,h4,h3,h2,h,l; } sb;
struct { INT16 h3,h2,h,l; } sw;
struct { INT32 h,l; } sd;
#endif
UINT64 q;
INT64 sq;
};
//**************************************************************************
// COMMON CONSTANTS
//**************************************************************************
// constants for expression endianness
enum endianness_t
{
ENDIANNESS_LITTLE,
ENDIANNESS_BIG
};
// declare native endianness to be one or the other
#ifdef LSB_FIRST
const endianness_t ENDIANNESS_NATIVE = ENDIANNESS_LITTLE;
#else
const endianness_t ENDIANNESS_NATIVE = ENDIANNESS_BIG;
#endif
// M_PI is not part of the C/C++ standards and is not present on
// strict ANSI compilers or when compiling under GCC with -ansi
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// orientation of bitmaps
#define ORIENTATION_FLIP_X 0x0001 /* mirror everything in the X direction */
#define ORIENTATION_FLIP_Y 0x0002 /* mirror everything in the Y direction */
#define ORIENTATION_SWAP_XY 0x0004 /* mirror along the top-left/bottom-right diagonal */
#define ROT0 0
#define ROT90 (ORIENTATION_SWAP_XY | ORIENTATION_FLIP_X) /* rotate clockwise 90 degrees */
#define ROT180 (ORIENTATION_FLIP_X | ORIENTATION_FLIP_Y) /* rotate 180 degrees */
#define ROT270 (ORIENTATION_SWAP_XY | ORIENTATION_FLIP_Y) /* rotate counter-clockwise 90 degrees */
//**************************************************************************
// COMMON MACROS
//**************************************************************************
// macro for defining a copy constructor and assignment operator to prevent copying
#define DISABLE_COPYING(_Type) \
private: \
_Type(const _Type &); \
_Type &operator=(const _Type &) \
// macro for declaring enumerator operators that increment/decrement like plain old C
#define DECLARE_ENUM_OPERATORS(_Type) \
inline void operator++(_Type &value) { value = (_Type)((int)value + 1); } \
inline void operator++(_Type &value, int) { value = (_Type)((int)value + 1); } \
inline void operator--(_Type &value) { value = (_Type)((int)value - 1); } \
inline void operator--(_Type &value, int) { value = (_Type)((int)value - 1); }
// standard assertion macros
#undef assert
#undef assert_always
#ifdef MAME_DEBUG
#define assert(x) do { if (!(x)) throw emu_fatalerror("assert: %s:%d: %s", __FILE__, __LINE__, #x); } while (0)
#define assert_always(x, msg) do { if (!(x)) throw emu_fatalerror("Fatal error: %s\nCaused by assert: %s:%d: %s", msg, __FILE__, __LINE__, #x); } while (0)
#else
#define assert(x) do { } while (0)
#define assert_always(x, msg) do { if (!(x)) throw emu_fatalerror("Fatal error: %s (%s:%d)", msg, __FILE__, __LINE__); } while (0)
#endif
// map mame_* helpers to core_* helpers */
#define mame_stricmp core_stricmp
#define mame_strnicmp core_strnicmp
#define mame_strdup core_strdup
#define mame_strwildcmp core_strwildcmp
// prevent the use of rand() -- use mame_rand() instead
#define rand __error_use_mame_rand_instead__
// macros to convert radians to degrees and degrees to radians
#define RADIAN_TO_DEGREE(x) ((180.0 / M_PI) * (x))
#define DEGREE_TO_RADIAN(x) ((M_PI / 180.0) * (x))
// endian-based value: first value is if 'endian' is little-endian, second is if 'endian' is big-endian
#define ENDIAN_VALUE_LE_BE(endian,leval,beval) (((endian) == ENDIANNESS_LITTLE) ? (leval) : (beval))
// endian-based value: first value is if native endianness is little-endian, second is if native is big-endian
#define NATIVE_ENDIAN_VALUE_LE_BE(leval,beval) ENDIAN_VALUE_LE_BE(ENDIANNESS_NATIVE, leval, beval)
// endian-based value: first value is if 'endian' matches native, second is if 'endian' doesn't match native
#define ENDIAN_VALUE_NE_NNE(endian,leval,beval) (((endian) == ENDIANNESS_NATIVE) ? (neval) : (nneval))
// useful macros to deal with bit shuffling encryptions
#define BIT(x,n) (((x)>>(n))&1)
#define BITSWAP8(val,B7,B6,B5,B4,B3,B2,B1,B0) \
((BIT(val,B7) << 7) | (BIT(val,B6) << 6) | (BIT(val,B5) << 5) | (BIT(val,B4) << 4) | \
(BIT(val,B3) << 3) | (BIT(val,B2) << 2) | (BIT(val,B1) << 1) | (BIT(val,B0) << 0))
#define BITSWAP16(val,B15,B14,B13,B12,B11,B10,B9,B8,B7,B6,B5,B4,B3,B2,B1,B0) \
((BIT(val,B15) << 15) | (BIT(val,B14) << 14) | (BIT(val,B13) << 13) | (BIT(val,B12) << 12) | \
(BIT(val,B11) << 11) | (BIT(val,B10) << 10) | (BIT(val, B9) << 9) | (BIT(val, B8) << 8) | \
(BIT(val, B7) << 7) | (BIT(val, B6) << 6) | (BIT(val, B5) << 5) | (BIT(val, B4) << 4) | \
(BIT(val, B3) << 3) | (BIT(val, B2) << 2) | (BIT(val, B1) << 1) | (BIT(val, B0) << 0))
#define BITSWAP24(val,B23,B22,B21,B20,B19,B18,B17,B16,B15,B14,B13,B12,B11,B10,B9,B8,B7,B6,B5,B4,B3,B2,B1,B0) \
((BIT(val,B23) << 23) | (BIT(val,B22) << 22) | (BIT(val,B21) << 21) | (BIT(val,B20) << 20) | \
(BIT(val,B19) << 19) | (BIT(val,B18) << 18) | (BIT(val,B17) << 17) | (BIT(val,B16) << 16) | \
(BIT(val,B15) << 15) | (BIT(val,B14) << 14) | (BIT(val,B13) << 13) | (BIT(val,B12) << 12) | \
(BIT(val,B11) << 11) | (BIT(val,B10) << 10) | (BIT(val, B9) << 9) | (BIT(val, B8) << 8) | \
(BIT(val, B7) << 7) | (BIT(val, B6) << 6) | (BIT(val, B5) << 5) | (BIT(val, B4) << 4) | \
(BIT(val, B3) << 3) | (BIT(val, B2) << 2) | (BIT(val, B1) << 1) | (BIT(val, B0) << 0))
#define BITSWAP32(val,B31,B30,B29,B28,B27,B26,B25,B24,B23,B22,B21,B20,B19,B18,B17,B16,B15,B14,B13,B12,B11,B10,B9,B8,B7,B6,B5,B4,B3,B2,B1,B0) \
((BIT(val,B31) << 31) | (BIT(val,B30) << 30) | (BIT(val,B29) << 29) | (BIT(val,B28) << 28) | \
(BIT(val,B27) << 27) | (BIT(val,B26) << 26) | (BIT(val,B25) << 25) | (BIT(val,B24) << 24) | \
(BIT(val,B23) << 23) | (BIT(val,B22) << 22) | (BIT(val,B21) << 21) | (BIT(val,B20) << 20) | \
(BIT(val,B19) << 19) | (BIT(val,B18) << 18) | (BIT(val,B17) << 17) | (BIT(val,B16) << 16) | \
(BIT(val,B15) << 15) | (BIT(val,B14) << 14) | (BIT(val,B13) << 13) | (BIT(val,B12) << 12) | \
(BIT(val,B11) << 11) | (BIT(val,B10) << 10) | (BIT(val, B9) << 9) | (BIT(val, B8) << 8) | \
(BIT(val, B7) << 7) | (BIT(val, B6) << 6) | (BIT(val, B5) << 5) | (BIT(val, B4) << 4) | \
(BIT(val, B3) << 3) | (BIT(val, B2) << 2) | (BIT(val, B1) << 1) | (BIT(val, B0) << 0))
//**************************************************************************
// EXCEPTION CLASSES
//**************************************************************************
// emu_exception is the base class for all emu-related exceptions
class emu_exception : public std::exception { };
// emu_fatalerror is a generic fatal exception that provides an error string
class emu_fatalerror : public emu_exception
{
public:
emu_fatalerror(const char *format, ...)
: code(0)
{
va_list ap;
va_start(ap, format);
vsprintf(text, format, ap);
va_end(ap);
osd_break_into_debugger(text);
}
emu_fatalerror(const char *format, va_list ap)
: code(0)
{
vsprintf(text, format, ap);
osd_break_into_debugger(text);
}
emu_fatalerror(int _exitcode, const char *format, va_list ap)
: code(_exitcode)
{
vsprintf(text, format, ap);
osd_break_into_debugger(text);
}
const char *string() const { return text; }
int exitcode() const { return code; }
private:
char text[1024];
int code;
};
//**************************************************************************
// CASTING TEMPLATES
//**************************************************************************
// template function for casting from a base class to a derived class that is checked
// in debug builds and fast in release builds
template<class _Dest, class _Source>
inline _Dest downcast(_Source *src)
{
assert(dynamic_cast<_Dest>(src) == src);
return static_cast<_Dest>(src);
}
template<class _Dest, class _Source>
inline _Dest downcast(_Source &src)
{
assert(&dynamic_cast<_Dest>(src) == &src);
return static_cast<_Dest>(src);
}
// template function for cross-casting from one class to another that throws a bad_cast
// exception instead of returning NULL
template<class _Dest, class _Source>
inline _Dest crosscast(_Source *src)
{
_Dest result = dynamic_cast<_Dest>(src);
assert(result != NULL);
if (result == NULL)
throw std::bad_cast();
return result;
}
//**************************************************************************
// COMMON TEMPLATES
//**************************************************************************
template<class T>
class tagged_list
{
DISABLE_COPYING(tagged_list);
T *m_head;
T **m_tailptr;
tagmap_t<T *> m_map;
resource_pool &m_pool;
public:
tagged_list(resource_pool &pool = global_resource_pool) :
m_head(NULL),
m_tailptr(&m_head),
m_pool(pool) { }
virtual ~tagged_list()
{
reset();
}
void reset()
{
while (m_head != NULL)
remove(m_head);
}
T *first() const { return m_head; }
int count() const
{
int num = 0;
for (T *cur = m_head; cur != NULL; cur = cur->m_next)
num++;
return num;
}
int index(T *object) const
{
int num = 0;
for (T *cur = m_head; cur != NULL; cur = cur->m_next)
if (cur == object)
return num;
else
num++;
return -1;
}
int index(const char *tag) const
{
T *object = find(tag);
return (object != NULL) ? index(object) : -1;
}
T *replace(const char *tag, T *object)
{
T *existing = find(tag);
if (existing == NULL)
return append(tag, object);
for (T **objectptr = &m_head; *objectptr != NULL; objectptr = &(*objectptr)->m_next)
if (*objectptr == existing)
{
*objectptr = object;
object->m_next = existing->m_next;
if (m_tailptr == &existing->m_next)
m_tailptr = &object->m_next;
m_map.remove(existing);
pool_free(m_pool, existing);
if (m_map.add_unique_hash(tag, object, false) != TMERR_NONE)
throw emu_fatalerror("Error replacing object named '%s'", tag);
break;
}
return object;
}
T *append(const char *tag, T *object, bool replace_if_duplicate = false)
{
if (m_map.add_unique_hash(tag, object, false) != TMERR_NONE)
throw emu_fatalerror("Error adding object named '%s'", tag);
*m_tailptr = object;
object->m_next = NULL;
m_tailptr = &object->m_next;
return object;
}
void remove(T *object)
{
for (T **objectptr = &m_head; *objectptr != NULL; objectptr = &(*objectptr)->m_next)
if (*objectptr == object)
{
*objectptr = object->m_next;
if (m_tailptr == &object->m_next)
m_tailptr = objectptr;
m_map.remove(object);
pool_free(m_pool, object);
return;
}
}
void remove(const char *tag)
{
T *object = find(tag);
if (object != NULL)
remove(object);
}
T *find(const char *tag) const
{
return m_map.find_hash_only(tag);
}
T *find(int index) const
{
for (T *cur = m_head; cur != NULL; cur = cur->m_next)
if (index-- == 0)
return cur;
return NULL;
}
};
//**************************************************************************
// FUNCTION PROTOTYPES
//**************************************************************************
DECL_NORETURN void fatalerror(const char *format, ...) ATTR_PRINTF(1,2) ATTR_NORETURN;
DECL_NORETURN void fatalerror_exitcode(running_machine *machine, int exitcode, const char *format, ...) ATTR_PRINTF(3,4) ATTR_NORETURN;
inline void fatalerror(const char *format, ...)
{
va_list ap;
va_start(ap, format);
throw emu_fatalerror(format, ap);
va_end(ap);
}
inline void fatalerror_exitcode(running_machine *machine, int exitcode, const char *format, ...)
{
va_list ap;
va_start(ap, format);
throw emu_fatalerror(exitcode, format, ap);
va_end(ap);
}
//**************************************************************************
// INLINE FUNCTIONS
//**************************************************************************
// population count
inline int popcount(UINT32 val)
{
int count;
for (count = 0; val != 0; count++)
val &= val - 1;
return count;
}
// convert a series of 32 bits into a float
inline float u2f(UINT32 v)
{
union {
float ff;
UINT32 vv;
} u;
u.vv = v;
return u.ff;
}
// convert a float into a series of 32 bits
inline UINT32 f2u(float f)
{
union {
float ff;
UINT32 vv;
} u;
u.ff = f;
return u.vv;
}
// convert a series of 64 bits into a double
inline double u2d(UINT64 v)
{
union {
double dd;
UINT64 vv;
} u;
u.vv = v;
return u.dd;
}
// convert a double into a series of 64 bits
inline UINT64 d2u(double d)
{
union {
double dd;
UINT64 vv;
} u;
u.dd = d;
return u.vv;
}
#endif /* __EMUCORE_H__ */
|
worbli/PortalFrontEnd
|
src/components/identity/wbi-camsnap.js
|
import {createMixin} from 'polymer-redux';
import {PolymerElement, html} from '@polymer/polymer/polymer-element.js';
import {translations} from '../../translations/languages.js';
import '../../css/shared-styles.js';
import '../../components/data/wbi-api.js';
import store from '../../global/store.js';
const ReduxMixin = createMixin(store);
class WbiCamsnap extends ReduxMixin(PolymerElement) {
static get template() {
return html`
<style include="shared-styles">
:host {
display: block;
}
*:focus {outline:none}
video {
-webkit-transform: scaleX(-1);
transform: scaleX(-1);
display: var(--video-display, block);
border-radius: 3px;
}
canvas {
display: var(--canvas-display, none);
border-radius: 3px;
}
#capture {
display: var(--capture-display, block);
position:absolute;
bottom:25px;
right: 35px;
background-color: transparent;
border: none;
width: 100px;
height: 100px;
z-index: 200;
}
#retake {
display: var(--retake-display, none);
position:absolute;
bottom:26px;
right: 38px;
z-index: 200;
width: 100px;
height: 100px;
z-index: 200;
border: none;
background-color: transparent;
}
#upload {
display: var(--retake-display, none);
position:absolute;
bottom:25px;
left: 20px;
z-index: 200;
width: 100px;
height: 100px;
z-index: 200;
border: none;
background-color: transparent;
}
.content {
position:relative;
max-width: 640px;
height: 480px;
border-radius: 3px;
}
.overlay {
display: var(--capture-display, block);
position:absolute;
top: -6px;
left: -6px;
z-index: 100;
border-radius: 3px;
}
video {
object-fit: cover;
max-width: 640px;
height: 480px;
width: 67vw;
}
.openCamera {
width: 400px;
}
.error {
padding: 12px;
}
</style>
<wbi-api id='api'></wbi-api>
<template is="dom-if" if="{{showVid}}">
<div class="content">
<template is="dom-if" if="{{selfie}}">
<img src="/images/faceMask.svg" class="overlay">
</template>
<video id="player" autoplay></video>
<canvas id="canvas" width=640 height=480></canvas>
<button id="capture" on-click="_capture"><img src="/images/cam.svg"></button>
<button id="retake" on-click="_retake"><img src="/images/bin2.svg"></button>
<button id="upload" on-click="_upload"><img src="/images/upload2.svg"></button>
</div>
<template is="dom-if" if="{{selfieError}}">
<p class="error">[[selfieError]]</p>
</template>
</template>
<template is="dom-if" if="{{!showVid}}">
<button type="button" on-click="_getCam" class="openCamera">[[txt.enableCameraTakePicture]]</button>
</template>
`;
}
static get properties() {
return {
language: {
type: String,
readOnly: true,
observer: '_language',
},
mode: {
type: Text,
readOnly: true,
},
showVid: {
type: Boolean,
value: false,
},
selfie: {
type: Boolean,
value: false,
},
upload: {
type: Boolean,
value: false,
notify: true,
reflectToAttribue: true,
},
base64: {
type: String,
notify: true,
reflectToAttribue: true,
},
blob: {
type: Object,
notify: true,
reflectToAttribue: true,
},
fileName: {
type: String,
},
stopCam: {
type: Boolean,
observer: '_stopCam',
},
closenow: {
type: Boolean,
notify: true,
reflectToAttribue: true,
},
};
}
static mapStateToProps(state, element) {
return {
language: state.language,
mode: state.mode,
color: state.color,
env: state.env,
};
}
_stopCam() {
if (this.stopCam) {
this.selfieError = '';
this.showVid = false;
this.stream.getTracks()[0].stop();
}
}
_getCam() {
const constraints = {video: {width: 800, height: 600}};
navigator.mediaDevices.getUserMedia(constraints)
.then((stream) => {
this.stream = stream;
this.shadowRoot.querySelector('#player').srcObject = this.stream;
});
this.showVid = true;
}
_upload() {
this.selfieError = '';
localStorage.setItem(this.fileName, this.base64);
// flip base 64
this.$.api.uploadImage(this.blob, this.fileName)
.then((response) => {
if (response.rejectedDocuments.length === 0) {
this.closenow = true;
this._retake();
this.showVid = false;
} else {
this._retake();
this.selfieError = 'Face detection failed. Ensure your face is clearly visible and no other people in the background.';
};
});
this.upload = true;
}
_capture() {
this.updateStyles({'--capture-display': 'none'});
this.updateStyles({'--retake-display': 'block'});
this.updateStyles({'--video-display': 'none'});
this.updateStyles({'--canvas-display': 'block'});
const player = this.shadowRoot.querySelector('#player');
const canvas = this.shadowRoot.querySelector('#canvas');
const context = canvas.getContext('2d');
context.save();
context.scale(1, 1);
context.drawImage(player, 0, 0, canvas.width*1, canvas.height);
context.restore();
this.base64 = canvas.toDataURL('image/jpeg');
this.blob = this._dataURLToBlob(this.base64);
}
_retake() {
this.updateStyles({'--capture-display': 'block'});
this.updateStyles({'--retake-display': 'none'});
this.updateStyles({'--video-display': 'block'});
this.updateStyles({'--canvas-display': 'none'});
}
_dataURLToBlob(dataURL) {
const BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
const parts = dataURL.split(',');
const contentType = parts[0].split(':')[1];
const raw = parts[1];
return new Blob([raw], {type: contentType});
}
const parts = dataURL.split(BASE64_MARKER);
const contentType = parts[0].split(':')[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
_language(e) {
this.txt = translations[this.language];
}
} window.customElements.define('wbi-camsnap', WbiCamsnap);
|
tormath1/jclouds
|
apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseServerWithAddressExtensionsTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jclouds.openstack.nova.v2_0.parse;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.json.BaseItemParserTest;
import org.jclouds.json.config.GsonModule;
import org.jclouds.openstack.nova.v2_0.config.NovaParserModule;
import org.jclouds.openstack.nova.v2_0.domain.Address;
import org.jclouds.openstack.nova.v2_0.domain.Server;
import org.jclouds.openstack.nova.v2_0.domain.Server.Status;
import org.jclouds.openstack.nova.v2_0.domain.ServerExtendedStatus;
import org.jclouds.openstack.v2_0.domain.Link;
import org.jclouds.openstack.v2_0.domain.Link.Relation;
import org.jclouds.openstack.v2_0.domain.Resource;
import org.jclouds.rest.annotations.SelectJson;
import org.testng.annotations.Test;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import java.net.URI;
@Test(groups = "unit", testName = "ParseServerWithAddressExtensionsTest")
public class ParseServerWithAddressExtensionsTest extends BaseItemParserTest<Server> {
@Override
public String resource() {
return "/server_details_with_address_ext.json";
}
@Override
@SelectJson("server")
@Consumes(MediaType.APPLICATION_JSON)
public Server expected() {
return Server
.builder()
.id("0bdc3a8d-3a96-4ccc-bb40-715537a7df7b")
.tenantId("cac29c920a6149aabe499757b6ba81c7")
.userId("ed15e338032f4a2c85b7fa80e40b9917")
.name("cloudts-f07")
.updated(new SimpleDateFormatDateService().iso8601SecondsDateParse("2016-02-17T14:48:00Z"))
.created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2016-02-17T14:46:13Z"))
.hostId("18a9cd55f76c520dcad6c31d5b2b8f4c921979629c0274c0f7d2de39")
.status(Status.ACTIVE)
.image(
Resource
.builder()
.id("9a9f496a-f5c2-4286-81a4-98189a48777a")
.links(
Link.create(
Relation.BOOKMARK,
URI.create("http://openstack:8774/cac29c920a6149aabe499757b6ba81c7/images/9a9f496a-f5c2-4286-81a4-98189a48777a")))
.build())
.flavor(
Resource
.builder()
.id("3")
.links(
Link.create(
Relation.BOOKMARK,
URI.create("http://openstack:8774/cac29c920a6149aabe499757b6ba81c7/flavors/3")))
.build())
.links(
Link.create(
Relation.SELF,
URI.create("http://openstack:8774/v2/cac29c920a6149aabe499757b6ba81c7/servers/0bdc3a8d-3a96-4ccc-bb40-715537a7df7b")),
Link.create(
Relation.BOOKMARK,
URI.create("http://openstack:8774/cac29c920a6149aabe499757b6ba81c7/servers/0bdc3a8d-3a96-4ccc-bb40-715537a7df7b")))
.metadata(ImmutableMap.<String, String>of("jclouds-group", "cloudts"))
.addresses(ImmutableMultimap.<String, Address>builder()
.putAll("jenkins",
Address.builder().version(4).addr("172.16.130.24").macAddr("fa:16:3e:bf:82:43").type("fixed").build(),
Address.builder().version(4).addr("10.8.54.75").macAddr("fa:16:3e:bf:82:43").type("floating").build())
.build())
.diskConfig("MANUAL")
.configDrive("")
.availabilityZone("nova")
.accessIPv4("")
.accessIPv6("")
.keyName("jenkins")
.extendedStatus(ServerExtendedStatus.builder().vmState("active").powerState(1).build())
.build();
}
protected Injector injector() {
return Guice.createInjector(new NovaParserModule(), new GsonModule());
}
}
|
onmyway133/Runtime-Headers
|
iOS/10.0.2/PrivateFrameworks/ChatKit.framework/CKAvatarPickerViewController.h
|
/* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/ChatKit.framework/ChatKit
*/
@interface CKAvatarPickerViewController : UIViewController <CKAvatarPickerLayoutDelegate, CNAvatarViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate> {
UIViewController * _avatarOrbPresentingViewController;
UICollectionView * _collectionView;
CKConversation * _conversation;
<CKAvatarPickerViewControllerDelegate> * _delegate;
CKAvatarPickerLayout * _layout;
long long _style;
CNContactStore * _suggestionsEnabledContactStore;
UITapGestureRecognizer * _tapGestureRecognizer;
CKAvatarTitleCollectionReusableView * _titleView;
NSMapTable * _visibleTitleViews;
}
@property (nonatomic) UIViewController *avatarOrbPresentingViewController;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) CKConversation *conversation;
@property (readonly, copy) NSString *debugDescription;
@property (nonatomic) <CKAvatarPickerViewControllerDelegate> *delegate;
@property (readonly, copy) NSString *description;
@property (readonly) unsigned long long hash;
@property (nonatomic, retain) CKAvatarPickerLayout *layout;
@property (nonatomic) long long style;
@property (nonatomic, retain) CNContactStore *suggestionsEnabledContactStore;
@property (readonly) Class superclass;
@property (nonatomic, retain) UITapGestureRecognizer *tapGestureRecognizer;
@property (nonatomic, retain) CKAvatarTitleCollectionReusableView *titleView;
@property (nonatomic, readonly) struct CGRect { struct CGPoint { double x_1_1_1; double x_1_1_2; } x1; struct CGSize { double x_2_1_1; double x_2_1_2; } x2; } titleViewFrame;
@property (nonatomic, retain) NSMapTable *visibleTitleViews;
- (void).cxx_destruct;
- (void)_animateInTitleView;
- (void)_animateOutTitleView;
- (void)_animateToLayout:(unsigned long long)arg1;
- (bool)_canCollapseToPancakeView;
- (id)_contactNameSupplementaryViewAtIndexPath:(id)arg1;
- (id)_cutoutSupplementaryViewAtIndexPath:(id)arg1;
- (void)_handleAddressBookChange:(id)arg1;
- (void)_handleConversationRecipientsDidChange:(id)arg1;
- (void)_handleGroupNameChange:(id)arg1;
- (void)_handleTapOnCollectionView:(id)arg1;
- (void)_handleTranscriptScroll:(id)arg1;
- (void)_setTitle:(id)arg1 animated:(bool)arg2;
- (id)_titleSupplementaryViewAtIndexPath:(id)arg1;
- (id)avatarOrbPresentingViewController;
- (bool)avatarPickerLayoutShouldShowTitle:(id)arg1;
- (id)avatarView:(id)arg1 orderedPropertiesForProperties:(id)arg2 category:(id)arg3;
- (void)collapseToPancakeView;
- (id)collectionView;
- (id)collectionView:(id)arg1 cellForItemAtIndexPath:(id)arg2;
- (long long)collectionView:(id)arg1 numberOfItemsInSection:(long long)arg2;
- (id)collectionView:(id)arg1 viewForSupplementaryElementOfKind:(id)arg2 atIndexPath:(id)arg3;
- (id)conversation;
- (void)dealloc;
- (id)delegate;
- (void)expandToExpandedView;
- (bool)hasTitle;
- (id)initWithConversation:(id)arg1;
- (id)layout;
- (void)loadView;
- (long long)numberOfSectionsInCollectionView:(id)arg1;
- (id)presentingViewControllerForAvatarView:(id)arg1;
- (void)setAvatarOrbPresentingViewController:(id)arg1;
- (void)setCollectionView:(id)arg1;
- (void)setConversation:(id)arg1;
- (void)setDelegate:(id)arg1;
- (void)setLayout:(id)arg1;
- (void)setStyle:(long long)arg1;
- (void)setSuggestionsEnabledContactStore:(id)arg1;
- (void)setTapGestureRecognizer:(id)arg1;
- (void)setTitleView:(id)arg1;
- (void)setVisibleTitleViews:(id)arg1;
- (long long)style;
- (id)suggestionsEnabledContactStore;
- (id)tapGestureRecognizer;
- (id)titleView;
- (struct CGRect { struct CGPoint { double x_1_1_1; double x_1_1_2; } x1; struct CGSize { double x_2_1_1; double x_2_1_2; } x2; })titleViewFrame;
- (void)viewWillLayoutSubviews;
- (id)visibleTitleViews;
@end
|
liuhaozzu/linux
|
assembly-language/inline.c
|
<filename>assembly-language/inline.c
#include <stdio.h>
int main(void){
int a=10,b;
__asm__("movl %1, %%eax\n\t"
"movl %%eax, %0\n\t"
:"=r"(b) /*output*/
:"r"(a) /*input*/
:"%eax" /*clobbered register*/
);
printf("Result : %d, %d\n",a,b);
return 0;
}
|
wkoszek/book-programming-ruby
|
src/ex0641.rb
|
# Sample code from Programing Ruby, page 371
class Test
@cls_var = 123
class <<self
attr_reader :cls_var
end
end
Test.cls_var
|
loriab/qccddb
|
qcdb/tests/nwchem_tests/test_tce_uhf_uccsd.py
|
<reponame>loriab/qccddb<filename>qcdb/tests/nwchem_tests/test_tce_uhf_uccsd.py<gh_stars>1-10
# TCE UHF UCCSD
import os
import sys
import pytest
import qcdb
from ..utils import *
def tce_uccsd(return_value):
hf = -74.656470840577
ccsd_tot = -74.695659393231864
ccsd_corl = -0.039188552654924
assert compare_values(hf, qcdb.variable("HF TOTAL ENERGY"), 5, "hf ref")
assert compare_values(ccsd_tot, qcdb.variable("CCSD TOTAL ENERGY"), 5, "ccsd tot")
assert compare_values(ccsd_corl, qcdb.variable("CCSD CORRELATION ENERGY"), 5, "ccsd corl")
@using("nwchem")
def test_1_uccsd():
h2o = qcdb.set_molecule(
"""
1 2
H
O H 0.96
H O 0.96 H 104.0
"""
)
qcdb.set_options(
{
"basis": "sto-3g",
"scf__e_convergence": 1e-10,
"nwchem_charge": 1,
"nwchem_scf__uhf": True,
"nwchem_scf__doublet": True,
"nwchem_scf__tol2e": 1e-10,
"qc_module": "TCE",
"nwchem_tce__ccsd": True,
}
)
val = qcdb.energy("nwc-ccsd")
tce_uccsd(val)
@using("nwchem")
def test_mol_chg_error():
h2o = qcdb.set_molecule(
"""
H
O H 0.96
H O 0.96 H 104.0
"""
)
qcdb.set_options(
{
"basis": "sto-3g",
"nwchem_charge": 1,
}
)
with pytest.raises(qcdb.KeywordReconciliationError):
qcdb.energy("nwc-ccsd")
|
bocke/ucc
|
test/cases/type_propagation/truncation.c
|
<reponame>bocke/ucc<gh_stars>10-100
// RUN: %check %s -Wtruncation
main()
{
char c = 0;
short s = 0;
int i = 0;
long l = 0;
long long ll = 0;
float f = 0;
double d = 0;
c = 5; // CHECK: !/warn.*trunc/
c = s; // CHECK: warning: possible truncation converting short to char
s = c; // CHECK: !/warn.*trunc/
s = l; // CHECK: warning: possible truncation converting long to short
i = c; // CHECK: !/warn.*trunc/
f = d; // CHECK: warning: possible truncation converting double to float
d = f; // CHECK: !/warn.*trunc/
}
|
austenmadden/arelastic
|
test/arelastic/queries/regexp_test.rb
|
require 'helper'
class Arelastic::Queries::ExistsTest < Minitest::Test
def test_setting_value_as_regexp_object
assert_raises TypeError do
Arelastic::Queries::Regexp.new('color', /yellow(-green)?/)
end
end
def test_string_value
expected = { 'regexp' => { 'color' => 'blue(-green)?' } }
assert_equal expected, Arelastic::Queries::Regexp.new('color', 'blue(-green)?').as_elastic
end
end
|
brunolmfg/resteasy
|
testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/form/resource/NestedCollectionsFormTelephoneNumber.java
|
package org.jboss.resteasy.test.form.resource;
import org.jboss.resteasy.annotations.Form;
import jakarta.ws.rs.FormParam;
public class NestedCollectionsFormTelephoneNumber {
@Form(prefix = "country")
public NestedCollectionsFormCountry country;
@FormParam("number")
public String number;
}
|
freder/PageBotExamples
|
More/E00_Publications/TypeSpecimens/FitLinesBanner.py
|
<filename>More/E00_Publications/TypeSpecimens/FitLinesBanner.py
# -----------------------------------------------------------------------------
#
# P A G E B O T E X A M P L E S
#
# Copyright (c) 2017 <NAME> <https://github.com/thomgb>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyxyz.org/flat
# -----------------------------------------------------------------------------
#
from random import random
from math import sin, cos, radians
from pagebot.fonttoolbox.objects.font import findFont, Font
from pagebot.elements import *
from pagebot.elements.variablefonts.animationframe import AnimationFrame
from pagebot.document import Document
from pagebot.constants import Letter, RIGHT
from pagebot import getContext
from pagebot.toolbox.units import em
from pagebot.toolbox.color import blackColor, whiteColor
class AnimatedBannerFrame(AnimationFrame):
def drawAnimatedFrame(self, view, origin):
"""Draw the content of the element, responding to size, styles, font and content.
Create 2 columns for the self.fontSizes ranges that show the text with and without [opsz]
if the axis exists.
"""
ox, oy, _ = origin
c = self.context
# Now make fitting text instance
bs = c.fitString(self.sampleText, style=self.style, w=self.w, h=self.h)
tx, ty, _, _ = bs.bounds()
c.text(bs, (ox-tx, oy-ty))
c = getContext('DrawBot')
W, H = 2040, 1020 # Type Network banners
M = 30
# Claire: for now, add your Fit-Variable_1.ttf to your /Library/Fonts and it can be found.
font = findFont('Fit-Variable_1')
# Fit axes to select from: here we are showing the optical size.
# Define tag list for axes to be part of the animation as sequence
sequenceAxes = ['wdth']
sequenceLength = 3 # Seconds per sequence
sequences = 2 # Amount of sequences in choreography
duration = sequenceLength * sequences # Total duration of the animation in seconds
framesPerSecond = 15 # 2 for testing
frameCnt = duration * framesPerSecond # Total number of frames
axisFrames = sequenceLength * framesPerSecond # Number of frames per axis sequence.
# Create a new doc, with the right amount of frames/pages.
doc = Document(w=W, h=H, frameDuration=1.0/framesPerSecond,
autoPages=frameCnt, context=c)
# Sample text to show in the animation
sample1 = 'Fitting'
sample2 = 'in with'
sample3 = 'Fit'
frameIndex = 1 # Same as page index in the document
for sequenceIndex in range(sequences):
for axisFrameIndex in range(axisFrames):
page = doc[frameIndex] # Get the current frame-page
newRect(x=0, y=0, w=page.w, h=page.h, fill=blackColor, parent=page)
page.padding = M
phicos = cos(radians(axisFrameIndex/axisFrames * 360))*0.5+0.5
# Overall style for the frame
pw = page.pw # Usable page/frame area, without paddind
ph = page.ph
if sequenceIndex == 0:
x1 = 0
y1 = ph/3 + M + ph/3*phicos
ww1 = pw
hh1 = ph - y1
x2 = 0
y2 = 0
ww2 = pw*3/4
hh2 = ph - hh1 - M
x3 = ww2 + M
y3 = 0
ww3 = pw - x3
hh3 = hh2
elif sequenceIndex == 1:
x1 = 0
y1 = ph/3 + M + ph/3*phicos
ww1 = pw/3 + ph*2/3*phicos
hh1 = ph - y1
x2 = 0
y2 = 0
hh2 = ph - hh1 - M
if ww1 < pw*2/3:
ww2 = ww1
x3 = ww2 + M
y3 = 0
ww3 = pw - x3
hh3 = ph
else:
ww2 = pw/2 + pw/4*phicos
x3 = ww2 + M
y3 = 0
ww3 = pw - x3
hh3 = hh2
style = dict(leading=em(1.4), font=font, xTextAlign=RIGHT, textFill=whiteColor,
fill=blackColor, roundVariableFitLocation=False)
AnimatedBannerFrame(sample1, font, frameCnt, frameIndex, parent=page, style=style,
x=x1+M, y=y1+M, w=ww1, h=hh1, context=c)
AnimatedBannerFrame(sample2, font, frameCnt, frameIndex, parent=page, style=style,
x=x2+M, y=y2+M, w=ww2, h=hh2, context=c)
AnimatedBannerFrame(sample3, font, frameCnt, frameIndex, parent=page, style=style,
x=x3+M, y=y3+M, w=ww3, h=hh3, context=c)
frameIndex += 1 # Prepare for the next frame
doc.solve()
doc.export('_export/%s_%s%s%s.gif' % (font.info.familyName, sample1, sample2, sample3))
|
osehra-ocp/ocp-ui
|
app/components/SearchBar/index.js
|
<reponame>osehra-ocp/ocp-ui<filename>app/components/SearchBar/index.js
/**
*
* SearchBar
*
*/
import {
SEARCH_BY_DATE,
SEARCH_BY_DUE_DATE,
SEARCH_BY_ID,
SEARCH_BY_NAME,
SEARCH_PATIENT,
SEARCH_PRACTITIONER,
} from 'components/SearchBar/constants';
import { Formik } from 'formik';
import head from 'lodash/head';
import isEmpty from 'lodash/isEmpty';
import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage } from 'react-intl';
import yup from 'yup';
import messages from './messages';
import SearchBarForm from './SearchBarForm';
function SearchBar(props) {
const { minimumLength, onSearch, searchField, showToDoSpecificFilters, showUserRegistrationRoleSelection } = props;
const composedSearchFields = getToDoSpecificSearchField(searchField, showToDoSpecificFilters);
const searchFormProps = { searchField: composedSearchFields, showToDoSpecificFilters, showUserRegistrationRoleSelection };
function getToDoSpecificSearchField(searchFieldObject, showAdditionalSearchFields) {
const newSearchTypes = !showAdditionalSearchFields ? searchFieldObject.searchTypes : [...searchFieldObject.searchTypes,
{
value: SEARCH_BY_DATE,
display: <FormattedMessage {...messages.searchByDate} />,
}, {
value: SEARCH_BY_DUE_DATE,
display: <FormattedMessage {...messages.searchByDueDate} />,
},
];
return {
searchTypes: newSearchTypes,
resourceTypes: searchFieldObject.resourceTypes,
searchValueHintText: searchFieldObject.searchValueHintText,
};
}
function initialFormValues() {
let initialValues = { showInactive: false, searchType: SEARCH_BY_NAME, resourceType: SEARCH_PRACTITIONER };
if (!isEmpty(searchField.searchTypes)) {
initialValues = {
showInactive: false,
searchType: head(searchField.searchTypes).value,
};
}
if (!isEmpty(searchField.searchTypes) && showUserRegistrationRoleSelection) {
initialValues = {
showInactive: false,
searchType: head(searchField.searchTypes).value,
resourceType: head(searchField.resourceTypes).value,
};
}
return initialValues;
}
return (
<div>
<Formik
initialValues={initialFormValues(searchField)}
onSubmit={(values, actions) => {
const { searchValue, showInactive, searchType, resourceType } = values;
if (showUserRegistrationRoleSelection) {
onSearch(searchValue, showInactive, searchType, resourceType);
} else {
onSearch(searchValue, showInactive, searchType);
}
actions.setSubmitting(false);
}}
validationSchema={yup.object().shape({
searchValue: yup.string()
.min(minimumLength, (<FormattedMessage {...messages.validation.minLength} values={{ minimumLength }} />)),
searchType: yup.string()
.required((<FormattedMessage {...messages.validation.required} />)),
showInactive: yup.boolean(),
})}
render={(formikProps) => <SearchBarForm {...formikProps} {...searchFormProps} />}
/>
</div>
);
}
SearchBar.propTypes = {
onSearch: PropTypes.func.isRequired,
minimumLength: PropTypes.number.isRequired,
showToDoSpecificFilters: PropTypes.bool,
showUserRegistrationRoleSelection: PropTypes.bool,
searchField: PropTypes.shape({
searchTypes: PropTypes.arrayOf(PropTypes.shape({
value: PropTypes.string.isRequired,
display: PropTypes.node.isRequired,
})).isRequired,
resourceTypes: PropTypes.arrayOf(PropTypes.shape({
value: PropTypes.string.isRequired,
display: PropTypes.node.isRequired,
})),
searchValueHintText: PropTypes.node.isRequired,
}),
};
SearchBar.defaultProps = {
minimumLength: 3,
showToDoSpecificFilters: false,
showUserRegistrationRoleSelection: false,
searchField: {
searchTypes: [{
value: SEARCH_BY_NAME,
display: <FormattedMessage {...messages.searchByName} />,
}, {
value: SEARCH_BY_ID,
display: <FormattedMessage {...messages.searchById} />,
}],
resourceTypes: [{
value: SEARCH_PRACTITIONER,
display: <FormattedMessage {...messages.searchPractitioner} />,
}, {
value: SEARCH_PATIENT,
display: <FormattedMessage {...messages.searchPatient} />,
}],
searchValueHintText: <FormattedMessage {...messages.hintText} />,
},
};
export default SearchBar;
|
MZQi/Fragrans
|
Fragrans/Fragrans/Fragrans/UIKit/UITableView+Fragrans.h
|
//
// UITableView+Fragrans.h
// Fragrans
//
// Created by qmz on 2019/3/11.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UITableView (Fragrans)
/**
create tableView by UITableViewStyle
*/
- (UITableView *)initWithStyle:(UITableViewStyle)style;
/**
create tableView by UITableViewStyle
*/
+ (UITableView *)tableViewWithStyle:(UITableViewStyle)style;
/**
create tableView by UITableViewStyle + UITableViewCellSeparatorStyle
*/
- (UITableView *)initWithStyle:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle;
/**
create tableView by UITableViewStyle + UITableViewCellSeparatorStyle
*/
+ (UITableView *)tableViewWithStyle:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle;
/**
create tableView by UITableViewStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithStyle:(UITableViewStyle)style backgroundColor:(id)backgroundColor;
/**
create tableView by UITableViewStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithStyle:(UITableViewStyle)style backgroundColor:(id)backgroundColor;
/**
create tableView by UITableViewStyle + UITableViewCellSeparatorStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithStyle:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(id)backgroundColor;
/**
create tableView by UITableViewStyle + UITableViewCellSeparatorStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithStyle:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(id)backgroundColor;
/**
create tableView by UITableViewStyle + delegateAndDataSource
*/
- (UITableView *)initWithStyle:(UITableViewStyle)style delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by UITableViewStyle + delegateAndDataSource
*/
+ (UITableView *)tableViewWithStyle:(UITableViewStyle)style delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by UITableViewStyle + UITableViewCellSeparatorStyle + delegateAndDataSource
*/
- (UITableView *)initWithStyle:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by UITableViewStyle + UITableViewCellSeparatorStyle + delegateAndDataSource
*/
+ (UITableView *)tableViewWithStyle:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by UITableViewStyle + backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithStyle:(UITableViewStyle)style backgroundColor:(id)backgroundColor delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by UITableViewStyle + backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithStyle:(UITableViewStyle)style backgroundColor:(id)backgroundColor delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by UITableViewStyle + UITableViewCellSeparatorStyle
+ backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithStyle:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(id)backgroundColor delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by UITableViewStyle + UITableViewCellSeparatorStyle
+ backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithStyle:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(nullable id)backgroundColor delegateAndDataSource:(nullable id)delegateAndDataSource;
/**
create tableView by frame + UITableViewStyle + UITableViewCellSeparatorStyle
*/
- (UITableView *)initWithFrame:(CGRect)frame style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle;
/**
create tableView by frame + UITableViewStyle + UITableViewCellSeparatorStyle
*/
+ (UITableView *)tableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle;
/**
create tableView by frame + UITableViewStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithFrame:(CGRect)frame style:(UITableViewStyle)style backgroundColor:(id)backgroundColor;
/**
create tableView by frame + UITableViewStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style backgroundColor:(id)backgroundColor;
/**
create tableView by frame + UITableViewStyle + UITableViewCellSeparatorStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithFrame:(CGRect)frame style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(id)backgroundColor;
/**
create tableView by frame + UITableViewStyle + UITableViewCellSeparatorStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(id)backgroundColor;
/**
create tableView by frame + UITableViewStyle + delegateAndDataSource
*/
- (UITableView *)initWithFrame:(CGRect)frame style:(UITableViewStyle)style delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by frame + UITableViewStyle + delegateAndDataSource
*/
+ (UITableView *)tableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by frame + UITableViewStyle + UITableViewCellSeparatorStyle
+ delegateAndDataSource
*/
- (UITableView *)initWithFrame:(CGRect)frame style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by frame + UITableViewStyle + UITableViewCellSeparatorStyle
+ delegateAndDataSource
*/
+ (UITableView *)tableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by frame + UITableViewStyle + backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithFrame:(CGRect)frame style:(UITableViewStyle)style backgroundColor:(id)backgroundColor delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by frame + UITableViewStyle + backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style backgroundColor:(id)backgroundColor delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by frame + UITableViewStyle + UITableViewCellSeparatorStyle
+ backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithFrame:(CGRect)frame style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(id)backgroundColor delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by frame + UITableViewStyle + UITableViewCellSeparatorStyle
+ backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithFrame:(CGRect)frame style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(nullable id)backgroundColor delegateAndDataSource:(nullable id)delegateAndDataSource;
/**
create tableView by center and bounds
*/
- (UITableView *)initWithCenter:(CGPoint)center bounds:(CGRect)bounds;
/**
create tableView by center and bounds
*/
+ (UITableView *)tableViewWithCenter:(CGPoint)center bounds:(CGRect)bounds;
/**
create tableView by center and bounds + UITableViewStyle
*/
- (UITableView *)initWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style;
/**
create tableView by center and bounds + UITableViewStyle
*/
+ (UITableView *)tableViewWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style;
/**
create tableView by center and bounds + UITableViewStyle + UITableViewCellSeparatorStyle
*/
- (UITableView *)initWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle;
/**
create tableView by center and bounds + UITableViewStyle + UITableViewCellSeparatorStyle
*/
+ (UITableView *)tableViewWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle;
/**
create tableView by center and bounds + UITableViewStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style backgroundColor:(id)backgroundColor;
/**
create tableView by center and bounds + UITableViewStyle + backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style backgroundColor:(id)backgroundColor;
/**
create tableView by center and bounds + UITableViewStyle + UITableViewCellSeparatorStyle
+ backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(id)backgroundColor;
/**
create tableView by center and bounds + UITableViewStyle + UITableViewCellSeparatorStyle
+ backgroundColor
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(id)backgroundColor;
/**
create tableView by center and bounds + UITableViewStyle + delegateAndDataSource
*/
- (UITableView *)initWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by center and bounds + UITableViewStyle + delegateAndDataSource
*/
+ (UITableView *)tableViewWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by center and bounds + UITableViewStyle
+ UITableViewCellSeparatorStyle + delegateAndDataSource
*/
- (UITableView *)initWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by center and bounds + UITableViewStyle + UITableViewCellSeparatorStyle
+ delegateAndDataSource
*/
+ (UITableView *)tableViewWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by center and bounds + UITableViewStyle + backgroundColor
+ delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style backgroundColor:(id)backgroundColor delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by center and bounds + UITableViewStyle + backgroundColor
+ delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style backgroundColor:(id)backgroundColor delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by center and bounds + UITableViewStyle + UITableViewCellSeparatorStyle
+ backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
- (UITableView *)initWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(id)backgroundColor delegateAndDataSource:(id)delegateAndDataSource;
/**
create tableView by center and bounds + UITableViewStyle + UITableViewCellSeparatorStyle
+ backgroundColor + delegateAndDataSource
@param backgroundColor UIColor或者NSString或者NSNumber格式
*/
+ (UITableView *)tableViewWithCenter:(CGPoint)center bounds:(CGRect)bounds style:(UITableViewStyle)style separatorStyle:(UITableViewCellSeparatorStyle)separatorStyle backgroundColor:(nullable id)backgroundColor delegateAndDataSource:(nullable id)delegateAndDataSource;
@end
NS_ASSUME_NONNULL_END
|
donoghuc/puppet
|
lib/puppet/ssl/key.rb
|
require 'puppet/ssl/base'
require 'puppet/indirector'
# Manage private and public keys as a pair.
class Puppet::SSL::Key < Puppet::SSL::Base
wraps OpenSSL::PKey::RSA
extend Puppet::Indirector
indirects :key, :terminus_class => :file, :doc => <<DOC
This indirection wraps an `OpenSSL::PKey::RSA object, representing a private key.
The indirection key is the certificate CN (generally a hostname).
DOC
# Because of how the format handler class is included, this
# can't be in the base class.
def self.supported_formats
[:s]
end
attr_accessor :password_file
# Knows how to create keys with our system defaults.
def generate
Puppet.info _("Creating a new SSL key for %{name}") % { name: name }
@content = OpenSSL::PKey::RSA.new(Puppet[:keylength].to_i)
end
def initialize(name)
super
if ca?
@password_file = Puppet[:capass]
else
@password_file = Puppet[:passfile]
end
end
def password
return nil unless password_file and Puppet::FileSystem.exist?(password_file)
# Puppet generates files at the default Puppet[:capass] using ASCII
# User configured :passfile could be in any encoding
# Use BINARY given the string is passed to an OpenSSL API accepting bytes
# note this is only called internally
Puppet::FileSystem.read(password_file, :encoding => Encoding::BINARY)
end
# Optionally support specifying a password file.
def read(path)
return super unless password_file
# RFC 1421 states PEM is 7-bit ASCII https://tools.ietf.org/html/rfc1421
@content = wrapped_class.new(Puppet::FileSystem.read(path, :encoding => Encoding::ASCII), password)
end
def to_s
if pass = password
@content.export(OpenSSL::Cipher::DES.new(:EDE3, :CBC), pass)
else
return super
end
end
end
|
shaneing/droplets
|
src/utils/keycodes.js
|
const keycodes = {
ENTER: {
key: 'Enter',
code: 13,
},
ESCAPE: {
key: 'Escape',
code: '27',
},
};
module.exports = keycodes;
|
1550324080/yblog
|
src/main/java/com/boot/pojo/archive.java
|
<reponame>1550324080/yblog<filename>src/main/java/com/boot/pojo/archive.java
package com.boot.pojo;
import io.swagger.annotations.ApiModel;
import java.io.Serializable;
@ApiModel(value = "归档实体类",description = "封装归档的信息")
public class archive implements Serializable {
/**
* 不建立对应的数据库,因为这个归档每次都是从t_article表中查询
*/
private String months; //归档年-月
private String count; //对应归档年-月匹配的文章数量
public archive() {
}
public archive(String months, String count) {
this.months = months;
this.count = count;
}
public String getMonths() {
return months;
}
public void setMonths(String months) {
this.months = months;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@Override
public String toString() {
return "archive{" +
"months='" + months + '\'' +
", count='" + count + '\'' +
'}';
}
}
|
FeiyangJin/hclib
|
test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/Experimental/Bspline3DSetTrunc.cpp
|
/////////////////////////////////////////////////////////////////
// (c) Copyright 2007- <NAME>
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// Modified by <NAME> for qmcpack
// National Center for Supercomputing Applications &
// Materials Computation Center
// University of Illinois, Urbana-Champaign
// Urbana, IL 61801
// e-mail: <EMAIL>
//
// Supported by
// National Center for Supercomputing Applications, UIUC
// Materials Computation Center, UIUC
//////////////////////////////////////////////////////////////////
// -*- C++ -*-
/** @file Bspline3DSet.cpp
* @brief Implement derived classes from Bspline3DBase
*/
#include "QMCWaveFunctions/Bspline3DSetTrunc.h"
namespace qmcplusplus
{
////////////////////////////////////////////////////////////
//Implementation of Bspline3DSet_MLW
////////////////////////////////////////////////////////////
Bspline3DSet_MLW::Bspline3DSet_MLW()
{
//testing only
Lx=1.3665365600e+01;
Ly=1.3665365600e+01;
Lz=1.3665365600e+01;
LxInv=1.0/Lx;
LyInv=1.0/Ly;
LzInv=1.0/Lz;
LxSq=Lx*Lx;
LySq=Ly*Ly;
LzSq=Lz*Lz;
}
Bspline3DSet_MLW::~Bspline3DSet_MLW()
{
}
void Bspline3DSet_MLW::evaluate(const ParticleSet& e, int iat, ValueVector_t& vals)
{
PosType r(e.R[iat]);
for(int j=0; j<OrbitalSetSize; j++)
{
if(getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2)
vals[j]=0.0;
else
{
PosType rtr=translate(r,j);
bKnots.Find(rtr[0],rtr[1],rtr[2]);
vals[j]=bKnots.evaluate(*P[j]);
}
}
}
void Bspline3DSet_MLW::evaluate(const ParticleSet& e, int iat,
ValueVector_t& vals, GradVector_t& grads, ValueVector_t& laps)
{
PosType r(e.R[iat]);
for(int j=0; j<OrbitalSetSize; j++)
{
if(getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2)
{
vals[j]=0.0;
grads[j]=0.0;
laps[j]=0.0;
}
else
{
PosType rtr=translate(r,j);
bKnots.FindAll(rtr[0],rtr[1],rtr[2]);
vals[j]=bKnots.evaluate(*P[j],grads[j],laps[j]);
}
}
}
void Bspline3DSet_MLW::evaluate(const ParticleSet& e, int first, int last,
ValueMatrix_t& vals, GradMatrix_t& grads, ValueMatrix_t& laps)
{
for(int iat=first,i=0; iat<last; iat++,i++)
{
PosType r(e.R[iat]);
for(int j=0; j<OrbitalSetSize; j++)
{
//PosType dr=r-Centers[j];
//RealType sep2=getSep2(dr[0],dr[1],dr[2]);
//if(sep2>Rcut2)
if(getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2)
{
//cout << "Skip " << j << " | " << sep2 << " | " << Centers[j] << endl;
vals(j,i)=0.0;
grads(i,j)=0.0;
laps(i,j)=0.0;
}
else
{
PosType rtr(translate(r,j));
bKnots.FindAll(rtr[0],rtr[1],rtr[2]);
vals(j,i)=bKnots.evaluate(*P[j],grads(i,j),laps(i,j));
//cout << "Skip " << j << " | " << sep2 << " | " << Centers[j] << endl;
}
}
}
}
void Bspline3DSet_MLW::evaluate_notranspose(const ParticleSet& e, int first, int last,
ValueMatrix_t& vals, GradMatrix_t& grads, ValueMatrix_t& laps)
{
for(int iat=first,i=0; iat<last; iat++,i++)
{
PosType r(e.R[iat]);
for(int j=0; j<OrbitalSetSize; j++)
{
//PosType dr=r-Centers[j];
//RealType sep2=getSep2(dr[0],dr[1],dr[2]);
//if(sep2>Rcut2)
if(getSep2(r[0]-Centers[j][0],r[1]-Centers[j][1],r[2]-Centers[j][2])>Rcut2)
{
//cout << "Skip " << j << " | " << sep2 << " | " << Centers[j] << endl;
vals(i,j)=0.0;
grads(i,j)=0.0;
laps(i,j)=0.0;
}
else
{
PosType rtr(translate(r,j));
bKnots.FindAll(rtr[0],rtr[1],rtr[2]);
vals(i,j)=bKnots.evaluate(*P[j],grads(i,j),laps(i,j));
//cout << "Skip " << j << " | " << sep2 << " | " << Centers[j] << endl;
}
}
}
}
}
/***************************************************************************
* $RCSfile$ $Author: jnkim $
* $Revision: 2013 $ $Date: 2007-05-22 16:47:09 -0500 (Tue, 22 May 2007) $
* $Id: TricubicBsplineSet.h 2013 2007-05-22 21:47:09Z jnkim $
***************************************************************************/
|
StefanPenndorf/FluentLenium
|
fluentlenium-assertj/src/main/java/org/fluentlenium/assertj/custom/FluentListAssert.java
|
<reponame>StefanPenndorf/FluentLenium
package org.fluentlenium.assertj.custom;
import org.assertj.core.api.ListAssert;
import org.fluentlenium.core.domain.FluentList;
import org.fluentlenium.core.domain.FluentWebElement;
import org.openqa.selenium.Dimension;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import static org.fluentlenium.assertj.custom.HtmlConstants.CLASS_ATTRIBUTE;
/**
* Default implementation for {@link FluentList} assertions.
*/
@SuppressWarnings("unchecked")
public class FluentListAssert extends AbstractFluentAssert<FluentListAssert, FluentList>
implements ListStateAssert, ListAttributeAssert {
public FluentListAssert(FluentList<? extends FluentWebElement> actual) {
super(actual, FluentListAssert.class);
}
@Override
public FluentListAssert isEmpty() {
return hasSize(0);
}
@Override
public FluentListAssert isNotEmpty() {
return hasSize().notEqualTo(0);
}
@Override
public FluentListAssert hasSize(int expectedSize) {
int actualSize = actual.count();
if (actualSize != expectedSize) {
failWithMessage("Expected size: " + expectedSize + ". Actual size: " + actualSize + ".");
}
return this;
}
@Override
public FluentListSizeBuilder hasSize() {
return new FluentListSizeBuilder(actual.count(), this);
}
@Override
public FluentListAssert hasText(String textToFind) {
List<String> actualTexts = requiresNonEmpty(actual.texts());
if (actualTexts.stream().noneMatch(text -> text.contains(textToFind))) {
failWithMessage("No selected elements contains text: " + textToFind
+ ". Actual texts found: " + actualTexts);
}
return this;
}
@Override
public FluentListAssert hasTextContaining(String textToFind) {
List<String> actualTexts = requiresNonEmpty(actual.texts());
if (actualTexts.stream().noneMatch(text -> text.contains(textToFind))) {
failWithMessage("No selected elements contains text: " + textToFind
+ ". Actual texts found: " + actualTexts);
}
return this;
}
@Override
public FluentListAssert hasTextMatching(String regexToBeMatched) {
List<String> actualTexts = requiresNonEmpty(actual.texts());
if (actualTexts.stream().noneMatch(text -> text.matches(regexToBeMatched))) {
failWithMessage("No selected elements contains text matching: " + regexToBeMatched
+ ". Actual texts found: " + actualTexts);
}
return this;
}
@Override
public FluentListAssert hasNotText(String textToFind) {
List<String> actualTexts = requiresNonEmpty(actual.texts());
for (String text : actualTexts) {
if (text.contains(textToFind)) {
failWithMessage(
"At least one selected elements contains text: " + textToFind
+ ". Actual texts found: " + actualTexts);
}
}
return this;
}
@Override
public FluentListAssert hasNotTextContaining(String textToFind) {
List<String> actualTexts = requiresNonEmpty(actual.texts());
for (String text : actualTexts) {
if (text.contains(textToFind)) {
failWithMessage(
"At least one selected elements contains text: " + textToFind
+ ". Actual texts found: " + actualTexts);
}
}
return this;
}
@Override
public FluentListAssert hasId(String idToFind) {
List<String> actualIds = requiresNonEmpty(actual.ids());
if (!actualIds.contains(idToFind)) {
failWithMessage("No selected elements have id: " + idToFind
+ ". Actual ids found : " + actualIds);
}
return this;
}
@Override
public FluentListAssert hasClass(String classToFind) {
return validateHasClasses("No selected elements have class: ", classToFind);
}
@Override
public FluentListAssert hasClasses(String... classesToFind) {
return validateHasClasses("No selected element have classes: ", classesToFind);
}
@Override
public FluentListAssert hasNotClass(String htmlClass) {
notHasClasses("At least one selected element has class: ", htmlClass);
return this;
}
@Override
public FluentListAssert hasNotClasses(String... htmlClasses) {
notHasClasses("At least one selected element has classes: ", htmlClasses);
return this;
}
@Override
public FluentListAssert hasValue(String value) {
List<String> actualValues = requiresNonEmpty(actual.values());
if (!actualValues.contains(value)) {
failWithMessage("No selected elements have value: " + value
+ ". Actual values found : " + actualValues);
}
return this;
}
@Override
public FluentListAssert hasName(String name) {
List<String> actualNames = requiresNonEmpty(actual.names());
if (!actualNames.contains(name)) {
failWithMessage("No selected elements have name: " + name
+ ". Actual names found : " + actualNames);
}
return this;
}
@Override
public FluentListAssert hasTagName(String tagName) {
List<String> actualTags = requiresNonEmpty(actual.tagNames());
if (!actualTags.contains(tagName)) {
failWithMessage("No selected elements have tag: " + tagName
+ ". Actual tags found : " + actualTags);
}
return this;
}
@Override
public FluentListAssert hasDimension(Dimension dimension) {
List<Dimension> actualDimensions = requiresNonEmpty(actual.dimensions());
if (!actualDimensions.contains(dimension)) {
failWithMessage("No selected elements have dimension: " + dimension.toString()
+ ". Actual dimensions found : " + actualDimensions.toString());
}
return this;
}
@Override
public FluentListAssert hasAttributeValue(String attribute, String value) {
List<String> actualValues = requiresNonEmpty(actual.attributes(attribute));
if (!actualValues.contains(value)) {
failWithMessage("No selected elements have attribute " + attribute
+ " with value: " + value + ". Actual values found: " + actualValues);
}
return this;
}
@Override
public ListAssert<String> hasAttribute(String attribute) {
List<String> actualValues = requiresNonEmpty(actual.attributes(attribute));
if (actualValues.stream().allMatch(Objects::isNull)) {
failWithMessage("No selected element has attribute " + attribute);
}
return new ListAssert<>(actualValues);
}
@Override
public FluentListAssert hasNotAttribute(String attribute) {
List<String> actualValues = requiresNonEmpty(actual.attributes(attribute));
if (actualValues.stream().anyMatch(Objects::nonNull)) {
failWithMessage("At least one selected element has attribute " + attribute);
}
return this;
}
private FluentListAssert validateHasClasses(String message, String... classesToFind) {
List<String> elementsClasses = requiresNonEmpty(actual.attributes(CLASS_ATTRIBUTE));
for (String elementClass : elementsClasses) {
List<String> classesLst = getClasses(elementClass);
if (classesLst.containsAll(Arrays.asList(classesToFind))) {
return this;
}
}
String classesFromElement = String.join(", ", elementsClasses);
failWithMessage(
message + String.join(", ", classesToFind)
+ ". Actual classes found : " + classesFromElement);
return this;
}
private void notHasClasses(String message, String... htmlClasses) {
List<String> elementsClasses = requiresNonEmpty(actual.attributes(CLASS_ATTRIBUTE));
for (String elementClass : elementsClasses) {
if (elementClass != null && getClasses(elementClass).containsAll(Arrays.asList(htmlClasses))) {
failWithMessage(message + Arrays.asList(htmlClasses));
}
}
}
void failWithMessage(String errorMessage) {
super.failWithMessage(errorMessage);
}
private <T> List<T> requiresNonEmpty(List<T> elements) {
if (elements.isEmpty()) {
throw new AssertionError("List is empty. Please make sure you use correct selector.");
}
return elements;
}
}
|
tqrg-bot/rubinius
|
spec/core/false/xor_spec.rb
|
require File.dirname(__FILE__) + '/../../spec_helper'
describe "FalseClass#^" do
def false_xor(other)
false ^ other
end
it "returns false if other is nil or false, otherwise true" do
false_xor(false).should == false
false_xor(true).should == true
false_xor(nil).should == false
false_xor("").should == true
false_xor(Object.new).should == true
end
end
|
stori-es/stories
|
dashboard/src/main/java/org/consumersunion/stories/dashboard/client/application/collection/widget/SummaryWidgetView.java
|
package org.consumersunion.stories.dashboard.client.application.collection.widget;
import org.consumersunion.stories.common.client.i18n.StoryTellerDashboardI18nLabels;
import org.consumersunion.stories.dashboard.client.resource.Resources;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.ViewImpl;
import static com.google.gwt.query.client.GQuery.$;
public class SummaryWidgetView extends ViewImpl implements SummaryWidgetPresenter.MyView {
interface Binder extends UiBinder<Widget, SummaryWidgetView> {
}
@UiField
Resources resource;
@UiField
DivElement count;
@UiField
SimplePanel charts;
@UiField
DivElement noSummary;
private final StoryTellerDashboardI18nLabels storyTellerLabels;
private final NumberFormat numberFormat;
@Inject
SummaryWidgetView(Binder binder,
StoryTellerDashboardI18nLabels storyTellerLabels) {
this.storyTellerLabels = storyTellerLabels;
this.numberFormat = NumberFormat.getFormat("#,##0");
initWidget(binder.createAndBindUi(this));
}
@Override
public void setStoriesCount(int numberOfStories) {
if (numberOfStories > 0) {
count.setInnerHTML(storyTellerLabels.storiesCount(numberFormat.format(numberOfStories)).asString());
$("span", count).addClass(resource.generalStyleCss().bold());
$(count).show();
$(noSummary).hide();
} else {
$(count).hide();
$(noSummary).show();
}
}
@Override
public void setInSlot(Object slot, IsWidget content) {
if (slot == SummaryWidgetPresenter.SLOT_CHARTS) {
charts.setWidget(content);
}
}
}
|
Monxun/PortainerPractice
|
project/apps/MS-transaction/core/src/main/java/com/aline/core/aws/sms/SMSService.java
|
package com.aline.core.aws.sms;
import com.aline.core.aws.config.AWSSMSConfig;
import com.aline.core.exception.UnprocessableException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.model.MessageAttributeValue;
import com.amazonaws.services.sns.model.PublishRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
@ConditionalOnBean(AWSSMSConfig.class)
@RequiredArgsConstructor
@Slf4j(topic = "SMS Service")
public class SMSService {
/**
* Amazon SNS Client
*/
private final AmazonSNS snsClient;
/**
* Send an SMS text message to the provided
* phone number.
* @param phoneNumber Phone number string
* @param message Message string
* @param type The SMSType (Transactional, Promotional)
*/
public void sendSMSMessage(String phoneNumber, String message, SMSType type) {
log.debug("Building SMS Message [Phone number: {}, Message: {}, Type: {}]",
phoneNumber, message, type.getType());
Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("AWS.SNS.SMS.SenderID",
new MessageAttributeValue()
.withStringValue("Aline")
.withDataType("String"));
messageAttributes.put("AWS.SNS.SMS.MaxPrice",
new MessageAttributeValue()
.withStringValue("0.50")
.withDataType("Number"));
messageAttributes.put("AWS.SNS.SMS.SMSType",
new MessageAttributeValue()
.withStringValue(type.getType())
.withDataType("String"));
PublishRequest publishRequest = new PublishRequest()
.withPhoneNumber("+1 " + phoneNumber)
.withMessage(message)
.withMessageAttributes(messageAttributes);
try {
log.debug("Attempting to send SMS message...");
snsClient.publish(publishRequest);
log.debug("Successfully sent SMS message...");
} catch (SdkClientException | IllegalArgumentException e) {
log.error("Something went wrong with sending your SMS message.");
e.printStackTrace();
throw new UnprocessableException("Something went wrong with sending an SMS message.");
}
}
}
|
CheRut/chedmitry
|
chapter_006/src/main/java/ru/chedmitriy/test/bomberman/GamePlay.java
|
package ru.chedmitriy.test.bomberman;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* ru.chedmitriy.multithreading.threads.test.bomberman
*
* @author cheDmitry
* @version 1.0
* @since 05.12.2017
* запускаем приложение
* модели премещаются хааотично,
* блокировки устанавливаются в случайном порядке
*/
public class GamePlay {
public static void main(String[] args) {
final int threadCount = 2;
final ExecutorService service = Executors.newFixedThreadPool(threadCount);
final Board board = new Board();
MoveAct moveAct = new MoveAct(board);
StayAct stayAct = new StayAct(board);
for (int i = 0; i < 10; i++) {
service.execute(stayAct);
service.execute(moveAct);
}
service.shutdown();
}
}
|
wilebeast/FireFox-OS
|
B2G/gecko/xpfe/appshell/src/nsChromeTreeOwner.cpp
|
/* -*- Mode: C++; tab-width: 3; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// Local Includes
#include "nsChromeTreeOwner.h"
#include "nsXULWindow.h"
// Helper Classes
#include "nsString.h"
#include "nsIEmbeddingSiteWindow.h"
#include "nsIServiceManager.h"
#include "nsIDocShellTreeItem.h"
// Interfaces needed to include
#include "nsIPrompt.h"
#include "nsIAuthPrompt.h"
#include "nsIWebProgress.h"
#include "nsIWindowMediator.h"
#include "nsIDOMNode.h"
#include "nsIDOMElement.h"
#include "nsIDOMNodeList.h"
#include "nsIDOMXULElement.h"
#include "nsIXULBrowserWindow.h"
// CIDs
static NS_DEFINE_CID(kWindowMediatorCID, NS_WINDOWMEDIATOR_CID);
//*****************************************************************************
// nsChromeTreeOwner string literals
//*****************************************************************************
struct nsChromeTreeOwnerLiterals
{
const nsLiteralString kPersist;
const nsLiteralString kScreenX;
const nsLiteralString kScreenY;
const nsLiteralString kWidth;
const nsLiteralString kHeight;
const nsLiteralString kSizemode;
const nsLiteralString kSpace;
nsChromeTreeOwnerLiterals()
: NS_LITERAL_STRING_INIT(kPersist,"persist")
, NS_LITERAL_STRING_INIT(kScreenX,"screenX")
, NS_LITERAL_STRING_INIT(kScreenY,"screenY")
, NS_LITERAL_STRING_INIT(kWidth,"width")
, NS_LITERAL_STRING_INIT(kHeight,"height")
, NS_LITERAL_STRING_INIT(kSizemode,"sizemode")
, NS_LITERAL_STRING_INIT(kSpace," ")
{}
};
static nsChromeTreeOwnerLiterals *gLiterals;
nsresult
nsChromeTreeOwner::InitGlobals()
{
NS_ASSERTION(gLiterals == nullptr, "already initialized");
gLiterals = new nsChromeTreeOwnerLiterals();
if (!gLiterals)
return NS_ERROR_OUT_OF_MEMORY;
return NS_OK;
}
void
nsChromeTreeOwner::FreeGlobals()
{
delete gLiterals;
gLiterals = nullptr;
}
//*****************************************************************************
//*** nsChromeTreeOwner: Object Management
//*****************************************************************************
nsChromeTreeOwner::nsChromeTreeOwner() : mXULWindow(nullptr)
{
}
nsChromeTreeOwner::~nsChromeTreeOwner()
{
}
//*****************************************************************************
// nsChromeTreeOwner::nsISupports
//*****************************************************************************
NS_IMPL_ADDREF(nsChromeTreeOwner)
NS_IMPL_RELEASE(nsChromeTreeOwner)
NS_INTERFACE_MAP_BEGIN(nsChromeTreeOwner)
NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIDocShellTreeOwner)
NS_INTERFACE_MAP_ENTRY(nsIDocShellTreeOwner)
NS_INTERFACE_MAP_ENTRY(nsIBaseWindow)
NS_INTERFACE_MAP_ENTRY(nsIWebProgressListener)
NS_INTERFACE_MAP_ENTRY(nsIInterfaceRequestor)
NS_INTERFACE_MAP_ENTRY(nsISupportsWeakReference)
NS_INTERFACE_MAP_END
//*****************************************************************************
// nsChromeTreeOwner::nsIInterfaceRequestor
//*****************************************************************************
NS_IMETHODIMP nsChromeTreeOwner::GetInterface(const nsIID& aIID, void** aSink)
{
NS_ENSURE_ARG_POINTER(aSink);
if(aIID.Equals(NS_GET_IID(nsIPrompt))) {
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetInterface(aIID, aSink);
}
if(aIID.Equals(NS_GET_IID(nsIAuthPrompt))) {
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetInterface(aIID, aSink);
}
if(aIID.Equals(NS_GET_IID(nsIWebBrowserChrome))) {
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetInterface(aIID, aSink);
}
if (aIID.Equals(NS_GET_IID(nsIEmbeddingSiteWindow))) {
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetInterface(aIID, aSink);
}
if (aIID.Equals(NS_GET_IID(nsIXULWindow))) {
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->QueryInterface(aIID, aSink);
}
return QueryInterface(aIID, aSink);
}
//*****************************************************************************
// nsChromeTreeOwner::nsIDocShellTreeOwner
//*****************************************************************************
NS_IMETHODIMP nsChromeTreeOwner::FindItemWithName(const PRUnichar* aName,
nsIDocShellTreeItem* aRequestor, nsIDocShellTreeItem* aOriginalRequestor,
nsIDocShellTreeItem** aFoundItem)
{
NS_ENSURE_ARG_POINTER(aFoundItem);
*aFoundItem = nullptr;
bool fIs_Content = false;
/* Special Cases */
if(!aName || !*aName)
return NS_OK;
nsDependentString name(aName);
if(name.LowerCaseEqualsLiteral("_blank"))
return NS_OK;
// _main is an IE target which should be case-insensitive but isn't
// see bug 217886 for details
if(name.LowerCaseEqualsLiteral("_content") || name.EqualsLiteral("_main"))
{
NS_ENSURE_STATE(mXULWindow);
fIs_Content = true;
mXULWindow->GetPrimaryContentShell(aFoundItem);
if(*aFoundItem)
return NS_OK;
// Otherwise fall through and ask the other windows for a content area.
}
nsCOMPtr<nsIWindowMediator> windowMediator(do_GetService(kWindowMediatorCID));
NS_ENSURE_TRUE(windowMediator, NS_ERROR_FAILURE);
nsCOMPtr<nsISimpleEnumerator> windowEnumerator;
NS_ENSURE_SUCCESS(windowMediator->GetXULWindowEnumerator(nullptr,
getter_AddRefs(windowEnumerator)), NS_ERROR_FAILURE);
bool more;
windowEnumerator->HasMoreElements(&more);
while(more)
{
nsCOMPtr<nsISupports> nextWindow = nullptr;
windowEnumerator->GetNext(getter_AddRefs(nextWindow));
nsCOMPtr<nsIXULWindow> xulWindow(do_QueryInterface(nextWindow));
NS_ENSURE_TRUE(xulWindow, NS_ERROR_FAILURE);
nsCOMPtr<nsIDocShellTreeItem> shellAsTreeItem;
if(fIs_Content)
{
xulWindow->GetPrimaryContentShell(aFoundItem);
}
else
{
// Note that we don't look for targetable content shells here...
// in fact, we aren't looking for content shells at all!
nsCOMPtr<nsIDocShell> shell;
xulWindow->GetDocShell(getter_AddRefs(shell));
shellAsTreeItem = do_QueryInterface(shell);
if (shellAsTreeItem) {
// Get the root tree item of same type, since roots are the only
// things that call into the treeowner to look for named items.
nsCOMPtr<nsIDocShellTreeItem> root;
shellAsTreeItem->GetSameTypeRootTreeItem(getter_AddRefs(root));
shellAsTreeItem = root;
}
if(shellAsTreeItem && aRequestor != shellAsTreeItem)
{
// Do this so we can pass in the tree owner as the requestor so the child knows not
// to call back up.
nsCOMPtr<nsIDocShellTreeOwner> shellOwner;
shellAsTreeItem->GetTreeOwner(getter_AddRefs(shellOwner));
nsCOMPtr<nsISupports> shellOwnerSupports(do_QueryInterface(shellOwner));
shellAsTreeItem->FindItemWithName(aName, shellOwnerSupports,
aOriginalRequestor, aFoundItem);
}
}
if(*aFoundItem)
return NS_OK;
windowEnumerator->HasMoreElements(&more);
}
return NS_OK;
}
NS_IMETHODIMP
nsChromeTreeOwner::ContentShellAdded(nsIDocShellTreeItem* aContentShell,
bool aPrimary, bool aTargetable,
const nsAString& aID)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->ContentShellAdded(aContentShell, aPrimary, aTargetable,
aID);
}
NS_IMETHODIMP
nsChromeTreeOwner::ContentShellRemoved(nsIDocShellTreeItem* aContentShell)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->ContentShellRemoved(aContentShell);
}
NS_IMETHODIMP nsChromeTreeOwner::GetPrimaryContentShell(nsIDocShellTreeItem** aShell)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetPrimaryContentShell(aShell);
}
NS_IMETHODIMP nsChromeTreeOwner::SizeShellTo(nsIDocShellTreeItem* aShellItem,
int32_t aCX, int32_t aCY)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->SizeShellTo(aShellItem, aCX, aCY);
}
NS_IMETHODIMP
nsChromeTreeOwner::SetPersistence(bool aPersistPosition,
bool aPersistSize,
bool aPersistSizeMode)
{
NS_ENSURE_STATE(mXULWindow);
nsCOMPtr<nsIDOMElement> docShellElement = mXULWindow->GetWindowDOMElement();
if (!docShellElement)
return NS_ERROR_FAILURE;
nsAutoString persistString;
docShellElement->GetAttribute(gLiterals->kPersist, persistString);
bool saveString = false;
int32_t index;
#define FIND_PERSIST_STRING(aString, aCond) \
index = persistString.Find(aString); \
if (!aCond && index > kNotFound) { \
persistString.Cut(index, aString.Length()); \
saveString = true; \
} else if (aCond && index == kNotFound) { \
persistString.Append(gLiterals->kSpace + aString); \
saveString = true; \
}
FIND_PERSIST_STRING(gLiterals->kScreenX, aPersistPosition);
FIND_PERSIST_STRING(gLiterals->kScreenY, aPersistPosition);
FIND_PERSIST_STRING(gLiterals->kWidth, aPersistSize);
FIND_PERSIST_STRING(gLiterals->kHeight, aPersistSize);
FIND_PERSIST_STRING(gLiterals->kSizemode, aPersistSizeMode);
if (saveString)
docShellElement->SetAttribute(gLiterals->kPersist, persistString);
return NS_OK;
}
NS_IMETHODIMP
nsChromeTreeOwner::GetPersistence(bool* aPersistPosition,
bool* aPersistSize,
bool* aPersistSizeMode)
{
NS_ENSURE_STATE(mXULWindow);
nsCOMPtr<nsIDOMElement> docShellElement = mXULWindow->GetWindowDOMElement();
if (!docShellElement)
return NS_ERROR_FAILURE;
nsAutoString persistString;
docShellElement->GetAttribute(gLiterals->kPersist, persistString);
// data structure doesn't quite match the question, but it's close enough
// for what we want (since this method is never actually called...)
if (aPersistPosition)
*aPersistPosition = persistString.Find(gLiterals->kScreenX) > kNotFound ||
persistString.Find(gLiterals->kScreenY) > kNotFound;
if (aPersistSize)
*aPersistSize = persistString.Find(gLiterals->kWidth) > kNotFound ||
persistString.Find(gLiterals->kHeight) > kNotFound;
if (aPersistSizeMode)
*aPersistSizeMode = persistString.Find(gLiterals->kSizemode) > kNotFound;
return NS_OK;
}
NS_IMETHODIMP
nsChromeTreeOwner::GetTargetableShellCount(uint32_t* aResult)
{
*aResult = 0;
return NS_OK;
}
//*****************************************************************************
// nsChromeTreeOwner::nsIBaseWindow
//*****************************************************************************
NS_IMETHODIMP nsChromeTreeOwner::InitWindow(nativeWindow aParentNativeWindow,
nsIWidget* parentWidget, int32_t x, int32_t y, int32_t cx, int32_t cy)
{
// Ignore widget parents for now. Don't think those are a vaild thing to call.
NS_ENSURE_SUCCESS(SetPositionAndSize(x, y, cx, cy, false), NS_ERROR_FAILURE);
return NS_OK;
}
NS_IMETHODIMP nsChromeTreeOwner::Create()
{
NS_ASSERTION(false, "You can't call this");
return NS_ERROR_UNEXPECTED;
}
NS_IMETHODIMP nsChromeTreeOwner::Destroy()
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->Destroy();
}
NS_IMETHODIMP nsChromeTreeOwner::GetUnscaledDevicePixelsPerCSSPixel(double *aScale)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetUnscaledDevicePixelsPerCSSPixel(aScale);
}
NS_IMETHODIMP nsChromeTreeOwner::SetPosition(int32_t x, int32_t y)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->SetPosition(x, y);
}
NS_IMETHODIMP nsChromeTreeOwner::GetPosition(int32_t* x, int32_t* y)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetPosition(x, y);
}
NS_IMETHODIMP nsChromeTreeOwner::SetSize(int32_t cx, int32_t cy, bool fRepaint)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->SetSize(cx, cy, fRepaint);
}
NS_IMETHODIMP nsChromeTreeOwner::GetSize(int32_t* cx, int32_t* cy)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetSize(cx, cy);
}
NS_IMETHODIMP nsChromeTreeOwner::SetPositionAndSize(int32_t x, int32_t y, int32_t cx,
int32_t cy, bool fRepaint)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->SetPositionAndSize(x, y, cx, cy, fRepaint);
}
NS_IMETHODIMP nsChromeTreeOwner::GetPositionAndSize(int32_t* x, int32_t* y, int32_t* cx,
int32_t* cy)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetPositionAndSize(x, y, cx, cy);
}
NS_IMETHODIMP nsChromeTreeOwner::Repaint(bool aForce)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->Repaint(aForce);
}
NS_IMETHODIMP nsChromeTreeOwner::GetParentWidget(nsIWidget** aParentWidget)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetParentWidget(aParentWidget);
}
NS_IMETHODIMP nsChromeTreeOwner::SetParentWidget(nsIWidget* aParentWidget)
{
NS_ASSERTION(false, "You can't call this");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsChromeTreeOwner::GetParentNativeWindow(nativeWindow* aParentNativeWindow)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetParentNativeWindow(aParentNativeWindow);
}
NS_IMETHODIMP nsChromeTreeOwner::SetParentNativeWindow(nativeWindow aParentNativeWindow)
{
NS_ASSERTION(false, "You can't call this");
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsChromeTreeOwner::GetNativeHandle(nsAString& aNativeHandle)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetNativeHandle(aNativeHandle);
}
NS_IMETHODIMP nsChromeTreeOwner::GetVisibility(bool* aVisibility)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetVisibility(aVisibility);
}
NS_IMETHODIMP nsChromeTreeOwner::SetVisibility(bool aVisibility)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->SetVisibility(aVisibility);
}
NS_IMETHODIMP nsChromeTreeOwner::GetEnabled(bool *aEnabled)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetEnabled(aEnabled);
}
NS_IMETHODIMP nsChromeTreeOwner::SetEnabled(bool aEnable)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->SetEnabled(aEnable);
}
NS_IMETHODIMP nsChromeTreeOwner::GetMainWidget(nsIWidget** aMainWidget)
{
NS_ENSURE_ARG_POINTER(aMainWidget);
NS_ENSURE_STATE(mXULWindow);
*aMainWidget = mXULWindow->mWindow;
NS_IF_ADDREF(*aMainWidget);
return NS_OK;
}
NS_IMETHODIMP nsChromeTreeOwner::SetFocus()
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->SetFocus();
}
NS_IMETHODIMP nsChromeTreeOwner::GetTitle(PRUnichar** aTitle)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->GetTitle(aTitle);
}
NS_IMETHODIMP nsChromeTreeOwner::SetTitle(const PRUnichar* aTitle)
{
NS_ENSURE_STATE(mXULWindow);
return mXULWindow->SetTitle(aTitle);
}
//*****************************************************************************
// nsChromeTreeOwner::nsIWebProgressListener
//*****************************************************************************
NS_IMETHODIMP
nsChromeTreeOwner::OnProgressChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
int32_t aCurSelfProgress,
int32_t aMaxSelfProgress,
int32_t aCurTotalProgress,
int32_t aMaxTotalProgress)
{
return NS_OK;
}
NS_IMETHODIMP
nsChromeTreeOwner::OnStateChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
uint32_t aProgressStateFlags,
nsresult aStatus)
{
return NS_OK;
}
NS_IMETHODIMP nsChromeTreeOwner::OnLocationChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
nsIURI* aLocation,
uint32_t aFlags)
{
bool itsForYou = true;
if (aWebProgress) {
NS_ENSURE_STATE(mXULWindow);
nsCOMPtr<nsIDOMWindow> progressWin;
aWebProgress->GetDOMWindow(getter_AddRefs(progressWin));
nsCOMPtr<nsIDocShell> docshell;
mXULWindow->GetDocShell(getter_AddRefs(docshell));
nsCOMPtr<nsIDOMWindow> ourWin(do_QueryInterface(docshell));
if (ourWin != progressWin)
itsForYou = false;
}
// If loading a new root .xul document, then redo chrome.
if (itsForYou) {
NS_ENSURE_STATE(mXULWindow);
mXULWindow->mChromeLoaded = false;
}
return NS_OK;
}
NS_IMETHODIMP
nsChromeTreeOwner::OnStatusChange(nsIWebProgress* aWebProgress,
nsIRequest* aRequest,
nsresult aStatus,
const PRUnichar* aMessage)
{
return NS_OK;
}
NS_IMETHODIMP
nsChromeTreeOwner::OnSecurityChange(nsIWebProgress *aWebProgress,
nsIRequest *aRequest,
uint32_t state)
{
return NS_OK;
}
//*****************************************************************************
// nsChromeTreeOwner: Helpers
//*****************************************************************************
//*****************************************************************************
// nsChromeTreeOwner: Accessors
//*****************************************************************************
void nsChromeTreeOwner::XULWindow(nsXULWindow* aXULWindow)
{
mXULWindow = aXULWindow;
}
nsXULWindow* nsChromeTreeOwner::XULWindow()
{
return mXULWindow;
}
|
angriestalien/ghidra
|
Ghidra/Framework/Project/src/main/java/ghidra/framework/main/ProjectAccessPanel.java
|
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.framework.main;
import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.*;
import docking.options.editor.ButtonPanelFactory;
import docking.widgets.table.GTable;
import docking.wizard.AbstractWizardJPanel;
import ghidra.app.util.GenericHelpTopics;
import ghidra.framework.client.RepositoryAdapter;
import ghidra.framework.plugintool.PluginTool;
import ghidra.framework.remote.User;
import ghidra.util.HelpLocation;
import resources.ResourceManager;
import util.CollectionUtils;
/**
* Panel that shows the users for a given repository and the users associated with the current
* shared project. There are 3 main sub-panels:
* <p>
* <li>Known Users Panel: Displays all users in the repository</li>
* <li>Button Panel: Provides buttons for adding/removing users from the project</li>
* <li>User Access Panel: Displays all users on the project, and their access permissions</li>
* <p>
* If the current user is an admin, he may change user permissions and add/remove them
* from the project. If not, only the User Access Panel will be visible and it will
* be read-only.
*
*/
public class ProjectAccessPanel extends AbstractWizardJPanel {
protected KnownUsersPanel knownUsersPanel;
protected UserAccessPanel userAccessPanel;
protected ButtonPanel addRemoveButtonPanel;
protected JCheckBox anonymousAccessCB;
protected String currentUser;
protected List<User> origProjectUserList;
protected boolean origAnonymousAccessEnabled;
protected String repositoryName;
protected HelpLocation helpLoc;
protected final Color SELECTION_BG_COLOR = new Color(204, 204, 255);
protected final Color SELECTION_FG_COLOR = Color.BLACK;
protected PluginTool tool;
/**
* Construct a new panel from a {@link RepositoryAdapter} instance.
*
* @param knownUser names of the users that are known to the remote server
* @param repository the repository adapter instance
* @param tool the current tool
* @throws IOException if there's an error processing the repository user list
*/
public ProjectAccessPanel(String[] knownUsers, RepositoryAdapter repository, PluginTool tool)
throws IOException {
this(knownUsers, repository.getServer().getUser(), Arrays.asList(repository.getUserList()),
repository.getName(), repository.getServer().anonymousAccessAllowed(),
repository.anonymousAccessAllowed(), tool);
}
/**
* Constructs a new panel from the given arguments.
*
* @param knownUsers names of the users that are known to the remote server
* @param currentUser the current user
* @param allUsers all users known to the repository
* @param repositoryName the name of the repository
* @param anonymousServerAccessAllowed true if the server allows anonymous access
* @param anonymousAccessEnabled true if the repository allows anonymous access
* (ignored if anonymousServerAccessAllowed is false)
* @param tool the current tool
*/
public ProjectAccessPanel(String[] knownUsers, String currentUser, List<User> allUsers,
String repositoryName, boolean anonymousServerAccessAllowed,
boolean anonymousAccessEnabled, PluginTool tool) {
super(new BorderLayout());
this.currentUser = currentUser;
this.origProjectUserList = allUsers;
this.origAnonymousAccessEnabled = anonymousAccessEnabled;
this.repositoryName = repositoryName;
this.tool = tool;
createMainPanel(knownUsers, anonymousServerAccessAllowed);
}
@Override
public boolean isValidInformation() {
return true;
}
@Override
public String getTitle() {
return "Specify Users for Repository " + repositoryName;
}
@Override
public void initialize() {
userAccessPanel.resetUserList();
if (anonymousAccessCB != null) {
anonymousAccessCB.setSelected(origAnonymousAccessEnabled);
}
}
@Override
public HelpLocation getHelpLocation() {
if (helpLoc != null) {
return helpLoc;
}
return new HelpLocation(GenericHelpTopics.FRONT_END, "UserAccessList");
}
/**
* Sets the help location.
*
* @param helpLoc the help location
*/
void setHelpLocation(HelpLocation helpLoc) {
this.helpLoc = helpLoc;
}
/**
* Returns a list of all users with permission to access the project.
*
* @return the list of users
*/
User[] getProjectUsers() {
return userAccessPanel.getProjectUsers();
}
/**
* Returns true if anonymous access is allowed by the repository.
*
* @return true if allowed
*/
boolean allowAnonymousAccess() {
return anonymousAccessCB != null && anonymousAccessCB.isSelected();
}
/**
* Returns the repository name.
*
* @return the repository name
*/
String getRepositoryName() {
return repositoryName;
}
/**
* Creates the main gui panel, containing the known users, button, and user access
* panels.
*/
protected void createMainPanel(String[] knownUsers, boolean anonymousServerAccessAllowed) {
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
knownUsersPanel = new KnownUsersPanel(Arrays.asList(knownUsers));
userAccessPanel = new UserAccessPanel(currentUser);
addRemoveButtonPanel = new ButtonPanel();
mainPanel.add(knownUsersPanel);
mainPanel.add(addRemoveButtonPanel);
mainPanel.add(userAccessPanel);
add(mainPanel, BorderLayout.CENTER);
if (anonymousServerAccessAllowed) {
anonymousAccessCB = new JCheckBox("Allow Anonymous Access");
anonymousAccessCB.setSelected(origAnonymousAccessEnabled);
anonymousAccessCB.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 0));
add(anonymousAccessCB, BorderLayout.SOUTH);
}
}
/**
* Panel containing the buttons for adding/removing users from the current project.
*/
class ButtonPanel extends JPanel {
private JButton addButton;
private JButton addAllButton;
private JButton removeButton;
private JButton removeAllButton;
public ButtonPanel() {
addButton = new JButton("Add >>");
addButton.setEnabled(false);
addButton.addActionListener(e -> {
userAccessPanel.addUsers(knownUsersPanel.getSelectedUsers());
});
addAllButton = new JButton("Add All");
addAllButton.addActionListener(e -> {
userAccessPanel.addUsers(knownUsersPanel.getAllUsers());
knownUsersPanel.clearSelection();
});
addAllButton.setEnabled(true);
removeButton = new JButton("<< Remove");
removeButton.setEnabled(false);
removeButton.addActionListener(e -> userAccessPanel.removeSelectedUsers());
removeAllButton = new JButton("Remove All");
removeAllButton.addActionListener(e -> {
userAccessPanel.removeAllUsers();
knownUsersPanel.clearSelection();
});
removeAllButton.setEnabled(true);
JPanel panel = ButtonPanelFactory.createButtonPanel(
new JButton[] { addButton, addAllButton, removeButton, removeAllButton }, 5);
panel.setMinimumSize(panel.getPreferredSize());
// Set up a listener so this panel can update its state when something in the user
// permissions list has been selected.
userAccessPanel.getTable().getSelectionModel().addListSelectionListener(e -> {
if (e.getValueIsAdjusting()) {
return;
}
updateState();
});
// Need to update the known users panel whenever a user is added/removed from the
// access panel (the icon showing whether they're in the project or not needs
// to be updated).
userAccessPanel.tableModel.addTableModelListener(e -> {
knownUsersPanel.repaint();
});
// Set up a listener so this panel can update its state when something in the known
// users list has been selected.
knownUsersPanel.getList().getSelectionModel().addListSelectionListener(e -> {
if (e.getValueIsAdjusting()) {
return;
}
updateState();
});
add(panel);
}
/**
* Ensures that all buttons are enabled/disabled appropriately based on the current
* selections.
* <p>
* Note that the "add all" and "remove all" buttons are always enabled so they aren't addressed
* here.
*/
public void updateState() {
updateAddButtonState();
updateRemoveButtonState();
}
/**
* Updates the 'remove' button state based on the selections in the user access panel.
*/
private void updateRemoveButtonState() {
boolean enabled = false;
List<String> selectedUserNames = userAccessPanel.getSelectedUsers();
if (selectedUserNames.isEmpty()) {
enabled = false;
}
else if (selectedUserNames.size() == 1) {
if (selectedUserNames.get(0).equals(currentUser)) {
enabled = false;
}
else {
enabled = true;
}
}
else {
enabled = true;
}
removeButton.setEnabled(enabled);
}
/**
* Updates the 'add' button state based on the selections in the known users panel.
*/
private void updateAddButtonState() {
boolean enabled = false;
List<String> selectedUserNames = knownUsersPanel.getSelectedUsers();
for (String user : selectedUserNames) {
if (!userAccessPanel.isInProjectAccessList(user)) {
enabled = true;
break;
}
}
addButton.setEnabled(enabled);
}
}
/**
* Panel for displaying project users and their access permissions. Users with admin rights
* can edit the permissions of other users.
*/
class UserAccessPanel extends JPanel {
private GTable table;
private UserAccessTableModel tableModel;
/**
* Creates a new user access panel.
*
* @param user the current user
* @param userList the list of users to display in the table
*/
UserAccessPanel(String user) {
setLayout(new BorderLayout());
tableModel = new UserAccessTableModel(user, origProjectUserList, tool);
table = new GTable(tableModel);
table.setShowGrid(false);
table.setSelectionBackground(SELECTION_BG_COLOR);
table.setSelectionForeground(SELECTION_FG_COLOR);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
table.setBorder(BorderFactory.createEmptyBorder());
JScrollPane sp = new JScrollPane(table);
sp.setBorder(BorderFactory.createTitledBorder("Project Users"));
sp.setBackground(getBackground());
add(sp, BorderLayout.CENTER);
setPreferredSize(new Dimension(400, 200));
}
/**
* Returns the user table.
*
* @return the user table
*/
GTable getTable() {
return table;
}
/**
* Reset user list with the original set of users and permissions
*/
void resetUserList() {
tableModel.setUserList(origProjectUserList);
}
/**
* Returns a list of all selected users in the table.
*
* @return list of user names
*/
List<String> getSelectedUsers() {
List<String> users = new ArrayList<>();
int[] selectedRows = table.getSelectedRows();
for (int i = 0; i < selectedRows.length; i++) {
User user = tableModel.getRowObject(selectedRows[i]);
users.add(user.getName());
}
return users;
}
/**
* Returns true if the given user is in the project access list.
*
* @param name the user name
* @return true if already has project access
*/
boolean isInProjectAccessList(String name) {
List<User> usersInProject = tableModel.getDataSource();
for (User user : usersInProject) {
if (user.getName().equals(name)) {
return true;
}
}
return false;
}
/**
* Returns a list of all users who have project access.
*
* @return list of users
*/
User[] getProjectUsers() {
User[] users = new User[tableModel.getModelData().size()];
return tableModel.getModelData().toArray(users);
}
/**
* Removes all users from the table.
*/
private void removeAllUsers() {
ArrayList<User> list = new ArrayList<>();
// Remove all users, except the user entry that represents the one
// doing the removing.
for (User user : tableModel.getModelData()) {
if (user.getName().equals(currentUser)) {
continue;
}
list.add(user);
}
tableModel.removeUsers(list);
}
/**
* Removes only the selected users from the table.
*/
private void removeSelectedUsers() {
ArrayList<User> users = new ArrayList<>();
// Remove all selected users, except the user entry that represents the one
// doing the removing.
for (int selectedRow : table.getSelectedRows()) {
User user = tableModel.getRowObject(selectedRow);
if (user.getName().equals(currentUser)) {
continue;
}
users.add(user);
}
tableModel.removeUsers(users);
}
/**
* Adds the give list of users to the table.
*
* @param users the users to add
*/
private void addUsers(List<String> users) {
ArrayList<User> list = new ArrayList<>();
// Only add the user if they don't already have access.
for (String user : users) {
if (!isInProjectAccessList(user)) {
list.add(new User(user, User.WRITE));
}
}
tableModel.addUsers(list);
}
}
/**
* Panel for displaying the list of users with repository access.
*/
class KnownUsersPanel extends JPanel {
private JList<String> userList;
private DefaultListModel<String> listModel;
/**
* Creates a new users panel.
*
* @param users list of users to display
*/
KnownUsersPanel(List<String> users) {
setLayout(new BorderLayout());
users.sort(String::compareToIgnoreCase);
listModel = new DefaultListModel<>();
for (String user : users) {
listModel.addElement(user);
}
userList = new JList<>(listModel);
userList.setSelectionBackground(SELECTION_BG_COLOR);
userList.setSelectionForeground(SELECTION_FG_COLOR);
userList.setCellRenderer(new UserListCellRenderer());
JScrollPane sp = new JScrollPane(userList);
sp.setBorder(BorderFactory.createTitledBorder("Known Users"));
sp.setOpaque(false);
// Set the minimum dimensions of the scroll pane so we can't collapse it.
Dimension d = userList.getPreferredSize();
d.width = 100;
sp.setPreferredSize(d);
sp.setMinimumSize(new Dimension(100, 200));
add(sp, BorderLayout.CENTER);
}
/**
* Returns a list of selected users
*
* @return list of user names
*/
List<String> getSelectedUsers() {
return userList.getSelectedValuesList();
}
/**
* Returns the user list.
*
* @return the user list
*/
JList<String> getList() {
return userList;
}
/**
* Returns a list of all users in the panel
*
* @return list of user names
*/
List<String> getAllUsers() {
List<String> allUsers = CollectionUtils.asList(listModel.elements());
return allUsers;
}
/**
* Clears any user selection in the panel.
*/
void clearSelection() {
userList.getSelectionModel().clearSelection();
}
/**
* Renderer for the {@link KnownUsersPanel}. This is to ensure that we render the
* correct icon for each user in the list, and that the text is colored properly.
*/
private class UserListCellRenderer extends JLabel implements ListCellRenderer {
private Icon icon;
private Icon inProjectIcon;
UserListCellRenderer() {
icon = ResourceManager.loadImage("images/EmptyIcon.gif");
inProjectIcon = ResourceManager.loadImage("images/user.png");
icon = ResourceManager.getScaledIcon(icon, inProjectIcon.getIconWidth(),
inProjectIcon.getIconHeight());
setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
setOpaque(true);
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
String name = (String) value;
if (userAccessPanel != null) {
setIcon(userAccessPanel.isInProjectAccessList(name) ? inProjectIcon : icon);
}
setText(name);
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
}
else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}
}
}
|
Carreau/ADIOS2
|
source/adios2/toolkit/format/bpOperation/compress/BPBZIP2.tcc
|
/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* BPBZIP2.tcc
*
* Created on: Jun 10, 2019
* Author: <NAME> <EMAIL>
*/
#ifndef ADIOS2_TOOLKIT_FORMAT_BPOPERATION_COMPRESS_BPBZIP2_TCC_
#define ADIOS2_TOOLKIT_FORMAT_BPOPERATION_COMPRESS_BPBZIP2_TCC_
#include "BPBZIP2.h"
#include "adios2/helper/adiosFunctions.h"
namespace adios2
{
namespace format
{
template <class T>
void BPBZIP2::SetMetadataCommon(
const core::Variable<T> &variable,
const typename core::Variable<T>::Info &blockInfo,
const typename core::Variable<T>::Operation &operation,
std::vector<char> &buffer) const noexcept
{
const uint64_t inputSize = static_cast<uint64_t>(
helper::GetTotalSize(blockInfo.Count) * sizeof(T));
// being naughty here
Params &info = const_cast<Params &>(operation.Info);
info["InputSize"] = std::to_string(inputSize);
// fixed size
const uint16_t batches =
static_cast<uint16_t>(inputSize / DefaultMaxFileBatchSize + 1);
const uint16_t metadataSize = 8 + 8 + 2 + batches * (4 * 8);
helper::InsertToBuffer(buffer, &metadataSize);
helper::InsertToBuffer(buffer, &inputSize);
info["OutputSizeMetadataPosition"] = std::to_string(buffer.size());
constexpr uint64_t outputSize = 0;
// dummy
helper::InsertToBuffer(buffer, &outputSize);
// additional batch info
helper::InsertToBuffer(buffer, &batches);
info["BatchesMetadataPosition"] = std::to_string(buffer.size());
// inserting dummies to preallocate, updated in UpdateMetadataCommon
buffer.resize(buffer.size() + batches * 4 * 8);
}
template <class T>
void BPBZIP2::UpdateMetadataCommon(
const core::Variable<T> &variable,
const typename core::Variable<T>::Info &blockInfo,
const typename core::Variable<T>::Operation &operation,
std::vector<char> &buffer) const noexcept
{
const uint64_t inputSize = static_cast<uint64_t>(
helper::GetTotalSize(blockInfo.Count) * sizeof(T));
const uint64_t outputSize =
static_cast<uint64_t>(std::stoll(operation.Info.at("OutputSize")));
size_t backPosition = static_cast<size_t>(
std::stoull(operation.Info.at("OutputSizeMetadataPosition")));
helper::CopyToBuffer(buffer, backPosition, &outputSize);
// being naughty here
Params &info = const_cast<Params &>(operation.Info);
// additional metadata for supporting 64-bit count
const uint16_t batches =
static_cast<uint16_t>(inputSize / DefaultMaxFileBatchSize + 1);
backPosition = static_cast<size_t>(
std::stoull(operation.Info.at("BatchesMetadataPosition")));
for (auto b = 0; b < batches; ++b)
{
const std::string bStr = std::to_string(b);
const uint64_t originalOffset =
std::stoull(info["OriginalOffset_" + bStr]);
const uint64_t originalSize = std::stoull(info["OriginalSize_" + bStr]);
const uint64_t compressedOffset =
std::stoull(info["CompressedOffset_" + bStr]);
const uint64_t compressedSize =
std::stoull(info["CompressedSize_" + bStr]);
helper::CopyToBuffer(buffer, backPosition, &originalOffset);
helper::CopyToBuffer(buffer, backPosition, &originalSize);
helper::CopyToBuffer(buffer, backPosition, &compressedOffset);
helper::CopyToBuffer(buffer, backPosition, &compressedSize);
}
info.erase("OutputSizeMetadataPosition");
info.erase("BatchesMetadataPosition");
}
} // end namespace format
} // end namespace adios2
#endif /** ADIOS2_TOOLKIT_FORMAT_BPOPERATION_COMPRESS_BPBZIP2_TCC_ */
|
Unknoob/buck
|
test/com/facebook/buck/util/AnsiEnvironmentCheckingTest.java
|
<reponame>Unknoob/buck
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.util;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableMap;
import org.junit.Test;
public class AnsiEnvironmentCheckingTest {
@Test
public void testSupportsAnsiEscapes() {
ImmutableMap<String, String> context =
ImmutableMap.of("TERM", "test_term", "NAILGUN_TTY_1", "1", "NAILGUN_TTY_2", "1");
assertTrue(AnsiEnvironmentChecking.environmentSupportsAnsiEscapes(Platform.LINUX, context));
assertTrue(AnsiEnvironmentChecking.environmentSupportsAnsiEscapes(Platform.WINDOWS, context));
}
}
|
yuexinok/lufax-jijin
|
src/main/java/com/lufax/jijin/event/handler/impl/YXLOPProductCancelHandler.java
|
<reponame>yuexinok/lufax-jijin
package com.lufax.jijin.event.handler.impl;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lufax.jijin.base.utils.Logger;
import com.lufax.jijin.event.entity.YLXOpProductResultEvent;
import com.lufax.jijin.event.entity.YLXOpProductResultEventParser;
import com.lufax.jijin.event.handler.EventContext;
import com.lufax.jijin.event.handler.EventHandler;
import com.lufax.jijin.product.dto.ProductDTO;
import com.lufax.jijin.product.repository.ProductRepository;
import com.lufax.jijin.ylx.dto.YLXBuyRequestDetailDTO;
import com.lufax.jijin.ylx.dto.repository.YLXBuyRequestDetailRepository;
import com.lufax.jijin.ylx.enums.YLXBuyRequestStatus;
@Component
public class YXLOPProductCancelHandler extends EventHandler{
@Autowired
private ProductRepository productRepository;
@Autowired
private YLXBuyRequestDetailRepository ylxBuyRequestDetailRepository;
private static final int ROWNUM = 500;
/* (non-Javadoc)
* @see com.lufax.jijin.event.handler.EventHandler#handle(com.lufax.jijin.event.handler.EventContext)
* 产品取消,把所有的认购确认记录翻转为失败
*/
@Override
public void handle(EventContext ctx) {
Logger.info(this, String.format("Event of [YLX-OP-Product-cancel][message: %s] received.", ctx.getMessage()));
YLXOpProductResultEvent event = YLXOpProductResultEventParser.parse(ctx.getMessage());
ProductDTO dto = productRepository.getById(event.getProductId());
if (null == dto) {
Logger.warn(this, String.format("ProductDTO not exists , event ignore. recordId [%s]", event.getProductId()));
return;
}
Logger.info(this, String.format("Event of [Update Buy requests of success]"));
List<YLXBuyRequestDetailDTO> buyRequestDetailDTOs = null;
do{
buyRequestDetailDTOs = ylxBuyRequestDetailRepository.getYLXBuyRequestDTOsByStatus(dto.getId(), ROWNUM, YLXBuyRequestStatus.SUCCESS.name());
if(null!= buyRequestDetailDTOs){
for(YLXBuyRequestDetailDTO ylxBuyRequestDetailDTO : buyRequestDetailDTOs){
ylxBuyRequestDetailDTO.setStatus(YLXBuyRequestStatus.FAIL.name());
}
ylxBuyRequestDetailRepository.batchUpdate(buyRequestDetailDTOs);
}
} while (CollectionUtils.isNotEmpty(buyRequestDetailDTOs));
Logger.info(this, String.format("Event of [YLX-OP-Product-cancel][message: %s] handled.", ctx.getMessage()));
}
}
|
joelturner79/real-time-income-information
|
project/AppDependencies.scala
|
import play.core.PlayVersion
import play.sbt.PlayImport._
import sbt._
object AppDependencies {
val compile = Seq(
ws,
"uk.gov.hmrc" %% "bootstrap-play-25" % "3.7.0",
"uk.gov.hmrc" %% "domain" % "5.2.0",
"com.eclipsesource" %% "play-json-schema-validator" % "0.8.9",
"uk.gov.hmrc" %% "play-auditing" % "3.9.0-play-25"
)
def test(scope: String = "test") = Seq(
"uk.gov.hmrc" %% "hmrctest" % "3.1.0" % scope,
"org.scalatest" %% "scalatest" % "3.0.4" % scope,
"org.pegdown" % "pegdown" % "1.6.0" % scope,
"org.scalatestplus.play" %% "scalatestplus-play" % "2.0.1" % scope,
"org.mockito" % "mockito-core" % "1.9.5",
"com.typesafe.play" %% "play-test" % PlayVersion.current % scope,
"com.github.tomakehurst" % "wiremock" % "2.15.0" % scope
)
}
|
Clevgs/RPIskel
|
node_modules/casperjs/tests/suites/tester/test-order.js
|
/*eslint strict:0*/
/*global CasperError, casper, console, phantom, require*/
var fs = require('fs');
casper.test.begin('Tester.sortFiles()', 1, function suite(test) {
var testDirRoot = fs.pathJoin(phantom.casperPath, 'tests', 'testdir');
var files = test.findTestFiles(testDirRoot);
var expected = [
"01_a/abc.js",
"01_a/def.js",
"02_b/abc.js",
"03_a.js",
"03_b.js",
"04/01_init.js",
"04/02_do.js"
].map(function(entry) {
return fs.pathJoin.apply(fs, [testDirRoot].concat(entry.split('/')));
});
test.assertEquals(files, expected, 'findTestFiles() find test files and sort them');
test.done();
});
|
BeneStem/togglz
|
core/src/main/java/org/togglz/core/repository/jdbc/JDBCStateRepository.java
|
package org.togglz.core.repository.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
import javax.sql.DataSource;
import org.togglz.core.Feature;
import org.togglz.core.logging.Log;
import org.togglz.core.logging.LogFactory;
import org.togglz.core.repository.FeatureState;
import org.togglz.core.repository.StateRepository;
import org.togglz.core.repository.util.DefaultMapSerializer;
import org.togglz.core.repository.util.MapSerializer;
import org.togglz.core.util.DbUtils;
import org.togglz.core.util.Strings;
/**
* <p>
* This repository implementation can be used to store the feature state in SQL database using the standard JDBC API.
* </p>
*
* <p>
* {@link JDBCStateRepository} stores the feature state in a single database table. You can choose the name of this table using
* a constructor argument. If the repository doesn't find the required table in the database, it will automatically create it.
* </p>
*
* <p>
* The database table has the following format:
* </p>
*
* <pre>
* CREATE TABLE <table> (
* FEATURE_NAME VARCHAR(100) PRIMARY KEY,
* FEATURE_ENABLED INTEGER,
* STRATEGY_ID VARCHAR(200),
* STRATEGY_PARAMS VARCHAR(2000)
* )
* </pre>
*
* <p>
* The class provides a builder which can be used to configure the repository:
* </p>
*
* <pre>
* StateRepository repository = JDBCStateRepository.newBuilder(dataSource)
* .tableName("features")
* .createTable(false)
* .serializer(DefaultMapSerializer.singleline())
* .noCommit(true)
* .build();
* </pre>
*
* <p>
* Please note that the structure of the database table changed with version 2.0.0 because of the new extensible activation
* strategy mechanism. The table structure will be automatically migrated to the new format.
* </p>
*
* @author <NAME>
*
*/
public class JDBCStateRepository implements StateRepository {
protected final Log log = LogFactory.getLog(JDBCStateRepository.class);
protected final DataSource dataSource;
protected final String tableName;
protected final MapSerializer serializer;
protected final boolean noCommit;
/**
* Constructor of {@link JDBCStateRepository}. A database table called <code>TOGGLZ</code> will be created automatically for
* you.
*
* @param dataSource The JDBC {@link DataSource} to obtain connections from
* @see #JDBCStateRepository(DataSource, String)
*/
public JDBCStateRepository(DataSource dataSource) {
this(new Builder(dataSource));
}
/**
* Constructor of {@link JDBCStateRepository}. The database table will be created automatically for you.
*
* @param dataSource The JDBC {@link DataSource} to obtain connections from
* @param tableName The name of the database table to use
*/
public JDBCStateRepository(DataSource dataSource, String tableName) {
this(new Builder(dataSource).tableName(tableName));
}
/**
* Constructor of {@link JDBCStateRepository}.
*
* @param dataSource The JDBC {@link DataSource} to obtain connections from
* @param tableName The name of the database table to use
* @param createTable If set to <code>true</code>, the table will be automatically created if it is missing
* @deprecated use {@link JDBCStateRepository#newBuilder(DataSource)} to create a builder that can be used to configure all
* aspects of the repository in a fluent way
*/
@Deprecated
public JDBCStateRepository(DataSource dataSource, String tableName, boolean createTable) {
this(new Builder(dataSource).tableName(tableName).createTable(createTable));
}
/**
* Constructor of {@link JDBCStateRepository}.
*
* @param dataSource The JDBC {@link DataSource} to obtain connections from
* @param tableName The name of the database table to use
* @param createTable If set to <code>true</code>, the table will be automatically created if it is missing
* @param serializer The {@link MapSerializer} for storing parameters
* @deprecated use {@link JDBCStateRepository#newBuilder(DataSource)} to create a builder that can be used to configure all
* aspects of the repository in a fluent way
*/
@Deprecated
public JDBCStateRepository(DataSource dataSource, String tableName, boolean createTable, MapSerializer serializer) {
this(new Builder(dataSource).tableName(tableName).createTable(createTable).serializer(serializer));
}
/**
* Constructor of {@link JDBCStateRepository}.
*
* @param dataSource The JDBC {@link DataSource} to obtain connections from
* @param tableName The name of the database table to use
* @param createTable If set to <code>true</code>, the table will be automatically created if it is missing
* @param serializer The {@link MapSerializer} for storing parameters
* @deprecated use {@link JDBCStateRepository#newBuilder(DataSource)} to create a builder that can be used to configure all
* aspects of the repository in a fluent way
*/
public JDBCStateRepository(DataSource dataSource, String tableName, boolean createTable, MapSerializer serializer,
boolean noCommit) {
this(new Builder(dataSource).tableName(tableName).createTable(createTable).serializer(serializer).noCommit(noCommit));
}
/**
* Private constructor initializing the class from a builder
*/
private JDBCStateRepository(Builder builder) {
this.dataSource = builder.dataSource;
this.tableName = builder.tableName;
this.serializer = builder.serializer;
this.noCommit = builder.noCommit;
if (builder.createTable) {
migrateSchema();
}
}
/**
* Method for creating/migrating the database schema
*/
protected void migrateSchema() {
try {
Connection connection = dataSource.getConnection();
try {
beforeSchemaMigration(connection);
SchemaUpdater updater = new SchemaUpdater(connection, tableName, serializer);
if (!updater.doesTableExist()) {
updater.migrateToVersion1();
}
if (updater.isSchemaVersion1()) {
updater.migrateToVersion2();
}
afterSchemaMigration(connection);
} finally {
DbUtils.closeQuietly(connection);
}
} catch (SQLException e) {
throw new IllegalStateException("Failed to migrate the database schema", e);
}
}
/**
* Method called <strong>before</strong> the database schema migration is performed.
*/
@SuppressWarnings("unused")
protected void beforeSchemaMigration(Connection connection) {
// overwrite me
}
/**
* Method called <strong>after</strong> the database schema migration has been performed.
*/
@SuppressWarnings("unused")
protected void afterSchemaMigration(Connection connection) {
// overwrite me
}
@Override
public FeatureState getFeatureState(Feature feature) {
try {
Connection connection = dataSource.getConnection();
try {
String sql = "SELECT FEATURE_ENABLED, STRATEGY_ID, STRATEGY_PARAMS FROM %TABLE% WHERE FEATURE_NAME = ?";
PreparedStatement statement = connection.prepareStatement(insertTableName(sql));
try {
statement.setString(1, feature.id());
ResultSet resultSet = statement.executeQuery();
try {
if (resultSet.next()) {
boolean enabled = resultSet.getInt(Columns.FEATURE_ENABLED) > 0;
FeatureState state = new FeatureState(feature, enabled);
String strategyId = resultSet.getString(Columns.STRATEGY_ID);
if (Strings.isNotBlank(strategyId)) {
state.setStrategyId(strategyId.trim());
}
String paramData = resultSet.getString(Columns.STRATEGY_PARAMS);
if (Strings.isNotBlank(paramData)) {
Map<String, String> params = serializer.deserialize(paramData);
for (Entry<String, String> param : params.entrySet()) {
state.setParameter(param.getKey(), param.getValue());
}
}
return state;
}
} finally {
DbUtils.closeQuietly(resultSet);
}
} finally {
DbUtils.closeQuietly(statement);
}
} finally {
DbUtils.closeQuietly(connection);
}
} catch (SQLException e) {
throw new IllegalStateException("Failed to fetch the feature's state from the database", e);
}
return null;
}
@Override
public void setFeatureState(FeatureState featureState) {
try {
Connection connection = dataSource.getConnection();
try {
int updatedRows = 0;
/*
* First try to update an existing row
*/
String updateSql = "UPDATE %TABLE% SET FEATURE_ENABLED = ?, STRATEGY_ID = ?, STRATEGY_PARAMS = ? WHERE FEATURE_NAME = ?";
PreparedStatement updateStatement = connection.prepareStatement(insertTableName(updateSql));
try {
String paramData = serializer.serialize(featureState.getParameterMap());
updateStatement.setInt(1, featureState.isEnabled() ? 1 : 0);
updateStatement.setString(2, Strings.trimToNull(featureState.getStrategyId()));
updateStatement.setString(3, Strings.trimToNull(paramData));
updateStatement.setString(4, featureState.getFeature().id());
updatedRows = updateStatement.executeUpdate();
} finally {
DbUtils.closeQuietly(updateStatement);
}
/*
* If our update didn't modify any data we have to insert a new row
*/
if (updatedRows == 0) {
String insertSql = "INSERT INTO %TABLE% (FEATURE_NAME, FEATURE_ENABLED, STRATEGY_ID, STRATEGY_PARAMS) VALUES (?,?,?,?)";
PreparedStatement insertStatement = connection.prepareStatement(insertTableName(insertSql));
try {
String paramsAsString = serializer.serialize(featureState.getParameterMap());
insertStatement.setString(1, featureState.getFeature().id());
insertStatement.setInt(2, featureState.isEnabled() ? 1 : 0);
insertStatement.setString(3, Strings.trimToNull(featureState.getStrategyId()));
insertStatement.setString(4, Strings.trimToNull(paramsAsString));
insertStatement.executeUpdate();
} finally {
DbUtils.closeQuietly(insertStatement);
}
}
if (!connection.getAutoCommit() && !noCommit) {
connection.commit();
}
} finally {
DbUtils.closeQuietly(connection);
}
} catch (SQLException e) {
throw new IllegalStateException("Failed to set the feature's state in the database", e);
}
}
private String insertTableName(String s) {
return s.replace("%TABLE%", tableName);
}
/**
* Creates a new builder for creating a {@link JDBCStateRepository}.
*
* @param dataSource the {@link DataSource} Togglz should use to obtain JDBC connections
*/
public static Builder newBuilder(DataSource dataSource) {
return new Builder(dataSource);
}
/**
* Builder for a {@link JDBCStateRepository}.
*/
public static class Builder {
private DataSource dataSource;
private String tableName = "TOGGLZ";
private MapSerializer serializer = DefaultMapSerializer.multiline();
private boolean noCommit = false;
private boolean createTable = true;
/**
* Creates a new builder for creating a {@link JDBCStateRepository}.
*
* @param dataSource the {@link DataSource} Togglz should use to obtain JDBC connections
*/
public Builder(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* Sets the table name to use for the Togglz feature state table. The default name is <code>TOGGLZ</code>.
*
* @param tableName The database table name
*/
public Builder tableName(String tableName) {
this.tableName = tableName;
return this;
}
/**
* The {@link MapSerializer} for storing parameters. By default the repository will use
* {@link DefaultMapSerializer#multiline()}.
*
* @param serializer The serializer to use
*/
public Builder serializer(MapSerializer serializer) {
this.serializer = serializer;
return this;
}
/**
* Can be used to suppress to commit after modifying data in the repository. Can be useful if Togglz uses managed
* connections provided by a JEE container. The default is <code>false</code>.
*
* @param noCommit <code>true</code> to suppress commits
*/
public Builder noCommit(boolean noCommit) {
this.noCommit = noCommit;
return this;
}
/**
* If set to <code>true</code>, the table will be automatically created if it is missing. The default is
* <code>true</code>.
*
* @param createTable <code>true</code> if the table should be created automatically
*/
public Builder createTable(boolean createTable) {
this.createTable = createTable;
return this;
}
/**
* Creates a {@link JDBCStateRepository} from the current configuration
*/
public JDBCStateRepository build() {
return new JDBCStateRepository(this);
}
}
}
|
Zealen408/Bike_registry
|
bikes/urls.py
|
<filename>bikes/urls.py
from .views import *
from django.urls import path
app_name = 'bikes'
urlpatterns = [
path('create', bike_create, name='create'),
path('delete/<int:pk>', BikeDelete.as_view(), name='delete'),
path('<str:username>', bike_list, name='list'),
path('<str:username>/<str:serial_number>', bike_detail, name='detail'),
path('lost', lost_bikes, name='lost')
]
|
Releed/Construct-2
|
plugins/keyboard/edittime.js
|
function GetPluginSettings()
{
return {
"name": "Keyboard",
"id": "Keyboard",
"version": "1.0",
"description": "Retrieve input from the keyboard.",
"author": "Scirra",
"help url": "http://www.scirra.com/manual/113/keyboard",
"category": "Input",
"type": "object", // not in layout
"rotatable": false,
"flags": pf_singleglobal
};
};
//////////////////////////////////////////////////////////////
// Conditions
AddKeybParam("Key", "Choose a key. Note that international users and users on different operating systems or devices may not have the same keys available.");
AddCondition(0, cf_trigger, "On key pressed", "Keyboard", "On <b>{0}</b> pressed", "Triggered when a keyboard key is pressed.", "OnKey");
AddCondition(1, cf_trigger, "On any key pressed", "Keyboard", "On any key pressed", "Triggered when any keyboard key is pressed.", "OnAnyKey");
AddCondition(7, cf_trigger, "On any key released", "Keyboard", "On any key released", "Triggered when any keyboard key is released.", "OnAnyKeyReleased");
AddKeybParam("Key", "Choose a key. Note that international users and users on different operating systems or devices may not have the same keys available.");
AddCondition(2, 0, "Key is down", "Keyboard", "<b>{0}</b> is down", "Test if a keyboard key is currently held down.", "IsKeyDown");
AddKeybParam("Key", "Choose a key. Note that international users and users on different operating systems or devices may not have the same keys available.");
AddCondition(3, cf_trigger, "On key released", "Keyboard", "On <b>{0}</b> released", "Triggered when a keyboard key is released.", "OnKeyReleased");
AddNumberParam("Keycode", "Choose a numeric key code to test.");
AddCondition(4, cf_trigger, "On key code pressed", "Key codes", "On key code <b>{0}</b> pressed", "Test for a key pressed by its numeric key code.", "OnKeyCode");
AddNumberParam("Keycode", "Choose a numeric key code to test.");
AddCondition(5, 0, "Key code is down", "Key codes", "Key code <b>{0}</b> is down", "Test if a keyboard key is currently held down by its numeric key code.", "IsKeyCodeDown");
AddNumberParam("Keycode", "Choose a numeric key code to test.");
AddCondition(6, cf_trigger, "On key code released", "Key codes", "On key code <b>{0}</b> released", "Test for a key released by its numeric key code.", "OnKeyCodeReleased");
//////////////////////////////////////////////////////////////
// Expressions
AddExpression(0, ef_return_number, "", "Key codes", "LastKeyCode", "Get the key code for the last pressed key.");
AddNumberParam("Key code", "The key code to get a string from");
AddExpression(1, ef_return_string, "", "Key codes", "StringFromKeyCode", "Get a character string representing a key code.");
ACESDone();
// Property grid properties for this plugin
var property_list = [
];
// Called by IDE when a new object type is to be created
function CreateIDEObjectType()
{
return new IDEObjectType();
}
// Class representing an object type in the IDE
function IDEObjectType()
{
assert2(this instanceof arguments.callee, "Constructor called as a function");
}
// Called by IDE when a new object instance of this type is to be created
IDEObjectType.prototype.CreateInstance = function(instance)
{
return new IDEInstance(instance, this);
}
// Class representing an individual instance of an object in the IDE
function IDEInstance(instance, type)
{
assert2(this instanceof arguments.callee, "Constructor called as a function");
// Save the constructor parameters
this.instance = instance;
this.type = type;
// Set the default property values from the property table
this.properties = {};
for (var i = 0; i < property_list.length; i++)
this.properties[property_list[i].name] = property_list[i].initial_value;
}
// Called by the IDE after all initialization on this instance has been completed
IDEInstance.prototype.OnCreate = function()
{
}
// Called by the IDE after a property has been changed
IDEInstance.prototype.OnPropertyChanged = function(property_name)
{
}
// Called by the IDE to draw this instance in the editor
IDEInstance.prototype.Draw = function(renderer)
{
}
// Called by the IDE when the renderer has been released (ie. editor closed)
// All handles to renderer-created resources (fonts, textures etc) must be dropped.
// Don't worry about releasing them - the renderer will free them - just null out references.
IDEInstance.prototype.OnRendererReleased = function()
{
}
|
silesiacoin/eth2-docker-compose
|
.docker/Prysm/prysm-spike/beacon-chain/rpc/debug/server.go
|
<reponame>silesiacoin/eth2-docker-compose
// Package debug defines a gRPC server implementation of a debugging service
// which allows for helpful endpoints to debug a beacon node at runtime, this server is
// gated behind the feature flag --enable-debug-rpc-endpoints.
package debug
import (
"context"
"os"
gethlog "github.com/ethereum/go-ethereum/log"
ptypes "github.com/gogo/protobuf/types"
golog "github.com/ipfs/go-log/v2"
"github.com/prysmaticlabs/prysm/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/beacon-chain/db"
"github.com/prysmaticlabs/prysm/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
pbrpc "github.com/prysmaticlabs/prysm/proto/beacon/rpc/v1"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// Server defines a server implementation of the gRPC Debug service,
// providing RPC endpoints for runtime debugging of a node, this server is
// gated behind the feature flag --enable-debug-rpc-endpoints.
type Server struct {
BeaconDB db.NoHeadAccessDatabase
GenesisTimeFetcher blockchain.TimeFetcher
StateGen *stategen.State
HeadFetcher blockchain.HeadFetcher
PeerManager p2p.PeerManager
PeersFetcher p2p.PeersProvider
}
// SetLoggingLevel of a beacon node according to a request type,
// either INFO, DEBUG, or TRACE.
func (ds *Server) SetLoggingLevel(_ context.Context, req *pbrpc.LoggingLevelRequest) (*ptypes.Empty, error) {
var verbosity string
switch req.Level {
case pbrpc.LoggingLevelRequest_INFO:
verbosity = "info"
case pbrpc.LoggingLevelRequest_DEBUG:
verbosity = "debug"
case pbrpc.LoggingLevelRequest_TRACE:
verbosity = "trace"
default:
return nil, status.Error(codes.InvalidArgument, "Expected valid verbosity level as argument")
}
level, err := logrus.ParseLevel(verbosity)
if err != nil {
return nil, status.Error(codes.Internal, "Could not parse verbosity level")
}
logrus.SetLevel(level)
if level == logrus.TraceLevel {
// Libp2p specific logging.
golog.SetAllLoggers(golog.LevelDebug)
// Geth specific logging.
glogger := gethlog.NewGlogHandler(gethlog.StreamHandler(os.Stderr, gethlog.TerminalFormat(true)))
glogger.Verbosity(gethlog.LvlTrace)
gethlog.Root().SetHandler(glogger)
}
return &ptypes.Empty{}, nil
}
|
baba-a461/Hypnotic-Fabric-1.17
|
src/main/java/badgamesinc/hypnotic/mixin/BlockMixin.java
|
package badgamesinc.hypnotic.mixin;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import badgamesinc.hypnotic.event.events.EventCollide;
import badgamesinc.hypnotic.module.ModuleManager;
import badgamesinc.hypnotic.module.render.Xray;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.util.function.BooleanBiFunction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.shape.VoxelShape;
import net.minecraft.util.shape.VoxelShapes;
import net.minecraft.world.BlockView;
import net.minecraft.world.World;
@Mixin(Block.class)
public class BlockMixin {
@Inject(method = "shouldDrawSide", at = @At("HEAD"), cancellable = true)
private static void shouldDrawSide(BlockState state, BlockView world, BlockPos pos, Direction side, BlockPos blockPos, CallbackInfoReturnable<Boolean> cir) {
if (ModuleManager.INSTANCE.getModule(Xray.class).isEnabled()) {
cir.setReturnValue(Xray.blocks.contains(state.getBlock()));
}
}
@Inject(method = "isTranslucent", at = @At("HEAD"), cancellable = true)
public void isTranslucent(BlockState state, BlockView world, BlockPos pos, CallbackInfoReturnable<Boolean> cir) {
if (ModuleManager.INSTANCE.getModule(Xray.class).isEnabled()) {
cir.setReturnValue(!Xray.blocks.contains(state.getBlock()));
}
}
@Inject(method = "pushEntitiesUpBeforeBlockChange", at = @At("HEAD"), cancellable = true)
private static void pushEntitiesUpBeforeBlockChange(BlockState from, BlockState to, World world, BlockPos pos, CallbackInfoReturnable<BlockState> cir) {
VoxelShape voxelShape = VoxelShapes.combine(from.getCollisionShape(world, pos), to.getCollisionShape(world, pos), BooleanBiFunction.ONLY_SECOND).offset((double)pos.getX(), (double)pos.getY(), (double)pos.getZ());
EventCollide.Block event = new EventCollide.Block(voxelShape.getBoundingBox(), pos);
event.call();
System.out.println("e");
if (event.isCancelled()) cir.cancel();
}
}
|
xuing/openrasp
|
agent/php7/hook/openrasp_pdo.cc
|
/*
* Copyright 2017-2021 Baidu Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "utils/regex.h"
#include "hook/data/sql_error_object.h"
#include "hook/checker/v8_detector.h"
#include "hook/data/sql_object.h"
#include "openrasp_sql.h"
#include "openrasp_hook.h"
extern "C"
{
#include "ext/pdo/php_pdo_driver.h"
#include "zend_ini.h"
#include "Zend/zend_objects_API.h"
}
POST_HOOK_FUNCTION_EX(__construct, pdo, DB_CONNECTION);
POST_HOOK_FUNCTION_EX(__construct, pdo, SQL_ERROR);
PRE_HOOK_FUNCTION_EX(query, pdo, SQL);
POST_HOOK_FUNCTION_EX(query, pdo, SQL_ERROR);
PRE_HOOK_FUNCTION_EX(exec, pdo, SQL);
POST_HOOK_FUNCTION_EX(exec, pdo, SQL_ERROR);
PRE_HOOK_FUNCTION_EX(prepare, pdo, SQL_PREPARED);
POST_HOOK_FUNCTION_EX(prepare, pdo, SQL_ERROR);
const static std::set<std::string> supported_server = {"mysql", "pgsql", "sqlite"};
static void error_info_check(const openrasp::data::V8Material &v8_material, const std::string &driver_name, zval *error_info);
static void pdo_exception_intercept(const openrasp::data::V8Material &v8_material, const std::string &driver_name, zval *object);
static void pdo_error_info_intercept(const openrasp::data::V8Material &v8_material, const std::string &driver_name, zval *statement);
extern void parse_connection_string(char *connstring, openrasp::data::SqlConnectionObject &sql_connection_obj);
static bool is_server_supported(const std::string &server)
{
auto found = supported_server.find(server);
return found != supported_server.end();
}
static char *dsn_from_uri(char *uri, char *buf, size_t buflen)
{
php_stream *stream = nullptr;
char *dsn = nullptr;
stream = php_stream_open_wrapper(uri, "rb", REPORT_ERRORS, nullptr);
if (stream)
{
dsn = php_stream_get_line(stream, buf, buflen, nullptr);
php_stream_close(stream);
}
return dsn;
}
static bool init_pdo_connection_entry(INTERNAL_FUNCTION_PARAMETERS, openrasp::data::SqlConnectionObject &sql_connection_obj)
{
char *data_source = nullptr;
size_t data_source_len = 0;
char *colon = nullptr;
char *username = nullptr, *password = nullptr;
size_t usernamelen = 0;
size_t passwordlen = 0;
zval *options = nullptr;
char alt_dsn[512];
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s|s!s!a!", &data_source, &data_source_len,
&username, &usernamelen, &password, &passwordlen, &options))
{
return false;
}
sql_connection_obj.set_connection_string(data_source);
/* parse the data source name */
colon = strchr(data_source, ':');
if (!colon)
{
/* let's see if this string has a matching dsn in the php.ini */
char *ini_dsn = nullptr;
snprintf(alt_dsn, sizeof(alt_dsn), "pdo.dsn.%s", data_source);
if (FAILURE == cfg_get_string(alt_dsn, &ini_dsn))
{
return false;
}
data_source = ini_dsn;
colon = strchr(data_source, ':');
if (!colon)
{
return false;
}
}
if (!strncmp(data_source, "uri:", sizeof("uri:") - 1))
{
/* the specified URI holds connection details */
data_source = dsn_from_uri(data_source + sizeof("uri:") - 1, alt_dsn, sizeof(alt_dsn));
if (!data_source)
{
return false;
}
colon = strchr(data_source, ':');
if (!colon)
{
return false;
}
}
static const char *server_names[] = {"mysql", "mssql", "oci", "pgsql"};
int server_size = sizeof(server_names) / sizeof(server_names[0]);
for (int index = 0; index < server_size; ++index)
{
if (strncmp(server_names[index], data_source, strlen(server_names[index])) == 0)
{
sql_connection_obj.set_server((const char *)server_names[index]);
}
}
if (sql_connection_obj.get_server() == "mysql")
{
struct pdo_data_src_parser mysql_vars[] = {
{"charset", nullptr, 0},
{"dbname", "", 0},
{"host", "localhost", 0},
{"port", "3306", 0},
{"unix_socket", nullptr, 0},
};
int matches = php_pdo_parse_data_source(colon + 1, strlen(colon + 1), mysql_vars, 5);
sql_connection_obj.set_host(mysql_vars[2].optval);
sql_connection_obj.set_using_socket(nullptr == mysql_vars[2].optval || strcmp("localhost", mysql_vars[2].optval) == 0);
sql_connection_obj.set_port(atoi(mysql_vars[3].optval));
sql_connection_obj.set_socket(SAFE_STRING(mysql_vars[4].optval));
if (username)
{
sql_connection_obj.set_username(username);
}
if (password)
{
sql_connection_obj.set_password(password);
}
for (int i = 0; i < 5; i++)
{
if (mysql_vars[i].freeme)
{
efree(mysql_vars[i].optval);
}
}
}
else if (sql_connection_obj.get_server() == "pgsql")
{
char *e = nullptr;
char *p = nullptr;
char *conn_str = nullptr;
char *dhn_data_source = estrdup(colon + 1);
e = (char *)dhn_data_source + strlen(dhn_data_source);
p = (char *)dhn_data_source;
while ((p = (char *)memchr(p, ';', (e - p))))
{
*p = ' ';
}
if (username && password)
{
spprintf(&conn_str, 0, "%s user=%s password=%s", dhn_data_source, username, password);
}
else if (username)
{
spprintf(&conn_str, 0, "%s user=%s", dhn_data_source, username);
}
else if (password)
{
spprintf(&conn_str, 0, "%s password=%s", dhn_data_source, password);
}
else
{
spprintf(&conn_str, 0, "%s", (char *)dhn_data_source);
}
parse_connection_string(conn_str, sql_connection_obj);
efree(conn_str);
efree(dhn_data_source);
}
else
{
//It is not supported at present
}
return true;
}
void pre_pdo_query_SQL(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)
{
pdo_dbh_t *dbh = Z_PDO_DBH_P(getThis());
zval *statement = nullptr;
if (!ZEND_NUM_ARGS() ||
FAILURE == zend_parse_parameters(1, "z", &statement))
{
return;
}
plugin_sql_check(statement, dbh->driver->driver_name);
}
void post_pdo_query_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)
{
pdo_dbh_t *dbh = Z_PDO_DBH_P(getThis());
std::string driver_name = std::string(dbh->driver->driver_name);
if (!is_server_supported(driver_name))
{
return;
}
zval *statement = nullptr;
if (!ZEND_NUM_ARGS() ||
FAILURE == zend_parse_parameters(1, "z", &statement))
{
return;
}
openrasp::data::SqlObject sql_obj(driver_name, statement);
if (Z_TYPE_P(return_value) == IS_FALSE)
{
if (dbh->error_mode == PDO_ERRMODE_EXCEPTION)
{
if (EG(exception) && EG(exception)->ce == php_pdo_get_exception())
{
zval object;
ZVAL_OBJ(&object, EG(exception));
pdo_exception_intercept(sql_obj, driver_name, &object);
}
}
else
{
pdo_error_info_intercept(sql_obj, driver_name, getThis());
}
}
}
void pre_pdo_exec_SQL(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)
{
pre_pdo_query_SQL(OPENRASP_INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
void post_pdo_exec_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)
{
post_pdo_query_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
void post_pdo___construct_DB_CONNECTION(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)
{
if (Z_TYPE_P(getThis()) == IS_OBJECT && !EG(exception))
{
openrasp::data::SqlConnectionObject sco;
sql_connection_policy_check(INTERNAL_FUNCTION_PARAM_PASSTHRU, init_pdo_connection_entry, sco);
}
}
void post_pdo___construct_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)
{
if (EG(exception) && EG(exception)->ce == php_pdo_get_exception())
{
openrasp::data::SqlConnectionObject sco;
init_pdo_connection_entry(INTERNAL_FUNCTION_PARAM_PASSTHRU, sco);
if (is_server_supported(sco.get_server()))
{
zval object;
ZVAL_OBJ(&object, EG(exception));
pdo_exception_intercept(sco, sco.get_server().c_str(), &object);
}
}
}
void pre_pdo_prepare_SQL_PREPARED(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)
{
pdo_dbh_t *dbh = Z_PDO_DBH_P(getThis());
zval *statement = nullptr;
zval *options = nullptr;
if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "z|a", &statement, &options))
{
return;
}
plugin_sql_check(statement, dbh->driver->driver_name);
}
void post_pdo_prepare_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAMETERS)
{
post_pdo_query_SQL_ERROR(OPENRASP_INTERNAL_FUNCTION_PARAM_PASSTHRU);
}
void error_info_check(const openrasp::data::V8Material &v8_material, const std::string &driver_name, zval *error_info)
{
if (nullptr != error_info && Z_TYPE_P(error_info) == IS_ARRAY)
{
zval *tmp = nullptr;
std::string error_msg;
if ((tmp = zend_hash_index_find(Z_ARRVAL_P(error_info), 2)) != nullptr &&
Z_TYPE_P(tmp) == IS_STRING)
{
error_msg = std::string(Z_STRVAL_P(tmp));
}
ulong code_index = driver_name == "pgsql" ? 0 : 1;
if ((tmp = zend_hash_index_find(Z_ARRVAL_P(error_info), code_index)) != nullptr)
{
if (Z_TYPE_P(tmp) == IS_LONG)
{
openrasp::data::SqlErrorObject seo(v8_material, driver_name, Z_LVAL_P(tmp), error_msg);
openrasp::checker::V8Detector error_checker(seo, OPENRASP_HOOK_G(lru), OPENRASP_V8_G(isolate), OPENRASP_CONFIG(plugin.timeout.millis));
error_checker.run();
}
else if (Z_TYPE_P(tmp) == IS_STRING)
{
openrasp::data::SqlErrorObject seo(v8_material, driver_name, Z_STRVAL_P(tmp), error_msg);
openrasp::checker::V8Detector error_checker(seo, OPENRASP_HOOK_G(lru), OPENRASP_V8_G(isolate), OPENRASP_CONFIG(plugin.timeout.millis));
error_checker.run();
}
}
}
}
void pdo_error_info_intercept(const openrasp::data::V8Material &v8_material, const std::string &driver_name, zval *statement)
{
zval retval;
if (openrasp_call_user_function(EG(function_table), statement, "errorinfo", &retval, 0, nullptr))
{
error_info_check(v8_material, driver_name, &retval);
zval_ptr_dtor(&retval);
}
}
static void pdo_exception_intercept(const openrasp::data::V8Material &v8_material, const std::string &driver_name, zval *object)
{
zval rv;
zval *error_info = zend_read_property(php_pdo_get_exception(), object, "errorInfo", sizeof("errorInfo") - 1, 1, &rv);
if (nullptr != error_info && Z_TYPE_P(error_info) == IS_ARRAY)
{
error_info_check(v8_material, driver_name, error_info);
}
else
{
if (driver_name == "mysql" ||
driver_name == "sqlite")
{
zval *code = zend_read_property(php_pdo_get_exception(), object, "code", sizeof("code") - 1, 1, &rv);
if (nullptr == code)
{
return;
}
std::string error_msg;
zval *message = zend_read_property(php_pdo_get_exception(), object, "message", sizeof("message") - 1, 1, &rv);
if (Z_TYPE_P(message) == IS_STRING)
{
error_msg = std::string(Z_STRVAL_P(message));
}
if (Z_TYPE_P(code) == IS_LONG)
{
openrasp::data::SqlErrorObject seo(v8_material, driver_name, Z_LVAL_P(code), error_msg);
openrasp::checker::V8Detector error_checker(seo, OPENRASP_HOOK_G(lru), OPENRASP_V8_G(isolate), OPENRASP_CONFIG(plugin.timeout.millis));
error_checker.run();
}
else if (Z_TYPE_P(code) == IS_STRING)
{
openrasp::data::SqlErrorObject seo(v8_material, driver_name, Z_STRVAL_P(code), error_msg);
openrasp::checker::V8Detector error_checker(seo, OPENRASP_HOOK_G(lru), OPENRASP_V8_G(isolate), OPENRASP_CONFIG(plugin.timeout.millis));
error_checker.run();
}
}
else if (driver_name == "pgsql")
{
zval *message = zend_read_property(php_pdo_get_exception(), object, "message", sizeof("message") - 1, 1, &rv);
if (nullptr != message && Z_TYPE_P(message) == IS_STRING)
{
std::string error_msg = std::string(Z_STRVAL_P(message), Z_STRLEN_P(message));
if (openrasp::regex_search(error_msg.c_str(), "^SQLSTATE\\[[0-9A-Z]{5}\\] .*"))
{
std::string error_code = error_msg.substr(9, 5);
openrasp::data::SqlErrorObject seo(v8_material, driver_name, error_code, error_msg);
openrasp::checker::V8Detector v8_detector(seo, OPENRASP_HOOK_G(lru), OPENRASP_V8_G(isolate), OPENRASP_CONFIG(plugin.timeout.millis));
v8_detector.run();
}
}
}
}
}
|
dbahat/conventions
|
Conventions/app/src/main/java/amai/org/conventions/events/adapters/FreeTimeSlotViewHolder.java
|
<reponame>dbahat/conventions
package amai.org.conventions.events.adapters;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import java.util.Date;
import amai.org.conventions.R;
import amai.org.conventions.ThemeAttributes;
import amai.org.conventions.events.activities.EventsTimeSlot;
import amai.org.conventions.networking.AmaiModelConverter;
import amai.org.conventions.utils.Dates;
public class FreeTimeSlotViewHolder extends RecyclerView.ViewHolder {
private TextView textView;
public FreeTimeSlotViewHolder(View view) {
super(view);
textView = (TextView) view.findViewById(R.id.small_text);
}
public void setModel(EventsTimeSlot slot) {
Date startTime = slot.getStartTime();
Date endTime = slot.getEndTime();
textView.setText(textView.getContext().getString(R.string.free_time,
Dates.toHumanReadableTimeDuration(endTime.getTime() - startTime.getTime())));
// Set color according to started/during/passed
int color;
if (!startTime.before(Dates.now())) {
color = ThemeAttributes.getColor(itemView.getContext(), R.attr.eventTypeNotStartedColor);
} else if (endTime.before(Dates.now())) {
color = ThemeAttributes.getColor(itemView.getContext(), R.attr.eventTypeEndedColor);
} else {
color = ThemeAttributes.getColor(itemView.getContext(), R.attr.eventTypeCurrentColor);
}
if (color == AmaiModelConverter.NO_COLOR) {
color = ThemeAttributes.getColor(itemView.getContext(), R.attr.eventTimeHeaderDefaultTextColor);
}
textView.setTextColor(color);
}
}
|
memeyankm/training-data-analyst
|
quests/dataflow_python/4_SQL_Batch_Analytics/solution/batch_minute_traffic_SQL_pipeline.py
|
import argparse
import time
import logging
import json
import typing
from datetime import datetime
import apache_beam as beam
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.transforms.sql import SqlTransform
from apache_beam.runners import DataflowRunner, DirectRunner
# ### functions and classes
class CommonLog(typing.NamedTuple):
ip: str
user_id: str
lat: float
lng: float
ts: str
http_request: str
http_response: int
num_bytes: int
user_agent: str
beam.coders.registry.register_coder(CommonLog, beam.coders.RowCoder)
def parse_json(element):
row = json.loads(element)
row['ts'] = row['timestamp']
row.pop('timestamp')
return CommonLog(**row)
def format_timestamp(element):
ts = datetime.strptime(element.ts[:-8], "%Y-%m-%dT%H:%M:%S")
ts = datetime.strftime(ts, "%Y-%m-%d %H:%M:%S")
temp_dict = element._asdict()
temp_dict['ts'] = ts
return CommonLog(**temp_dict)
def to_dict(row):
return {'page_views' : row.page_views,
'start_time' : row.start_time}
# ### main
def run():
# Command line arguments
parser = argparse.ArgumentParser(description='Load from Json into BigQuery')
parser.add_argument('--project',required=True, help='Specify Google Cloud project')
parser.add_argument('--region', required=True, help='Specify Google Cloud region')
parser.add_argument('--stagingLocation', required=True, help='Specify Cloud Storage bucket for staging')
parser.add_argument('--tempLocation', required=True, help='Specify Cloud Storage bucket for temp')
parser.add_argument('--runner', required=True, help='Specify Apache Beam Runner')
parser.add_argument('--inputPath', required=True, help='Path to events.json')
parser.add_argument('--tableName', required=True, help='BigQuery table name')
opts, pipeline_opts = parser.parse_known_args()
# Setting up the Beam pipeline options
options = PipelineOptions(pipeline_opts, save_main_session=True)
options.view_as(GoogleCloudOptions).project = opts.project
options.view_as(GoogleCloudOptions).region = opts.region
options.view_as(GoogleCloudOptions).staging_location = opts.stagingLocation
options.view_as(GoogleCloudOptions).temp_location = opts.tempLocation
options.view_as(GoogleCloudOptions).job_name = '{0}{1}'.format('batch-minute-traffic-pipeline-sql'
,time.time_ns())
options.view_as(StandardOptions).runner = opts.runner
input_path = opts.inputPath
table_name = opts.tableName
# Table schema for BigQuery
table_schema = {
"fields": [
{
"name": "page_views",
"type": "INTEGER"
},
{
"name": "start_time",
"type": "STRING"
},
]
}
query = '''
SELECT
COUNT(*) AS page_views,
STRING(window_start) AS start_time
FROM
TUMBLE(
(SELECT TIMESTAMP(ts) AS ts FROM PCOLLECTION),
DESCRIPTOR(ts),
'INTERVAL 1 MINUTE')
GROUP BY window_start
'''
# Create the pipeline
p = beam.Pipeline(options=options)
(p | 'ReadFromGCS' >> beam.io.ReadFromText(input_path)
| 'ParseJson' >> beam.Map(parse_json).with_output_types(CommonLog)
| 'FormatTimestamp' >> beam.Map(format_timestamp).with_output_types(CommonLog)
| "CountPerMinute" >> SqlTransform(query, dialect='zetasql')
| "ConvertToDict" >> beam.Map(to_dict)
| 'WriteToBQ' >> beam.io.WriteToBigQuery(
table_name,
schema=table_schema,
create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE
)
)
logging.getLogger().setLevel(logging.INFO)
logging.info("Building pipeline ...")
p.run()
if __name__ == '__main__':
run()
|
comicChiii/minigame-adaptor
|
js-adaptor/src/Animation/Animator.js
|
<filename>js-adaptor/src/Animation/Animator.js
Bridge.assembly("unity-script-converter", function ($asm, globals) {
"use strict";
Bridge.define("MiniGameAdaptor.Animator", {
inherits: [MiniGameAdaptor.Behaviour],
statics: {
fields: {
hash_id:0,
name_map:null
},
ctors: {
init: function () {
this.name_map = new Map();
}
},
methods: {
Deserialize: function(data, comp, context, builtContext) {
return MiniGameAdaptor.Component.Deserialize(data, comp, context, builtContext);
},
StringToHash: function (name) {
var exist = false;
for (var val of this.name_map) {
if(val[1] == name){
exist = true;
return val[0];
}
}
if(exist == false){
this.hash_id++;
this.name_map.set(this.hash_id, name);
return this.hash_id;
}
},
getHashName: function (id){
var name = this.name_map.get(id);
return name;
}
}
},
fields: {
// _ref: null
ref: null
},
props: {
// ref: {
// get: function () {
// if (!this._ref) {
// this._ref = this.entity.getComponent(engine.Animator);
// }
// return this._ref;
// },
// set: function (value) {
// this._ref = value;
// }
// },
angularVelocity: {
get: function () {
throw new System.Exception("not impl");
}
},
applyRootMotion: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
avatar: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
bodyPosition: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
bodyRotation: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
cullingMode: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
deltaPosition: {
get: function () {
throw new System.Exception("not impl");
}
},
deltaRotation: {
get: function () {
throw new System.Exception("not impl");
}
},
feetPivotActive: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
fireEvents: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
gravityWeight: {
get: function () {
throw new System.Exception("not impl");
}
},
hasBoundPlayables: {
get: function () {
throw new System.Exception("not impl");
}
},
hasRootMotion: {
get: function () {
throw new System.Exception("not impl");
}
},
hasTransformHierarchy: {
get: function () {
throw new System.Exception("not impl");
}
},
humanScale: {
get: function () {
throw new System.Exception("not impl");
}
},
isHuman: {
get: function () {
throw new System.Exception("not impl");
}
},
isInitialized: {
get: function () {
throw new System.Exception("not impl");
}
},
isMatchingTarget: {
get: function () {
throw new System.Exception("not impl");
}
},
isOptimizable: {
get: function () {
throw new System.Exception("not impl");
}
},
keepAnimatorControllerStateOnDisable: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
layerCount: {
get: function () {
throw new System.Exception("not impl");
}
},
layersAffectMassCenter: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
leftFeetBottomHeight: {
get: function () {
throw new System.Exception("not impl");
}
},
logWarnings: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
parameterCount: {
get: function () {
throw new System.Exception("not impl");
}
},
parameters: {
get: function () {
throw new System.Exception("not impl");
}
},
pivotPosition: {
get: function () {
throw new System.Exception("not impl");
}
},
pivotWeight: {
get: function () {
throw new System.Exception("not impl");
}
},
playableGraph: {
get: function () {
throw new System.Exception("not impl");
}
},
playbackTime: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
recorderMode: {
get: function () {
throw new System.Exception("not impl");
}
},
recorderStartTime: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
recorderStopTime: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
rightFeetBottomHeight: {
get: function () {
throw new System.Exception("not impl");
}
},
rootPosition: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
rootRotation: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
runtimeAnimatorController: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
speed: {
get: function () {
return this.ref.speed;
},
set: function (value) {
this.ref.speed = value;
}
},
stabilizeFeet: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
targetPosition: {
get: function () {
throw new System.Exception("not impl");
}
},
targetRotation: {
get: function () {
throw new System.Exception("not impl");
}
},
updateMode: {
get: function () {
throw new System.Exception("not impl");
},
set: function (value) {
throw new System.Exception("not impl");
}
},
velocity: {
get: function () {
throw new System.Exception("not impl");
}
}
},
ctors: {
ctor: function (animator) {
this.$initialize();
MiniGameAdaptor.Behaviour.ctor.call(this);
if (animator instanceof engine.Animator) {
this.ref = animator;
}
}
},
methods: {
ApplyBuiltinRootMotion: function () {
throw new System.Exception("not impl");
},
CrossFade: function (stateHashName, normalizedTransitionDuration) {
throw new System.Exception("not impl");
},
CrossFade$1: function (stateHashName, normalizedTransitionDuration, layer) {
throw new System.Exception("not impl");
},
CrossFade$2: function (stateHashName, normalizedTransitionDuration, layer, normalizedTimeOffset) {
throw new System.Exception("not impl");
},
CrossFade$3: function (stateHashName, normalizedTransitionDuration, layer, normalizedTimeOffset, normalizedTransitionTime) {
throw new System.Exception("not impl");
},
CrossFade$4: function (stateName, normalizedTransitionDuration) {
throw new System.Exception("not impl");
},
CrossFade$5: function (stateName, normalizedTransitionDuration, layer) {
throw new System.Exception("not impl");
},
CrossFade$6: function (stateName, normalizedTransitionDuration, layer, normalizedTimeOffset) {
throw new System.Exception("not impl");
},
CrossFade$7: function (stateName, normalizedTransitionDuration, layer, normalizedTimeOffset, normalizedTransitionTime) {
throw new System.Exception("not impl");
},
CrossFadeInFixedTime: function (stateHashName, fixedTransitionDuration) {
throw new System.Exception("not impl");
},
CrossFadeInFixedTime$1: function (stateHashName, fixedTransitionDuration, layer) {
throw new System.Exception("not impl");
},
CrossFadeInFixedTime$2: function (stateHashName, fixedTransitionDuration, layer, fixedTimeOffset) {
throw new System.Exception("not impl");
},
CrossFadeInFixedTime$3: function (stateHashName, fixedTransitionDuration, layer, fixedTimeOffset, normalizedTransitionTime) {
throw new System.Exception("not impl");
},
CrossFadeInFixedTime$4: function (stateName, fixedTransitionDuration) {
throw new System.Exception("not impl");
},
CrossFadeInFixedTime$5: function (stateName, fixedTransitionDuration, layer) {
throw new System.Exception("not impl");
},
CrossFadeInFixedTime$6: function (stateName, fixedTransitionDuration, layer, fixedTimeOffset) {
throw new System.Exception("not impl");
},
CrossFadeInFixedTime$7: function (stateName, fixedTransitionDuration, layer, fixedTimeOffset, normalizedTransitionTime) {
throw new System.Exception("not impl");
},
GetAnimatorTransitionInfo: function (layerIndex) {
throw new System.Exception("not impl");
},
GetBehaviour: function (T) {
throw new System.Exception("not impl");
},
GetBehaviours: function (T) {
throw new System.Exception("not impl");
},
GetBehaviours$1: function (fullPathHash, layerIndex) {
throw new System.Exception("not impl");
},
GetBoneTransform: function (humanBoneId) {
throw new System.Exception("not impl");
},
GetBool: function (id) {
throw new System.Exception("not impl");
},
GetBool$1: function (name) {
throw new System.Exception("not impl");
},
GetCurrentAnimatorClipInfo: function (layerIndex, clips) {
throw new System.Exception("not impl");
},
GetCurrentAnimatorClipInfo$1: function (layerIndex) {
throw new System.Exception("not impl");
},
GetCurrentAnimatorClipInfoCount: function (layerIndex) {
throw new System.Exception("not impl");
},
GetCurrentAnimatorStateInfo: function (layerIndex) {
throw new System.Exception("not impl");
},
GetFloat: function (id) {
throw new System.Exception("not impl");
},
GetFloat$1: function (name) {
throw new System.Exception("not impl");
},
GetIKHintPosition: function (hint) {
throw new System.Exception("not impl");
},
GetIKHintPositionWeight: function (hint) {
throw new System.Exception("not impl");
},
GetIKPosition: function (goal) {
throw new System.Exception("not impl");
},
GetIKPositionWeight: function (goal) {
throw new System.Exception("not impl");
},
GetIKRotation: function (goal) {
throw new System.Exception("not impl");
},
GetIKRotationWeight: function (goal) {
throw new System.Exception("not impl");
},
GetInteger: function (id) {
throw new System.Exception("not impl");
},
GetInteger$1: function (name) {
throw new System.Exception("not impl");
},
GetLayerIndex: function (layerName) {
let result = null;
this.ref.layers.forEach(layer => {
if (layer.name === layerName) {
result = layer.name;
return;
}
});
return result;
},
GetLayerName: function (layerIndex) {
return this.ref.layers.length >= layerIndex ? this.ref.layers[layerIndex] : null;
},
GetLayerWeight: function (layerIndex) {
throw new System.Exception("not impl");
},
GetNextAnimatorClipInfo: function (layerIndex, clips) {
throw new System.Exception("not impl");
},
GetNextAnimatorClipInfo$1: function (layerIndex) {
throw new System.Exception("not impl");
},
GetNextAnimatorClipInfoCount: function (layerIndex) {
throw new System.Exception("not impl");
},
GetNextAnimatorStateInfo: function (layerIndex) {
throw new System.Exception("not impl");
},
GetParameter: function (index) {
throw new System.Exception("not impl");
},
HasState: function (layerIndex, stateID) {
throw new System.Exception("not impl");
},
InterruptMatchTarget: function () {
throw new System.Exception("not impl");
},
InterruptMatchTarget$1: function (completeMatch) {
throw new System.Exception("not impl");
},
IsInTransition: function (layerIndex) {
throw new System.Exception("not impl");
},
IsParameterControlledByCurve: function (id) {
throw new System.Exception("not impl");
},
IsParameterControlledByCurve$1: function (name) {
throw new System.Exception("not impl");
},
MatchTarget: function (matchPosition, matchRotation, targetBodyPart, weightMask, startNormalizedTime) {
throw new System.Exception("not impl");
},
MatchTarget$1: function (matchPosition, matchRotation, targetBodyPart, weightMask, startNormalizedTime, targetNormalizedTime) {
throw new System.Exception("not impl");
},
Play: function (stateNameHash) {
throw new System.Exception("not impl");
},
Play$1: function (stateNameHash, layer) {
throw new System.Exception("not impl");
},
Play$2: function (stateNameHash, layer, normalizedTime) {
throw new System.Exception("not impl");
},
Play$3: function (stateName) {
this.Play$4(stateName, 0);
},
Play$4: function (stateName, layer) {
const layerName = this.GetLayerName(layer);
if (layerName) {
this.ref.play('Base Layer.' + stateName);
} else {
this.ref.play(layerName + '.' + stateName);
}
},
Play$5: function (stateName, layer, normalizedTime) {
throw new System.Exception("not impl");
},
PlayInFixedTime: function (stateNameHash) {
throw new System.Exception("not impl");
},
PlayInFixedTime$1: function (stateNameHash, layer) {
throw new System.Exception("not impl");
},
PlayInFixedTime$2: function (stateNameHash, layer, fixedTime) {
throw new System.Exception("not impl");
},
PlayInFixedTime$3: function (stateName) {
throw new System.Exception("not impl");
},
PlayInFixedTime$4: function (stateName, layer) {
throw new System.Exception("not impl");
},
PlayInFixedTime$5: function (stateName, layer, fixedTime) {
throw new System.Exception("not impl");
},
Rebind: function () {
throw new System.Exception("not impl");
},
ResetTrigger: function (id) {
throw new System.Exception("not impl");
},
ResetTrigger$1: function (name) {
throw new System.Exception("not impl");
},
SetBoneLocalRotation: function (humanBoneId, rotation) {
throw new System.Exception("not impl");
},
SetBool: function (id, value) {
var name = MiniGameAdaptor.Animator.getHashName(id);
this.ref.setBool(name, value);
},
SetBool$1: function (name, value) {
this.ref.setBool(name, value);
},
SetFloat: function (id, value) {
var name = MiniGameAdaptor.Animator.getHashName(id);
this.ref.setFloat(name, value);
},
SetFloat$1: function (id, value, dampTime, deltaTime) {
var name = MiniGameAdaptor.Animator.getHashName(id);
this.ref.setFloat(name, value);
},
SetFloat$2: function (name, value) {
this.ref.setFloat(name, value);
},
SetFloat$3: function (name, value, dampTime, deltaTime) {
this.ref.setFloat(name, value);
},
SetIKHintPosition: function (hint, hintPosition) {
throw new System.Exception("not impl");
},
SetIKHintPositionWeight: function (hint, value) {
throw new System.Exception("not impl");
},
SetIKPosition: function (goal, goalPosition) {
throw new System.Exception("not impl");
},
SetIKPositionWeight: function (goal, value) {
throw new System.Exception("not impl");
},
SetIKRotation: function (goal, goalRotation) {
throw new System.Exception("not impl");
},
SetIKRotationWeight: function (goal, value) {
throw new System.Exception("not impl");
},
SetInteger: function (id, value) {
var name = MiniGameAdaptor.Animator.getHashName(id);
this.ref.setInteger(name, value);
},
SetInteger$1: function (name, value) {
this.ref.setInteger(name, value);
},
SetLayerWeight: function (layerIndex, weight) {
throw new System.Exception("not impl");
},
SetLookAtPosition: function (lookAtPosition) {
throw new System.Exception("not impl");
},
SetLookAtWeight: function (weight) {
throw new System.Exception("not impl");
},
SetLookAtWeight$1: function (weight, bodyWeight) {
throw new System.Exception("not impl");
},
SetLookAtWeight$2: function (weight, bodyWeight, headWeight) {
throw new System.Exception("not impl");
},
SetLookAtWeight$3: function (weight, bodyWeight, headWeight, eyesWeight) {
throw new System.Exception("not impl");
},
SetLookAtWeight$4: function (weight, bodyWeight, headWeight, eyesWeight, clampWeight) {
throw new System.Exception("not impl");
},
SetTarget: function (targetIndex, targetNormalizedTime) {
throw new System.Exception("not impl");
},
SetTrigger: function (id) {
throw new System.Exception("not impl");
},
SetTrigger$1: function (name) {
throw new System.Exception("not impl");
},
StartPlayback: function () {
throw new System.Exception("not impl");
},
StartRecording: function (frameCount) {
throw new System.Exception("not impl");
},
StopPlayback: function () {
throw new System.Exception("not impl");
},
StopRecording: function () {
throw new System.Exception("not impl");
},
Update: function (deltaTime) {
throw new System.Exception("not impl");
},
WriteDefaultValues: function () {
throw new System.Exception("not impl");
}
}
});
});
engine.decorators.serialize('MiniGameAdaptor.Animator')(MiniGameAdaptor.Animator);
Object.defineProperty(MiniGameAdaptor.Animator.prototype, '__properties', {
enumerable: false,
configurable: true,
writable: false,
value: { ...MiniGameAdaptor.Animator.prototype.__properties }
})
// MiniGameAdaptor.Animator.prototype.__properties.ref = { type: "Animator" };
|
cbidici/multimedia-service
|
src/main/java/com/cbidici/filepreviewer/service/impl/DefaultFileService.java
|
<filename>src/main/java/com/cbidici/filepreviewer/service/impl/DefaultFileService.java<gh_stars>0
package com.cbidici.filepreviewer.service.impl;
import com.cbidici.filepreviewer.model.domain.FileDomain;
import com.cbidici.filepreviewer.model.entity.FileEntity;
import com.cbidici.filepreviewer.repo.FileRepo;
import com.cbidici.filepreviewer.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.awt.image.BufferedImage;
@Service
public class DefaultFileService implements FileService {
private final FileRepo fileRepo;
@Autowired
public DefaultFileService(FileRepo fileRepo) {
this.fileRepo = fileRepo;
}
@Override
public FileDomain getFile(String path) {
FileEntity file = fileRepo.getFile(path);
return file.toDomain();
}
@Override
public String getThumbnailPath(String filePath) {
return fileRepo.getThumbnailPath(filePath);
}
@Override
public String getOptimizedPath(String filePath, Integer optimizedWidth) {
return fileRepo.getOptimizedPath(filePath, optimizedWidth);
}
@Override
public String getAbsolutePathOf(String path) {
return fileRepo.getAbsolutePathOf(path);
}
@Override
public void writeToFile(String targetFilePath, BufferedImage bufferedImage) {
fileRepo.writeToFile(targetFilePath, bufferedImage);
}
}
|
prateekfxtd/ns_Startup
|
venv/Lib/site-packages/PyQt4/examples/webkit/formextractor/formextractor_rc2.py
|
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: Wed Mar 20 13:51:02 2013
# by: The Resource Compiler for PyQt (Qt v4.8.4)
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore
qt_resource_data = "\
\x00\x00\x03\xfd\
\x3c\
\x68\x74\x6d\x6c\x3e\x3c\x62\x6f\x64\x79\x3e\x0a\x3c\x68\x31\x3e\
\x0a\x54\x68\x65\x20\x47\x72\x65\x65\x6e\x20\x50\x65\x6f\x70\x6c\
\x65\x20\x42\x6f\x6f\x6b\x20\x43\x6c\x75\x62\x0a\x3c\x2f\x68\x31\
\x3e\x0a\x0a\x3c\x70\x3e\x0a\x57\x65\x6c\x63\x6f\x6d\x65\x20\x74\
\x6f\x20\x54\x68\x65\x20\x47\x72\x65\x65\x6e\x20\x50\x65\x6f\x70\
\x6c\x65\x20\x42\x6f\x6f\x6b\x20\x43\x6c\x75\x62\x2e\x20\x50\x6c\
\x65\x61\x73\x65\x20\x72\x65\x67\x69\x73\x74\x65\x72\x20\x74\x6f\
\x20\x6f\x62\x74\x61\x69\x6e\x20\x61\x20\x6d\x65\x6d\x62\x65\x72\
\x73\x68\x69\x70\x20\x77\x69\x74\x68\x20\x75\x73\x2e\x0a\x3c\x2f\
\x70\x3e\x0a\x20\x20\x20\x20\x3c\x66\x6f\x72\x6d\x20\x6f\x6e\x73\
\x75\x62\x6d\x69\x74\x3d\x22\x66\x6f\x72\x6d\x45\x78\x74\x72\x61\
\x63\x74\x6f\x72\x2e\x73\x75\x62\x6d\x69\x74\x28\x29\x22\x3e\x0a\
\x20\x20\x20\x20\x3c\x74\x61\x62\x6c\x65\x3e\x0a\x20\x20\x20\x20\
\x3c\x74\x62\x6f\x64\x79\x3e\x3c\x74\x72\x3e\x0a\x20\x20\x20\x20\
\x20\x20\x20\x20\x3c\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\
\x20\x46\x69\x72\x73\x74\x20\x6e\x61\x6d\x65\x3a\x0a\x20\x20\x20\
\x20\x20\x20\x20\x20\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\
\x20\x20\x20\x3c\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\
\x20\x20\x20\x20\x3c\x69\x6e\x70\x75\x74\x20\x74\x79\x70\x65\x3d\
\x22\x74\x65\x78\x74\x22\x20\x69\x64\x3d\x22\x66\x69\x72\x73\x74\
\x6e\x61\x6d\x65\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\
\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x74\x72\x3e\x0a\x20\
\x20\x20\x20\x3c\x74\x72\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\
\x3c\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x4c\x61\x73\
\x74\x20\x6e\x61\x6d\x65\x3a\x0a\x20\x20\x20\x20\x20\x20\x20\x20\
\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\
\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x3c\
\x69\x6e\x70\x75\x74\x20\x74\x79\x70\x65\x3d\x22\x74\x65\x78\x74\
\x22\x20\x69\x64\x3d\x22\x6c\x61\x73\x74\x6e\x61\x6d\x65\x22\x3e\
\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x74\x64\x3e\x0a\x20\
\x20\x20\x20\x3c\x2f\x74\x72\x3e\x0a\x20\x20\x20\x20\x3c\x74\x72\
\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x74\x64\x3e\x0a\x20\
\x20\x20\x20\x20\x20\x20\x20\x47\x65\x6e\x64\x65\x72\x3a\x0a\x20\
\x20\x20\x20\x20\x20\x20\x20\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\
\x20\x20\x20\x20\x20\x3c\x74\x64\x3e\x0a\x20\x20\x20\x20\x20\x20\
\x20\x20\x3c\x69\x6e\x70\x75\x74\x20\x74\x79\x70\x65\x3d\x22\x72\
\x61\x64\x69\x6f\x22\x20\x6e\x61\x6d\x65\x3d\x22\x67\x65\x6e\x64\
\x65\x72\x22\x20\x69\x64\x3d\x22\x67\x65\x6e\x64\x65\x72\x4d\x61\
\x6c\x65\x22\x20\x76\x61\x6c\x75\x65\x3d\x22\x4d\x61\x6c\x65\x22\
\x3e\x20\x4d\x61\x6c\x65\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\
\x69\x6e\x70\x75\x74\x20\x74\x79\x70\x65\x3d\x22\x72\x61\x64\x69\
\x6f\x22\x20\x6e\x61\x6d\x65\x3d\x22\x67\x65\x6e\x64\x65\x72\x22\
\x20\x69\x64\x3d\x22\x67\x65\x6e\x64\x65\x72\x46\x65\x6d\x61\x6c\
\x65\x22\x20\x76\x61\x6c\x75\x65\x3d\x22\x46\x65\x6d\x61\x6c\x65\
\x22\x3e\x20\x46\x65\x6d\x61\x6c\x65\x0a\x20\x20\x20\x20\x20\x20\
\x20\x20\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x74\x72\
\x3e\x0a\x20\x20\x20\x20\x3c\x74\x72\x3e\x0a\x20\x20\x20\x20\x20\
\x20\x20\x20\x3c\x74\x64\x20\x63\x6f\x6c\x73\x70\x61\x6e\x3d\x22\
\x32\x22\x3e\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x3c\x69\x6e\x70\
\x75\x74\x20\x74\x79\x70\x65\x3d\x22\x63\x68\x65\x63\x6b\x62\x6f\
\x78\x22\x20\x69\x64\x3d\x22\x75\x70\x64\x61\x74\x65\x73\x22\x20\
\x76\x61\x6c\x75\x65\x3d\x22\x72\x65\x63\x65\x69\x76\x65\x22\x3e\
\x0a\x20\x20\x20\x20\x20\x20\x20\x20\x43\x68\x65\x63\x6b\x20\x68\
\x65\x72\x65\x20\x69\x66\x20\x79\x6f\x75\x20\x77\x6f\x75\x6c\x64\
\x20\x6c\x69\x6b\x65\x20\x74\x6f\x20\x72\x65\x63\x65\x69\x76\x65\
\x20\x72\x65\x67\x75\x6c\x61\x72\x20\x75\x70\x64\x61\x74\x65\x73\
\x20\x66\x72\x6f\x6d\x20\x75\x73\x3a\x0a\x20\x20\x20\x20\x20\x20\
\x20\x20\x3c\x2f\x74\x64\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x74\x72\
\x3e\x0a\x20\x20\x20\x20\x3c\x2f\x74\x62\x6f\x64\x79\x3e\x3c\x2f\
\x74\x61\x62\x6c\x65\x3e\x0a\x20\x20\x20\x20\x3c\x69\x6e\x70\x75\
\x74\x20\x74\x79\x70\x65\x3d\x22\x73\x75\x62\x6d\x69\x74\x22\x20\
\x76\x61\x6c\x75\x65\x3d\x22\x53\x75\x62\x6d\x69\x74\x22\x3e\x0a\
\x20\x20\x20\x20\x3c\x2f\x66\x6f\x72\x6d\x3e\x0a\x0a\x3c\x2f\x62\
\x6f\x64\x79\x3e\x3c\x2f\x68\x74\x6d\x6c\x3e\x0a\
"
qt_resource_name = "\
\x00\x09\
\x09\x04\x21\xfc\
\x00\x66\
\x00\x6f\x00\x72\x00\x6d\x00\x2e\x00\x68\x00\x74\x00\x6d\x00\x6c\
"
qt_resource_struct = "\
\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\
\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\
"
def qInitResources():
QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
def qCleanupResources():
QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)
qInitResources()
|
bbglab/openvariant
|
tests/test_annotation/test_builder.py
|
import math
import os
import re
import unittest
from types import MethodType
from openvariant.annotation.builder import AnnotationTypesBuilders, Builder
from openvariant.config.config_annotation import AnnotationTypes
from openvariant.plugins.context import Context
class TestBuilder(unittest.TestCase):
def test_builder_static(self):
static_dict = {'type': 'static', 'field': 'PLATFORM', 'value': 'WSG'}
res_expect = (AnnotationTypes.STATIC.name, 'WSG')
result = AnnotationTypesBuilders[AnnotationTypes.STATIC.name].value(static_dict)
self.assertEqual(result, res_expect)
def test_builder_no_exist_static(self):
with self.assertRaises(KeyError):
static_dict = {'type': 'static'}
AnnotationTypesBuilders[AnnotationTypes.STATIC.name].value(static_dict)
def test_builder_none_static(self):
static_dict = {'type': 'static', 'field': None, 'value': None}
res_expect = (AnnotationTypes.STATIC.name, None)
result = AnnotationTypesBuilders[AnnotationTypes.STATIC.name].value(static_dict)
self.assertEqual(result, res_expect)
def test_builder_internal(self):
internal_dict = {'type': 'internal', 'field': 'variant', 'fieldSource': ['Variant_Type', 'Data'],
'function': "lambda c: c.upper().replace('CHR', '').replace('23', 'X').replace('24', 'Y')"}
type_annot, field_sources, annot, value = AnnotationTypesBuilders[AnnotationTypes.INTERNAL.name].value(
internal_dict)
self.assertEqual(type_annot, AnnotationTypes.INTERNAL.name)
self.assertEqual(field_sources, ['Variant_Type', 'Data'])
self.assertIsInstance(annot, Builder)
self.assertTrue(math.isnan(value))
def test_builder_internal_with_value(self):
internal_dict = {'type': 'internal', 'field': 'sample', 'fieldSource': ['icgc_sample_id', 'icgc_specimen_id'],
'value': '{icgc_sample_id}_{icgc_specimen_id}'}
type_annot, field_sources, annot, value = AnnotationTypesBuilders[AnnotationTypes.INTERNAL.name].value(
internal_dict)
self.assertEqual(type_annot, AnnotationTypes.INTERNAL.name)
self.assertEqual(field_sources, ['icgc_sample_id', 'icgc_specimen_id'])
self.assertIsInstance(annot, Builder)
self.assertEqual(value, '{icgc_sample_id}_{icgc_specimen_id}')
def test_builder_invalid_internal(self):
internal_dict = {'type': 'internal', 'field': 'variant', 'fieldSource': None, 'function': None}
type_annot, field_sources, annot, value = AnnotationTypesBuilders[AnnotationTypes.INTERNAL.name].value(
internal_dict)
self.assertEqual(type_annot, AnnotationTypes.INTERNAL.name)
self.assertEqual(field_sources, None)
self.assertIsInstance(annot, Builder)
def test_builder_invalid_internal_with_value(self):
internal_dict = {'type': 'internal', 'field': 'sample', 'fieldSource': ['icgc_sample_id', 'icgc_specimen_id'],
'value': None}
type_annot, field_sources, annot, value = AnnotationTypesBuilders[AnnotationTypes.INTERNAL.name].value(
internal_dict)
self.assertEqual(type_annot, AnnotationTypes.INTERNAL.name)
self.assertEqual(field_sources, ['icgc_sample_id', 'icgc_specimen_id'])
self.assertIsInstance(annot, Builder)
self.assertEqual(value, None)
def test_builder_no_exist_internal(self):
internal_dict = {'type': 'internal'}
with self.assertRaises(KeyError):
AnnotationTypesBuilders[AnnotationTypes.INTERNAL.name].value(
internal_dict)
def test_builder_dirname(self):
dirname_dict = {'type': 'dirname', 'field': 'PROJECT', 'function': 'lambda x: "{}".format(x.lower()[:-4])',
'regex': '[a-zA-Z0-9]*.'}
type_annot, annot, regexp = AnnotationTypesBuilders[AnnotationTypes.DIRNAME.name].value(dirname_dict)
self.assertEqual(type_annot, AnnotationTypes.DIRNAME.name)
self.assertIsInstance(annot, Builder)
self.assertIsInstance(regexp, re.Pattern)
def test_builder_invalid_dirname(self):
dirname_dict = {'type': 'dirname', 'field': 'PROJECT', 'function': None,
'regex': None}
type_annot, annot, regexp = AnnotationTypesBuilders[AnnotationTypes.DIRNAME.name].value(dirname_dict)
self.assertEqual(type_annot, AnnotationTypes.DIRNAME.name)
self.assertIsInstance(annot, Builder)
self.assertIsInstance(regexp, re.Pattern)
def test_builder_invalid_regex_dirname(self):
dirname_dict = {'type': 'dirname', 'field': 'PROJECT', 'function': None,
'regex': ']['}
with self.assertRaises(re.error):
AnnotationTypesBuilders[AnnotationTypes.FILENAME.name].value(dirname_dict)
def test_builder_filename(self):
filename_dict = {'type': 'filename', 'field': 'DATASET', 'function': 'lambda x: "{}".format(x.lower()[:-4])',
'regex': '[a-zA-Z0-9]*.'}
type_annot, annot, regexp = AnnotationTypesBuilders[AnnotationTypes.FILENAME.name].value(filename_dict)
self.assertEqual(type_annot, AnnotationTypes.FILENAME.name)
self.assertIsInstance(annot, Builder)
self.assertIsInstance(regexp, re.Pattern)
def test_builder_invalid_filename(self):
filename_dict = {'type': 'filename', 'field': 'DATASET', 'function': None,
'regex': None}
type_annot, annot, regexp = AnnotationTypesBuilders[AnnotationTypes.FILENAME.name].value(filename_dict)
self.assertEqual(type_annot, AnnotationTypes.FILENAME.name)
self.assertIsInstance(annot, Builder)
self.assertIsInstance(regexp, re.Pattern)
def test_builder_invalid_regex_filename(self):
filename_dict = {'type': 'filename', 'field': 'DATASET', 'function': None,
'regex': ']['}
with self.assertRaises(re.error):
AnnotationTypesBuilders[AnnotationTypes.FILENAME.name].value(filename_dict)
def test_builder_mapping(self):
mapping_dict = {'type': 'mapping', 'field': 'CANCER_TYPE', 'fieldSource': ['donor_id', 'id', 'Donor_Id'],
'fieldMapping': 'icgc_donor_id', 'fileMapping': 'metadata.tsv', 'fieldValue': 'cancer_type'}
annotation_path = f'{os.getcwd()}/tests/data/builder/metadata.yaml'
expect_mapping = {'DO48316': 'ESCA', 'DO48318': 'ESCA', 'DO48312': 'ESCA', 'DO50633': 'EWS'}
type_annot, field_sources, mapping = AnnotationTypesBuilders[AnnotationTypes.MAPPING.name].value(mapping_dict,
annotation_path)
self.assertEqual(type_annot, AnnotationTypes.MAPPING.name)
self.assertEqual(field_sources, ['donor_id', 'id', 'Donor_Id'])
self.assertEqual(mapping, expect_mapping)
def test_builder_invalid_mapping(self):
mapping_dict = {'type': 'mapping', 'field': 'CANCER_TYPE', 'fieldSource': None,
'fieldMapping': None, 'fileMapping': None, 'fieldValue': None}
annotation_path = f'{os.getcwd()}/tests/data/builder/metadata.yaml'
with self.assertRaises(FileNotFoundError):
AnnotationTypesBuilders[AnnotationTypes.MAPPING.name].value(mapping_dict, annotation_path)
def test_builder_invalid_file_mapping(self):
mapping_dict = {'type': 'mapping', 'field': 'CANCER_TYPE', 'fieldSource': ['donor_id', 'id', 'Donor_Id'],
'fieldMapping': 'icgc_donor_id', 'fileMapping': 'no_exist.tsv', 'fieldValue': 'cancer_type'}
annotation_path = f'{os.getcwd()}/tests/data/builder/metadata.yaml'
with self.assertRaises(FileNotFoundError):
AnnotationTypesBuilders[AnnotationTypes.MAPPING.name].value(mapping_dict, annotation_path)
def test_builder_invalid_path_mapping(self):
mapping_dict = {'type': 'mapping', 'field': 'CANCER_TYPE', 'fieldSource': ['donor_id', 'id', 'Donor_Id'],
'fieldMapping': 'icgc_donor_id', 'fileMapping': 'metadata.tsv', 'fieldValue': 'cancer_type'}
annotation_path = None
with self.assertRaises(TypeError):
AnnotationTypesBuilders[AnnotationTypes.MAPPING.name].value(mapping_dict, annotation_path)
def test_builder_plugin(self):
plugin_dict = {'type': 'plugin', 'plugin': 'alteration_type', 'field': 'ALT_TYPE'}
type_annot, func, ctxt = AnnotationTypesBuilders[AnnotationTypes.PLUGIN.name].value(plugin_dict)
self.assertEqual(type_annot, AnnotationTypes.PLUGIN.name)
self.assertIsInstance(func, MethodType)
self.assertTrue(issubclass(ctxt, Context))
def test_builder_invalid_plugin(self):
plugin_dict = {'type': 'plugin', 'plugin': None, 'field': None}
with self.assertRaises(FileNotFoundError):
AnnotationTypesBuilders[AnnotationTypes.PLUGIN.name].value(plugin_dict)
|
shreyasvj25/turicreate
|
deps/src/cmake-3.9.3/Tests/PerConfig/pcShared.h
|
<gh_stars>1-10
#ifndef pcShared_h
#define pcShared_h
#ifdef _WIN32
#ifdef pcShared_EXPORTS
#define PC_EXPORT __declspec(dllexport)
#else
#define PC_EXPORT __declspec(dllimport)
#endif
#else
#define PC_EXPORT
#endif
PC_EXPORT const char* pcShared(void);
#endif
|
xiaobin3/mavenEEWeb
|
EEWebCase/src/main/java/com/xiaobin/listener/domian/TestCustomerActiveServlet.java
|
package com.xiaobin.listener.domian;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TestCustomerActiveServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
//将customer放到session中
Customer customer =new Customer();
customer.setId("200");
customer.setName("lucy");
session.setAttribute("customer", customer);
System.out.println("customer被放到session域中了");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
|
DavidKo3/mctorch
|
caffe2/core/nomnigraph/include/nomnigraph/Graph/Graph.h
|
<reponame>DavidKo3/mctorch<filename>caffe2/core/nomnigraph/include/nomnigraph/Graph/Graph.h
//===- nomnigraph/Graph/Graph.h - Basic graph implementation ----*- C++ -*-===//
//
// TODO Licensing.
//
//===----------------------------------------------------------------------===//
//
// This file defines a basic graph API for generic and flexible use with
// graph algorithms.
//
//===----------------------------------------------------------------------===//
#ifndef NOM_GRAPH_GRAPH_H
#define NOM_GRAPH_GRAPH_H
#include "nomnigraph/Support/Common.h"
#include <algorithm>
#include <iterator>
#include <list>
#include <unordered_set>
#include <vector>
#include <assert.h>
#include <stdio.h>
#define DEBUG_PRINT(...)
namespace nom {
template <typename T, typename... U>
class Graph;
template <typename T, typename... U>
class Node;
// Template types:
// T : Data stored within a node.
// U...: Data stored within an edge. When this type is not
// specified, an empty StorageType is used. If it is
// specified, only a single type should be given (as supported
// by the underlying StorageType class).
// \brief Edge within a Graph.
template <typename T, typename... U>
class Edge : public StorageType<U...> {
public:
using NodeRef = typename Graph<T, U...>::NodeRef;
Edge(NodeRef tail, NodeRef head, U... args)
: StorageType<U...>(std::forward<U...>(args)...),
tail_(tail),
head_(head) {
DEBUG_PRINT("Creating instance of Edge: %p\n", this);
}
const NodeRef& tail() const {
return tail_;
}
const NodeRef& head() const {
return head_;
}
void setTail(NodeRef n) {
tail_ = n;
}
void setHead(NodeRef n) {
head_ = n;
}
private:
NodeRef tail_;
NodeRef head_;
friend class Graph<T, U...>;
};
// \brief Node within a Graph.
template <typename T, typename... U>
class Node : public StorageType<T>, public Notifier<Node<T, U...>> {
public:
using NodeRef = typename Graph<T, U...>::NodeRef;
using EdgeRef = typename Graph<T, U...>::EdgeRef;
/// \brief Create a node with data.
explicit Node(T&& data) : StorageType<T>(std::move(data)) {
DEBUG_PRINT("Creating instance of Node: %p\n", this);
}
/// \brief Create an empty node.
explicit Node() : StorageType<T>() {}
/// \brief Adds an edge by reference to known in-edges.
/// \p e A reference to an edge that will be added as an in-edge.
void addInEdge(EdgeRef e) {
inEdges_.emplace_back(e);
}
/// \brief Adds an edge by reference to known out-edges.
/// \p e A reference to an edge that will be added as an out-edge.
void addOutEdge(EdgeRef e) {
outEdges_.emplace_back(e);
}
/// \brief Removes an edge by reference to known in-edges.
/// \p e A reference to an edge that will be removed from in-edges.
void removeInEdge(EdgeRef e) {
removeEdgeInternal(inEdges_, e);
}
/// \brief Removes an edge by reference to known out-edges.
/// \p e A reference to an edge that will be removed from out-edges.
void removeOutEdge(EdgeRef e) {
removeEdgeInternal(outEdges_, e);
}
const std::vector<EdgeRef>& getOutEdges() const {
return outEdges_;
}
const std::vector<EdgeRef>& getInEdges() const {
return inEdges_;
}
void setInEdges(std::vector<EdgeRef> edges) {
inEdges_ = edges;
}
void setOutEdges(std::vector<EdgeRef> edges) {
outEdges_ = edges;
}
private:
std::vector<EdgeRef> inEdges_;
std::vector<EdgeRef> outEdges_;
friend class Graph<T, U...>;
void removeEdgeInternal(std::vector<EdgeRef>& edges, EdgeRef e) {
auto iter = std::find(edges.begin(), edges.end(), e);
assert(
iter != edges.end() &&
"Attempted to remove edge that isn't connected to this node");
edges.erase(iter);
}
};
/// \brief Effectively a constant reference to a graph.
///
/// \note A Subgraph could actually point to an entire Graph.
///
/// Subgraphs can only contain references to nodes/edges in a Graph.
/// They are technically mutable, but this should be viewed as a construction
/// helper rather than a fact to be exploited. There are no deleters,
/// for example.
///
template <typename T, typename... U>
class Subgraph {
public:
Subgraph() {
DEBUG_PRINT("Creating instance of Subgraph: %p\n", this);
}
using NodeRef = typename Graph<T, U...>::NodeRef;
using EdgeRef = typename Graph<T, U...>::EdgeRef;
void addNode(NodeRef n) {
nodes_.insert(n);
}
bool hasNode(NodeRef n) const {
return nodes_.count(n) != 0;
}
void removeNode(NodeRef n) {
nodes_.erase(n);
}
void addEdge(EdgeRef e) {
edges_.insert(e);
}
bool hasEdge(EdgeRef e) const {
return edges_.count(e) != 0;
}
void removeEdge(EdgeRef e) {
edges_.erase(e);
}
const std::unordered_set<NodeRef>& getNodes() const {
return nodes_;
}
size_t getNodesCount() const {
return (size_t)nodes_.size();
}
const std::unordered_set<EdgeRef>& getEdges() const {
return edges_;
}
private:
std::unordered_set<NodeRef> nodes_;
std::unordered_set<EdgeRef> edges_;
void printEdges() {
for (const auto& edge : edges_) {
printf("Edge: %p (%p -> %p)\n", &edge, edge->tail(), edge->head());
}
}
void printNodes() const {
for (const auto& node : nodes_) {
printf("Node: %p\n", node);
}
}
};
/// \brief A simple graph implementation
///
/// Everything is owned by the graph to simplify storage concerns.
///
template <typename T, typename... U>
class Graph {
public:
using SubgraphType = Subgraph<T, U...>;
using NodeRef = Node<T, U...>*;
using EdgeRef = Edge<T, U...>*;
Graph() {
DEBUG_PRINT("Creating instance of Graph: %p\n", this);
}
Graph(const Graph&) = delete;
Graph(Graph&&) = default;
Graph& operator=(Graph&&) = default;
~Graph() {}
/// \brief Creates a node and retains ownership of it.
/// \p data An rvalue of the data being held in the node.
/// \return A reference to the node created.
NodeRef createNode(T&& data) {
return createNodeInternal(Node<T, U...>(std::move(data)));
}
NodeRef createNode() {
return createNodeInternal(Node<T, U...>());
}
void importNode(NodeRef node, Graph<T, U...>& otherGraph) {
for (auto it = nodes_.begin(); it != nodes_.end(); ++it) {
if (&(*it) == node) {
std::list<Node<T, U...>>& otherNodes = otherGraph.nodes_;
otherNodes.splice(otherNodes.end(), nodes_, it, ++it);
otherGraph.nodeRefs_.insert(node);
break;
}
}
}
void importEdge(EdgeRef edge, Graph<T, U...>& otherGraph) {
std::list<Edge<T, U...>>& otherEdges = otherGraph.edges_;
for (auto it = edges_.begin(); it != edges_.end(); ++it) {
if (&(*it) == edge) {
otherEdges.splice(otherEdges.end(), edges_, it, ++it);
break;
}
}
}
void swapNodes(NodeRef n1, NodeRef n2) {
// First rectify the edges
for (auto& inEdge : n1->getInEdges()) {
inEdge->setHead(n2);
}
for (auto& outEdge : n1->getOutEdges()) {
outEdge->setTail(n2);
}
for (auto& inEdge : n2->getInEdges()) {
inEdge->setHead(n1);
}
for (auto& outEdge : n2->getOutEdges()) {
outEdge->setTail(n1);
}
// Then simply copy the edge vectors around
auto n1InEdges = n1->getInEdges();
auto n1OutEdges = n1->getOutEdges();
auto n2InEdges = n2->getInEdges();
auto n2OutEdges = n2->getOutEdges();
n1->setOutEdges(n2OutEdges);
n1->setInEdges(n2InEdges);
n2->setOutEdges(n1OutEdges);
n2->setInEdges(n1InEdges);
}
/// \brief Replace a node in the graph with a generic
/// set of nodes.
/// \note The node replaced simply has its edges cut, but it not
/// deleted from the graph. Call Graph::deleteNode to delete it.
/// \p old A node to be replaced in the graph.
/// \p newTail The node that inherit the old node's in-edges
/// \p newHead (optional) The node that inherit the old node's out-edges
void replaceNode(
const NodeRef& old,
const NodeRef& newTail,
const NodeRef& newHead_ = nullptr) {
// If no newHead is specified, make the tail the head as well.
// We are effectively replacing the node with one node in this case.
const NodeRef newHead = newHead_ ? newHead_ : newTail;
const auto inEdges = old->getInEdges();
const auto outEdges = old->getOutEdges();
for (const auto& inEdge : inEdges) {
inEdge->setHead(newTail);
old->removeInEdge(inEdge);
newTail->addInEdge(inEdge);
}
for (const auto& outEdge : outEdges) {
outEdge->setTail(newHead);
old->removeOutEdge(outEdge);
newTail->addOutEdge(outEdge);
}
}
/// \brief Creates a directed edge and retains ownership of it.
/// \p tail The node that will have this edge as an out-edge.
/// \p head The node that will have this edge as an in-edge.
/// \return A reference to the edge created.
EdgeRef createEdge(NodeRef tail, NodeRef head, U... data) {
DEBUG_PRINT("Creating edge (%p -> %p)\n", tail, head);
this->edges_.emplace_back(
Edge<T, U...>(tail, head, std::forward<U...>(data)...));
EdgeRef e = &this->edges_.back();
head->addInEdge(e);
tail->addOutEdge(e);
return e;
}
/// \brief Get a reference to the edge between two nodes if it exists.
/// note: will fail assertion if the edge does not exist.
EdgeRef getEdge(NodeRef tail, NodeRef head) const {
for (auto& inEdge : head->getInEdges()) {
if (inEdge->tail() == tail) {
return inEdge;
}
}
assert(0 && "Edge doesn't exist.");
return nullptr;
}
/// \brief Deletes a node from the graph.
/// \param n A reference to the node.
/// \param deleteEdges (optional) Whether or not to delete the edges
/// related to the node.
void deleteNode(NodeRef n, bool deleteEdges = true) {
if (deleteEdges) {
auto inEdges = n->inEdges_;
for (auto& edge : inEdges) {
deleteEdge(edge);
}
auto outEdges = n->outEdges_;
for (auto& edge : outEdges) {
deleteEdge(edge);
}
}
for (auto i = nodes_.begin(); i != nodes_.end(); ++i) {
if (&*i == n) {
nodeRefs_.erase(n);
nodes_.erase(i);
break;
}
}
}
bool hasNode(NodeRef node) const {
return nodeRefs_.find(node) != nodeRefs_.end();
}
/// \brief Deletes a edge from the graph.
/// \p e A reference to the edge.
void deleteEdge(EdgeRef e, bool removeRef = true) {
if (removeRef) {
e->tail_->removeOutEdge(e);
e->head_->removeInEdge(e);
}
for (auto i = edges_.begin(); i != edges_.end(); ++i) {
if (&*i == e) {
edges_.erase(i);
break;
}
}
}
const std::vector<NodeRef> getMutableNodes() {
std::vector<NodeRef> result;
for (auto& n : nodes_) {
DEBUG_PRINT("Adding node to mutable output (%p)\n", &n);
result.emplace_back(&n);
}
return result;
}
const std::vector<EdgeRef> getMutableEdges() {
std::vector<EdgeRef> result;
for (auto& e : edges_) {
DEBUG_PRINT("Adding edge to mutable output (%p)\n", &e);
result.emplace_back(&e);
}
return result;
}
private:
std::list<Node<T, U...>> nodes_;
std::list<Edge<T, U...>> edges_;
std::unordered_set<NodeRef> nodeRefs_;
NodeRef createNodeInternal(Node<T, U...>&& node) {
nodes_.emplace_back(std::move(node));
NodeRef nodeRef = &nodes_.back();
DEBUG_PRINT("Creating node (%p)\n", nodeRef);
nodeRefs_.insert(nodeRef);
return nodeRef;
}
void printEdges() {
for (const auto& edge : edges_) {
printf("Edge: %p (%p -> %p)\n", &edge, edge.tail(), edge.head());
}
}
void printNodes() const {
for (const auto& node : nodes_) {
printf("Node: %p\n", &node);
}
}
};
} // namespace nom
#endif // NOM_GRAPH_GRAPH_H
|
hardik00079/Enterprise-Resource-Planing-for-IT-Company
|
company/src/controler/LoginServlet.java
|
package controler;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.Session;
import pojo.Registration;
import pojo.Role;
import logic.BLmanager;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String email = request.getParameter("email");
String pass = request.getParameter("password");
BLmanager bl = new BLmanager();
try{
Boolean b = bl.validate(email, pass);
Registration r = bl.getUserByUserId(email);
String fname= r.getFname();
HttpSession s = request.getSession();
s.setAttribute("email", email);
s.setAttribute("name",fname);
s.setAttribute("reg",r);
Role id = r.getRole();
int rid = id.getRolId();
int regid = r.getRegId();
s.setAttribute("regid",regid);
s.setAttribute("rid",rid);
if(b == true)
{
if( rid==1)
{
response.sendRedirect("FinanceIndex.jsp");
}
else if(rid==2)
{
response.sendRedirect("HRIndex.jsp");
}
else if(rid==3)
{
response.sendRedirect("PMIndex.jsp");
}
else if(rid==4)
{
response.sendRedirect("UserIndex.jsp");
}
else if(rid==5)
{
response.sendRedirect("DevloperIndex.jsp");
}
}
else
{
response.sendRedirect("Login.jsp?msg=1");
}
}
catch(Exception e)
{
response.sendRedirect("Login.jsp?msg=1");
}
}
}
|
ahmed-basyouni/Capstone-Project
|
ArkWallpaper/app/src/main/java/com/ark/android/arkwallpaper/ui/customviews/AnimatedSvgView.java
|
<reponame>ahmed-basyouni/Capstone-Project
package com.ark.android.arkwallpaper.ui.customviews;
/**
* Created by ahmed-basyouni on 4/17/17.
*/
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.PointF;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import com.ark.android.arkanalytics.GATrackerManager;
import com.ark.android.arkwallpaper.R;
import com.ark.android.arkwallpaper.utils.MathUtil;
import com.ark.android.arkwallpaper.utils.SvgPathParser;
import com.crashlytics.android.Crashlytics;
import java.text.ParseException;
public class AnimatedSvgView extends View {
private static final String TAG = "AnimatedSvgView";
private int mTraceTime = 2000;
private int mTraceTimePerGlyph = 1000;
private int mFillStart = 1200;
private int mFillTime = 1000;
private static final int MARKER_LENGTH_DIP = 16;
private int[] mTraceResidueColors;
private int[] mTraceColors;
private RatioSizingUtils.RatioSizingInfo mRatioSizingInfo = new RatioSizingUtils.RatioSizingInfo();
private int mViewportWidth;
private int mViewportHeight;
private PointF mViewport = new PointF(mViewportWidth, mViewportHeight);
private static final Interpolator INTERPOLATOR = new DecelerateInterpolator();
private Paint mFillPaint;
private int[] mFillAlphas;
private int[] mFillReds;
private int[] mFillGreens;
private int[] mFillBlues;
private GlyphData[] mGlyphData;
private String[] mGlyphStrings;
private float mMarkerLength;
private int mWidth;
private int mHeight;
private long mStartTime;
public static final int STATE_NOT_STARTED = 0;
public static final int STATE_TRACE_STARTED = 1;
public static final int STATE_FILL_STARTED = 2;
public static final int STATE_FINISHED = 3;
private int mState = STATE_NOT_STARTED;
private OnStateChangeListener mOnStateChangeListener;
public AnimatedSvgView(Context context) {
super(context);
init(context, null);
}
public AnimatedSvgView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public AnimatedSvgView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
@SuppressWarnings("NewApi")
private void init(Context context, AttributeSet attrs) {
mFillPaint = new Paint();
mFillPaint.setAntiAlias(true);
mFillPaint.setStyle(Paint.Style.FILL);
mMarkerLength = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
MARKER_LENGTH_DIP, getResources().getDisplayMetrics());
mTraceColors = new int[1];
mTraceColors[0] = Color.WHITE;
mTraceResidueColors = new int[1];
mTraceResidueColors[0] = Color.argb(50, 255, 255, 255);;
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AnimatedSvgView);
mViewportWidth = a.getInt(R.styleable.AnimatedSvgView_oakSvgImageSizeX, 433);
mRatioSizingInfo.aspectRatioWidth = a.getInt(R.styleable.AnimatedSvgView_oakSvgImageSizeX, 433);
mViewportHeight = a.getInt(R.styleable.AnimatedSvgView_oakSvgImageSizeY, 433);
mRatioSizingInfo.aspectRatioHeight = a.getInt(R.styleable.AnimatedSvgView_oakSvgImageSizeY, 433);
mTraceTime = a.getInt(R.styleable.AnimatedSvgView_oakSvgTraceTime, 2000);
mTraceTimePerGlyph = a.getInt(R.styleable.AnimatedSvgView_oakSvgTraceTimePerGlyph, 1000);
mFillStart = a.getInt(R.styleable.AnimatedSvgView_oakSvgFillStart, 1200);
mFillTime = a.getInt(R.styleable.AnimatedSvgView_oakSvgFillTime, 1000);
a.recycle();
mViewport = new PointF(mViewportWidth, mViewportHeight);
}
// See https://github.com/romainguy/road-trip/blob/master/application/src/main/java/org/curiouscreature/android/roadtrip/IntroView.java
// Note: using a software layer here is an optimization. This view works with
// hardware accelerated rendering but every time a path is modified (when the
// dash path effect is modified), the graphics pipeline will rasterize the path
// again in a new texture. Since we are dealing with dozens of paths, it is much
// more efficient to rasterize the entire view into a single re-usable texture
// instead. Ideally this should be toggled using a heuristic based on the number
// and or dimensions of paths to render.
// Note that PathDashPathEffects can lead to clipping issues with hardware rendering.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
setLayerType(LAYER_TYPE_SOFTWARE, null);
}
}
public void setViewportSize(int viewportWidth, int viewportHeight) {
mViewportWidth = viewportWidth;
mViewportHeight = viewportHeight;
mRatioSizingInfo.aspectRatioWidth = viewportWidth;
mRatioSizingInfo.aspectRatioHeight = viewportHeight;
mViewport = new PointF(mViewportWidth, mViewportHeight);
requestLayout();
}
public void setGlyphStrings(String[] glyphStrings) {
mGlyphStrings = glyphStrings;
}
public void setTraceResidueColors(int[] traceResidueColors) {
mTraceResidueColors = traceResidueColors;
}
public void setTraceColors(int[] traceColors) {
mTraceColors = traceColors;
}
public void setFillPaints(int[] fillAlphas, int[] fillReds, int[] fillGreens, int[] fillBlues) {
mFillAlphas = fillAlphas;
mFillReds = fillReds;
mFillGreens = fillGreens;
mFillBlues = fillBlues;
}
public void start() {
mStartTime = System.currentTimeMillis();
changeState(STATE_TRACE_STARTED);
ViewCompat.postInvalidateOnAnimation(this);
}
public void reset() {
mStartTime = 0;
changeState(STATE_NOT_STARTED);
ViewCompat.postInvalidateOnAnimation(this);
}
public void setToFinishedFrame() {
mStartTime = 1;
changeState(STATE_FINISHED);
ViewCompat.postInvalidateOnAnimation(this);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
rebuildGlyphData();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
RatioSizingUtils.RatioMeasureInfo rmi = RatioSizingUtils
.getMeasureInfo(widthMeasureSpec, heightMeasureSpec, mRatioSizingInfo, 0, 0);
super.onMeasure(
MeasureSpec.makeMeasureSpec(rmi.width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(rmi.height, MeasureSpec.EXACTLY));
}
private void rebuildGlyphData() {
SvgPathParser parser = new SvgPathParser() {
@Override
protected float transformX(float x) {
return x * mWidth / mViewport.x;
}
@Override
protected float transformY(float y) {
return y * mHeight / mViewport.y;
}
};
mGlyphData = new GlyphData[mGlyphStrings.length];
for (int i = 0; i < mGlyphStrings.length; i++) {
mGlyphData[i] = new GlyphData();
try {
mGlyphData[i].path = parser.parsePath(mGlyphStrings[i]);
} catch (ParseException e) {
GATrackerManager.getInstance().trackException(e);
Crashlytics.logException(e);
mGlyphData[i].path = new Path();
Log.e(TAG, "Couldn't parse path", e);
}
PathMeasure pm = new PathMeasure(mGlyphData[i].path, true);
while (true) {
mGlyphData[i].length = Math.max(mGlyphData[i].length, pm.getLength());
if (!pm.nextContour()) {
break;
}
}
mGlyphData[i].paint = new Paint();
mGlyphData[i].paint.setStyle(Paint.Style.STROKE);
mGlyphData[i].paint.setAntiAlias(true);
mGlyphData[i].paint.setColor(Color.WHITE);
mGlyphData[i].paint.setStrokeWidth(
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
getResources().getDisplayMetrics()));
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mState == STATE_NOT_STARTED || mGlyphData == null) {
return;
}
long t = System.currentTimeMillis() - mStartTime;
// Draw outlines (starts as traced)
for (int i = 0; i < mGlyphData.length; i++) {
float phase = MathUtil.constrain(0, 1,
(t - (mTraceTime - mTraceTimePerGlyph) * i * 1f / mGlyphData.length)
* 1f / mTraceTimePerGlyph);
float distance = INTERPOLATOR.getInterpolation(phase) * mGlyphData[i].length;
mGlyphData[i].paint.setColor(mTraceResidueColors[0]);
mGlyphData[i].paint.setPathEffect(new DashPathEffect(
new float[]{distance, mGlyphData[i].length}, 0));
canvas.drawPath(mGlyphData[i].path, mGlyphData[i].paint);
mGlyphData[i].paint.setColor(mTraceColors[0]);
mGlyphData[i].paint.setPathEffect(new DashPathEffect(
new float[]{0, distance, phase > 0 ? mMarkerLength : 0,
mGlyphData[i].length}, 0));
canvas.drawPath(mGlyphData[i].path, mGlyphData[i].paint);
}
if (t > mFillStart) {
if (mState < STATE_FILL_STARTED) {
changeState(STATE_FILL_STARTED);
}
// If after fill start, draw fill
float phase = MathUtil.constrain(0, 1, (t - mFillStart) * 1f / mFillTime);
for (int i = 0; i < mGlyphData.length; i++) {
GlyphData glyphData = mGlyphData[i];
mFillPaint.setARGB((int) (phase * 255), 37, 152, 219);
canvas.drawPath(glyphData.path, mFillPaint);
}
}
if (t < mFillStart + mFillTime) {
// draw next frame if animation isn't finished
ViewCompat.postInvalidateOnAnimation(this);
} else {
changeState(STATE_FINISHED);
}
}
private void changeState(int state) {
if (mState == state) {
return;
}
mState = state;
if (mOnStateChangeListener != null) {
mOnStateChangeListener.onStateChange(state);
}
}
public void setOnStateChangeListener(OnStateChangeListener onStateChangeListener) {
mOnStateChangeListener = onStateChangeListener;
}
public static interface OnStateChangeListener {
void onStateChange(int state);
}
private static class GlyphData {
Path path;
Paint paint;
float length;
}
public static class RatioSizingUtils {
public static class RatioSizingInfo {
public long aspectRatioWidth = 1;
public long aspectRatioHeight = 1;
}
public static class RatioMeasureInfo {
public int width;
public int height;
}
public static RatioSizingInfo getRatioSizingInfoFromAttrs(Context context, AttributeSet attrs)
throws IllegalArgumentException {
RatioSizingInfo rsi = new RatioSizingInfo();
return rsi;
}
public static RatioSizingInfo parseRatioSizingInfo(String ratioString) throws IllegalArgumentException {
RatioSizingInfo rsi = new RatioSizingInfo();
if (TextUtils.isEmpty(ratioString)) {
rsi.aspectRatioWidth = 1;
rsi.aspectRatioHeight = 1;
return rsi;
}
String[] parts = ratioString.split("[x:]");
if (parts.length == 2) {
rsi.aspectRatioWidth = Integer.parseInt(parts[0]);
rsi.aspectRatioHeight = Integer.parseInt(parts[1]);
} else {
throw new IllegalArgumentException("Invalid ratio: " + ratioString);
}
return rsi;
}
public static RatioMeasureInfo getMeasureInfo(int widthMeasureSpec, int heightMeasureSpec,
RatioSizingInfo ratioSizingInfo, int widthPadding, int heightPadding) {
RatioMeasureInfo rmi = new RatioMeasureInfo();
rmi.width = View.MeasureSpec.getSize(widthMeasureSpec) - widthPadding;
rmi.height = View.MeasureSpec.getSize(heightMeasureSpec) - heightPadding;
int widthMode = View.MeasureSpec.getMode(widthMeasureSpec);
int heightMode = View.MeasureSpec.getMode(heightMeasureSpec);
if (rmi.height <= 0 && rmi.width <= 0 && heightMode == View.MeasureSpec.UNSPECIFIED
&& widthMode == View.MeasureSpec.UNSPECIFIED) {
rmi.width = 0;
rmi.height = 0;
} else if (rmi.height <= 0 && heightMode == View.MeasureSpec.UNSPECIFIED) {
rmi.height = (int) (rmi.width * ratioSizingInfo.aspectRatioHeight / ratioSizingInfo.aspectRatioWidth);
} else if (rmi.width <= 0 && widthMode == View.MeasureSpec.UNSPECIFIED) {
rmi.width = (int) (rmi.height * ratioSizingInfo.aspectRatioWidth / ratioSizingInfo.aspectRatioHeight);
} else if (rmi.width * ratioSizingInfo.aspectRatioHeight > ratioSizingInfo.aspectRatioWidth * rmi.height) {
rmi.width = (int) (rmi.height * ratioSizingInfo.aspectRatioWidth / ratioSizingInfo.aspectRatioHeight);
} else {
rmi.height = (int) (rmi.width * ratioSizingInfo.aspectRatioHeight / ratioSizingInfo.aspectRatioWidth);
}
return rmi;
}
}
}
|
tylerwinkler/msg-game
|
src/Components/ComponentFactory.cpp
|
<filename>src/Components/ComponentFactory.cpp
#include "Components/ComponentFactory.hpp"
#include "Components/AnimationComponent.hpp"
#include "Components/CollisionComponent.hpp"
#include "Components/DialogComponent.hpp"
#include "Components/HealthComponent.hpp"
#include "Components/InteractionComponent.hpp"
#include "Components/LootComponent.hpp"
#include "Components/SpriteComponent.hpp"
ComponentFactory::ComponentPtr ComponentFactory::createAnimationComponent()
{
std::unique_ptr<Component> component(new AnimationComponent());
return std::move(component);
}
ComponentFactory::ComponentPtr ComponentFactory::createCollisionComponent()
{
std::unique_ptr<Component> component(new CollisionComponent());
return std::move(component);
}
ComponentFactory::ComponentPtr ComponentFactory::createCollisionComponent(int x, int y, int width, int height)
{
std::unique_ptr<Component> component(new CollisionComponent(x, y, width, height));
return std::move(component);
}
ComponentFactory::ComponentPtr ComponentFactory::createDialogComponent()
{
std::unique_ptr<Component> component(new DialogComponent());
return std::move(component);
}
ComponentFactory::ComponentPtr ComponentFactory::createHealthComponent()
{
std::unique_ptr<Component> component(new HealthComponent());
return std::move(component);
}
ComponentFactory::ComponentPtr ComponentFactory::createInteractionComponent()
{
std::unique_ptr<Component> component(new InteractionComponent());
return std::move(component);
}
ComponentFactory::ComponentPtr ComponentFactory::createLootComponent()
{
std::unique_ptr<Component> component(new LootComponent());
return std::move(component);
}
ComponentFactory::ComponentPtr ComponentFactory::createSpriteComponent()
{
std::unique_ptr<Component> component(new SpriteComponent());
return std::move(component);
}
ComponentFactory::ComponentPtr ComponentFactory::createSpriteComponent(const std::string& texture)
{
std::unique_ptr<Component> component(new SpriteComponent(texture));
return std::move(component);
}
|
RWTH-OS/MP-MPICH
|
src/routing/rdebug.c
|
/* $Id$
* (c) 2005 Lehrstuhl fuer Betriebssysteme, RWTH Aachen, Germany
* author: <NAME> email: <EMAIL>
*/
char RDEBUG_dbgprefix[256]; /* prefix to display in front of message */
char RDEBUG_serr[512]; /* string for formatting debug/error messages */
int RDEBUG_verbose = 0; /* switch for turning on verbose output */
|
UserStack/ustackweb
|
Godeps/_workspace/src/github.com/beego/social-auth/apps/dropbox.go
|
<reponame>UserStack/ustackweb<gh_stars>1-10
// Copyright 2014 beego authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
// Maintain by https://github.com/slene
package apps
import (
"github.com/beego/social-auth"
)
type Dropbox struct {
BaseProvider
}
func (p *Dropbox) GetType() social.SocialType {
return social.SocialDropbox
}
func (p *Dropbox) GetName() string {
return "Dropbox"
}
func (p *Dropbox) GetPath() string {
return "dropbox"
}
func (p *Dropbox) GetIndentify(tok *social.Token) (string, error) {
return tok.GetExtra("uid"), nil
}
var _ social.Provider = new(Dropbox)
func NewDropbox(clientId, secret string) *Dropbox {
p := new(Dropbox)
p.App = p
p.ClientId = clientId
p.ClientSecret = secret
p.Scope = ""
p.AuthURL = "https://www.dropbox.com/1/oauth2/authorize"
p.TokenURL = "https://api.dropbox.com/1/oauth2/token"
p.RedirectURL = social.DefaultAppUrl + "login/dropbox/access"
p.AccessType = ""
p.ApprovalPrompt = ""
return p
}
|
SMCPartners/shape
|
src/main/java/com/smcpartners/shape/frameworks/producers/DBProducer.java
|
package com.smcpartners.shape.frameworks.producers;
import com.smcpartners.shape.frameworks.producers.annotations.ShapeDatabase;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* Responsible:<br/>
* 1. Producer mapping for data dao<br/>
* <p>
* Created by johndestefano on 9/10/15.
* <p>
* Changes:<b/>
*/
@ApplicationScoped
public class DBProducer {
@Produces
@PersistenceContext(unitName = "shape")
@ShapeDatabase
private EntityManager shape;
//@Produces
//@PersistenceContext(unitName = "aerogears")
//@AeroGearsDatabase
//private EntityManager aerogears;
/*
@PersistenceUnit(unitName = "jump")
private EntityManagerFactory emf;
@Produces
@RequestScoped
@JumpDatabase protected EntityManager createEntityManager() {
return this.emf.createEntityManager();
}
protected void closeEntityManager(@Disposes @JumpDatabase EntityManager em) {
if (em.isOpen()) {
em.close();
}
}
@PersistenceUnit(unitName = "aerogears")
private EntityManagerFactory emf2;
@Produces
@RequestScoped
@AeroGearsDatabase protected EntityManager createEntityManager2() {
return this.emf2.createEntityManager();
}
protected void closeEntityManager2(@Disposes @AeroGearsDatabase EntityManager em) {
if (em.isOpen()) {
em.close();
}
}
*/
}
|
hjkim-haga/TF-OD-API
|
official/vision/keras_cv/layers/deeplab.py
|
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Layers for DeepLabV3."""
import tensorflow as tf
@tf.keras.utils.register_keras_serializable(package='keras_cv')
class SpatialPyramidPooling(tf.keras.layers.Layer):
"""Implements the Atrous Spatial Pyramid Pooling.
Reference:
[Rethinking Atrous Convolution for Semantic Image Segmentation](
https://arxiv.org/pdf/1706.05587.pdf)
"""
def __init__(
self,
output_channels,
dilation_rates,
pool_kernel_size=None,
use_sync_bn=False,
batchnorm_momentum=0.99,
batchnorm_epsilon=0.001,
activation='relu',
dropout=0.5,
kernel_initializer='glorot_uniform',
kernel_regularizer=None,
interpolation='bilinear',
**kwargs):
"""Initializes `SpatialPyramidPooling`.
Args:
output_channels: Number of channels produced by SpatialPyramidPooling.
dilation_rates: A list of integers for parallel dilated conv.
pool_kernel_size: A list of integers or None. If None, global average
pooling is applied, otherwise an average pooling of pool_kernel_size
is applied.
use_sync_bn: A bool, whether or not to use sync batch normalization.
batchnorm_momentum: A float for the momentum in BatchNorm. Defaults to
0.99.
batchnorm_epsilon: A float for the epsilon value in BatchNorm. Defaults to
0.001.
activation: A `str` for type of activation to be used. Defaults to 'relu'.
dropout: A float for the dropout rate before output. Defaults to 0.5.
kernel_initializer: Kernel initializer for conv layers. Defaults to
`glorot_uniform`.
kernel_regularizer: Kernel regularizer for conv layers. Defaults to None.
interpolation: The interpolation method for upsampling. Defaults to
`bilinear`.
**kwargs: Other keyword arguments for the layer.
"""
super(SpatialPyramidPooling, self).__init__(**kwargs)
self.output_channels = output_channels
self.dilation_rates = dilation_rates
self.use_sync_bn = use_sync_bn
self.batchnorm_momentum = batchnorm_momentum
self.batchnorm_epsilon = batchnorm_epsilon
self.activation = activation
self.dropout = dropout
self.kernel_initializer = tf.keras.initializers.get(kernel_initializer)
self.kernel_regularizer = tf.keras.regularizers.get(kernel_regularizer)
self.interpolation = interpolation
self.input_spec = tf.keras.layers.InputSpec(ndim=4)
self.pool_kernel_size = pool_kernel_size
def build(self, input_shape):
height = input_shape[1]
width = input_shape[2]
channels = input_shape[3]
self.aspp_layers = []
if self.use_sync_bn:
bn_op = tf.keras.layers.experimental.SyncBatchNormalization
else:
bn_op = tf.keras.layers.BatchNormalization
if tf.keras.backend.image_data_format() == 'channels_last':
bn_axis = -1
else:
bn_axis = 1
conv_sequential = tf.keras.Sequential([
tf.keras.layers.Conv2D(
filters=self.output_channels, kernel_size=(1, 1),
kernel_initializer=self.kernel_initializer,
kernel_regularizer=self.kernel_regularizer,
use_bias=False),
bn_op(
axis=bn_axis,
momentum=self.batchnorm_momentum,
epsilon=self.batchnorm_epsilon),
tf.keras.layers.Activation(self.activation)
])
self.aspp_layers.append(conv_sequential)
for dilation_rate in self.dilation_rates:
conv_sequential = tf.keras.Sequential([
tf.keras.layers.Conv2D(
filters=self.output_channels, kernel_size=(3, 3),
padding='same', kernel_regularizer=self.kernel_regularizer,
kernel_initializer=self.kernel_initializer,
dilation_rate=dilation_rate, use_bias=False),
bn_op(axis=bn_axis, momentum=self.batchnorm_momentum,
epsilon=self.batchnorm_epsilon),
tf.keras.layers.Activation(self.activation)])
self.aspp_layers.append(conv_sequential)
if self.pool_kernel_size is None:
pool_sequential = tf.keras.Sequential([
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Reshape((1, 1, channels))])
else:
pool_sequential = tf.keras.Sequential([
tf.keras.layers.AveragePooling2D(self.pool_kernel_size)])
pool_sequential.add(
tf.keras.Sequential([
tf.keras.layers.Conv2D(
filters=self.output_channels,
kernel_size=(1, 1),
kernel_initializer=self.kernel_initializer,
kernel_regularizer=self.kernel_regularizer,
use_bias=False),
bn_op(
axis=bn_axis,
momentum=self.batchnorm_momentum,
epsilon=self.batchnorm_epsilon),
tf.keras.layers.Activation(self.activation),
tf.keras.layers.experimental.preprocessing.Resizing(
height,
width,
interpolation=self.interpolation,
dtype=tf.float32)
]))
self.aspp_layers.append(pool_sequential)
self.projection = tf.keras.Sequential([
tf.keras.layers.Conv2D(
filters=self.output_channels, kernel_size=(1, 1),
kernel_initializer=self.kernel_initializer,
kernel_regularizer=self.kernel_regularizer,
use_bias=False),
bn_op(
axis=bn_axis,
momentum=self.batchnorm_momentum,
epsilon=self.batchnorm_epsilon),
tf.keras.layers.Activation(self.activation),
tf.keras.layers.Dropout(rate=self.dropout)])
def call(self, inputs, training=None):
if training is None:
training = tf.keras.backend.learning_phase()
result = []
for layer in self.aspp_layers:
result.append(tf.cast(layer(inputs, training=training), inputs.dtype))
result = tf.concat(result, axis=-1)
result = self.projection(result, training=training)
return result
def get_config(self):
config = {
'output_channels': self.output_channels,
'dilation_rates': self.dilation_rates,
'pool_kernel_size': self.pool_kernel_size,
'use_sync_bn': self.use_sync_bn,
'batchnorm_momentum': self.batchnorm_momentum,
'batchnorm_epsilon': self.batchnorm_epsilon,
'activation': self.activation,
'dropout': self.dropout,
'kernel_initializer': tf.keras.initializers.serialize(
self.kernel_initializer),
'kernel_regularizer': tf.keras.regularizers.serialize(
self.kernel_regularizer),
'interpolation': self.interpolation,
}
base_config = super(SpatialPyramidPooling, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
|
unlimitedggames/gdxjam-ugg
|
core/src/com/ugg/gdxjam/model/enums/VelocityDataType.java
|
package com.ugg.gdxjam.model.enums;
import com.ugg.gdxjam.model.data.BulletData;
import com.ugg.gdxjam.model.data.VelocityData;
public enum VelocityDataType {
BulletNormal (new VelocityData(1f, 1f, 50f, VelocityType.Linear)),
BulletImpulse (new VelocityData(1f, 1f, 0.5f, VelocityType.Impulse)),
SlowBullet (new VelocityData(1f, 1f, 5f, VelocityType.Linear)),
SlowBulletImpulse (new VelocityData(1f, 1f, 0.37f, VelocityType.Impulse));
private final VelocityData data;
private VelocityDataType(
VelocityData data)
{
this.data = data;
}
public VelocityData get()
{
return data;
}
}
|
Xaxetrov/OSCAR
|
oscar/meta_action/harvest.py
|
<gh_stars>1-10
from oscar.constants import *
from oscar.util.selection import *
def harvest_mineral(obs, queued=True):
any_mineral = find_position(obs, ALL_MINERAL_FIELD,
player_relative=PLAYER_NEUTRAL,
select_method='random',
exception=NoUnitError)
return [actions.FunctionCall(HARVEST_GATHER_SCREEN, [QUEUED if queued else NOT_QUEUED, any_mineral])]
|
henrytao-me/react-native-mdcore-showcase
|
src/navigators/screen.js
|
import React from 'react'
import { PropTypes, PureComponent, Utils } from 'react-native-mdcore'
import {
addNavigationHelpers,
NavigationActions,
StackNavigator
} from 'react-navigation'
import {
BottomNavigation,
Buttons,
Cards,
Splash,
TextFields
} from '@containers'
import { Injector } from '@middlewares'
import Drawer from './drawer'
const ROUTERS = {
bottomNavigation: {
screen: BottomNavigation
},
buttons: {
screen: Buttons
},
cards: {
screen: Cards
},
home: {
screen: Drawer
},
splash: {
screen: Splash
},
textFields: {
screen: TextFields
}
}
const CARD_STYLE = {
backgroundColor: 'transparent'
}
const Stack = StackNavigator(ROUTERS, {
// initialRouteName: 'splash',
initialRouteName: 'textFields',
cardStyle: CARD_STYLE,
headerMode: 'none'
})
export default class ScreenComponent extends PureComponent {
static contextTypes = {
theme: PropTypes.object
}
state = {
navigation: Stack.router.getStateForAction({
type: NavigationActions.INIT
})
}
componentDidMount() {
Injector.inject({ screenNavigator: this.refs.navigator.props.navigation })
this._verifyNavigationState()
}
componentDidUpdate() {
Injector.inject({ screenNavigator: this.refs.navigator.props.navigation })
}
render() {
const { theme } = this.context
CARD_STYLE.backgroundColor = theme.palette.background
return (
<Stack
ref="navigator"
navigation={addNavigationHelpers({
dispatch: this._dispatch,
state: this.state.navigation
})}
/>
)
}
_dispatch = action => {
const { navigation } = this.state
const latestRoute = navigation.routes[navigation.index]
if (action.type === NavigationActions.NAVIGATE) {
if (action.routeName === latestRoute.routeName) {
if (!Utils.deepEqual(action.params, latestRoute.params)) {
navigation.index -= 1
navigation.routes.splice(-1)
} else {
return
}
}
}
const nextNavigation = Stack.router.getStateForAction(action, navigation)
this._verifyNavigationState(nextNavigation)
}
_verifyNavigationState = (navigation = this.state.navigation) => {
const { isAuthenticated } = this.props
let latestRouteName = navigation.routes[navigation.index].routeName
if (latestRouteName === 'splash') {
latestRouteName = 'home'
navigation = Stack.router.getStateForAction({
type: NavigationActions.NAVIGATE,
routeName: 'home'
})
}
if (
!isAuthenticated &&
ROUTERS[latestRouteName].requireAuthentication === true
) {
this.setState({
navigation: Stack.router.getStateForAction({
type: NavigationActions.NAVIGATE,
routeName: 'signin'
})
})
} else {
this.setState({ navigation })
}
}
}
|
lowks/vidscraper
|
vidscraper/utils/feedparser.py
|
import datetime
import re
from vidscraper.utils.mimetypes import is_accepted_filename, is_accepted_type
def struct_time_to_datetime(struct_time):
"""
Returns a python datetime for the passed-in ``struct_time``.
"""
return datetime.datetime(*struct_time[:6])
def _is_accepted_enclosure(enclosure):
return (is_accepted_type(enclosure.get('type', '')) or
is_accepted_filename(enclosure.get('url', '')))
def get_entry_enclosures(entry):
"""
Returns a list of either media_content or enclosures for the entry.
The enclosures (or media_content) are only returned if they are non-empty
and contain a non-empty first item.
"""
media_content = entry.get('media_content')
if media_content and media_content[0]:
return media_content
enclosures = entry.get('enclosures')
if enclosures and enclosures[0]:
return enclosures
return []
def get_accepted_enclosures(entry):
"""
Returns a list of either media_content or enclosure items with accepted
mime types for the entry.
"""
return filter(_is_accepted_enclosure, get_entry_enclosures(entry))
def get_default_enclosure(enclosures):
for enclosure in enclosures:
if enclosure.get('isdefault'):
return enclosure
return None
def get_item_thumbnail_url(item):
"""Returns the thumbnail for an enclosure or feedparser entry or raises a
:exc:`KeyError` if none is found."""
if 'media_thumbnail' in item:
return item['media_thumbnail'][0]['url']
blip_thumbnail_src = item.get('blip_thumbnail_src', None)
if blip_thumbnail_src:
return u'http://a.images.blip.tv/{0}'.format(blip_thumbnail_src)
if 'itunes_image' in item:
return item['itunes_image']['href']
if 'image' in item:
return item['image']['href']
raise KeyError
def get_entry_thumbnail_url(entry):
"""
Returns the URL for a thumbnail from a feedparser entry, or ``None`` if
no thumbnail is found. First tries to return the thumbnail for the default
enclosure, then for any enclosure, then for the entry in general. If these
all fail and the entry is from youtube, the content of the entry will be
searched for an image to use as the thumbnail.
"""
enclosures = get_accepted_enclosures(entry)
# Try the default enclosure's thumbnail.
default_enclosure = get_default_enclosure(enclosures)
if default_enclosure is not None:
try:
return get_item_thumbnail_url(default_enclosure)
except KeyError:
pass
# Try to get any enclosure thumbnail
for enclosure in enclosures:
if enclosure is not default_enclosure:
try:
return get_item_thumbnail_url(enclosure)
except KeyError:
pass
# Try to get the general thumbnail for the entry
try:
return get_item_thumbnail_url(entry)
except KeyError:
pass
# Check the content
if entry.get('link', '').find(u'youtube.com') != -1:
if 'content' in entry:
content = entry['content'][0]['value']
elif 'summary' in entry:
content = entry['summary']
else:
return None
match = re.search(r'<img alt="" src="([^"]+)" />',
content)
if match:
return match.group(1)
return None
|
gridgentoo/ServiceFabricAzure
|
src/prod/src/Management/RepairManager/ProcessRepairTaskContextsAsyncOperation.cpp
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace std;
using namespace ClientServerTransport;
using namespace Common;
using namespace Federation;
using namespace Naming;
using namespace Reliability;
using namespace ServiceModel;
using namespace Transport;
using namespace Query;
using namespace Store;
using namespace SystemServices;
using namespace Api;
using namespace Management;
using namespace Management::RepairManager;
StringLiteral const TraceComponent("ProcessRepairTaskContextsAsyncOperation");
ProcessRepairTaskContextsAsyncOperation::ProcessRepairTaskContextsAsyncOperation(
__in RepairManagerServiceReplica & owner,
vector<shared_ptr<RepairTaskContext>> && tasks,
Store::ReplicaActivityId const & activityId,
AsyncCallback const & callback,
AsyncOperationSPtr const & parent)
: AsyncOperation(callback, parent)
, ReplicaActivityTraceComponent(activityId)
, owner_(owner)
, tasks_(move(tasks))
, currentTaskIndex_(0)
, currentNestedActivityId_(this->ActivityId)
{
}
void ProcessRepairTaskContextsAsyncOperation::OnStart(AsyncOperationSPtr const & thisSPtr)
{
auto error = owner_.BeginOperation(this->ReplicaActivityId);
if (error.IsSuccess())
{
WriteInfo(TraceComponent,
"{0} Repair tasks in current batch: {1}",
this->ReplicaActivityId,
tasks_.size());
this->ScheduleProcessNextTask(thisSPtr);
}
else
{
this->TryComplete(thisSPtr, error);
}
}
void ProcessRepairTaskContextsAsyncOperation::ScheduleProcessNextTask(AsyncOperationSPtr const & thisSPtr)
{
timer_ = Timer::Create(TimerTagDefault, [this, thisSPtr](TimerSPtr const & timer)
{
timer->Cancel();
this->ProcessNextTask(thisSPtr);
},
true); // allow concurrency
timer_->Change(TimeSpan::Zero);
}
void ProcessRepairTaskContextsAsyncOperation::ProcessNextTask(AsyncOperationSPtr const & thisSPtr)
{
auto managerState = owner_.State;
if (managerState != RepairManagerState::Started)
{
WriteInfo(TraceComponent,
"{0} Halting processing because repair manager state is {1}",
this->ReplicaActivityId,
managerState);
owner_.EndOperation(this->ReplicaActivityId);
this->TryComplete(thisSPtr, ErrorCodeValue::NotPrimary);
}
else if (currentTaskIndex_ == tasks_.size())
{
WriteInfo(TraceComponent,
"{0} Finished processing all tasks in current batch",
this->ReplicaActivityId);
owner_.EndOperation(this->ReplicaActivityId);
this->TryComplete(thisSPtr, ErrorCode::Success());
}
else
{
RepairTaskContext & currentContext = *tasks_[currentTaskIndex_];
currentNestedActivityId_ = currentNestedActivityId_.GetNestedActivity();
++currentTaskIndex_;
WriteInfo(TraceComponent,
"{0} Processing task {1} of {2}",
this->ReplicaActivityId,
currentTaskIndex_,
tasks_.size());
auto operation = AsyncOperation::CreateAndStart<ProcessRepairTaskContextAsyncOperation>(
owner_,
currentContext,
Store::ReplicaActivityId(owner_.PartitionedReplicaId, currentNestedActivityId_),
[this] (AsyncOperationSPtr const & operation) { this->OnProcessNextTaskComplete(operation, false); },
thisSPtr);
this->OnProcessNextTaskComplete(operation, true);
}
}
void ProcessRepairTaskContextsAsyncOperation::OnProcessNextTaskComplete(
AsyncOperationSPtr const & operation,
bool expectedCompletedSynchronously)
{
if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; }
AsyncOperationSPtr const & thisSPtr = operation->Parent;
auto error = AsyncOperation::End<ProcessRepairTaskContextAsyncOperation>(operation)->Error;
WriteInfo(TraceComponent,
"{0} Finished processing task {1} of {2}, error = {3}",
this->ReplicaActivityId,
currentTaskIndex_,
tasks_.size(),
error);
this->ScheduleProcessNextTask(thisSPtr);
}
|
osak/mikutterd
|
core/plugin/mentions/mentions.rb
|
<reponame>osak/mikutterd<gh_stars>0
# -*- coding: utf-8 -*-
# mentions.rb
#
# Reply display/post support
Plugin.create :mentions do
tab :mentions, _("Replies") do
set_icon Skin.get("reply.png")
timeline :mentions end
on_mention do |service, messages|
timeline(:mentions) << messages end
on_favorite do |service, fav_by, message|
if UserConfig[:favorited_by_anyone_act_as_reply] and fav_by[:idname] != service.idname
timeline(:mentions) << message end end
end
|
shivi98g/EpilNet-EpilepsyPredictor
|
Mobile App/Code/sources/com/google/android/gms/analytics/C0547ab.java
|
<filename>Mobile App/Code/sources/com/google/android/gms/analytics/C0547ab.java
package com.google.android.gms.analytics;
import android.text.TextUtils;
/* renamed from: com.google.android.gms.analytics.ab */
public class C0547ab {
/* renamed from: Bu */
private String f188Bu;
/* renamed from: Bv */
private final long f189Bv;
/* renamed from: Bw */
private final long f190Bw;
/* renamed from: Bx */
private final String f191Bx;
/* renamed from: By */
private String f192By;
/* renamed from: Bz */
private String f193Bz = "https:";
public C0547ab(String str, long j, long j2, String str2) {
this.f188Bu = str;
this.f189Bv = j;
this.f190Bw = j2;
this.f191Bx = str2;
}
/* renamed from: aj */
public void mo10347aj(String str) {
this.f188Bu = str;
}
/* renamed from: ak */
public void mo10348ak(String str) {
if (str != null && !TextUtils.isEmpty(str.trim())) {
this.f192By = str;
if (str.toLowerCase().startsWith("http:")) {
this.f193Bz = "http:";
}
}
}
/* renamed from: fa */
public String mo10349fa() {
return this.f188Bu;
}
/* renamed from: fb */
public long mo10350fb() {
return this.f189Bv;
}
/* renamed from: fc */
public long mo10351fc() {
return this.f190Bw;
}
/* renamed from: fd */
public String mo10352fd() {
return this.f193Bz;
}
}
|
anoworl/dyngoose
|
dist/decorator/attribute-types/number.spec.js
|
<reponame>anoworl/dyngoose
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const setup_tests_spec_1 = require("../../setup-tests.spec");
describe('AttributeType/Number', () => {
let record;
beforeEach(() => {
record = new setup_tests_spec_1.TestableTable();
});
it('should store values as numbers', () => {
chai_1.expect(record.testNumber).eq(null);
record.testNumber = 10;
chai_1.expect(record.testNumber).eq(10);
chai_1.expect(record.get('testNumber')).eq(10);
chai_1.expect(record.getAttribute('testNumber')).eq(10);
chai_1.expect(record.getAttributeDynamoValue('testNumber')).deep.eq({ N: '10' });
});
it('supports BigInt values', () => {
const int = BigInt('9007199254740991');
chai_1.expect(record.testBigInt).eq(null);
record.testBigInt = int;
chai_1.expect(record.testBigInt).to.eq(Number(int), 'read from record');
chai_1.expect(record.get('testBigInt')).eq(Number(int), 'use .get');
chai_1.expect(record.getAttribute('testBigInt')).eq(Number(int), 'use .getAttribute');
chai_1.expect(record.getAttributeDynamoValue('testBigInt')).deep.eq({ N: int.toString() }, 'use .getAttributeDynamoValue');
});
it('rejects non-number values', () => {
chai_1.expect(record.testNumber).eq(null);
chai_1.expect(record.testString).eq(null);
// we do this primarily to ensure typing is enforced for queries
chai_1.expect(() => { record.testNumber = 'test'; }).to.throw();
});
});
//# sourceMappingURL=number.spec.js.map
|
swang927/CS585-Shaokang-Wang
|
game.m.cpp
|
<reponame>swang927/CS585-Shaokang-Wang
// game.m.cpp
// Author: <NAME>
#include <iostream>
#include <time.h>
#include "src/engine/memory/counting_allocator.h"
#include "src/engine/memory/default_allocator.h"
#include "src/engine/memory/iallocator.h"
#include "src/engine/memory/stack_guard.h"
#include "src/engine/containers/dynamic_array.h"
#include "src/engine/containers/map.h"
#include "src/engine/data/json_parser.h"
#include "src/engine/data/json_entity.h"
#include "src/engine/input/input.h"
#include "src/engine/rendering/renderable_sprite.h"
#include "src/engine/rendering/renderer.h"
#include "src/engine/scene/itickable.h"
#include "src/engine/scene/scene.h"
#include "src/engine/scene/rectangle_bounds.h"
#include "src/engine/scene/icollider.h"
#include "src/engine/scene/nxn_scene_graph.h"
#include "src/engine/events/event_bus.h"
#include "src/engine/events/event_dispatcher.h"
#include "src/engine/events/ievent.h"
#include "src/game/controllers/red_guard_controller.h"
#include "src/game/controllers/blue_guard_controller.h"
#include "src/game/controllers/player_controller.h"
#include "src/game/controllers/maze.h"
#include "src/game/controllers/state.h"
#include "src/game/controllers/state_machine.h"
#include "src/game/actors/wall.h"
#include "src/game/actors/guard.h"
#include "src/game/actors/player.h"
#include <SFML/Graphics.hpp>
#include <string>
#include <functional>
#include <stdio.h>
#define Num_Wall 400
#define Num_State 34
// set the frameCount and animation time
float frameCount = 0;
float holdCount = 0;
float elapseCount = 0;
clock_t animation_time, hold_time, game_time;
// enum the input types
enum Direction { Down, Left, Right, Up };
int source[2] = { 1, Down };
sgds::Scene* main_scene;
sgdr::Renderer render;
sgds::NxNSceneGraph static_grid;
sgda::Player player;
sgda::Guard red, blue;
sgda::Wall wall[Num_Wall];
mgc::State state[Num_State];
mgc::StateMachine state_machine;
mgc::RedGuardController seek;
mgc::BlueGuardController chase;
mgc::PlayerController play;
mgc::Maze maze;
sgdr::RenderableSprite tag, watch;
bool lose = false;
bool win = false;
bool stopwatch = false;
// switch between model 1 and 2
void switchModel(int model){
if (model == 2){
play.setModel(2);
seek.setModel(2);
chase.setModel(2);
player.d_sprite.setTexture(render.getTexture("dpTexture"));
red.d_sprite.setTexture(render.getTexture("drTexture"));
blue.d_sprite.setTexture(render.getTexture("dbTexture"));
}
if (model == 1){
play.setModel(1);
seek.setModel(1);
chase.setModel(1);
player.d_sprite.setTexture(render.getTexture("pTexture"));
red.d_sprite.setTexture(render.getTexture("rTexture"));
blue.d_sprite.setTexture(render.getTexture("bTexture"));
}
}
// load the texture
void loadTexture(){
//==== load texture =================================//
// load textures
if (!render.loadTexture("pTexture", "image/player.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("bTexture", "image/blue_guard.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("rTexture", "image/red_guard.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("dpTexture", "image/player_1.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("dbTexture", "image/blue_guard_1.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("drTexture", "image/red_guard_1.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("wTexture", "image/Brick_Wall.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("sTexture", "image/ninja_weapon.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("loseTexture", "image/youLoss.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("winTexture", "image/youWin.png"))
std::cout << "Error could not load player image" << std::endl;
if (!render.loadTexture("timeTexture", "image/number_sheets.png"))
std::cout << "Error could not load player image" << std::endl;
}
// inital all the data
void init(){
// 1. Scene and Render:
// create the main scene
main_scene = &(sgds::Scene::inst());
// create the render and set window 25*19
render.setupWindow("My First Game", 800, 608);
// add the player actor, AI acotrs and static sprites to render
render.addSprite(&(player.d_sprite));
render.addSprite(&(red.d_sprite));
render.addSprite(&(blue.d_sprite));
for (int i = 0; i < Num_Wall; i++){
render.addSprite(&(wall[i].d_sprite));
}
// scene add tickable and link render
main_scene->setRenderer(&render);
main_scene->addTickable(&sgdi::Input::inst());
// 2. Texture:
loadTexture();
// set texture
player.d_sprite.setTexture(render.getTexture("pTexture"));
red.d_sprite.setTexture(render.getTexture("rTexture"));
blue.d_sprite.setTexture(render.getTexture("bTexture"));
for (int i = 0; i < Num_Wall; i++){
wall[i].d_sprite.setTexture(render.getTexture("wTexture"));
}
watch.setTexture(render.getTexture("timeTexture"));
// 3. Grid
// init static grid
sgds::NxNSceneGraph grid(800, 608, 4);
static_grid = grid;
// 4. Controller
// init AI controller
mgc::RedGuardController AI1(render.window(), &static_grid, &state_machine);
seek = AI1;
mgc::BlueGuardController AI2(render.window(), &static_grid, &state_machine);
chase = AI2;
// init player controller
mgc::PlayerController Pl(render.window(), &static_grid, &state_machine);
play = Pl;
//init maze generator
mgc::Maze M(render.window(), &static_grid);
maze = M;
// 5. Actor
// link actor to controller=
// add to control
play.add_instance(&player);
seek.add_instance(&red);
chase.add_instance(&blue);
// add to generator
for (int i = 0; i < Num_Wall; i++){
maze.add_instance(&wall[i]);
}
for (int i = 0; i < Num_State; i++){
state_machine.add_instance(&state[i]);
}
// fill the grid
static_grid.addCollider(&player);
static_grid.addCollider(&red);
static_grid.addCollider(&blue);
for (int i = 0; i < Num_Wall; i++){
static_grid.addCollider(&wall[i]);
}
// 6. inital all
// inital state
maze.init();
state_machine.init();
play.init();
seek.init();
chase.init();
tag.setPosition(160, 144);
watch.setPosition(385, 310);
animation_time = clock();
}
// reset the data
void reset(){
player.setOn();
red.setOn();
blue.setOn();
// inital state
play.init();
seek.init();
chase.init();
lose = false;
win = false;
player.d_sprite.setTexture(render.getTexture("pTexture"));
red.d_sprite.setTexture(render.getTexture("rTexture"));
blue.d_sprite.setTexture(render.getTexture("bTexture"));
render.removeSprite(&tag);
render.removeSprite(&watch);
// rest game time
elapseCount = 0;
game_time = clock();
stopwatch = false;
}
// show the final result: win / lose
void ShowResult(){
if (lose)
tag.setTexture(render.getTexture("loseTexture"));
if (win)
tag.setTexture(render.getTexture("winTexture"));
if (!render.hasSprite(&tag))
render.addSprite(&tag);
// draw current scene
render.draw();
// hold for 0.5 second
while (holdCount<0.5){
hold_time = clock();
holdCount += ((float)(clock() - hold_time)) / CLOCKS_PER_SEC;
}
holdCount = 0;
}
// show the countdown clock
void timeTrigger(){
// get shift model with certain time
elapseCount += ((float)(clock() - game_time)) / CLOCKS_PER_SEC;
game_time = clock();
if (play.getModel() == 1){
if (30 - elapseCount <= 0){
elapseCount = 0;
switchModel(2);
}
if (30 - elapseCount < 10){
if (stopwatch){
watch.setTextureRect((29 - (int)elapseCount) * 35, 0, 35, 50);
}
else{
if (!render.hasSprite(&watch))
render.addSprite(&watch);
stopwatch = true;
}
}
}
if (play.getModel() == 2){
if (10 - elapseCount <= 0){
elapseCount = 0;
switchModel(1);
}
if (10 - elapseCount < 10){
if (stopwatch){
watch.setTextureRect((9 - (int)elapseCount) * 35, 0, 35, 50);
}
else{
if (!render.hasSprite(&watch))
render.addSprite(&watch);
stopwatch = true;
}
}
}
}
// get the keyboard input
void Keyboard(){
// use key board up to control player move up
if (sgdi::Input::inst().isDown(sgdi::InputType::UP_KEY)){
source[1] = Up;
play.move(0, 0, -0.5);
}
// use key board down to control player move down
if (sgdi::Input::inst().isDown(sgdi::InputType::DOWN_KEY)){
source[1] = Down;
play.move(0, 0, 0.5);
}
// use key board left to control player move left
if (sgdi::Input::inst().isDown(sgdi::InputType::LEFT_KEY)){
source[1] = Left;
play.move(0, -0.5, 0);
}
// use key board right to control player move right
if (sgdi::Input::inst().isDown(sgdi::InputType::RIGHT_KEY)){
source[1] = Right;
play.move(0, 0.5, 0);
}
// use key board return key close game
if (sgdi::Input::inst().isDown(sgdi::InputType::RETURN_KEY)){
render.closewindow();
}
// use key board space key close game
if (sgdi::Input::inst().isDown(sgdi::InputType::SPACE_KEY)){
switchModel(2);
}
}
// update the data
void Update(){
timeTrigger();
// do AI move
seek.update();
chase.update();
sgdi::Input::inst().preTick();
// check the result in model 1
if (player.isOff()){
lose = true;
ShowResult();
reset();
}
// check the result in model 2
if (red.isOff() && blue.isOff()){
win = true;
ShowResult();
reset();
}
}
// display the game
void Display(){
// do animation by swith the image every 0.1s
frameCount += ((float)(clock() - animation_time)) / CLOCKS_PER_SEC;
animation_time = clock();
if (frameCount > 0.1){
frameCount = 0;
source[0]++;
if ((unsigned int)source[0] * 32 >= render.getTexture("pTexture").getSize().x)
source[0] = 0;
}
// choose the right image form the texture
player.d_sprite.setTextureRect(source[0] * 32, source[1] * 32, 32, 32);
red.d_sprite.setTextureRect(source[0] * 32, red.direction() * 32, 32, 32);
blue.d_sprite.setTextureRect(source[0] * 32, blue.direction() * 32, 32, 32);
// draw current scene
render.draw();
}
// main function
int main()
{
std::cout << "Hello CS585, I am ready to fight\n";
init();
// give the start time
game_time = clock();
std::cout << "time : " << game_time << std::endl;
// start the game loop
while (render.isActive())
{
Update();
Display();
Keyboard();
}
return 0;
};
|
consulo/consulo-play
|
src/main/java/consulo/play1/template/base/editor/highlight/PlayBaseTemplateSyntaxHighlighter.java
|
/*
* Copyright 2013-2016 consulo.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package consulo.play1.template.base.editor.highlight;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;
import consulo.play1.editor.highlight.PlayJavaColors;
import consulo.play1.template.base.parser.PlayBaseTemplateTokenSets;
import consulo.play1.template.base.parser.PlayBaseTemplateTokens;
import consulo.play1.template.base.parser.lexer.PlayBaseTemplateLexer;
import com.intellij.lexer.Lexer;
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighterBase;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
/**
* @author VISTALL
* @since 19:45/18.03.13
*/
public class PlayBaseTemplateSyntaxHighlighter extends SyntaxHighlighterBase implements PlayBaseTemplateTokens
{
private static final Map<IElementType,TextAttributesKey> map = new HashMap<IElementType, TextAttributesKey>();
static
{
safeMap(map, TokenSet.create(COMMENT, COMMENT_START, COMMENT_END), DefaultLanguageHighlighterColors.LINE_COMMENT);
safeMap(map, STRING, DefaultLanguageHighlighterColors.STRING);
safeMap(map, COMMA, DefaultLanguageHighlighterColors.COMMA);
safeMap(map, PlayBaseTemplateTokenSets.TEMPLATE_ELEMENTS, PlayJavaColors.TEMPLATE_ELEMENTS);
safeMap(map, TAG_NAME, PlayJavaColors.PLAY_TAG_NAME);
}
@Nonnull
@Override
public Lexer getHighlightingLexer()
{
return new PlayBaseTemplateLexer();
}
@Nonnull
@Override
public TextAttributesKey[] getTokenHighlights(IElementType tokenType)
{
return pack(map.get(tokenType));
}
}
|
Grace-Shopper-PPE/Grace-Shopper
|
server/db/models/user.spec.js
|
/* global describe beforeEach it */
const {expect} = require('chai')
const db = require('../db')
const {User, Order} = require('./index')
const seed = require('../../../script/seed')
describe('User model', () => {
beforeEach(() => {
return db.sync({force: true})
})
describe('Validations', () => {
it('firstName, lastName and email are not null', async () => {
const user1 = User.build({lastName: 'Dog', email: '<EMAIL>'})
const user2 = User.build({firstName: 'Cody', email: '<EMAIL>'})
const user3 = User.build({firstName: 'Cody', lastName: 'Dog'})
try {
await user1.validate()
await user2.validate()
await user3.validate()
throw Error('validation was successful but field is missing')
} catch (err) {
expect(err.message).to.contain('notNull Violation')
}
})
})
it('`email` contains a valid email address', async () => {
const user = User.build({firstName: 'Cody', lastName: 'Dog', email: 'pug'})
try {
await user.validate()
throw Error(
'validation was successful but the email address is not valid'
)
} catch (err) {
expect(err.message).to.contain('Validation isEmail on email failed')
}
})
describe('instanceMethods', () => {
describe('correctPassword', () => {
let cody
beforeEach(async () => {
cody = await User.create({
firstName: 'Cody',
lastName: 'Dog',
email: '<EMAIL>',
password: '<PASSWORD>'
})
})
it('returns true if the password is correct', () => {
expect(cody.correctPassword('<PASSWORD>')).to.be.equal(true)
})
it('returns false if the password is incorrect', () => {
expect(cody.correctPassword('<PASSWORD>')).to.be.equal(false)
})
}) // end describe('correctPassword')
}) // end describe('instanceMethods')
describe('Model associations', () => {
it('a user may have many orders', async () => {
const sallysCampus = await student1.getCampus()
expect(sallysCampus.name).to.equal(campus.name)
})
it('a campus may have many enrolled students', async () => {
const result = await campus.hasStudents([student1, student2])
expect(result).to.be.equal(true)
})
})
}) // end describe('User model')
|
Yuzhen11/tangram
|
core/scheduler/checkpoint_loader.cpp
|
#include "core/scheduler/checkpoint_loader.hpp"
namespace xyz {
void CheckpointLoader::LoadCheckpoint(int cid, std::string url,
std::function<void()> f) {
LOG(INFO) << "[CheckpointLoader] loading checkpoint for collection: " << cid;
auto& collection_view = elem_->collection_map->Get(cid);
loadcheckpoint_reply_count_map_[cid] = 0;
expected_loadcheckpoint_reply_count_map_[cid] = collection_view.mapper.GetNumParts();
callbacks_.insert({cid, f});
for (int i = 0; i < collection_view.mapper.GetNumParts(); ++ i) {
int node_id = collection_view.mapper.Get(i);
SendLoadCommand(cid, i, node_id, url);
}
}
void CheckpointLoader::LoadCheckpointPartial(int cid, std::string url,
std::vector<int> parts,
std::function<void()> f) {
LOG(INFO) << "[CheckpointLoader] loading checkpoint (partial) for collection: " << cid << ", parts size: " << parts.size();
loadcheckpoint_reply_count_map_[cid] = 0;
callbacks_.insert({cid, f});
expected_loadcheckpoint_reply_count_map_[cid] = parts.size();
auto& collection_view = elem_->collection_map->Get(cid);
auto& part_to_node_map = collection_view.mapper.Get();
for (auto part_id: parts) {
CHECK_LT(part_id, part_to_node_map.size());
int node_id = part_to_node_map[part_id];
SendLoadCommand(cid, part_id, node_id, url);
}
}
void CheckpointLoader::SendLoadCommand(int cid, int part_id, int node_id, std::string url) {
SArrayBinStream bin;
std::string dest_url = GetCheckpointUrl(url, cid, part_id);
bin << cid << part_id << dest_url; // collection_id, partition_id, url
SendTo(elem_, node_id, ScheduleFlag::kLoadCheckpoint, bin);
}
void CheckpointLoader::FinishLoadCheckpoint(SArrayBinStream bin) {
int qid, collection_id;
bin >> qid >> collection_id;
loadcheckpoint_reply_count_map_[collection_id] += 1;
if (loadcheckpoint_reply_count_map_[collection_id] == expected_loadcheckpoint_reply_count_map_[collection_id]){
CHECK(callbacks_.find(collection_id) != callbacks_.end());
callbacks_[collection_id](); // invoke the callback
callbacks_.erase(collection_id);
}
}
} // namespace xyz
|
Discord-Wiz/dyno-bot-master
|
dyno-bot-master/mobile-api-master/src/core/Client.js
|
<reponame>Discord-Wiz/dyno-bot-master<gh_stars>1-10
const Eris = require('eris');
const Server = require('./Server');
const config = require('./config');
const logger = require('./logger');
const { Dyno } = require('./models');
let client;
class Client {
constructor() {
process.on('uncaughtException', this.handleException.bind(this));
process.on('unhandledRejection', this.handleRejection.bind(this));
this.server = new Server(config);
this.reconnectIntervals = {};
this.setup();
}
/**
* Uncaught exception handler
* @param {Object} err Error object
*/
handleException(err) {
logger.error(err);
setTimeout(() => process.exit(), 3000);
}
handleRejection(reason, p) {
console.error('Unhandled rejection at: Promise ', p, 'reason: ', reason); // eslint-disable-line
}
async setup() {
const options = {
restMode: true,
};
this.client = client = new Eris(`Bot ${config.client.token}`, options);
await Dyno.findOne().lean()
.then(doc => { config.global = doc; })
.catch(err => logger.error(err));
if (config.prefix) {
this.prefix = (typeof config.prefix === 'string') ? config.prefix : '?';
}
// event listeners
client.on('error', err => logger.error(err));
client.user = await client.getRESTUser(config.client.userid).catch(err => logger.error(err));
this.server.start(this);
}
}
module.exports = Client;
|
cugone/Abrams2018
|
Engine/Code/Engine/System/System.hpp
|
<reponame>cugone/Abrams2018<filename>Engine/Code/Engine/System/System.hpp<gh_stars>0
#pragma once
#include "Engine/System/Cpu.hpp"
#include "Engine/System/Ram.hpp"
#include "Engine/System/OS.hpp"
#include <ostream>
namespace System {
struct SystemDesc {
System::Ram::RamDesc ram{};
System::Cpu::CpuDesc cpu{};
System::OS::OsDesc os{};
friend std::ostream& operator<<(std::ostream& out, const SystemDesc& desc) noexcept;
};
SystemDesc GetSystemDesc() noexcept;
}
|
SonicYeager/CppPractice
|
ProjectReversi/Reversi/Reversi.cpp
|
#include "Reversi.h"
#include <iostream>
#include "ReversiKI.h"
#include "ReversiKIPro.h"
namespace Reversi
{
char row[] = { 'A', 'B', 'C' ,'D' ,'E' ,'F' ,'G' ,'H' };
char column[] = { '1', '2', '3' ,'4' ,'5' ,'6' ,'7' ,'8' };
void ShowBoard(const Board board) {
char representative[] = { '.', 'O', 'X' };
std::cout << " | " ;
for (int index = 0; index < 8; index++)
{
std::cout << column[index] << " | ";
}
std::cout << std::endl;
for (int index_x = 0; index_x < 8; index_x++)
{
std::cout << row[index_x] << " | ";
for (int index_y = 0; index_y < 8; index_y++)
{
std::cout << representative[board[index_x][index_y]] << " | ";
}
std::cout << std::endl;
}
}
Player DetermineWinner(const Board board) {
//count each players owned space, the player with the most is returned
int counterWhite = 0;
int counterBlack = 0;
for (int index_y = 0; index_y < 8; index_y++)
{
for (int index_x = 0; index_x < 8; index_x++)
{
if (board[index_y][index_x] == 0)
{
continue;
}
else if (board[index_y][index_x] == 1)
{
counterWhite += 1;
}
else
{
counterBlack += 1;
}
}
}
if (counterBlack > counterWhite)
{
return Reversi::P_BLACK;
}
else if (counterBlack == counterWhite)
{
return Reversi::P_NONE;
}
else
return Reversi::P_WHITE;;
}
bool IsMoveValid(const Player player, const Board board, int pos_x, int pos_y) {
if (board[pos_y][pos_x] != P_NONE)
{
return false;
}
else
{
//set enemy value
const Player enemyPlayer = Player(1 - player + 2);
//check validity of move
int coordinateModifier_x[] = { 0 , 1 , 1 ,1 ,0,-1,-1 ,-1 };
int coordinateModifier_y[] = { -1, -1 ,0 ,1 ,1 ,1 ,0 ,-1 };
for (int toCheckFields = 0; toCheckFields < 8; toCheckFields++)
{
if ((pos_x + coordinateModifier_x[toCheckFields] < 0 || pos_x + coordinateModifier_x[toCheckFields] > 7) || (pos_y + coordinateModifier_y[toCheckFields] < 0 || pos_y + coordinateModifier_y[toCheckFields] > 7))
{
continue;
}
if (board[pos_y + coordinateModifier_y[toCheckFields]][pos_x + coordinateModifier_x[toCheckFields]] == enemyPlayer) {
int newPos_x = pos_x;
int newPos_y = pos_y;
for (int index = 0; index < 8; index++)
{
newPos_x += coordinateModifier_x[toCheckFields];
newPos_y += coordinateModifier_y[toCheckFields];
if ((newPos_x < 0 || newPos_x > 7) || (newPos_y < 0 || newPos_y > 7))
{
break;
}
if (board[newPos_y][newPos_x] == P_NONE)
{
break;
}
if (board[newPos_y][newPos_x] == player)
{
return true;
}
}
}
}
return false;
}
}
bool MakeMove(const Player player, Board board, const int pos_x, const int pos_y) {
if (IsMoveValid(player, board, pos_x, pos_y))
{
//Set the field which is desired and valid to player
board[pos_y][pos_x] = player;
//set enemy value
const Player enemyPlayer = Player(1 - player + 2);
//check validity of move
int coordinateModifier_x[] = { 0, 1, 1 ,1 ,0 ,-1 ,-1 ,-1 };
int coordinateModifier_y[] = { -1, -1 ,0 ,1 ,1 ,1 ,0 ,-1 };
for (int toCheckFields = 0; toCheckFields < 8; toCheckFields++)
{
if ((pos_x + coordinateModifier_x[toCheckFields] < 0 || pos_x + coordinateModifier_x[toCheckFields] > 7) || (pos_y + coordinateModifier_y[toCheckFields] < 0 || pos_y + coordinateModifier_y[toCheckFields] > 7))
{
continue;
}
if (board[pos_y + coordinateModifier_y[toCheckFields]][pos_x + coordinateModifier_x[toCheckFields]] == enemyPlayer) {
int newPos_x = pos_x;
int newPos_y = pos_y;
for (int index = 0; index < 8; index++)
{
newPos_x += coordinateModifier_x[toCheckFields];
newPos_y += coordinateModifier_y[toCheckFields];
if ((newPos_x < 0 || newPos_x > 7) || (newPos_y < 0 || newPos_y > 7))
{
break;
}
if (board[newPos_y][newPos_x] == P_NONE)
{
break;
}
if (board[newPos_y][newPos_x] == player)
{
int iterativeIndex_x = newPos_x - pos_x;
int iterativeIndex_y = newPos_y - pos_y;
int iterateTimes_x = iterativeIndex_x < 0 ? iterativeIndex_x * -1 : iterativeIndex_x;
int iterateTimes_y = iterativeIndex_y < 0 ? iterativeIndex_y * -1 : iterativeIndex_y;
int iterateTimes = iterateTimes_x < iterateTimes_y ? iterateTimes_y : iterateTimes_x;
int newCoordinates_x = pos_x;
int newCoordinates_y = pos_y;
for (int toChangeFields = 0; toChangeFields < iterateTimes; toChangeFields++)
{
if (iterativeIndex_x != 0)
newCoordinates_x += iterativeIndex_x > 0 ? +1 : -1;
if (iterativeIndex_y != 0)
newCoordinates_y += iterativeIndex_y > 0 ? +1 : -1;
board[newCoordinates_y ][newCoordinates_x] = player;
if (iterativeIndex_x != 0)
iterativeIndex_x = iterativeIndex_x > 0 ? --iterativeIndex_x : ++iterativeIndex_x;
if (iterativeIndex_y != 0)
iterativeIndex_y = iterativeIndex_y > 0 ? --iterativeIndex_y : ++iterativeIndex_y;
}
break;
}
}
}
}
//Only true if rly done something -> else report error
return true;
}
else
return false;
}
int NumberPossibleMoves(Player player, const Board board) {
int countPosibleMoves = 0;
for (int index_y = 0; index_y < 8; index_y++){
for (int index_x = 0; index_x < 8; index_x++){
if (IsMoveValid(player, board, index_x, index_y))
{
countPosibleMoves++;
}
}
}
return countPosibleMoves;
}
bool MakeHumanMove(Player player, Board board) {
char userInput[10] = {};
std::cin >> userInput;
int pos_y = 0;
switch (userInput[0]) {
case 'A': pos_y = 0;
break;
case 'B': pos_y = 1;
break;
case 'C': pos_y = 2;
break;
case 'D': pos_y = 3;
break;
case 'E': pos_y = 4;
break;
case 'F': pos_y = 5;
break;
case 'G': pos_y = 6;
break;
case 'H': pos_y = 7;
break;
default: return false;
}
int pos_x = 0;
switch (userInput[1]) {
case '1': pos_x = 0;
break;
case '2': pos_x = 1;
break;
case '3': pos_x = 2;
break;
case '4': pos_x = 3;
break;
case '5': pos_x = 4;
break;
case '6': pos_x = 5;
break;
case '7': pos_x = 6;
break;
case '8': pos_x = 7;
break;
default: return false;
}
return MakeMove(player, board, pos_x, pos_y);
}
void RunGame(PlayerKind players[2]) {
//test for possible moves and take actions
//handle valid and invalid input and or possible moves
//keep the battlefield up to date
Player p = P_WHITE;
Player p2 = P_BLACK;
Player p0 = P_NONE;
Board board = { {p0,p0,p0,p0,p0,p0,p0,p0},
{p0,p0,p0,p0,p0,p0,p0,p0} ,
{p0,p0,p0,p0,p0,p0,p0,p0} ,
{p0,p0,p0,p2,p,p0,p0,p0} ,
{p0,p0,p0,p,p2,p0,p0,p0} ,
{p0,p0,p0,p0,p0,p0,p0,p0} ,
{p0,p0,p0,p0,p0,p0,p0,p0} ,
{p0,p0,p0,p0,p0,p0,p0,p0} };
int noMoveTaken = 0;
int index = 0;
std::string playerKind[] = {"Human","KI", "KI Pro"};
//The Loop for the game
while (noMoveTaken < 2)
{
const PlayerKind actualPlayer = players[index];
const PlayerKind player = actualPlayer;
if (NumberPossibleMoves(index == 0 ? P_WHITE : P_BLACK, board) == 0) {
index = 1 - index;
noMoveTaken++;
continue;
}
else {
noMoveTaken = 0;
system("cls");
if (index == 1) {
std::cout << " Player White [O] : " << playerKind[players[0]] << "\t | \t" << " > Player Black [X] : " << playerKind[players[1]] << std::endl;
}
else
std::cout << " > Player White [O] : " << playerKind[players[0]] << "\t | \t" << " Player Black [X] : " << playerKind[players[1]] << std::endl;
ShowBoard(board);
}
if (index == 1) {
std::cout << "Player Black, its your turn!: You have " << NumberPossibleMoves(P_BLACK, board) << " possible moves!" << std::endl;
}
else
std::cout << "Player White, its your turn!: You have " << NumberPossibleMoves(P_WHITE, board) << " possible moves!" << std::endl;
if (player == KI_PRO)
MakeComputerMovePro(index == 0 ? P_WHITE : P_BLACK , board);
else if (player == KI)
MakeComputerMove(index == 0 ? P_WHITE : P_BLACK, board);
else {
while (!MakeHumanMove(index == 0 ? P_WHITE : P_BLACK, board)) {
std::cout << "Your input was nor possible neither correct! Please retry!: " << std::endl;
}
}
index = 1 - index;
}
const Player player = DetermineWinner(board);
if (player == P_WHITE)
std::cout << "You have won player WHITE!";
else
std::cout << "You have won player BLACK!";
}
}
|
Levi-Armstrong/ign-gui
|
.v0_unported/src/Vector3dWidget_TEST.cc
|
/*
* Copyright (C) 2017 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <gtest/gtest.h>
#include <ignition/msgs.hh>
#include "test_config.h" // NOLINT(build/include)
#include "ignition/gui/Iface.hh"
#include "ignition/gui/QtMetatypes.hh"
#include "ignition/gui/Vector3dWidget.hh"
using namespace ignition;
using namespace gui;
/////////////////////////////////////////////////
TEST(Vector3dWidgetTest, Signal)
{
setVerbosity(4);
EXPECT_TRUE(initApp());
// Create widget
auto widget = new Vector3dWidget("a vector");
ASSERT_NE(widget, nullptr);
// Connect signals
bool signalReceived = false;
widget->connect(widget, &Vector3dWidget::ValueChanged,
[&signalReceived](QVariant _var)
{
auto v = _var.value<math::Vector3d>();
EXPECT_EQ(v, math::Vector3d(0, -4.5, 0));
signalReceived = true;
});
// Check default value
EXPECT_EQ(widget->Value().value<math::Vector3d>(), math::Vector3d::Zero);
// Get signal emitting widgets
auto spins = widget->findChildren<QDoubleSpinBox *>();
ASSERT_EQ(spins.size(), 3);
// Get preset combo
auto combos = widget->findChildren<QComboBox *>();
EXPECT_EQ(combos.size(), 1);
EXPECT_EQ(combos[0]->currentIndex(), 0);
// Change the value, finish edit, and check new value at callback
spins[1]->setValue(-4.5);
spins[1]->editingFinished();
// Check callback was called
EXPECT_TRUE(signalReceived);
// Change values without finishing editi and check preset
spins[0]->setValue(0.0);
spins[1]->setValue(0.0);
spins[2]->setValue(-1.0);
spins[2]->valueChanged(-1.0);
EXPECT_EQ(combos[0]->currentIndex(), 6);
delete widget;
EXPECT_TRUE(stop());
}
/////////////////////////////////////////////////
TEST(Vector3dWidgetTest, SetValue)
{
setVerbosity(4);
EXPECT_TRUE(initApp());
auto widget = new Vector3dWidget("a vector");
ASSERT_NE(widget, nullptr);
// Set good value
EXPECT_TRUE(widget->SetValue(QVariant::fromValue(
math::Vector3d(0, 1, 2))));
// Set bad value
EXPECT_FALSE(widget->SetValue(true));
delete widget;
EXPECT_TRUE(stop());
}
/////////////////////////////////////////////////
TEST(Vector3dWidgetTest, Presets)
{
setVerbosity(4);
EXPECT_TRUE(initApp());
// Create widget
auto widget = new Vector3dWidget("a vector");
ASSERT_NE(widget, nullptr);
// Get preset combo
auto combos = widget->findChildren<QComboBox *>();
EXPECT_EQ(combos.size(), 1);
// +X
combos[0]->setCurrentIndex(1);
EXPECT_EQ(widget->Value().value<math::Vector3d>(), math::Vector3d::UnitX);
// -X
combos[0]->setCurrentIndex(2);
EXPECT_EQ(widget->Value().value<math::Vector3d>(), -math::Vector3d::UnitX);
// +Y
combos[0]->setCurrentIndex(3);
EXPECT_EQ(widget->Value().value<math::Vector3d>(), math::Vector3d::UnitY);
// -Y
combos[0]->setCurrentIndex(4);
EXPECT_EQ(widget->Value().value<math::Vector3d>(), -math::Vector3d::UnitY);
// +Z
combos[0]->setCurrentIndex(5);
EXPECT_EQ(widget->Value().value<math::Vector3d>(), math::Vector3d::UnitZ);
// -Z
combos[0]->setCurrentIndex(6);
EXPECT_EQ(widget->Value().value<math::Vector3d>(), -math::Vector3d::UnitZ);
// Invalid index doesn't change anything
combos[0]->setCurrentIndex(7);
EXPECT_EQ(widget->Value().value<math::Vector3d>(), -math::Vector3d::UnitZ);
delete widget;
EXPECT_TRUE(stop());
}
|
Zirias/stoneage
|
src/eearth.c
|
<gh_stars>1-10
#include "eearth.h"
#include "board.h"
#include "screen.h"
static void
m_dispose(THIS)
{
METHOD(EEarth);
DELETE(EEarth, this);
}
CTOR(EEarth)
{
Entity e;
BASECTOR(EEarth, Entity);
e = CAST(this, Entity);
e->dispose = &m_dispose;
e->bg = BG_Earth;
return this;
}
DTOR(EEarth)
{
BASEDTOR(Entity);
}
|
Juicestus/Computer-Science
|
CS-1-Labs/FileLab03.java
|
<gh_stars>1-10
import java.util.Scanner;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileWriter;
public class FileLab03 {
public static void main(String[] args) throws IOException {
Scanner fileReader = new Scanner(new File("../dat/03.dat"));
fileReader.nextLine();
PrintWriter fileOut = new PrintWriter(new FileWriter("../RowSum.dat"));
for (Scanner lineReader; fileReader.hasNextLine(); ) {
lineReader = new Scanner(fileReader.nextLine());
int rowSum = 0;
while (lineReader.hasNextInt())
rowSum += lineReader.nextInt();
fileOut.println(rowSum);
}
fileOut.close();
}
}
|
un-knower/embrace-datacollector3.0.1
|
spark-processor-protolib/src/main/java/com/streamsets/pipeline/stage/processor/spark/SparkProcessorConfigBean.java
|
/*
* Copyright 2017 StreamSets Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.streamsets.pipeline.stage.processor.spark;
import com.streamsets.pipeline.api.ConfigDef;
import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.lib.el.VaultEL;
import java.util.ArrayList;
import java.util.List;
@GenerateResourceBundle
public class SparkProcessorConfigBean {
public static final String DEFAULT_THREAD_COUNT = "4";
public static final String DEFAULT_APP_NAME = "SDC Spark App";
@ConfigDef(
required = false,
type = ConfigDef.Type.NUMBER,
defaultValue = DEFAULT_THREAD_COUNT,
label = "并发性(仅单机模式)",
description = "每次批处理创建的分区并发数。群集模式无效",
// label = "Parallelism (Standalone Mode Only)",
// description = "Number of partitions to create per batch of records. Ignored in Cluster Mode.",
group = "SPARK",
displayPosition = 10
)
public int threadCount;
@ConfigDef(
required = false,
type = ConfigDef.Type.STRING,
defaultValue = DEFAULT_APP_NAME,
label = "应用程序名称(仅单机模式)",
description = "向Spark提交的应用程序名称. 集群模式下此项无效.",
// label = "Application Name (Standalone Mode Only)",
// description = "Name of the Application submitted to Spark. Ignored in Cluster Mode.",
group = "SPARK",
displayPosition = 20
)
public String appName;
@ConfigDef(
required = true,
type = ConfigDef.Type.STRING,
label = "Spark转换器类",
description = "SparkTransformer API的实现类.",
// label = "Spark Transformer Class",
// description = "Class that implements SparkTransformer API.",
group = "SPARK",
displayPosition = 30
)
public String transformerClass;
@ConfigDef(
required = false,
type = ConfigDef.Type.LIST,
label = "初始化方法参数",
description = "传递给转换器初始化方法的参数。用于外部连接或者从外部系统读取配置或已有数据",
// label = "Init Method Arguments",
// description = "Arguments to pass to the init method of the Transformer. " +
// "Use to make external connections or to read configuration or pre-existing data from external systems.",
elDefs = VaultEL.class,
group = "SPARK",
displayPosition = 40
)
public List<String> preprocessMethodArgs = new ArrayList<>();
}
|
ccatterina/casl
|
packages/casl-ability/spec/rulesToAST.spec.js
|
<filename>packages/casl-ability/spec/rulesToAST.spec.js
import { defineAbility } from '../src'
import { rulesToAST } from '../src/extra'
describe('rulesToAST', () => {
it('returns empty "and" `Condition` if there are no conditions in `Ability`', () => {
const ability = defineAbility(can => can('read', 'Post'))
const ast = rulesToAST(ability, 'read', 'Post')
expect(ast.operator).to.equal('and')
expect(ast.value).to.be.an('array').that.is.empty
})
it('returns `null` if there is no ability to do an action', () => {
const ability = defineAbility(can => can('read', 'Post'))
const ast = rulesToAST(ability, 'update', 'Post')
expect(ast).to.be.null
})
it('returns only "or" `Condition` if there are no forbidden rules', () => {
const ability = defineAbility((can) => {
can('read', 'Post', { author: 1 })
can('read', 'Post', { private: false })
})
const ast = rulesToAST(ability, 'read', 'Post')
expect(ast).to.deep.equal({
operator: 'or',
value: [
{ operator: 'eq', field: 'private', value: false },
{ operator: 'eq', field: 'author', value: 1 },
]
})
})
it('returns "and" condition that includes "or" if there are forbidden and regular rules', () => {
const ability = defineAbility((can, cannot) => {
can('read', 'Post', { author: 1 })
can('read', 'Post', { sharedWith: 1 })
cannot('read', 'Post', { private: true })
})
const ast = rulesToAST(ability, 'read', 'Post')
expect(ast).to.deep.equal({
operator: 'and',
value: [
{ operator: 'eq', field: 'private', value: true },
{
operator: 'or',
value: [
{ operator: 'eq', field: 'sharedWith', value: 1 },
{ operator: 'eq', field: 'author', value: 1 },
]
}
]
})
})
})
|
zaqwes8811/smart-vocabulary-cards
|
projects/shadow/kmap-builder-java-desk/src/core/evaluators/NotesBuilder.java
|
package pipeline.evaluators;
import com.google.common.base.Joiner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import common.Tools;
import frozen.crosscuttings.AppConstants;
import frozen.dal.accessors_text_file_storage.ImmutableIdxGetters;
import frozen.jobs_processors.ProcessorTargets;
import frozen.old.SentencesReduce;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NotesBuilder {
static public final String NOTE_N80_CAPACITY = "f80_p"; // Core
static public final String NOTE_N20_CAPACITY = "f20";
static public final String NOTE_N20_COUNT = "w20_p"; // Core
static public final String NOTE_N80_COUNT = "w80";
static public String json_get_notes_for_node(String node) {
return new Gson().toJson(get_notes_for_node(node));
}
static public Map<String, String> get_notes_for_node(String node) {
HashMap<String, HashMap<String, String>> metadataStaticNotes = ImmutableIdxGetters.getStaticNotes(); // TODO(): bad!
// Получаем статические данные по сложности
// Статические оценки
Map<String, String> nodeStaticNotesInfo = metadataStaticNotes.get(node);
// Данные для каждого из индексов по 80/20
List<String> sorted_full_idx = ImmutableIdxGetters.get_sorted_idx(node);
// сам частотынй индекс индекс
HashMap<String, Integer> sorted_freq_idx = ImmutableIdxGetters.get_freq_idx(node);
Integer total_amount = 0;
for (String word: sorted_full_idx) total_amount += sorted_freq_idx.get(word);
Double threshold = total_amount*0.8;
// Оценка - 20% слов
Integer count_unique_words = sorted_full_idx.size();
Double N20 = count_unique_words*0.2;
Double N80 = count_unique_words - N20;
// Оценка - 80% интегральной частоты
Double sum = new Double(0);
Integer N80_Amount = 0;
for (String word: sorted_full_idx) {
if (sum > threshold) {
break;
}
N80_Amount++;
sum += sorted_freq_idx.get(word);
}
Double N20_Amount = new Double(count_unique_words)-N80_Amount;
// Итого
nodeStaticNotesInfo.put(NOTE_N80_CAPACITY, N80_Amount.toString());
nodeStaticNotesInfo.put(NOTE_N20_CAPACITY, N20_Amount.toString());
nodeStaticNotesInfo.put(NOTE_N20_COUNT, N20.toString());
nodeStaticNotesInfo.put(NOTE_N80_COUNT, N80.toString());
return nodeStaticNotesInfo;
}
static public String get_one_record(String node, Map<String, String> info) {
Tools.print(node + " " + info);
String record = Joiner.on(";")
.join(
node,
info.get(SentencesReduce.NOTE_RE).replace('.', ','),
info.get(SentencesReduce.NOTE_MEAN_TIME_FOR_READ).replace('.', ','),
info.get(SentencesReduce.NOTE_MEAN_LEN_SENT).replace('.', ','),
info.get(NotesBuilder.NOTE_N20_COUNT).replace('.', ','),
info.get(NotesBuilder.NOTE_N80_COUNT).replace('.', ','),
info.get(NotesBuilder.NOTE_N80_CAPACITY).replace('.', ','),
info.get(NotesBuilder.NOTE_N20_CAPACITY).replace('.', ','));
return record;
}
public static List<String> get_urls_and_langs_node(String node){
// Путь к мета-файлу
String pathToMetaFile = Joiner.on(AppConstants.PATH_SPLITTER)
.join(
ProcessorTargets.getPathToIndex(),
AppConstants.CONTENT_FOLDER,
node,
AppConstants.CONTENT_META_FILENAME);
// Преобразуем в json
String settingsInJson = Tools.file2string(pathToMetaFile);
Type type = new TypeToken<List<List<String>>>() {}.getType();
List<List<String>> metadata = new Gson().fromJson(settingsInJson, type);
// Можно вытряхивать
List<String> info = new ArrayList<String>();
for (List<String> item: metadata) {
String record = "Source url: "+item.get(0)+" Language: "+item.get(1);
info.add(record);
}
return info;
}
}
|
alonmm/VCSamples
|
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Network information sample (Windows 8)/C++/ProfileLocalUsageData.xaml.cpp
|
<filename>VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Network information sample (Windows 8)/C++/ProfileLocalUsageData.xaml.cpp
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
// ProfileLocalUsageData.xaml.cpp
// Implementation of the ProfileLocalUsageData class
#include "pch.h"
#include "ProfileLocalUsageData.xaml.h"
using namespace SDKSample::NetworkInformationApi;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
using namespace Windows::System;
using namespace Windows::Foundation;
using namespace Platform;
using namespace Windows::Networking;
using namespace Windows::Networking::Connectivity;
ProfileLocalUsageData::ProfileLocalUsageData()
{
InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
void ProfileLocalUsageData::OnNavigatedTo(NavigationEventArgs^ e)
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
rootPage = MainPage::Current;
}
// Display Local Data Usage for Internet Connection Profile for the past 1 hour
void SDKSample::NetworkInformationApi::ProfileLocalUsageData::ProfileLocalUsageData_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
try
{
FILETIME ftCurrTime;
//Get Current time as FILETIME in UTC
GetSystemTimeAsFileTime(&ftCurrTime);
//Get the DateTime object with current time
DateTime dtCurrentTime;
dtCurrentTime.UniversalTime = (((ULONGLONG) ftCurrTime.dwHighDateTime) << 32) + ftCurrTime.dwLowDateTime;
//Set Start time to one hour behind current time
DateTime dtStartTime;
dtStartTime.UniversalTime = dtCurrentTime.UniversalTime - (3600 * 10000000ULL);;
ConnectionProfile^ internetConnectionProfile = NetworkInformation::GetInternetConnectionProfile();
if (internetConnectionProfile == nullptr)
{
rootPage->NotifyUser(L"Not connected to Internet\n", NotifyType::StatusMessage);
}
else
{
//Get Local Data usage for the Internet Connection Profile for the past 1 hour
DataUsage^ localUsage = internetConnectionProfile->GetLocalUsage(dtStartTime, dtCurrentTime);
String^ localUsageInfo = L"Local Data Usage:\n";
localUsageInfo += L" Bytes Sent : " + localUsage->BytesSent.ToString() + "\n";
localUsageInfo += L" Bytes Received : " + localUsage->BytesReceived.ToString() + "\n";
rootPage->NotifyUser(localUsageInfo, NotifyType::StatusMessage);
}
}
catch (Exception^ ex)
{
rootPage->NotifyUser("An unexpected exception occured: " + ex->Message, NotifyType::ErrorMessage);
}
}
|
antkmsft/azure-sdk-for-go
|
sdk/resourcemanager/visualstudio/armvisualstudio/zz_generated_response_types.go
|
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armvisualstudio
// AccountsClientCheckNameAvailabilityResponse contains the response from method AccountsClient.CheckNameAvailability.
type AccountsClientCheckNameAvailabilityResponse struct {
CheckNameAvailabilityResult
}
// AccountsClientCreateOrUpdateResponse contains the response from method AccountsClient.CreateOrUpdate.
type AccountsClientCreateOrUpdateResponse struct {
AccountResource
}
// AccountsClientDeleteResponse contains the response from method AccountsClient.Delete.
type AccountsClientDeleteResponse struct {
// placeholder for future response values
}
// AccountsClientGetResponse contains the response from method AccountsClient.Get.
type AccountsClientGetResponse struct {
AccountResource
}
// AccountsClientListByResourceGroupResponse contains the response from method AccountsClient.ListByResourceGroup.
type AccountsClientListByResourceGroupResponse struct {
AccountResourceListResult
}
// AccountsClientUpdateResponse contains the response from method AccountsClient.Update.
type AccountsClientUpdateResponse struct {
AccountResource
}
// ExtensionsClientCreateResponse contains the response from method ExtensionsClient.Create.
type ExtensionsClientCreateResponse struct {
ExtensionResource
}
// ExtensionsClientDeleteResponse contains the response from method ExtensionsClient.Delete.
type ExtensionsClientDeleteResponse struct {
// placeholder for future response values
}
// ExtensionsClientGetResponse contains the response from method ExtensionsClient.Get.
type ExtensionsClientGetResponse struct {
ExtensionResource
}
// ExtensionsClientListByAccountResponse contains the response from method ExtensionsClient.ListByAccount.
type ExtensionsClientListByAccountResponse struct {
ExtensionResourceListResult
}
// ExtensionsClientUpdateResponse contains the response from method ExtensionsClient.Update.
type ExtensionsClientUpdateResponse struct {
ExtensionResource
}
// OperationsClientListResponse contains the response from method OperationsClient.List.
type OperationsClientListResponse struct {
OperationListResult
}
// ProjectsClientCreateResponse contains the response from method ProjectsClient.Create.
type ProjectsClientCreateResponse struct {
ProjectResource
}
// ProjectsClientGetJobStatusResponse contains the response from method ProjectsClient.GetJobStatus.
type ProjectsClientGetJobStatusResponse struct {
ProjectResource
}
// ProjectsClientGetResponse contains the response from method ProjectsClient.Get.
type ProjectsClientGetResponse struct {
ProjectResource
}
// ProjectsClientListByResourceGroupResponse contains the response from method ProjectsClient.ListByResourceGroup.
type ProjectsClientListByResourceGroupResponse struct {
ProjectResourceListResult
}
// ProjectsClientUpdateResponse contains the response from method ProjectsClient.Update.
type ProjectsClientUpdateResponse struct {
ProjectResource
}
|
lastwhispers/code
|
distributed/gateway/service-order-load1/src/main/java/cn/lastwhisper/service/ServiceB1Application.java
|
<reponame>lastwhispers/code
package cn.lastwhisper.service;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
@SpringBootApplication
public class ServiceB1Application {
public static void main(String[] args) {
SpringApplication.run(ServiceB1Application.class, args);
}
@RequestMapping("/method")
public Map methodA(){
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("service","order 1");
return hashMap;
}
}
|
frankjoshua/PocketBot
|
src/main/java/com/tesseractmobile/pocketbot/service/VoiceRecognitionState.java
|
<reponame>frankjoshua/PocketBot
package com.tesseractmobile.pocketbot.service;
/**
* Created by josh on 8/25/2015.
*/
public enum VoiceRecognitionState {
BEGINNING_OF_SPEECH, END_OF_SPEECH, ERROR, READY, STARTING_LISTENING, READY_FOR_SPEECH
}
|
egyware/fp4g
|
Apollo/src/com/apollo/messages/BeginContactMessage.java
|
<gh_stars>0
package com.apollo.messages;
import com.apollo.Entity;
import com.apollo.Message;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.Fixture;
public class BeginContactMessage extends Message
{
public Entity other;
public Fixture ownFixture;
public Fixture otherFixture;
public Contact contact;
@Override
public Class<? extends Message> getType()
{
return BeginContactMessage.class;
}
}
|
aakbar5/handy-c
|
advanced_linux_programming/chapter08/write_journal_entry.c
|
// Listing 8.3 (write_journal_entry.c) Write and Sync a Journal Entry
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
//
// App entry point
//
int main()
{
const char* file_name = "journal.log";
int fd = open(file_name, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
write(fd, file_name, strlen(file_name));
write(fd, "\n", 1);
fsync(fd);
close(fd);
return 0;
}
|
olavloite/spanner-jdbc
|
src/main/java/nl/topicus/jdbc/statement/AbstractTablePartWorker.java
|
<reponame>olavloite/spanner-jdbc
package nl.topicus.jdbc.statement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Callable;
import com.google.cloud.spanner.SpannerException;
import com.google.common.annotations.VisibleForTesting;
import com.google.rpc.Code;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.Limit;
import net.sf.jsqlparser.statement.select.Select;
import nl.topicus.jdbc.CloudSpannerConnection;
import nl.topicus.jdbc.CloudSpannerDriver;
import nl.topicus.jdbc.exception.CloudSpannerSQLException;
public abstract class AbstractTablePartWorker implements Callable<ConversionResult> {
private enum Mode {
UNKNOWN, NORMAL, EXTENDED;
}
enum DMLOperation {
INSERT, ONDUPLICATEKEYUPDATE, UPDATE, DELETE;
}
protected final CloudSpannerConnection connection;
protected final Select select;
/**
* This flag indicates whether the worker should go into 'extended' mode if the number of
* records/mutations is expected to exceed the limitations of Cloud Spanner. Extended mode means
* that a separate connection will be opened and that the inserts will be performed on that
* connection. These inserts will also be committed automatically, and there is no guarantee that
* the entire insert operation will succeed (the insert is not performed atomically)
*/
private boolean allowExtendedMode;
private Mode mode = Mode.UNKNOWN;
protected final DMLOperation operation;
private final ParameterStore parameters;
private long estimatedRecordCount = -1;
private long recordCount = 0;
AbstractTablePartWorker(CloudSpannerConnection connection, Select select,
ParameterStore parameters, boolean allowExtendedMode, DMLOperation operation) {
this.connection = connection;
this.select = select;
this.parameters = parameters;
this.allowExtendedMode = allowExtendedMode;
this.operation = operation;
}
@Override
public ConversionResult call() {
Exception exception = null;
long startTime = System.currentTimeMillis();
try {
genericRun();
} catch (Exception e) {
exception = e;
}
long endTime = System.currentTimeMillis();
return new ConversionResult(recordCount, 0, startTime, endTime, exception);
}
protected void genericRun() throws SQLException {
String unquotedTableName = CloudSpannerDriver.unquoteIdentifier(getTable().getName());
List<String> columnNamesList = getColumnNames();
long batchSize = ConverterUtils.calculateActualBatchSize(columnNamesList.size(), connection,
null, null, unquotedTableName);
boolean isExtendedMode = isExtendedMode(batchSize);
boolean wasAutocommit = connection.getAutoCommit();
if (!isExtendedMode && wasAutocommit) {
connection.setAutoCommit(false);
}
try (Connection destination = isExtendedMode ? connection.createCopyConnection() : null) {
if (destination != null) {
destination.setAutoCommit(false);
}
String sql = createSQL();
try (PreparedStatement statement = destination == null ? connection.prepareStatement(sql)
: destination.prepareStatement(sql)) {
if (operation == DMLOperation.UPDATE) {
// Set force update
((CloudSpannerPreparedStatement) statement).setForceUpdate(true);
}
CloudSpannerPreparedStatement selectStatement =
connection.prepareStatement(select.toString());
for (int i = 1; i <= parameters.getHighestIndex(); i++) {
selectStatement.setObject(i, parameters.getParameter(i));
}
try (ResultSet rs = selectStatement.executeQuery()) {
ResultSetMetaData metadata = rs.getMetaData();
while (rs.next()) {
for (int index = 1; index <= metadata.getColumnCount(); index++) {
Object object = rs.getObject(index);
statement.setObject(index, object);
}
statement.executeUpdate();
recordCount++;
if (destination != null && recordCount % batchSize == 0)
destination.commit();
}
}
}
if (destination != null) {
destination.commit();
}
if (wasAutocommit && !isExtendedMode) {
connection.commit();
connection.setAutoCommit(true);
}
} catch (SpannerException e) {
throw new CloudSpannerSQLException(e);
} catch (CloudSpannerSQLException e) {
throw e;
} catch (Exception e) {
throw new CloudSpannerSQLException(e.getMessage(), Code.UNKNOWN, e);
} finally {
if (wasAutocommit && !isExtendedMode) {
connection.rollback();
connection.setAutoCommit(true);
}
}
}
protected abstract List<String> getColumnNames() throws SQLException;
protected abstract Table getTable();
protected abstract String createSQL() throws SQLException;
private long isRecordCountGreaterThan(Select select, long batchSize) throws SQLException {
if (estimatedRecordCount == -1) {
PreparedStatement ps = connection.prepareStatement(createCountQuery(select, batchSize));
for (int i = 1; i <= parameters.getHighestIndex(); i++) {
setParameter(i, ps);
}
try (ResultSet count = ps.executeQuery()) {
if (count.next())
estimatedRecordCount = count.getLong(1);
}
}
return estimatedRecordCount;
}
private void setParameter(int i, PreparedStatement ps) throws SQLException {
if (parameters.getParameter(i) == null && parameters.getType(i) != null) {
ps.setNull(i, parameters.getType(i));
} else if (parameters.getParameter(i) != null) {
if (parameters.getType(i) != null && parameters.getScaleOrLength(i) != null) {
ps.setObject(i, parameters.getParameter(i), parameters.getType(i),
parameters.getScaleOrLength(i));
} else if (parameters.getType(i) != null) {
ps.setObject(i, parameters.getParameter(i), parameters.getType(i));
} else {
ps.setObject(i, parameters.getParameter(i));
}
}
}
@VisibleForTesting
String createCountQuery(Select select, long batchSize) {
Limit limit = new Limit();
limit.setRowCount(new LongValue(batchSize));
return String.format("SELECT COUNT(*) AS C FROM ((%s)%s) Q", select, limit);
}
private boolean isExtendedMode(long batchSize) throws SQLException {
if (mode == Mode.UNKNOWN) {
if (!allowExtendedMode) {
mode = Mode.NORMAL;
} else {
long count = isRecordCountGreaterThan(select, batchSize);
if (count >= batchSize) {
mode = Mode.EXTENDED;
} else {
mode = Mode.NORMAL;
}
}
}
return mode == Mode.EXTENDED;
}
public long getRecordCount() {
return recordCount;
}
}
|
huanglei579/eoscannon-online-tool
|
app/components/Header/styles.js
|
<filename>app/components/Header/styles.js
import styled from 'styled-components'
const BodyBox = styled.article`
background: #262626;
color: #eee;
.ant-layout{
background: none;
}
.ant-btn{
color: #fff;
}
`
const ConBox = styled.div`
box-sizing: border-box;
position: relative;
width: 100%;
.content{
display:flex;
padding-top:2rem;
}
.firstContent{
width:50%;
span{
display:block;
padding-bottom: 1.2rem;
}
}
.contentDetail{
text-align: center;
}
.secondContent{
display:flex;
width:100%;
justify-content: space-around;
}
.contentDetailDesc{
display:block;
.contentDetailDescTitle{
padding-top:1rem;
font-weight:bold;
}
span{
text-align:center;
display:block;
}
}
`
const styleComps = {
BodyBox,
ConBox
}
export default styleComps
|
skounis/ionic-stage
|
stage/e22/scripts/products/products.controller.js
|
<filename>stage/e22/scripts/products/products.controller.js
(function() {
'use strict';
angular
.module('catalogue.products')
.filter('stripdecimals', function(){
return function(input){
return input.replace('.00', '');
}
})
.controller('ProductsController', ProductsController);
ProductsController.$inject = ['$state', 'products', 'points', '_', '$ionicSlideBoxDelegate'];
/* @ngInject */
function ProductsController($state, products, points, _, $ionicSlideBoxDelegate) {
// _.map(points, function(element){
// element.pointsFormated = element.points.replace('.00', '');
// });
var vm = angular.extend(this, {
points: points,
cache: products.slice(0),
products: products,
showProductDetails: showProductDetails,
filterByPoints: filterByPoints
});
(function activate() {
})();
// ******************************************************
function showProductDetails(productId) {
$state.go('app.product', {
productId: productId
});
}
function filterByPoints(index){
var selection = vm.points[index];
var filtered = _.filter(vm.cache,function(element){
return element.points == selection.value
});
// _.map(filtered, function(element){
// element.pointsFormated = element.points.replace('.00', '');
// });
vm.products.splice(0, vm.products.length);
for(var i in filtered){
vm.products.push(filtered[i]);
}
$ionicSlideBoxDelegate.update();
}
}
})();
|
TheidenHD/CompatSkills
|
src/main/java/codersafterdark/compatskills/common/compats/gamestages/gamestagelocks/GameStageLockTweaker.java
|
package codersafterdark.compatskills.common.compats.gamestages.gamestagelocks;
import codersafterdark.compatskills.CompatSkills;
import codersafterdark.compatskills.common.compats.gamestages.GameStageCompatHandler;
import codersafterdark.compatskills.utils.CheckMethods;
import codersafterdark.compatskills.utils.Utils;
import codersafterdark.reskillable.api.data.RequirementHolder;
import crafttweaker.IAction;
import crafttweaker.annotations.ModOnly;
import crafttweaker.annotations.ZenRegister;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
@ModOnly("gamestages")
@ZenClass("mods.compatskills.GameStageLocks")
@ZenRegister
public class GameStageLockTweaker {
@ZenMethod
public static void addGameStageLock(String gamestage, String... defaultRequirements) {
if (GameStageCompatHandler.ENABLED) {
CompatSkills.LATE_ADDITIONS.add(new AddGameStageLock(gamestage, defaultRequirements));
}
}
private static class AddGameStageLock implements IAction {
private final String gameStage;
private final String[] requirements;
private AddGameStageLock(String gameStage, String... requirements) {
this.gameStage = gameStage;
this.requirements = requirements;
}
@Override
public void apply() {
if (CheckMethods.checkString(gameStage) & CheckMethods.checkStringArray(requirements)) {
GameStageCompatHandler.addGameStageLock(new GameStageLock(gameStage), RequirementHolder.fromStringList(requirements));
}
}
@Override
public String describe() {
return "Added GameStage Lock: " + gameStage + ", With Requirements: " + Utils.formatRequirements(requirements);
}
}
}
|
bingchunjin/1806_SDK
|
linux-4.14.90-dev/linux-4.14.90/drivers/clk/renesas/clk-r8a7778.c
|
/*
* r8a7778 Core CPG Clocks
*
* Copyright (C) 2014 <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*/
#include <linux/clk-provider.h>
#include <linux/clk/renesas.h>
#include <linux/of_address.h>
#include <linux/slab.h>
#include <linux/soc/renesas/rcar-rst.h>
struct r8a7778_cpg {
struct clk_onecell_data data;
spinlock_t lock;
void __iomem *reg;
};
/* PLL multipliers per bits 11, 12, and 18 of MODEMR */
static const struct {
unsigned long plla_mult;
unsigned long pllb_mult;
} r8a7778_rates[] __initconst = {
[0] = { 21, 21 },
[1] = { 24, 24 },
[2] = { 28, 28 },
[3] = { 32, 32 },
[5] = { 24, 21 },
[6] = { 28, 21 },
[7] = { 32, 24 },
};
/* Clock dividers per bits 1 and 2 of MODEMR */
static const struct {
const char *name;
unsigned int div[4];
} r8a7778_divs[6] __initconst = {
{ "b", { 12, 12, 16, 18 } },
{ "out", { 12, 12, 16, 18 } },
{ "p", { 16, 12, 16, 12 } },
{ "s", { 4, 3, 4, 3 } },
{ "s1", { 8, 6, 8, 6 } },
};
static u32 cpg_mode_rates __initdata;
static u32 cpg_mode_divs __initdata;
static struct clk * __init
r8a7778_cpg_register_clock(struct device_node *np, struct r8a7778_cpg *cpg,
const char *name)
{
if (!strcmp(name, "plla")) {
return clk_register_fixed_factor(NULL, "plla",
of_clk_get_parent_name(np, 0), 0,
r8a7778_rates[cpg_mode_rates].plla_mult, 1);
} else if (!strcmp(name, "pllb")) {
return clk_register_fixed_factor(NULL, "pllb",
of_clk_get_parent_name(np, 0), 0,
r8a7778_rates[cpg_mode_rates].pllb_mult, 1);
} else {
unsigned int i;
for (i = 0; i < ARRAY_SIZE(r8a7778_divs); i++) {
if (!strcmp(name, r8a7778_divs[i].name)) {
return clk_register_fixed_factor(NULL,
r8a7778_divs[i].name,
"plla", 0, 1,
r8a7778_divs[i].div[cpg_mode_divs]);
}
}
}
return ERR_PTR(-EINVAL);
}
static void __init r8a7778_cpg_clocks_init(struct device_node *np)
{
struct r8a7778_cpg *cpg;
struct clk **clks;
unsigned int i;
int num_clks;
u32 mode;
if (rcar_rst_read_mode_pins(&mode))
return;
BUG_ON(!(mode & BIT(19)));
cpg_mode_rates = (!!(mode & BIT(18)) << 2) |
(!!(mode & BIT(12)) << 1) |
(!!(mode & BIT(11)));
cpg_mode_divs = (!!(mode & BIT(2)) << 1) |
(!!(mode & BIT(1)));
num_clks = of_property_count_strings(np, "clock-output-names");
if (num_clks < 0) {
pr_err("%s: failed to count clocks\n", __func__);
return;
}
cpg = kzalloc(sizeof(*cpg), GFP_KERNEL);
clks = kcalloc(num_clks, sizeof(*clks), GFP_KERNEL);
if (cpg == NULL || clks == NULL) {
/* We're leaking memory on purpose, there's no point in cleaning
* up as the system won't boot anyway.
*/
return;
}
spin_lock_init(&cpg->lock);
cpg->data.clks = clks;
cpg->data.clk_num = num_clks;
cpg->reg = of_iomap(np, 0);
if (WARN_ON(cpg->reg == NULL))
return;
for (i = 0; i < num_clks; ++i) {
const char *name;
struct clk *clk;
of_property_read_string_index(np, "clock-output-names", i,
&name);
clk = r8a7778_cpg_register_clock(np, cpg, name);
if (IS_ERR(clk))
pr_err("%s: failed to register %s %s clock (%ld)\n",
__func__, np->name, name, PTR_ERR(clk));
else
cpg->data.clks[i] = clk;
}
of_clk_add_provider(np, of_clk_src_onecell_get, &cpg->data);
cpg_mstp_add_clk_domain(np);
}
CLK_OF_DECLARE(r8a7778_cpg_clks, "renesas,r8a7778-cpg-clocks",
r8a7778_cpg_clocks_init);
|
sktocha/ab_admin
|
lib/generators/ab_admin/install/templates/helpers/admin/structures_helper.rb
|
<gh_stars>0
module Admin::StructuresHelper
def edit_structure_record_path(structure)
case structure.structure_type
when StructureType.static_page
if structure.static_page
edit_admin_structure_static_page_path(structure_id: structure.id)
else
new_admin_structure_static_page_path(structure_id: structure.id)
end
when StructureType.posts
'#'
when StructureType.main
'#'
when StructureType.redirect
edit_admin_structure_path(structure)
when StructureType.group
'#'
else
'#'
end
end
end
|
ctimbai/coding-demo
|
C/dpdk/cache_opt/c.c
|
<gh_stars>0
#include <stdio.h>
#include <stdlib.h>
#include "common.h"
#define N 36*1024*1024
struct DATA {
char a;
int b;
char c;
};
int main(void) {
int i;
struct DATA* p = (struct DATA*) malloc(sizeof(struct DATA) * N);
uint64_t start, stop;
start = rte_rdtsc();
for(i=0; i<N; i++) {
p[i].a++;
}
stop = rte_rdtsc();
printf(FMT64 "\n", stop - start);
return 0;
}
|
DxChainNetwork/godx
|
common/bigint_test.go
|
<reponame>DxChainNetwork/godx
// Copyright 2019 DxChain, All rights reserved.
// Use of this source code is governed by an Apache
// License 2.0 that can be found in the LICENSE file.
package common
import (
"math"
"testing"
)
func TestRandomBigIntRange(t *testing.T) {
testingRange := []BigInt{
BigInt0,
NewBigInt(-200),
NewBigInt(1000),
}
for _, data := range testingRange {
val, err := RandomBigIntRange(data)
if data.IsNeg() || data.IsEqual(BigInt0) {
if err == nil {
t.Errorf("negative or 0 range, expecte error")
}
continue
}
if val.Cmp(BigInt0) == -1 || val.Cmp(data) == 1 {
t.Errorf("range from 0 - %v, %v is not expected", data, val)
}
}
}
func TestBigInt_IsNeg(t *testing.T) {
tables := []struct {
a int64
result bool
}{
{0, false},
{1, false},
{-1, true},
{1000000000000, false},
{-1000000000000, true},
}
for _, table := range tables {
isNeg := NewBigInt(table.a).IsNeg()
if isNeg != table.result {
t.Errorf("input: %v, expected is negative: %t, got %t", table.a, table.result,
isNeg)
}
}
}
func TestBigInt_IsEqual(t *testing.T) {
tables := []struct {
a BigInt
b BigInt
result bool
}{
{BigInt1, BigInt1, true},
{BigInt0, BigInt1, false},
{NewBigInt(-1), NewBigInt(-1), true},
{BigInt0, BigInt0, true},
}
for _, table := range tables {
isEqual := table.a.IsEqual(table.b)
if isEqual != table.result {
t.Errorf("input %v, %v expected eqality %t, got %t", table.a, table.b, table.result,
isEqual)
}
}
}
func TestBigInt_Add(t *testing.T) {
tables := []struct {
a BigInt
b BigInt
result BigInt
}{
{NewBigInt(100000), NewBigInt(-100000), BigInt0},
{NewBigInt(100000), NewBigInt(100000), NewBigInt(200000)},
{NewBigInt(0), NewBigInt(-100000), NewBigInt(-100000)},
}
for _, table := range tables {
val := table.a.Add(table.b)
isEqual := val.Cmp(table.result)
if isEqual != 0 {
t.Errorf("input %v, %v. Expected sum %v, got sum %v", table.a, table.b, table.result,
val)
}
}
}
func TestBigInt_Sub(t *testing.T) {
tables := []struct {
a BigInt
b BigInt
result BigInt
}{
{NewBigInt(-100000), NewBigInt(0), NewBigInt(-100000)},
{NewBigInt(100000), NewBigInt(100000), BigInt0},
{NewBigInt(0), NewBigInt(-100000), NewBigInt(100000)},
}
for _, table := range tables {
val := table.a.Sub(table.b)
if !val.IsEqual(table.result) {
t.Errorf("input %v, %v. Expected sum %v, got sum %v", table.a, table.b, table.result,
val)
}
}
}
func TestBigInt_Mult(t *testing.T) {
tables := []struct {
a BigInt
b BigInt
result BigInt
}{
{BigInt0, BigInt1, BigInt0},
{BigInt1, NewBigInt(-1), NewBigInt(-1)},
{NewBigInt(-1), NewBigInt(-1), BigInt1},
}
for _, table := range tables {
val := table.a.Mult(table.b)
if !val.IsEqual(table.result) {
t.Errorf("input %v, %v. Expected product %v, got product %v", table.a, table.b, table.result,
val)
}
}
}
func TestBigInt_MultInt(t *testing.T) {
tables := []struct {
a BigInt
b int64
result BigInt
}{
{BigInt0, 10000, BigInt0},
{BigInt1, 10000, NewBigInt(10000)},
{BigInt1, -1, NewBigInt(-1)},
}
for _, table := range tables {
val := table.a.MultInt64(table.b)
if !val.IsEqual(table.result) {
t.Errorf("input %v, %v. Expected product %v, got product %v", table.a, table.b,
table.result, val)
}
}
}
func TestBigInt_Div(t *testing.T) {
tables := []struct {
a BigInt
b BigInt
result BigInt
}{
{BigInt0, BigInt1, BigInt0},
{BigInt1, NewBigInt(-1), NewBigInt(-1)},
{BigInt1, NewBigInt(-2), NewBigInt(0)},
{NewBigInt(1000), NewBigInt(2), NewBigInt(500)},
}
for _, table := range tables {
val := table.a.Div(table.b)
if !val.IsEqual(table.result) {
t.Errorf("input %v, %v. Expected quotient %v, got quotient %v", table.a,
table.b, table.result, val)
}
}
}
func TestBigInt_DivUint64(t *testing.T) {
tables := []struct {
a BigInt
b uint64
result BigInt
}{
{BigInt0, 10000, BigInt0},
{BigInt1, 10000, BigInt0},
{NewBigInt(500), 2, NewBigInt(250)},
{NewBigInt(500), 3, NewBigInt(166)},
}
for _, table := range tables {
val := table.a.DivUint64(table.b)
if !val.IsEqual(table.result) {
t.Errorf("input %v, %v. Expected quotient %v, got quotient %v", table.a,
table.b, table.result, val)
}
}
}
func TestBigInt_Cmp(t *testing.T) {
tables := []struct {
a int64
b int64
result int
}{
{-1, 0, -1},
{0, 0, 0},
{1, 0, 1},
}
for _, table := range tables {
val := NewBigInt(table.a).Cmp(NewBigInt(table.b))
if val != table.result {
t.Errorf("error: comparison bettwen %v and %v should result %v instead of %v",
table.a, table.b, table.result, val)
}
}
}
func TestCmp(t *testing.T) {
tables := []struct {
a int64
b int64
result int
}{
{200, 100, 1},
{100, 200, -1},
{100, 100, 0},
}
for _, table := range tables {
val := NewBigInt(table.a).Cmp(NewBigInt(table.b))
if val != table.result {
t.Errorf("error comparing between %d and %d, expected %d, got %d",
table.a, table.b, table.result, val)
}
}
}
func TestBigInt_DivWithFloatResult(t *testing.T) {
tables := []struct {
a int64
b int64
result float64
}{
{10000, 300, float64(10000) / float64(300)},
{73846123, 321, float64(73846123) / float64(321)},
{938381398213, 738321338211, float64(938381398213) / float64(738321338211)},
}
for _, table := range tables {
got := NewBigInt(table.a).DivWithFloatResult(NewBigInt(table.b))
if got != table.result {
t.Errorf("Division result does not match. Expected %v, got %v", table.result, got)
}
}
}
func TestBigInt_AddInt64(t *testing.T) {
tables := []struct {
a int64
b int64
result BigInt
}{
{1000, 300, NewBigInt(1300)},
{-50, -100, NewBigInt(-150)},
{0, -100, NewBigInt(-100)},
}
for _, table := range tables {
got := NewBigInt(table.a).AddInt64(table.b)
if !got.IsEqual(table.result) {
t.Errorf("error AddInt64. Expected %v, got %v", table.result, got)
}
}
}
func TestBigInt_AddUint64(t *testing.T) {
tables := []struct {
a uint64
b uint64
result BigInt
}{
{240000, 31000, NewBigInt(240000 + 31000)},
{300, 200, NewBigInt(500)},
{0, 0, NewBigInt(0)},
}
for _, table := range tables {
got := NewBigIntUint64(table.a).AddUint64(table.b)
if !got.IsEqual(table.result) {
t.Errorf("error AddUint64. Expected %v, got %v", table.result, got)
}
}
}
func TestBigInt_SubInt64(t *testing.T) {
tables := []struct {
a int64
b int64
result BigInt
}{
{1000, 300, NewBigInt(1000 - 300)},
{-50, -100, NewBigInt(-50 - -100)},
{0, -100, NewBigInt(0 - -100)},
}
for _, table := range tables {
got := NewBigInt(table.a).SubInt64(table.b)
if !got.IsEqual(table.result) {
t.Errorf("error SubInt64. Expected %v, got %v", table.result, got)
}
}
}
func TestBigInt_SubUint64(t *testing.T) {
tables := []struct {
a uint64
b uint64
result BigInt
}{
{240000, 31000, NewBigInt(240000 - 31000)},
{300, 200, NewBigInt(300 - 200)},
{0, 0, NewBigInt(0)},
}
for _, table := range tables {
got := NewBigIntUint64(table.a).SubUint64(table.b)
if !got.IsEqual(table.result) {
t.Errorf("error SubUint64. Expected %v, got %v", table.result, got)
}
}
}
func TestBigInt_MultFloat64(t *testing.T) {
tables := []struct {
a float64
b float64
result BigInt
}{
{100, 0, NewBigInt(100 * 0)},
{0, 500, NewBigInt(0 * 500)},
{100, 50.5, NewBigInt(50.5 * 100)},
{100, math.NaN(), NewBigInt(100)},
}
for _, table := range tables {
got := NewBigIntFloat64(table.a).MultFloat64(table.b)
if !got.IsEqual(table.result) {
t.Errorf("error MultFloat64. Expected %v, got %v", table.result, got)
}
}
}
|
josebright/tulip_foundation_website
|
resources/js/react/Components/CountDown/EventTimer.js
|
<reponame>josebright/tulip_foundation_website
import React, { Fragment, useState, useEffect } from 'react';
export default function EventTimer({ events }) {
const [DayTime, setDay] = useState('00');
const [Hrs, setHrs] = useState('00');
const [Min, setMin] = useState('00');
const [Sec, setSec] = useState('00');
let interval = React.useRef();
const countDown = () => {
interval = setInterval(() => {
const now = new Date().getTime();
const event = new Date(events).getTime();
const daysSeconds = event - now;
let sec = Math.floor(daysSeconds / 1000);
let min = Math.floor(sec / 60);
let hrs = Math.floor(min / 60);
let days = Math.floor(hrs / 24);
sec %= 60;
min %= 60;
hrs %= 24;
sec = sec < 10 ? '0' + sec : sec;
min = min < 10 ? '0' + min : min;
hrs = hrs < 10 ? '0' + hrs : hrs;
if (daysSeconds < 0) {
clearInterval(interval.current);
} else {
setDay(days);
setHrs(hrs);
setMin(min);
setSec(sec);
clearInterval(interval.current);
}
}, 1000);
clearInterval(interval.current);
};
useEffect(() => {
countDown();
return () => clearTimeout(countDown);
});
return (
<div>
<div className='timer'>
<div>
<h3>
Count Every Second <br />
Until the Event
</h3>
</div>
{/* {console.log(event)} */}
{Sec ? (
<>
<div className='row'>
<div className='col-6 col-lg-3'>
{DayTime ? <span> {`${DayTime} Days`}</span> : null}
</div>
<div className='col-6 col-lg-3'>
{Hrs ? <span>{`${Hrs} Hours`}</span> : null}
</div>
<div className='col-6 col-lg-3'>
{Min ? <span>{`${Min} Mins`}</span> : null}
</div>
<div className='col-6 col-lg-3'>
{Sec ? <span>{`${Sec} Secs`}</span> : null}
</div>
</div>
</>
) : null}
</div>
</div>
);
}
|
LogSentinel/sentineldb-java-client
|
src/main/java/com/logsentinel/sentineldb/model/ChangePasswordRequest.java
|
<reponame>LogSentinel/sentineldb-java-client
/*
* SentinelDB RESTful API
* Read more at https://docs.sentineldb.io
*
* OpenAPI spec version: 1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.logsentinel.sentineldb.model;
import java.util.Objects;
import java.util.Arrays;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* ChangePasswordRequest
*/
public class ChangePasswordRequest {
@JsonProperty("newPassword")
private String newPassword = null;
@JsonProperty("oldPassword")
private String oldPassword = null;
public ChangePasswordRequest newPassword(String newPassword) {
this.newPassword = <PASSWORD>Password;
return this;
}
/**
* Get newPassword
* @return newPassword
**/
@ApiModelProperty(value = "")
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public ChangePasswordRequest oldPassword(String oldPassword) {
this.oldPassword = oldPassword;
return this;
}
/**
* Get oldPassword
* @return oldPassword
**/
@ApiModelProperty(value = "")
public String getOldPassword() {
return oldPassword;
}
public void setOldPassword(String oldPassword) {
this.oldPassword = oldPassword;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ChangePasswordRequest changePasswordRequest = (ChangePasswordRequest) o;
return Objects.equals(this.newPassword, changePasswordRequest.newPassword) &&
Objects.equals(this.oldPassword, changePasswordRequest.oldPassword);
}
@Override
public int hashCode() {
return Objects.hash(newPassword, oldPassword);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ChangePasswordRequest {\n");
sb.append(" newPassword: ").append(toIndentedString(newPassword)).append("\n");
sb.append(" oldPassword: ").append(toIndentedString(oldPassword)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
solnic/rom-relation
|
spec/unit/rom/relation/restrict_spec.rb
|
# encoding: utf-8
require 'spec_helper'
describe Relation, '#restrict' do
include_context 'Relation'
share_examples_for 'restricted relation' do
specify do
should eq([jane])
end
end
context 'with condition hash' do
subject { relation.restrict(name: 'Jane').to_a }
it_behaves_like 'restricted relation'
end
context 'with a block' do
subject { relation.restrict { |r| r.name.eq('Jane') }.to_a }
it_behaves_like 'restricted relation'
end
end
|
UnknownStudio/KnownDomain
|
graphics/src/main/java/engine/graphics/texture/ColorFormat.java
|
package engine.graphics.texture;
public enum ColorFormat {
RGBA8,
BGRA8,
RGB8,
BGR8,
RG8,
RED8,
RGB10_A2,
R11F_G11F_B10F,
RGBA32F,
RGBA16F,
RGB32F,
RGB16F,
RED32F,
RED16F,
RGBA32UI,
RED32UI,
RED16UI,
RED8UI,
DEPTH32,
DEPTH24,
DEPTH24_STENCIL8
}
|
jamesjmurtagh/direktiv
|
scripts/testing/tests/_Isolates/isolate-validate/main.go
|
<reponame>jamesjmurtagh/direktiv
/*
Validate and sets plain varaibles
*/
package main
import (
"bytes"
"os"
"encoding/gob"
"encoding/json"
"fmt"
"io/ioutil"
)
const code = "com.%s.error"
type isolateInput struct {
Validate []file `json:"validate"`
Setter []variable `json:"set"`
}
type file struct {
Key string `json:"key"`
Value string `json:"value"`
}
type variable struct {
Key string `json:"key"`
Value string `json:"value"`
Scope string `json:"scope"`
}
// output for the requester container
type output struct {
}
func Log(msg string) {
fmt.Println(msg)
if logf == nil {
return
}
fmt.Fprintln(logf, msg)
}
var hasFailed bool
func Error(code, msg string) {
Log(fmt.Sprintf("ERROR: %s; %s", code, msg))
if hasFailed {
return
}
hasFailed = true
m := map[string]string{
"code": code,
"msg": msg,
}
data, _ := json.Marshal(m)
err := ioutil.WriteFile("/direktiv-data/error.json", data, 0755)
if err != nil {
Error("", err.Error())
}
}
func Respond(data []byte) {
err := ioutil.WriteFile("/direktiv-data/output.json", data, 0755)
if err != nil {
Error("", err.Error())
}
}
func GetBytes(key interface{}) ([]byte, error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(key)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func Request(input []byte) {
obj := new(isolateInput)
err := json.Unmarshal(input, obj)
if err != nil {
Error(fmt.Sprintf(code, "unmarshal-input"), err.Error())
return
}
// Validate Variables
for _, v := range obj.Validate {
Log(fmt.Sprintf("validating %s", v.Key))
path := fmt.Sprintf("/direktiv-data/vars/%s", v.Key)
f, err := ioutil.ReadFile(path)
if err != nil {
Error(fmt.Sprintf(code, "bad-path"), err.Error())
return
}
if string(f) != v.Value {
Log("validation failed")
Log(fmt.Sprintf("found value = %s", string(f)))
Log(fmt.Sprintf("given value = %s", v.Value))
Error(fmt.Sprintf(code, "value-mismatch"), fmt.Sprintf("var %s does not match value inside %s", v.Key, path))
return
}
}
// Set Variables
for _, v := range obj.Setter {
Log(fmt.Sprintf("validating %s", v.Key))
path := fmt.Sprintf("/direktiv-data/vars/out/%s/%s", v.Scope, v.Key)
err = ioutil.WriteFile(path, []byte(v.Value), 0644)
if err != nil {
Error(fmt.Sprintf(code, "bad-write"), err.Error())
return
}
}
Respond([]byte{})
}
var logf *os.File
func initialize() error {
var err error
logf, err = os.Create("/direktiv-data/out.log")
if err != nil {
return err
}
return nil
}
func cleanup() {
if logf != nil {
logf.Close()
}
f, err := os.Create("/direktiv-data/done")
if err == nil {
f.Close()
}
}
func main() {
err := initialize()
if err != nil {
Error("", err.Error())
return
}
defer cleanup()
input, err := ioutil.ReadFile("/direktiv-data/input.json")
if err != nil {
Error("", err.Error())
return
}
Log(fmt.Sprintf("INPUT: %s\n", input))
Request(input)
}
|
iduart/smefys
|
src/pages/verify-account.js
|
import React, { useState } from "react"
import { Auth } from 'aws-amplify';
import queryString from 'query-string';
import { Link, navigate } from 'gatsby'
import styled from "styled-components"
import { Logo } from "../components/Icons"
import { Input } from "../components/Input/Input"
import { PrimaryButton } from "../components/Button/Button"
const Page = styled.div`
padding: 2rem;
display: flex;
flex-flow: column nowrap;
align-items: center;
font-family: arial;
color: #7C7C7C;
.user-icon {
margin-top: 1.2rem;
}
`
const LoginForm = styled.form`
display: flex;
width: 100%;
margin-top: 0.5rem;
margin-bottom: 2rem;
flex-flow: column nowrap;
align-items: center;
input {
width: 100%;
&:first-child {
margin-top: 1rem;
}
margin-bottom: 1rem;
}
button {
margin-top: 2rem;
}
`;
const Footer = styled.div`
display: flex;
flex-flow: column nowrap;
align-items: center;
a {
color: #7C7C7C;
margin-bottom: 1.8rem;
text-decoration: underline;
}
`;
const ConfirmationMessage = styled.div`
text-align: center;
margin-top: 1rem;
`
const VerifyAccountPage = ({ location }) => {
const [code, setCode] = useState('');
const query = queryString.parse(location.search)
const { username } = query;
const verify = async (e) => {
e.preventDefault();
if (!username || !code) {
alert('No se encontró un nombre de usuario o codigo para verificar');
return;
}
try {
await Auth.confirmSignUp(username, code);
navigate('/', { hola: 'mindo '})
} catch(error) {
alert('Codigo no valido');
}
}
return (
<Page>
<div className="logo">
<Logo width="150" height="100" />
</div>
<ConfirmationMessage>
Un código de confirmación fue enviado al correo <b>{username}</b>
</ConfirmationMessage>
<LoginForm>
<Input type="text" placeholder="CÓDIGO" onChange={ event => setCode(event.target.value)} />
<PrimaryButton onClick={verify}>ENVIAR</PrimaryButton>
</LoginForm>
<Footer>
Ya tienes cuenta?<Link to="/"> Ingresa</Link>
</Footer>
</Page>
)
}
export default VerifyAccountPage
|
LittleShrimp1987/frostmourne
|
frostmourne-monitor/src/main/java/com/autohome/frostmourne/monitor/controller/AdminController.java
|
<reponame>LittleShrimp1987/frostmourne<filename>frostmourne-monitor/src/main/java/com/autohome/frostmourne/monitor/controller/AdminController.java<gh_stars>100-1000
package com.autohome.frostmourne.monitor.controller;
import javax.annotation.Resource;
import com.autohome.frostmourne.core.contract.PagerContract;
import com.autohome.frostmourne.core.contract.Protocol;
import com.autohome.frostmourne.monitor.contract.AlarmContract;
import com.autohome.frostmourne.monitor.dao.mybatis.frostmourne.domain.Alarm;
import com.autohome.frostmourne.monitor.service.admin.IAlarmAdminService;
import com.autohome.frostmourne.monitor.tool.AuthTool;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = {"/admin", "/api/monitor-api/admin"})
public class AdminController {
@Resource
private IAlarmAdminService alarmAdminService;
@RequestMapping(value = "/save", method = RequestMethod.POST)
public Protocol<Boolean> save(@RequestParam(value = "_appId", required = true) String _appId,
@RequestBody AlarmContract alarmContract) {
alarmContract.setOperator(AuthTool.currentUser().getAccount());
boolean result = alarmAdminService.atomicSave(alarmContract);
return new Protocol<>(result);
}
@RequestMapping(value = "/saveAnother", method = RequestMethod.POST)
public Protocol<Boolean> saveAnother(@RequestParam(value = "_appId", required = true) String _appId,
@RequestBody AlarmContract alarmContract) {
alarmContract.setOperator(AuthTool.currentUser().getAccount());
alarmContract.setId(null);
boolean result = alarmAdminService.atomicSave(alarmContract);
return new Protocol<>(result);
}
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public Protocol<Boolean> delete(@RequestParam(value = "_appId", required = true) String _appId,
@RequestParam(value = "alarmId", required = true) Long alarmId) {
boolean result = alarmAdminService.delete(alarmId);
return new Protocol<>(result);
}
@RequestMapping(value = "/open", method = RequestMethod.POST)
public Protocol<Boolean> open(@RequestParam(value = "_appId", required = true) String _appId,
@RequestParam(value = "alarmId", required = true) Long alarmId) {
boolean result = alarmAdminService.open(alarmId);
return new Protocol<>(result);
}
@RequestMapping(value = "/close", method = RequestMethod.POST)
public Protocol<Boolean> close(@RequestParam(value = "_appId", required = true) String _appId,
@RequestParam(value = "alarmId", required = true) Long alarmId) {
boolean result = alarmAdminService.close(alarmId);
return new Protocol<>(result);
}
@RequestMapping(value = "/findById", method = RequestMethod.GET)
public Protocol<AlarmContract> findById(@RequestParam(value = "_appId", required = true) String _appId,
@RequestParam(value = "alarmId", required = true) Long alarmId) {
AlarmContract alarmContract = this.alarmAdminService.findById(alarmId);
if (alarmContract == null) {
return new Protocol<>(404, "监控不存在");
}
return new Protocol<>(alarmContract);
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public Protocol<PagerContract<Alarm>> list(String _appId, int pageIndex, int pageSize,
Long alarmId, String name, String teamName, String status,
Long serviceId) {
PagerContract<Alarm> pagerContract = this.alarmAdminService.find(pageIndex, pageSize, alarmId, name, teamName, status, serviceId);
return new Protocol<>(pagerContract);
}
}
|
fishKingYu/homeAndSchool
|
jiaxiaohuiDemo/jiaxiaohuiDemo/Class/Module/Home/JHHomeViewController.h
|
//
// JHHomeViewController.h
// jiaxiaohuiDemo
//
// Created by 陈钰全 on 16/6/15.
// Copyright © 2016年 jiaXiaoHui. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface JHHomeViewController : UIViewController
@end
|
ealuna/pedimap
|
public/assets/js/chart1.js
|
/**
* Created by <NAME> on 03/10/17.
*/
var ctx = document.getElementById('myChart').getContext('2d');
function GenerarReporte() {
$.ajax({
type: 'POST',
url: '/terranorte/app/reporte/indicador1',
contentType: "application/json",
data: JSON.stringify({fechainicial: init, fechafinal: to}),
success: function (result) {
console.log(result);
ExtraerDatos(result);
CrearTabla(result);
}
});
}
function ExtraerDatos(result) {
var pedidos = 0;
var cumplidos = 0;
for (var i = 0; i < result.length; i++) {
pedidos += result[i].pedidos;
cumplidos += result[i].cumplidos;
}
CrearGrafico(cumplidos, pedidos - cumplidos );
}
function CrearGrafico(a, b) {
var data = {
datasets: [{
data: [b, a],
backgroundColor: [
'rgb(209, 41, 44)',
'rgb(16, 209, 69)'
]
}],
labels: [
'No cumplidos a tiempo',
'Cumplidos a tiempo'
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'pie',
data: data,
options: {
legend: {position: 'bottom'},
responsive: true,
maintainAspectRatio: false,
pieceLabel: {
render: 'percentage',
fontColor: ['white', 'white'],
precision: 2
}
}
});
}
function CrearTabla(data) {
var clientes = $('#detalle').DataTable({
'destroy': true,
'language': {
"url": "http://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
},
dom: 'frtip',
"pageLength": 50,
"paging": true,
'filter': true,
responsive: true,
'stateSave': false,
data: data,
'columns': [
{data: 'fecha'},
{data: 'pedidos'},
{data: 'cumplidos'},
{data: 'resultado'}
] /*
"columnDefs": [
{
"targets": [9],
"data": "anulado",
"render": function (data, type, row) {
if (data === 0) {
return "<span class='label label-success'>Activo</span>";
} else if (data === 1) {
return "<span class='label label-danger'>Anulado</span>";
}
}
}
]*/
});
new $.fn.dataTable.FixedHeader(clientes);
}
/*
var data = {
datasets: [{
data: [30, 70],
backgroundColor: [
'rgb(209, 41, 44)',
'rgb(16, 209, 69)'
]
}],
labels: [
'No cumplidos a tiempo',
'Cumplidos a tiempo'
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'pie',
data: data,
options: {
legend: {position: 'bottom'},
responsive: true,
maintainAspectRatio: false,
pieceLabel: {
render: 'percentage',
fontColor: ['white', 'white'],
precision: 2
}
}
});
*/
|
AlberLC/qt-app
|
utilities/searchs.py
|
from difflib import SequenceMatcher
from utilities.various import operators, normalize, split_operator_filter, to_date, to_number, NumericFilter, DateFilter
def match_ratio(string_a, string_b):
return SequenceMatcher(None, string_a.lower(), string_b.lower()).ratio()
def match_all_words(line_words, item_words):
if line_words:
coincidences = 0
objective = len(line_words)
for line_word in line_words:
for item_word in item_words:
if line_word in item_word or match_ratio(line_word, item_word) > 0.7:
coincidences += 1
break
if coincidences == objective:
break
else:
return False
return True
def filtered_items(items, text_line):
filtered_items = []
line_words = set(normalize(text_line).split())
for i, item in enumerate(items):
item_words = normalize(item).split()
if match_all_words(line_words, item_words):
filtered_items.append(item)
return filtered_items
def rows_indices_filtered(items, text_line, my_strings=None):
indices = []
line_words = set(normalize(text_line).split())
discards = {'-', '<', '>', '=', '<=', '>=', '=<', '=>'}
line_words -= discards
positive_words = set()
negative_words = set()
prices = set()
powers = set()
dates = set()
# Classify line sub-strings in their respective sets
for word in line_words:
operator, data = split_operator_filter(word)
if word[0] == '-':
negative_words.add(word[1:])
elif operator:
if data:
date = to_date(data)
if date:
dates.add(DateFilter(operator, date))
elif data[-1].lower() == 'w':
powers.add(NumericFilter(operator, to_number(data[:-1])))
else:
prices.add(NumericFilter(operator, to_number(data)))
else:
positive_words.add(word)
for i, item in enumerate(items):
item_words = item.get_keywords(my_strings)
skip = False
if skip:
continue
# Discard dates out of range
for date in dates:
if (
not operators[date.operator](item.date_quotation, date.date) and
not operators[date.operator](item.date_validity, date.date)
):
skip = True
break
if skip:
continue
# Discard prices out of range
for price in prices:
if not operators[price.operator](item.price, price.number):
skip = True
break
if skip:
continue
# Discard powers out of range
for power in powers:
if (
not operators[power.operator](item.total_power, power.number) and
not operators[power.operator](item.panel_power, power.number)
):
skip = True
break
if skip:
continue
# Discard negative words
for negative_word in negative_words:
for item_word in item_words:
if negative_word in item_word:
skip = True
break
else:
continue
break
if skip:
continue
# Search positive words coincidences
if match_all_words(positive_words, item_words):
indices.append(i)
return indices
|
dhis2/maps-app
|
src/components/edit/shared/Labels.js
|
<gh_stars>10-100
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import i18n from '@dhis2/d2-i18n';
import cx from 'classnames';
import { Checkbox, FontStyle } from '../../core';
import styles from '../styles/LayerDialog.module.css';
import {
setLabels,
setLabelFontColor,
setLabelFontSize,
setLabelFontWeight,
setLabelFontStyle,
} from '../../../actions/layerEdit';
const Labels = ({
labels,
labelFontColor,
labelFontSize,
labelFontStyle,
labelFontWeight,
setLabels,
setLabelFontColor,
setLabelFontSize,
setLabelFontWeight,
setLabelFontStyle,
}) => {
return (
<div className={cx(styles.flexInnerColumnFlow)}>
<div>
<Checkbox
label={i18n.t('Labels')}
checked={labels}
onChange={setLabels}
/>
{labels && (
<FontStyle
color={labelFontColor}
size={labelFontSize}
weight={labelFontWeight}
fontStyle={labelFontStyle}
onColorChange={setLabelFontColor}
onSizeChange={setLabelFontSize}
onWeightChange={setLabelFontWeight}
onStyleChange={setLabelFontStyle}
/>
)}
</div>
</div>
);
};
Labels.propTypes = {
labels: PropTypes.bool,
labelFontColor: PropTypes.string,
labelFontSize: PropTypes.string,
labelFontStyle: PropTypes.string,
labelFontWeight: PropTypes.string,
setLabels: PropTypes.func.isRequired,
setLabelFontColor: PropTypes.func.isRequired,
setLabelFontSize: PropTypes.func.isRequired,
setLabelFontWeight: PropTypes.func.isRequired,
setLabelFontStyle: PropTypes.func.isRequired,
};
export default connect(
({ layerEdit }) => ({
labels: layerEdit.labels,
labelFontColor: layerEdit.labelFontColor,
labelFontSize: layerEdit.labelFontSize,
labelFontStyle: layerEdit.labelFontStyle,
labelFontWeight: layerEdit.labelFontWeight,
}),
{
setLabels,
setLabelFontColor,
setLabelFontSize,
setLabelFontWeight,
setLabelFontStyle,
}
)(Labels);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.