repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
jportway/shady-side
shader/src/test/scala/com/jsuereth/gl/shaders/TestMathTranslations.scala
<reponame>jportway/shady-side<filename>shader/src/test/scala/com/jsuereth/gl/shaders/TestMathTranslations.scala<gh_stars>10-100 package com.jsuereth.gl package shaders package testmathtranslation import org.junit.Test import org.junit.Assert._ import com.jsuereth.gl.math._ import com.jsuereth.gl.test.assertCleanEquals /** This is our target syntax. */ // Attempt at cel-shading import com.jsuereth.gl.math.{given _, _} object ExampleShader extends DslShaderProgram { // Used for vertex shader val lightPosition = Uniform[Vec3[Float]]() val eyePosition = Uniform[Vec3[Float]]() val (vertexShaderCode, fragmentShaderCode) = defineShaders { val inPosition = Input[Vec3[Float]](location=0) glPosition(Vec4(inPosition, 1)) // Fragment shader fragmentShader { val L = pow(1f, max(min(0f, lightPosition().x), lightPosition().y)) Output("color", 0, Vec4(L, L, L, 1f)) } } } class Test1 { @Test def extractVertexShaderProgramString(): Unit = { assertCleanEquals( """#version 300 es precision highp float; precision highp int; layout (location = 0) in vec3 inPosition; void main() { gl_Position = vec4(inPosition,1.0); }""", ExampleShader.vertexShaderCode) } @Test def extractFragmentShaderProgramString(): Unit = { assertCleanEquals( """#version 300 es precision highp float; precision highp int; uniform vec3 lightPosition; layout (location = 0) out vec4 color; void main() { float L = pow(1.0,max(min(0.0,(lightPosition).x),(lightPosition).y)); color = vec4(L,L,L,1.0); }""", ExampleShader.fragmentShaderCode) } }
insphereapplication/rhodes
platform/shared/ruby/vm_eval.c
<filename>platform/shared/ruby/vm_eval.c /********************************************************************** vm_eval.c - $Author: yugui $ created at: Sat May 24 16:02:32 JST 2008 Copyright (C) 1993-2007 <NAME> Copyright (C) 2000 Network Applied Communication Laboratory, Inc. Copyright (C) 2000 Information-technology Promotion Agency, Japan **********************************************************************/ static inline VALUE method_missing(VALUE obj, ID id, int argc, const VALUE *argv, int call_status); static inline VALUE rb_vm_set_finish_env(rb_thread_t * th); static inline VALUE vm_yield_with_cref(rb_thread_t *th, int argc, const VALUE *argv, const NODE *cref); static inline VALUE vm_yield(rb_thread_t *th, int argc, const VALUE *argv); static inline VALUE vm_backtrace(rb_thread_t *th, int lev); static NODE *vm_cref_push(rb_thread_t *th, VALUE klass, int noex); static VALUE vm_exec(rb_thread_t *th); static void vm_set_eval_stack(rb_thread_t * th, VALUE iseqval, const NODE *cref); static int vm_collect_local_variables_in_heap(rb_thread_t *th, VALUE *dfp, VALUE ary); static inline VALUE vm_call0(rb_thread_t * th, VALUE klass, VALUE recv, VALUE id, ID oid, int argc, const VALUE *argv, const NODE *body, int nosuper) { VALUE val; rb_block_t *blockptr = 0; if (0) printf("id: %s, nd: %s, argc: %d, passed: %p\n", rb_id2name(id), ruby_node_name(nd_type(body)), argc, (void *)th->passed_block); if (th->passed_block) { blockptr = th->passed_block; th->passed_block = 0; } again: switch (nd_type(body)) { case RUBY_VM_METHOD_NODE:{ rb_control_frame_t *reg_cfp; VALUE iseqval = (VALUE)body->nd_body; int i; rb_vm_set_finish_env(th); reg_cfp = th->cfp; CHECK_STACK_OVERFLOW(reg_cfp, argc + 1); *reg_cfp->sp++ = recv; for (i = 0; i < argc; i++) { *reg_cfp->sp++ = argv[i]; } vm_setup_method(th, reg_cfp, argc, blockptr, 0, iseqval, recv); val = vm_exec(th); break; } case NODE_CFUNC: { EXEC_EVENT_HOOK(th, RUBY_EVENT_C_CALL, recv, id, klass); { rb_control_frame_t *reg_cfp = th->cfp; rb_control_frame_t *cfp = vm_push_frame(th, 0, VM_FRAME_MAGIC_CFUNC, recv, (VALUE)blockptr, 0, reg_cfp->sp, 0, 1); cfp->method_id = oid; cfp->method_class = klass; val = call_cfunc(body->nd_cfnc, recv, body->nd_argc, argc, argv); if (reg_cfp != th->cfp + 1) { SDR2(reg_cfp); SDR2(th->cfp-5); rb_bug("cfp consistency error - call0"); th->cfp = reg_cfp; } vm_pop_frame(th); } EXEC_EVENT_HOOK(th, RUBY_EVENT_C_RETURN, recv, id, klass); break; } case NODE_ATTRSET:{ if (argc != 1) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc); } val = rb_ivar_set(recv, body->nd_vid, argv[0]); break; } case NODE_IVAR: { if (argc != 0) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc); } val = rb_attr_get(recv, body->nd_vid); break; } case NODE_BMETHOD:{ val = vm_call_bmethod(th, oid, body->nd_cval, recv, klass, argc, (VALUE *)argv, blockptr); break; } case NODE_ZSUPER:{ klass = RCLASS_SUPER(klass); if (!klass || !(body = rb_method_node(klass, id))) { return method_missing(recv, id, argc, argv, 0); } RUBY_VM_CHECK_INTS(); nosuper = CALL_SUPER; body = body->nd_body; goto again; } default: rb_bug("unsupported: vm_call0(%s)", ruby_node_name(nd_type(body))); } RUBY_VM_CHECK_INTS(); return val; } VALUE rb_vm_call(rb_thread_t * th, VALUE klass, VALUE recv, VALUE id, ID oid, int argc, const VALUE *argv, const NODE *body, int nosuper) { return vm_call0(th, klass, recv, id, oid, argc, argv, body, nosuper); } static inline VALUE vm_call_super(rb_thread_t * const th, const int argc, const VALUE * const argv) { VALUE recv = th->cfp->self; VALUE klass; ID id; NODE *body; rb_control_frame_t *cfp = th->cfp; if (!cfp->iseq) { klass = cfp->method_class; klass = RCLASS_SUPER(klass); if (klass == 0) { klass = vm_search_normal_superclass(cfp->method_class, recv); } id = cfp->method_id; } else { rb_bug("vm_call_super: should not be reached"); } body = rb_method_node(klass, id); /* this returns NODE_METHOD */ if (!body) { return method_missing(recv, id, argc, argv, 0); } return vm_call0(th, klass, recv, id, (ID)body->nd_file, argc, argv, body->nd_body, CALL_SUPER); } VALUE rb_call_super(int argc, const VALUE *argv) { PASS_PASSED_BLOCK(); return vm_call_super(GET_THREAD(), argc, argv); } static inline void stack_check(void) { rb_thread_t *th = GET_THREAD(); if (!rb_thread_raised_p(th, RAISED_STACKOVERFLOW) && ruby_stack_check()) { rb_thread_raised_set(th, RAISED_STACKOVERFLOW); rb_exc_raise(sysstack_error); } } static inline VALUE rb_call0(VALUE klass, VALUE recv, ID mid, int argc, const VALUE *argv, int scope, VALUE self) { NODE *body, *method; int noex; ID id = mid; struct cache_entry *ent; rb_thread_t *th = GET_THREAD(); if (!klass) { rb_raise(rb_eNotImpError, "method `%s' called on terminated object (%p)", rb_id2name(mid), (void *)recv); } /* is it in the method cache? */ ent = cache + EXPR1(klass, mid); if (ent->mid == mid && ent->klass == klass) { if (!ent->method) return method_missing(recv, mid, argc, argv, scope == 2 ? NOEX_VCALL : 0); id = ent->mid0; noex = ent->method->nd_noex; klass = ent->method->nd_clss; body = ent->method->nd_body; } else if ((method = rb_get_method_body(klass, id, &id)) != 0) { noex = method->nd_noex; klass = method->nd_clss; body = method->nd_body; } else { if (scope == 3) { return method_missing(recv, mid, argc, argv, NOEX_SUPER); } return method_missing(recv, mid, argc, argv, scope == 2 ? NOEX_VCALL : 0); } if (mid != idMethodMissing) { /* receiver specified form for private method */ if (UNLIKELY(noex)) { if (((noex & NOEX_MASK) & NOEX_PRIVATE) && scope == 0) { return method_missing(recv, mid, argc, argv, NOEX_PRIVATE); } /* self must be kind of a specified form for protected method */ if (((noex & NOEX_MASK) & NOEX_PROTECTED) && scope == 0) { VALUE defined_class = klass; if (TYPE(defined_class) == T_ICLASS) { defined_class = RBASIC(defined_class)->klass; } if (self == Qundef) { self = th->cfp->self; } if (!rb_obj_is_kind_of(self, rb_class_real(defined_class))) { return method_missing(recv, mid, argc, argv, NOEX_PROTECTED); } } if (NOEX_SAFE(noex) > th->safe_level) { rb_raise(rb_eSecurityError, "calling insecure method: %s", rb_id2name(mid)); } } } stack_check(); return vm_call0(th, klass, recv, mid, id, argc, argv, body, noex & NOEX_NOSUPER); } static inline VALUE rb_call(VALUE klass, VALUE recv, ID mid, int argc, const VALUE *argv, int scope) { return rb_call0(klass, recv, mid, argc, argv, scope, Qundef); } NORETURN(static void raise_method_missing(rb_thread_t *th, int argc, const VALUE *argv, VALUE obj, int call_status)); /* * call-seq: * obj.method_missing(symbol [, *args] ) => result * * Invoked by Ruby when <i>obj</i> is sent a message it cannot handle. * <i>symbol</i> is the symbol for the method called, and <i>args</i> * are any arguments that were passed to it. By default, the interpreter * raises an error when this method is called. However, it is possible * to override the method to provide more dynamic behavior. * If it is decided that a particular method should not be handled, then * <i>super</i> should be called, so that ancestors can pick up the * missing method. * The example below creates * a class <code>Roman</code>, which responds to methods with names * consisting of roman numerals, returning the corresponding integer * values. * * class Roman * def romanToInt(str) * # ... * end * def method_missing(methId) * str = methId.id2name * romanToInt(str) * end * end * * r = Roman.new * r.iv #=> 4 * r.xxiii #=> 23 * r.mm #=> 2000 */ static VALUE rb_method_missing(int argc, const VALUE *argv, VALUE obj) { rb_thread_t *th = GET_THREAD(); raise_method_missing(th, argc, argv, obj, th->method_missing_reason); return Qnil; /* not reached */ } #define NOEX_MISSING 0x80 static void raise_method_missing(rb_thread_t *th, int argc, const VALUE *argv, VALUE obj, int last_call_status) { ID id; VALUE exc = rb_eNoMethodError; const char *format = 0; if (argc == 0 || !SYMBOL_P(argv[0])) { rb_raise(rb_eArgError, "no id given"); } stack_check(); id = SYM2ID(argv[0]); if (last_call_status & NOEX_PRIVATE) { format = "private method `%s' called for %s"; } else if (last_call_status & NOEX_PROTECTED) { format = "protected method `%s' called for %s"; } else if (last_call_status & NOEX_VCALL) { format = "undefined local variable or method `%s' for %s"; exc = rb_eNameError; } else if (last_call_status & NOEX_SUPER) { format = "super: no superclass method `%s' for %s"; } if (!format) { format = "undefined method `%s' for %s"; } { int n = 0; VALUE args[3]; args[n++] = rb_funcall(rb_const_get(exc, rb_intern("message")), '!', 3, rb_str_new2(format), obj, argv[0]); args[n++] = argv[0]; if (exc == rb_eNoMethodError) { args[n++] = rb_ary_new4(argc - 1, argv + 1); } exc = rb_class_new_instance(n, args, exc); if (!(last_call_status & NOEX_MISSING)) { th->cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp); } rb_exc_raise(exc); } } static inline VALUE method_missing(VALUE obj, ID id, int argc, const VALUE *argv, int call_status) { VALUE *nargv, result, argv_ary = 0; rb_thread_t *th = GET_THREAD(); th->method_missing_reason = call_status; th->passed_block = 0; if (id == idMethodMissing) { raise_method_missing(th, argc, argv, obj, call_status | NOEX_MISSING); } else if (id == ID_ALLOCATOR) { rb_raise(rb_eTypeError, "allocator undefined for %s", rb_class2name(obj)); } if (argc < 0x100) { nargv = ALLOCA_N(VALUE, argc + 1); } else { argv_ary = rb_ary_tmp_new(argc + 1); nargv = RARRAY_PTR(argv_ary); } nargv[0] = ID2SYM(id); MEMCPY(nargv + 1, argv, VALUE, argc); result = rb_funcall2(obj, idMethodMissing, argc + 1, nargv); if (argv_ary) rb_ary_clear(argv_ary); return result; } void rb_raise_method_missing(rb_thread_t *th, int argc, VALUE *argv, VALUE obj, int call_status) { th->passed_block = 0; raise_method_missing(th, argc, argv, obj, call_status | NOEX_MISSING); } VALUE rb_apply(VALUE recv, ID mid, VALUE args) { int argc; VALUE *argv; argc = RARRAY_LEN(args); /* Assigns LONG, but argc is INT */ argv = ALLOCA_N(VALUE, argc); MEMCPY(argv, RARRAY_PTR(args), VALUE, argc); return rb_call(CLASS_OF(recv), recv, mid, argc, argv, CALL_FCALL); } VALUE rb_funcall(VALUE recv, ID mid, int n, ...) { VALUE *argv; va_list ar; va_init_list(ar, n); if (n > 0) { long i; argv = ALLOCA_N(VALUE, n); for (i = 0; i < n; i++) { argv[i] = va_arg(ar, VALUE); } va_end(ar); } else { argv = 0; } return rb_call(CLASS_OF(recv), recv, mid, n, argv, CALL_FCALL); } VALUE rb_funcall2(VALUE recv, ID mid, int argc, const VALUE *argv) { return rb_call(CLASS_OF(recv), recv, mid, argc, argv, CALL_FCALL); } VALUE rb_funcall3(VALUE recv, ID mid, int argc, const VALUE *argv) { return rb_call(CLASS_OF(recv), recv, mid, argc, argv, CALL_PUBLIC); } static VALUE send_internal(int argc, VALUE *argv, VALUE recv, int scope) { VALUE vid; VALUE self = RUBY_VM_PREVIOUS_CONTROL_FRAME(GET_THREAD()->cfp)->self; rb_thread_t *th = GET_THREAD(); if (argc == 0) { rb_raise(rb_eArgError, "no method name given"); } vid = *argv++; argc--; PASS_PASSED_BLOCK_TH(th); return rb_call0(CLASS_OF(recv), recv, rb_to_id(vid), argc, argv, scope, self); } /* * call-seq: * obj.send(symbol [, args...]) => obj * obj.__send__(symbol [, args...]) => obj * * Invokes the method identified by _symbol_, passing it any * arguments specified. You can use <code>__send__</code> if the name * +send+ clashes with an existing method in _obj_. * * class Klass * def hello(*args) * "Hello " + args.join(' ') * end * end * k = Klass.new * k.send :hello, "gentle", "readers" #=> "Hello gentle readers" */ VALUE rb_f_send(int argc, VALUE *argv, VALUE recv) { return send_internal(argc, argv, recv, NOEX_NOSUPER | NOEX_PRIVATE); } /* * call-seq: * obj.public_send(symbol [, args...]) => obj * * Invokes the method identified by _symbol_, passing it any * arguments specified. Unlike send, public_send calls public * methods only. * * 1.public_send(:puts, "hello") # causes NoMethodError */ VALUE rb_f_public_send(int argc, VALUE *argv, VALUE recv) { return send_internal(argc, argv, recv, NOEX_PUBLIC); } /* yield */ static inline VALUE rb_yield_0(int argc, const VALUE * argv) { return vm_yield(GET_THREAD(), argc, argv); } VALUE rb_yield(VALUE val) { if (val == Qundef) { return rb_yield_0(0, 0); } else { return rb_yield_0(1, &val); } } VALUE rb_yield_values(int n, ...) { if (n == 0) { return rb_yield_0(0, 0); } else { int i; VALUE *argv; va_list args; argv = ALLOCA_N(VALUE, n); va_init_list(args, n); for (i=0; i<n; i++) { argv[i] = va_arg(args, VALUE); } va_end(args); return rb_yield_0(n, argv); } } VALUE rb_yield_values2(int argc, const VALUE *argv) { return rb_yield_0(argc, argv); } VALUE rb_yield_splat(VALUE values) { VALUE tmp = rb_check_array_type(values); volatile VALUE v; if (NIL_P(tmp)) { rb_raise(rb_eArgError, "not an array"); } v = rb_yield_0(RARRAY_LEN(tmp), RARRAY_PTR(tmp)); return v; } static VALUE loop_i(void) { for (;;) { rb_yield_0(0, 0); } return Qnil; } /* * call-seq: * loop {|| block } * * Repeatedly executes the block. * * loop do * print "Input: " * line = gets * break if !line or line =~ /^qQ/ * # ... * end * * StopIteration raised in the block breaks the loop. */ static VALUE rb_f_loop(void) { rb_rescue2(loop_i, (VALUE)0, 0, 0, rb_eStopIteration, (VALUE)0); return Qnil; /* dummy */ } VALUE rb_iterate(VALUE (* it_proc) (VALUE), VALUE data1, VALUE (* bl_proc) (ANYARGS), VALUE data2) { int state; volatile VALUE retval = Qnil; NODE *node = NEW_IFUNC(bl_proc, data2); rb_thread_t *th = GET_THREAD(); rb_control_frame_t *cfp = th->cfp; TH_PUSH_TAG(th); state = TH_EXEC_TAG(); if (state == 0) { iter_retry: { rb_block_t *blockptr = RUBY_VM_GET_BLOCK_PTR_IN_CFP(th->cfp); blockptr->iseq = (void *)node; blockptr->proc = 0; th->passed_block = blockptr; } retval = (*it_proc) (data1); } else { VALUE err = th->errinfo; if (state == TAG_BREAK) { VALUE *escape_dfp = GET_THROWOBJ_CATCH_POINT(err); VALUE *cdfp = cfp->dfp; if (cdfp == escape_dfp) { state = 0; th->state = 0; th->errinfo = Qnil; th->cfp = cfp; } else{ /* SDR(); printf("%p, %p\n", cdfp, escape_dfp); */ } } else if (state == TAG_RETRY) { VALUE *escape_dfp = GET_THROWOBJ_CATCH_POINT(err); VALUE *cdfp = cfp->dfp; if (cdfp == escape_dfp) { state = 0; th->state = 0; th->errinfo = Qnil; th->cfp = cfp; goto iter_retry; } } } TH_POP_TAG(); switch (state) { case 0: break; default: TH_JUMP_TAG(th, state); } return retval; } struct iter_method_arg { VALUE obj; ID mid; int argc; VALUE *argv; }; static VALUE iterate_method(VALUE obj) { const struct iter_method_arg * arg = (struct iter_method_arg *) obj; return rb_call(CLASS_OF(arg->obj), arg->obj, arg->mid, arg->argc, arg->argv, CALL_FCALL); } VALUE rb_block_call(VALUE obj, ID mid, int argc, VALUE * argv, VALUE (*bl_proc) (ANYARGS), VALUE data2) { struct iter_method_arg arg; arg.obj = obj; arg.mid = mid; arg.argc = argc; arg.argv = argv; return rb_iterate(iterate_method, (VALUE)&arg, bl_proc, data2); } VALUE rb_each(VALUE obj) { return rb_call(CLASS_OF(obj), obj, idEach, 0, 0, CALL_FCALL); } /*RHO static*/ VALUE eval_string_with_cref(VALUE self, VALUE src, VALUE scope, NODE *cref, const char *file, int line) { int state; VALUE result = Qundef; VALUE envval; rb_binding_t *bind = 0; rb_thread_t *th = GET_THREAD(); rb_env_t *env = NULL; rb_block_t block; volatile int parse_in_eval; volatile int mild_compile_error; if (file == 0) { file = rb_sourcefile(); line = rb_sourceline(); } parse_in_eval = th->parse_in_eval; mild_compile_error = th->mild_compile_error; PUSH_TAG(); if ((state = EXEC_TAG()) == 0) { rb_iseq_t *iseq; volatile VALUE iseqval; if (scope != Qnil) { if (rb_obj_is_kind_of(scope, rb_cBinding)) { GetBindingPtr(scope, bind); envval = bind->env; } else { rb_raise(rb_eTypeError, "wrong argument type %s (expected Binding)", rb_obj_classname(scope)); } GetEnvPtr(envval, env); th->base_block = &env->block; } else { rb_control_frame_t *cfp = rb_vm_get_ruby_level_next_cfp(th, th->cfp); if (cfp != 0) { block = *RUBY_VM_GET_BLOCK_PTR_IN_CFP(cfp); th->base_block = &block; th->base_block->self = self; th->base_block->iseq = cfp->iseq; /* TODO */ } else { rb_raise(rb_eRuntimeError, "Can't eval on top of Fiber or Thread"); } } //RHO if ( TYPE(src) != T_STRING ){ iseqval = src; }else //RHO { /* make eval iseq */ th->parse_in_eval++; th->mild_compile_error++; iseqval = rb_iseq_compile(src, rb_str_new2(file), INT2FIX(line)); th->mild_compile_error--; th->parse_in_eval--; } vm_set_eval_stack(th, iseqval, cref); th->base_block = 0; if (0) { /* for debug */ printf("%s\n", RSTRING_PTR(rb_iseq_disasm(iseqval))); } /* save new env */ GetISeqPtr(iseqval, iseq); if (bind && iseq->local_size > 0) { bind->env = rb_vm_make_env_object(th, th->cfp); } /* kick */ CHECK_STACK_OVERFLOW(th->cfp, iseq->stack_max); result = vm_exec(th); } POP_TAG(); th->mild_compile_error = mild_compile_error; th->parse_in_eval = parse_in_eval; if (state) { if (state == TAG_RAISE) { VALUE errinfo = th->errinfo; if (strcmp(file, "(eval)") == 0) { VALUE mesg, errat, bt2; extern VALUE rb_get_backtrace(VALUE info); ID id_mesg; CONST_ID(id_mesg, "mesg"); errat = rb_get_backtrace(errinfo); mesg = rb_attr_get(errinfo, id_mesg); if (!NIL_P(errat) && TYPE(errat) == T_ARRAY && (bt2 = vm_backtrace(th, -2), RARRAY_LEN(bt2) > 0)) { if (!NIL_P(mesg) && TYPE(mesg) == T_STRING && !RSTRING_LEN(mesg)) { if (OBJ_FROZEN(mesg)) { VALUE m = rb_str_cat(rb_str_dup(RARRAY_PTR(errat)[0]), ": ", 2); rb_ivar_set(errinfo, id_mesg, rb_str_append(m, mesg)); } else { rb_str_update(mesg, 0, 0, rb_str_new2(": ")); rb_str_update(mesg, 0, 0, RARRAY_PTR(errat)[0]); } } RARRAY_PTR(errat)[0] = RARRAY_PTR(bt2)[0]; } } rb_exc_raise(errinfo); } JUMP_TAG(state); } return result; } static VALUE eval_string(VALUE self, VALUE src, VALUE scope, const char *file, int line) { return eval_string_with_cref(self, src, scope, 0, file, line); } /* * call-seq: * eval(string [, binding [, filename [,lineno]]]) => obj * * Evaluates the Ruby expression(s) in <em>string</em>. If * <em>binding</em> is given, the evaluation is performed in its * context. The binding may be a <code>Binding</code> object or a * <code>Proc</code> object. If the optional <em>filename</em> and * <em>lineno</em> parameters are present, they will be used when * reporting syntax errors. * * def getBinding(str) * return binding * end * str = "hello" * eval "str + ' Fred'" #=> "hello Fred" * eval "str + ' Fred'", getBinding("bye") #=> "bye Fred" */ VALUE rb_f_eval(int argc, VALUE *argv, VALUE self) { //RHO VALUE s = rb_gv_get("$_s"); VALUE sString = rb_funcall(s, rb_intern("to_s"),0); char *sockStr = StringValuePtr(sString); if( sockStr == NULL || strstr(sockStr,"TCPSocket") == NULL) { rb_raise(rb_eNotImpError, "Not implemented: eval is not supported."); } else { VALUE src, scope, vfile, vline; const char *file = "(eval)"; int line = 1; rb_scan_args(argc, argv, "13", &src, &scope, &vfile, &vline); if (rb_safe_level() >= 4) { StringValue(src); if (!NIL_P(scope) && !OBJ_TAINTED(scope)) { rb_raise(rb_eSecurityError, "Insecure: can't modify trusted binding"); } } else { SafeStringValue(src); } if (argc >= 3) { StringValue(vfile); } if (argc >= 4) { line = NUM2INT(vline); } if (!NIL_P(vfile)) file = RSTRING_PTR(vfile); return eval_string(self, src, scope, file, line); } //RHO } VALUE rb_eval_string(const char *str) { return eval_string(rb_vm_top_self(), rb_str_new2(str), Qnil, "(eval)", 1); } VALUE rb_eval_string_protect(const char *str, int *state) { return rb_protect((VALUE (*)(VALUE))rb_eval_string, (VALUE)str, state); } VALUE rb_eval_string_wrap(const char *str, int *state) { int status; rb_thread_t *th = GET_THREAD(); VALUE self = th->top_self; VALUE wrapper = th->top_wrapper; VALUE val; th->top_wrapper = rb_module_new(); th->top_self = rb_obj_clone(rb_vm_top_self()); rb_extend_object(th->top_self, th->top_wrapper); val = rb_eval_string_protect(str, &status); th->top_self = self; th->top_wrapper = wrapper; if (state) { *state = status; } else if (status) { JUMP_TAG(status); } return val; } VALUE rb_eval_cmd(VALUE cmd, VALUE arg, int level) { int state; VALUE val = Qnil; /* OK */ volatile int safe = rb_safe_level(); if (OBJ_TAINTED(cmd)) { level = 4; } if (TYPE(cmd) != T_STRING) { PUSH_TAG(); rb_set_safe_level_force(level); if ((state = EXEC_TAG()) == 0) { val = rb_funcall2(cmd, rb_intern("call"), RARRAY_LEN(arg), RARRAY_PTR(arg)); } POP_TAG(); rb_set_safe_level_force(safe); if (state) JUMP_TAG(state); return val; } PUSH_TAG(); if ((state = EXEC_TAG()) == 0) { val = eval_string(rb_vm_top_self(), cmd, Qnil, 0, 0); } POP_TAG(); rb_set_safe_level_force(safe); if (state) rb_vm_jump_tag_but_local_jump(state, val); return val; } /* block eval under the class/module context */ static VALUE yield_under(VALUE under, VALUE self, VALUE values) { rb_thread_t *th = GET_THREAD(); rb_block_t block, *blockptr; NODE *cref = vm_cref_push(th, under, NOEX_PUBLIC); if ((blockptr = GC_GUARDED_PTR_REF(th->cfp->lfp[0])) != 0) { block = *blockptr; block.self = self; th->cfp->lfp[0] = GC_GUARDED_PTR(&block); } if (values == Qundef) { return vm_yield_with_cref(th, 0, 0, cref); } else { return vm_yield_with_cref(th, RARRAY_LEN(values), RARRAY_PTR(values), cref); } } /* string eval under the class/module context */ static VALUE eval_under(VALUE under, VALUE self, VALUE src, const char *file, int line) { NODE *cref = vm_cref_push(GET_THREAD(), under, NOEX_PUBLIC); if (rb_safe_level() >= 4) { StringValue(src); } else { SafeStringValue(src); } return eval_string_with_cref(self, src, Qnil, cref, file, line); } static VALUE specific_eval(int argc, VALUE *argv, VALUE klass, VALUE self) { if (rb_block_given_p()) { if (argc > 0) { rb_raise(rb_eArgError, "wrong number of arguments (%d for 0)", argc); } return yield_under(klass, self, Qundef); } else { const char *file = "(eval)"; int line = 1; //RHO rb_raise(rb_eNotImpError, "Not implemented: only eval of block is supported."); //RHO if (argc == 0) { rb_raise(rb_eArgError, "block not supplied"); } else { if (rb_safe_level() >= 4) { StringValue(argv[0]); } else { SafeStringValue(argv[0]); } if (argc > 3) { const char *name = rb_id2name(rb_frame_callee()); rb_raise(rb_eArgError, "wrong number of arguments: %s(src) or %s{..}", name, name); } if (argc > 2) line = NUM2INT(argv[2]); if (argc > 1) { file = StringValuePtr(argv[1]); } } return eval_under(klass, self, argv[0], file, line); } } /* * call-seq: * obj.instance_eval(string [, filename [, lineno]] ) => obj * obj.instance_eval {| | block } => obj * * Evaluates a string containing Ruby source code, or the given block, * within the context of the receiver (_obj_). In order to set the * context, the variable +self+ is set to _obj_ while * the code is executing, giving the code access to _obj_'s * instance variables. In the version of <code>instance_eval</code> * that takes a +String+, the optional second and third * parameters supply a filename and starting line number that are used * when reporting compilation errors. * * class KlassWithSecret * def initialize * @secret = 99 * end * end * k = KlassWithSecret.new * k.instance_eval { @secret } #=> 99 */ VALUE rb_obj_instance_eval(int argc, VALUE *argv, VALUE self) { VALUE klass; if (SPECIAL_CONST_P(self)) { klass = Qnil; } else { klass = rb_singleton_class(self); } return specific_eval(argc, argv, klass, self); } /* * call-seq: * obj.instance_exec(arg...) {|var...| block } => obj * * Executes the given block within the context of the receiver * (_obj_). In order to set the context, the variable +self+ is set * to _obj_ while the code is executing, giving the code access to * _obj_'s instance variables. Arguments are passed as block parameters. * * class KlassWithSecret * def initialize * @secret = 99 * end * end * k = KlassWithSecret.new * k.instance_exec(5) {|x| @secret+x } #=> 104 */ VALUE rb_obj_instance_exec(int argc, VALUE *argv, VALUE self) { VALUE klass; if (SPECIAL_CONST_P(self)) { klass = Qnil; } else { klass = rb_singleton_class(self); } return yield_under(klass, self, rb_ary_new4(argc, argv)); } /* * call-seq: * mod.class_eval(string [, filename [, lineno]]) => obj * mod.module_eval {|| block } => obj * * Evaluates the string or block in the context of _mod_. This can * be used to add methods to a class. <code>module_eval</code> returns * the result of evaluating its argument. The optional _filename_ * and _lineno_ parameters set the text for error messages. * * class Thing * end * a = %q{def hello() "Hello there!" end} * Thing.module_eval(a) * puts Thing.new.hello() * Thing.module_eval("invalid code", "dummy", 123) * * <em>produces:</em> * * Hello there! * dummy:123:in `module_eval': undefined local variable * or method `code' for Thing:Class */ VALUE rb_mod_module_eval(int argc, VALUE *argv, VALUE mod) { return specific_eval(argc, argv, mod, mod); } /* * call-seq: * mod.module_exec(arg...) {|var...| block } => obj * mod.class_exec(arg...) {|var...| block } => obj * * Evaluates the given block in the context of the class/module. * The method defined in the block will belong to the receiver. * * class Thing * end * Thing.class_exec{ * def hello() "Hello there!" end * } * puts Thing.new.hello() * * <em>produces:</em> * * Hello there! */ VALUE rb_mod_module_exec(int argc, VALUE *argv, VALUE mod) { return yield_under(mod, mod, rb_ary_new4(argc, argv)); } NORETURN(static VALUE rb_f_throw _((int, VALUE *))); /* * call-seq: * throw(symbol [, obj]) * * Transfers control to the end of the active +catch+ block * waiting for _symbol_. Raises +NameError+ if there * is no +catch+ block for the symbol. The optional second * parameter supplies a return value for the +catch+ block, * which otherwise defaults to +nil+. For examples, see * <code>Kernel::catch</code>. */ static VALUE rb_f_throw(int argc, VALUE *argv) { VALUE tag, value; rb_thread_t *th = GET_THREAD(); struct rb_vm_tag *tt = th->tag; rb_scan_args(argc, argv, "11", &tag, &value); while (tt) { if (tt->tag == tag) { tt->retval = value; break; } tt = tt->prev; } if (!tt) { VALUE desc = rb_inspect(tag); rb_raise(rb_eArgError, "uncaught throw %s", RSTRING_PTR(desc)); } rb_trap_restore_mask(); th->errinfo = NEW_THROW_OBJECT(tag, 0, TAG_THROW); JUMP_TAG(TAG_THROW); #ifndef __GNUC__ return Qnil; /* not reached */ #endif } void rb_throw(const char *tag, VALUE val) { VALUE argv[2]; argv[0] = ID2SYM(rb_intern(tag)); argv[1] = val; rb_f_throw(2, argv); } void rb_throw_obj(VALUE tag, VALUE val) { VALUE argv[2]; argv[0] = tag; argv[1] = val; rb_f_throw(2, argv); } /* * call-seq: * catch(symbol) {| | block } > obj * * +catch+ executes its block. If a +throw+ is * executed, Ruby searches up its stack for a +catch+ block * with a tag corresponding to the +throw+'s * _symbol_. If found, that block is terminated, and * +catch+ returns the value given to +throw+. If * +throw+ is not called, the block terminates normally, and * the value of +catch+ is the value of the last expression * evaluated. +catch+ expressions may be nested, and the * +throw+ call need not be in lexical scope. * * def routine(n) * puts n * throw :done if n <= 0 * routine(n-1) * end * * * catch(:done) { routine(3) } * * <em>produces:</em> * * 3 * 2 * 1 * 0 */ static VALUE rb_f_catch(int argc, VALUE *argv) { VALUE tag; int state; VALUE val = Qnil; /* OK */ rb_thread_t *th = GET_THREAD(); rb_control_frame_t *saved_cfp = th->cfp; if (argc == 0) { tag = rb_obj_alloc(rb_cObject); } else { rb_scan_args(argc, argv, "01", &tag); } PUSH_TAG(); th->tag->tag = tag; if ((state = EXEC_TAG()) == 0) { val = rb_yield_0(1, &tag); } else if (state == TAG_THROW && RNODE(th->errinfo)->u1.value == tag) { th->cfp = saved_cfp; val = th->tag->retval; th->errinfo = Qnil; state = 0; } POP_TAG(); if (state) JUMP_TAG(state); return val; } static VALUE catch_null_i(VALUE dmy) { return rb_funcall(Qnil, rb_intern("catch"), 0, 0); } static VALUE catch_i(VALUE tag) { return rb_funcall(Qnil, rb_intern("catch"), 1, tag); } VALUE rb_catch(const char *tag, VALUE (*func)(), VALUE data) { if (!tag) { return rb_iterate(catch_null_i, 0, func, data); } return rb_iterate(catch_i, ID2SYM(rb_intern(tag)), func, data); } VALUE rb_catch_obj(VALUE tag, VALUE (*func)(), VALUE data) { return rb_iterate((VALUE (*)_((VALUE)))catch_i, tag, func, data); } /* * call-seq: * caller(start=1) => array * * Returns the current execution stack---an array containing strings in * the form ``<em>file:line</em>'' or ``<em>file:line: in * `method'</em>''. The optional _start_ parameter * determines the number of initial stack entries to omit from the * result. * * def a(skip) * caller(skip) * end * def b(skip) * a(skip) * end * def c(skip) * b(skip) * end * c(0) #=> ["prog:2:in `a'", "prog:5:in `b'", "prog:8:in `c'", "prog:10"] * c(1) #=> ["prog:5:in `b'", "prog:8:in `c'", "prog:11"] * c(2) #=> ["prog:8:in `c'", "prog:12"] * c(3) #=> ["prog:13"] */ static VALUE rb_f_caller(int argc, VALUE *argv) { VALUE level; int lev; rb_scan_args(argc, argv, "01", &level); if (NIL_P(level)) lev = 1; else lev = NUM2INT(level); if (lev < 0) rb_raise(rb_eArgError, "negative level (%d)", lev); return vm_backtrace(GET_THREAD(), lev); } void rb_backtrace(void) { long i; VALUE ary; ary = vm_backtrace(GET_THREAD(), -1); for (i = 0; i < RARRAY_LEN(ary); i++) { printf("\tfrom %s\n", RSTRING_PTR(RARRAY_PTR(ary)[i])); } } VALUE rb_make_backtrace(void) { return vm_backtrace(GET_THREAD(), -1); } /* * call-seq: * local_variables => array * * Returns the names of the current local variables. * * fred = 1 * for i in 1..10 * # ... * end * local_variables #=> ["fred", "i"] */ static VALUE rb_f_local_variables(void) { VALUE ary = rb_ary_new(); rb_thread_t *th = GET_THREAD(); rb_control_frame_t *cfp = vm_get_ruby_level_caller_cfp(th, RUBY_VM_PREVIOUS_CONTROL_FRAME(th->cfp)); int i; while (cfp) { if (cfp->iseq) { for (i = 0; i < cfp->iseq->local_table_size; i++) { ID lid = cfp->iseq->local_table[i]; if (lid) { const char *vname = rb_id2name(lid); /* should skip temporary variable */ if (vname) { rb_ary_push(ary, ID2SYM(lid)); } } } } if (cfp->lfp != cfp->dfp) { /* block */ VALUE *dfp = GC_GUARDED_PTR_REF(cfp->dfp[0]); if (vm_collect_local_variables_in_heap(th, dfp, ary)) { break; } else { while (cfp->dfp != dfp) { cfp = RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp); } } } else { break; } } return ary; } /* * call-seq: * block_given? => true or false * iterator? => true or false * * Returns <code>true</code> if <code>yield</code> would execute a * block in the current context. The <code>iterator?</code> form * is mildly deprecated. * * def try * if block_given? * yield * else * "no block" * end * end * try #=> "no block" * try { "hello" } #=> "hello" * try do "hello" end #=> "hello" */ VALUE rb_f_block_given_p(void) { rb_thread_t *th = GET_THREAD(); rb_control_frame_t *cfp = th->cfp; cfp = vm_get_ruby_level_caller_cfp(th, RUBY_VM_PREVIOUS_CONTROL_FRAME(cfp)); if (cfp != 0 && (cfp->lfp[0] & 0x02) == 0 && GC_GUARDED_PTR_REF(cfp->lfp[0])) { return Qtrue; } else { return Qfalse; } } void Init_vm_eval(void) { rb_define_global_function("eval", rb_f_eval, -1); rb_define_global_function("local_variables", rb_f_local_variables, 0); rb_define_global_function("iterator?", rb_f_block_given_p, 0); rb_define_global_function("block_given?", rb_f_block_given_p, 0); rb_define_global_function("catch", rb_f_catch, -1); rb_define_global_function("throw", rb_f_throw, -1); rb_define_global_function("loop", rb_f_loop, 0); rb_define_method(rb_cBasicObject, "instance_eval", rb_obj_instance_eval, -1); rb_define_method(rb_cBasicObject, "instance_exec", rb_obj_instance_exec, -1); rb_define_private_method(rb_cBasicObject, "method_missing", rb_method_missing, -1); rb_define_method(rb_cBasicObject, "__send__", rb_f_send, -1); rb_define_method(rb_mKernel, "send", rb_f_send, -1); rb_define_method(rb_mKernel, "public_send", rb_f_public_send, -1); rb_define_method(rb_cModule, "module_exec", rb_mod_module_exec, -1); rb_define_method(rb_cModule, "class_exec", rb_mod_module_exec, -1); rb_define_method(rb_cModule, "module_eval", rb_mod_module_eval, -1); rb_define_method(rb_cModule, "class_eval", rb_mod_module_eval, -1); rb_define_global_function("caller", rb_f_caller, -1); }
Chromico/bk-base
src/api/upizza/common/errorcodes.py
<filename>src/api/upizza/common/errorcodes.py # -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ class ErrorCode: # 数据平台的平台代码--7位错误码的前2位 BKDATA_PLAT_CODE = "15" # 数据平台子模块代码--7位错误码的3,4位 BKDATA_COMMON = "00" BKDATA_DATABUS = "06" BKDATA_DATAAPI_DATABUS = "70" BKDATA_DATAAPI_STREAM = "71" BKDATA_DATAAPI_BATCH = "72" BKDATA_DATAAPI_ADMIN = "73" BKDATA_DATAAPI_FLOW = "74" BKDATA_DATAAPI_JOBNAVI = "75" BKDATA_DATAAPI_ACCESS = "76" BKDATA_DATAAPI_COLLECTOR = "77" BKDATA_DATAAPI_STOREKIT = "78" BKDATA_DATAAPI_MODELFLOW = "79" BKDATA_DATAAPI_DATALAB = "80" BKDATA_DATAAPI_UDF = "81" BKDATA_DATAAPI_DATACUBE = "82" BKDATA_DATAAPI_RESOURCECENTER = "84" BKDATA_DATAAPI_CODECHECK = "85" BKDATA_STREAM = "08" BKDATA_BATCH = "09" BKDATA_DMONITOR = "10" BKDATA_AUTH = "11" BKDATA_MODELFLOW = "12" BKDATA_META = "21" BKDATA_METADATA = "30" BKDATA_UC = "31" BKDATA_DATAQUERY = "32" BKDATA_OLD = "33" BKDATA_SUPERSET = "34" BKDATA_DATAAPI_APPS = { "access": BKDATA_DATAAPI_ACCESS, "auth": BKDATA_AUTH, "dataquery": BKDATA_DATAQUERY, "dataflow": BKDATA_DATAAPI_FLOW, "storekit": BKDATA_DATAAPI_STOREKIT, "datamanage": BKDATA_DATAAPI_ADMIN, "databus": BKDATA_DATAAPI_DATABUS, "jobnavi": BKDATA_DATAAPI_JOBNAVI, "datalab": BKDATA_DATAAPI_DATALAB, "meta": BKDATA_META, "old": BKDATA_OLD, "codecheck": BKDATA_DATAAPI_CODECHECK, }
StudyDaedalus/ChatterBeta
app/src/main/java/com/blessingsoftware/chatterbeta/Adapter/NewFriendListAdapter.java
<gh_stars>0 package com.blessingsoftware.chatterbeta.Adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; import com.blessingsoftware.chatterbeta.Logs.Logs; import com.blessingsoftware.chatterbeta.Models.Beans.FriendInfo; import com.blessingsoftware.chatterbeta.Models.DAO.InvitationTable; import com.blessingsoftware.chatterbeta.Models.Model; import com.blessingsoftware.chatterbeta.R; import com.blessingsoftware.chatterbeta.ServerRequest.SRequest; import com.hyphenate.chat.EMClient; import com.hyphenate.exceptions.HyphenateException; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.util.HashMap; import java.util.List; import java.util.Map; public class NewFriendListAdapter extends BaseAdapter { private Context context; private List<Map<String, Object>> newFriendListData; public NewFriendListAdapter(Context context, List<Map<String, Object>> newFriendListData) { this.context = context; this.newFriendListData = newFriendListData; } @Override public int getCount() { return newFriendListData.size(); } @Override public Object getItem(int position) { return newFriendListData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = View.inflate(context, R.layout.listview_row_newfriend, null); TextView tvUserName = (TextView) convertView.findViewById(R.id.lvRow_newfriend_userName); TextView tvRequestMsg = (TextView) convertView.findViewById(R.id.lvRow_newfriend_requestMsg); tvUserName.setText(newFriendListData.get(position).get(InvitationTable.ACCOUNT).toString()); tvRequestMsg.setText(newFriendListData.get(position).get(InvitationTable.REASON).toString()); final Button btnAddNewFriend = (Button) convertView.findViewById(R.id.btn_add_new_friend); final TextView txtShowAdded = (TextView) convertView.findViewById(R.id.txtShowAdded); final String Account = (String) tvUserName.getText(); btnAddNewFriend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //按钮消失 btnAddNewFriend.setVisibility(View.GONE); //文字出现 txtShowAdded.setVisibility(View.VISIBLE); Model.getInstance().getGlobalTheadPool().execute(new Runnable() { @Override public void run() { try { EMClient.getInstance().contactManager().acceptInvitation(Account); Logs.d("Lss","成功"); //把邀请信息改为受理 Model.getInstance().getDbManager().getInvitataionTableDao().setAdded(Account); //去服务器获取用户信息 Model.getInstance().getGlobalTheadPool().execute(new Runnable() { @Override public void run() { Map<String, String> data = new HashMap<String, String>(); data.put("username", Account); data.put("type", "1"); //请求1,为获取个人信息 String reDate = SRequest.PostRequest(data); Logs.d("POST", reDate); try { JSONTokener jsonParser = new JSONTokener(reDate); JSONObject jsonObject = (JSONObject) jsonParser.nextValue(); if (jsonObject.isNull("error")) { //获取数据 FriendInfo friendInfo = new FriendInfo(); friendInfo.setFriendID(jsonObject.getInt("id")); friendInfo.setFriendAccount(jsonObject.getString("username")); friendInfo.setFriendName(jsonObject.getString("nickname")); friendInfo.setFriendSex(jsonObject.getString("sex")); friendInfo.setFriendLocation(jsonObject.getString("location")); Model.getInstance().getDbManager().getFriendTableDao().AddFriend(friendInfo); } } catch (JSONException e) { e.printStackTrace(); } } }); } catch (HyphenateException e) { e.printStackTrace(); } } }); } }); return convertView; } }
gromgit/homebrew-oldcore
Formula/hblock.rb
class Hblock < Formula desc "Adblocker that creates a hosts file from multiple sources" homepage "https://hblock.molinero.dev/" url "https://github.com/hectorm/hblock/archive/v3.3.2.tar.gz" sha256 "35bd4af1dbae3b57de6cede6c05f3d4ce25227b33a53358ef47c76a491304eb0" license "MIT" bottle do root_url "https://github.com/gromgit/homebrew-core-mojave/releases/download/hblock" sha256 cellar: :any_skip_relocation, mojave: "b408e7de0b8d0d3634deac27adcf630e303dcf03eee853a16af4b8b9d2f75714" end uses_from_macos "curl" def install system "make", "install", "prefix=#{prefix}", "bindir=#{bin}", "mandir=#{man}" end test do output = shell_output("#{bin}/hblock -H none -F none -S none -A none -D none -qO-") assert_match "Blocked domains:", output end end
siu91/myboot
myboot-demo-ganxu/ganxu-core/src/test/java/org/siu/myboot/server/controller/DemoControllerTests.java
package org.siu.myboot.server.controller; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; /** * 单元测试示例 * * @Author Siu * @Date 2020/2/16 13:00 * @Version 0.0.1 */ @SpringBootTest public class DemoControllerTests { private MockMvc mockMvc; @Before public void setUp() throws Exception { // mockMvc = MockMvcBuilders.standaloneSetup(new DemoController()).build(); } @Test public void getHello() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=小明") .accept(MediaType.APPLICATION_JSON_UTF8))/*.andDo(print())*/ .andExpect(MockMvcResultMatchers.content().string(Matchers.containsString("小明"))); } @Test public void getUser() throws Exception { String responseString = mockMvc.perform(MockMvcRequestBuilders.post("/getUser")) .andReturn().getResponse().getContentAsString(); System.out.println("result : "+responseString); } @Test public void getUserName() throws Exception { String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/get/UserName1")) .andReturn().getResponse().getContentAsString(); System.out.println("result : "+responseString); } @Test public void saveUsers() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/saveUser") .param("name","") .param("age","666") .param("pass","<PASSWORD>") ); } }
SoyaLeaf/calendarII
app/src/main/java/top/soyask/calendarii/ui/activity/LaunchActivity.java
package top.soyask.calendarii.ui.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import top.soyask.calendarii.MainActivity; import top.soyask.calendarii.R; import top.soyask.calendarii.global.Setting; import static top.soyask.calendarii.MainActivity.THEMES; public class LaunchActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { setupTheme(); super.onCreate(savedInstanceState); setContentView(R.layout.activity_theme); new Handler().postDelayed(() -> { Intent intent = new Intent(LaunchActivity.this, MainActivity.class); startActivity(intent); finish(); },200); } private void setupTheme() { int theme = THEMES[Setting.theme]; setTheme(theme); } }
linhaolin1/BlockServer
demo/plugins/exampleWeixinPlugin/src/main/java/com/lin/wechat/resp/WechatPayResp.java
<filename>demo/plugins/exampleWeixinPlugin/src/main/java/com/lin/wechat/resp/WechatPayResp.java package com.lin.wechat.resp; public class WechatPayResp { }
ParaParty/gugu-utils
src/main/java/com/warmthdawn/mod/gugu_utils/network/Messages.java
package com.warmthdawn.mod.gugu_utils.network; import com.warmthdawn.mod.gugu_utils.common.Enables; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side; public class Messages { public static SimpleNetworkWrapper INSTANCE; private static int ID = 0; private static int nextID() { return ID++; } public static void registerMessages(String channelName) { INSTANCE = NetworkRegistry.INSTANCE.newSimpleChannel(channelName); // Server side INSTANCE.registerMessage(PacketSetContainerSlot.Handler.class, PacketSetContainerSlot.class, nextID(), Side.SERVER); // Client side if (Enables.ASTRAL_SORCERY) INSTANCE.registerMessage(PacketStarlight.Handler.class, PacketStarlight.class, nextID(), Side.CLIENT); if (Enables.BOTANIA) { INSTANCE.registerMessage(PacketCollectorPostion.Handler.class, PacketCollectorPostion.class, nextID(), Side.CLIENT); INSTANCE.registerMessage(PacketMana.Handler.class, PacketMana.class, nextID(), Side.CLIENT); } INSTANCE.registerMessage(PacketParticles.Handler.class, PacketParticles.class, nextID(), Side.CLIENT); } }
acamacho82/softlayer-python
SoftLayer/CLI/block/replication/failover.py
<gh_stars>1-10 """Failover to a replicant volume.""" # :license: MIT, see LICENSE for more details. import click import SoftLayer from SoftLayer.CLI import environment @click.command() @click.argument('volume-id') @click.option('--replicant-id', help="ID of the replicant volume") @click.option('--immediate', is_flag=True, default=False, help="Failover to replicant immediately.") @environment.pass_env def cli(env, volume_id, replicant_id, immediate): """Failover a block volume to the given replicant volume.""" block_storage_manager = SoftLayer.BlockStorageManager(env.client) success = block_storage_manager.failover_to_replicant( volume_id, replicant_id, immediate ) if success: click.echo("Failover to replicant is now in progress.") else: click.echo("Failover operation could not be initiated.")
shuframework/framework-common
common-base/src/main/java/com/shuframework/designpattern/creation_factory/factorymethod/DivideOperateFactory.java
<reponame>shuframework/framework-common package com.shuframework.designpattern.creation_factory.factorymethod; import com.shuframework.designpattern.creation_factory.cacl.AddOperate; import com.shuframework.designpattern.creation_factory.cacl.DivideOperate; import com.shuframework.designpattern.creation_factory.cacl.OperateApi; import com.shuframework.designpattern.creation_factory.cacl.SubtractOperate; /** * @author shuheng */ public class DivideOperateFactory extends AbstractCaclOperate { @Override protected OperateApi getOperate() { return new DivideOperate(); } }
noidname01/EndOfWeb
backend/routes/srcs/in/account/auth/handlePending.js
<filename>backend/routes/srcs/in/account/auth/handlePending.js const { dbCatch, ErrorHandler } = require('../../../../error') const Login = require('../../../../Schemas/user_login') const Pending = require('../../../../Schemas/user_pending') const Visual = require('../../../../Schemas/user_visual_new') const asyncHandler = require('express-async-handler') /** * @api {post} /handlePending 身分驗證 * @apiName handlePending * @apiGroup In/auth * @apiDescription 身分驗證 * * @apiparam {String} account 學號 * @apiparam {Boolean} acceptUser 是否接受此用戶 * * @apiSuccess (204) - * * @apiError (404) {String} description user not found * @apiError (500) {String} description 資料庫錯誤 */ const manage = async (req, res, next) => { const { account, acceptUser } = req.body const pending = await Pending.findOne({ account }).catch(dbCatch) if (!pending) throw new ErrorHandler(404, 'user not found') if (!acceptUser) { await Pending.deleteMany({ account }).catch(dbCatch) return res.end() } const { username, userpsw, facebookID, email } = pending const { _id: visualID } = await Visual({ username, account, publicEmail: email, }) .save() .catch(dbCatch) await Login({ username, account, facebookID, userpsw, visual: visualID }) .save() .catch(async (e) => { await Visual.deleteOne({ _id: visualID }).catch(dbCatch) throw new ErrorHandler(500, '資料庫錯誤') }) await Pending.deleteMany({ account }).catch(dbCatch) return res.send({ account }) } const valid = require('../../../../middleware/validation') const rules = ['account', { filename: 'required', type: 'bool', field: 'acceptUser' }] module.exports = [valid(rules), asyncHandler(manage)]
AlhonGelios/AO
com/microsoft/schemas/office/visio/x2012/main/MastersType.java
package com.microsoft.schemas.office.visio.x2012.main; import com.microsoft.schemas.office.visio.x2012.main.MasterShortcutType; import com.microsoft.schemas.office.visio.x2012.main.MasterType; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URL; import java.util.List; import javax.xml.stream.XMLStreamReader; import org.apache.poi.POIXMLTypeLoader; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.xml.stream.XMLInputStream; import org.apache.xmlbeans.xml.stream.XMLStreamException; import org.w3c.dom.Node; public interface MastersType extends XmlObject { SchemaType type = (SchemaType)XmlBeans.typeSystemForClassLoader(MastersType.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sF1327CCA741569E70F9CA8C9AF9B44B2").resolveHandle("masterstypeaebatype"); List getMasterList(); MasterType[] getMasterArray(); MasterType getMasterArray(int var1); int sizeOfMasterArray(); void setMasterArray(MasterType[] var1); void setMasterArray(int var1, MasterType var2); MasterType insertNewMaster(int var1); MasterType addNewMaster(); void removeMaster(int var1); List getMasterShortcutList(); MasterShortcutType[] getMasterShortcutArray(); MasterShortcutType getMasterShortcutArray(int var1); int sizeOfMasterShortcutArray(); void setMasterShortcutArray(MasterShortcutType[] var1); void setMasterShortcutArray(int var1, MasterShortcutType var2); MasterShortcutType insertNewMasterShortcut(int var1); MasterShortcutType addNewMasterShortcut(); void removeMasterShortcut(int var1); public static final class Factory { public static MastersType newInstance() { return (MastersType)POIXMLTypeLoader.newInstance(MastersType.type, (XmlOptions)null); } public static MastersType newInstance(XmlOptions var0) { return (MastersType)POIXMLTypeLoader.newInstance(MastersType.type, var0); } public static MastersType parse(String var0) throws XmlException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, (XmlOptions)null); } public static MastersType parse(String var0, XmlOptions var1) throws XmlException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, var1); } public static MastersType parse(File var0) throws XmlException, IOException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, (XmlOptions)null); } public static MastersType parse(File var0, XmlOptions var1) throws XmlException, IOException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, var1); } public static MastersType parse(URL var0) throws XmlException, IOException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, (XmlOptions)null); } public static MastersType parse(URL var0, XmlOptions var1) throws XmlException, IOException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, var1); } public static MastersType parse(InputStream var0) throws XmlException, IOException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, (XmlOptions)null); } public static MastersType parse(InputStream var0, XmlOptions var1) throws XmlException, IOException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, var1); } public static MastersType parse(Reader var0) throws XmlException, IOException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, (XmlOptions)null); } public static MastersType parse(Reader var0, XmlOptions var1) throws XmlException, IOException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, var1); } public static MastersType parse(XMLStreamReader var0) throws XmlException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, (XmlOptions)null); } public static MastersType parse(XMLStreamReader var0, XmlOptions var1) throws XmlException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, var1); } public static MastersType parse(Node var0) throws XmlException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, (XmlOptions)null); } public static MastersType parse(Node var0, XmlOptions var1) throws XmlException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, var1); } public static MastersType parse(XMLInputStream var0) throws XmlException, XMLStreamException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, (XmlOptions)null); } public static MastersType parse(XMLInputStream var0, XmlOptions var1) throws XmlException, XMLStreamException { return (MastersType)POIXMLTypeLoader.parse(var0, MastersType.type, var1); } public static XMLInputStream newValidatingXMLInputStream(XMLInputStream var0) throws XmlException, XMLStreamException { return POIXMLTypeLoader.newValidatingXMLInputStream(var0, MastersType.type, (XmlOptions)null); } public static XMLInputStream newValidatingXMLInputStream(XMLInputStream var0, XmlOptions var1) throws XmlException, XMLStreamException { return POIXMLTypeLoader.newValidatingXMLInputStream(var0, MastersType.type, var1); } } }
fratbots/trainhack
actors.go
package main type Actor struct { Class Class Position Position Energy Energy Behavior Behavior Interaction Interaction Hp int Mp int Weapons []Weapon ManaRegen int ImagePath string MustBeDeleted bool Direction Direction } type Behavior func() *Action type Interaction func(target *Actor) *Action func (a *Actor) SetNextAction(action *Action) { a.Behavior = func() *Action { a.Behavior = nil return action } } func NewClassActor(stage *Stage, pos Position, direction Direction, class string) *Actor { classes := Classes() cls, ok := classes[class] if !ok { return nil } actor := &Actor{ Class: cls, Position: pos, Energy: Energy{Value: 0}, Behavior: nil, Interaction: nil, // нужно для игры с мыслями Direction: direction, } // default behavior if actor.Class.BehaviorInit != nil { actor.Behavior = actor.Class.BehaviorInit(stage, actor) } // default interaction if actor.Class.InteractionInit != nil { actor.Interaction = actor.Class.InteractionInit(stage, actor) } return actor } func GetActorState(actor *Actor) ActorState { return ActorState{ ClassName: actor.Class.Name, Position: actor.Position, Energy: actor.Energy, } } func NewHero() *Actor { return &Actor{ Class: Class{ Name: "hero", IsHero: true, Rune: '@', Speed: 1, }, Position: Position{0, 0}, Energy: Energy{Value: energyAction}, // full Behavior: nil, Interaction: nil, // TODO rid off: Hp: 100, Mp: 100, ManaRegen: 5, ImagePath: "./example/hero.png", Weapons: DefaultWeapons, } } func (a *Actor) GetHp() int { return a.Hp } func (a *Actor) GetMp() int { return a.Mp } func (a *Actor) GetWeapons() []Weapon { return a.Weapons } func (a *Actor) GetManaRegen() int { return a.ManaRegen } func (a *Actor) GetImagePath() string { return a.ImagePath } func (a *Actor) SetHp(hp int) { a.Hp = hp } func (a *Actor) SetMp(mp int) { a.Mp = mp }
Duffleman/tflgame-go
server/db/pagination.go
package db import ( "fmt" "tflgame" ) var mappedOrder = map[string]string{ "oldest_first": "ASC", "newest_first": "DESC", } type Pagination struct { before, after *string order string limit int } var defaultPagination = Pagination{ order: "ASC", limit: 100, } func NewPagination(p *tflgame.Pagination) (Pagination, error) { if p == nil { return defaultPagination, nil } order, ok := mappedOrder[p.Order] if !ok { return Pagination{}, fmt.Errorf("invalid pagination order: %s", p.Order) } return Pagination{ before: p.Before, after: p.After, order: order, limit: p.Limit, }, nil }
lindemann18/outfittery
src/app/shared/components/facebookSend/index.js
import angular from 'angular'; import ngFacebook from 'ng-facebook'; import referral from '../../services/resources/ps-referral'; import { COMPONENT_NAME, component } from './facebookSend.component'; require('./facebookSend.style'); const MODULE_NAME = 'ps-facebookSendComponent'; angular.module(MODULE_NAME, [ 'ngFacebook', referral ]).component(COMPONENT_NAME, component); export default MODULE_NAME;
jxg01713/zstack
header/src/main/java/org/zstack/header/core/Completion.java
package org.zstack.header.core; import org.zstack.header.errorcode.ErrorCode; public abstract class Completion extends AbstractCompletion { public Completion(AsyncBackup...backup) { super(backup); } public Completion() { super(); } public abstract void success(); public abstract void fail(ErrorCode errorCode); }
davidsli/boubei-tss
src/main/java/com/boubei/tss/um/action/ResourceAction.java
<reponame>davidsli/boubei-tss /* ================================================================== * Created [2009-08-29] by Jon.King * ================================================================== * TSS * ================================================================== * mailTo:<EMAIL> * Copyright (c) boubei.com, 2015-2018 * ================================================================== */ package com.boubei.tss.um.action; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.boubei.tss.framework.web.display.tree.TreeEncoder; import com.boubei.tss.framework.web.display.xform.XFormEncoder; import com.boubei.tss.framework.web.mvc.BaseActionSupport; import com.boubei.tss.um.UMConstants; import com.boubei.tss.um.entity.Application; import com.boubei.tss.um.entity.Operation; import com.boubei.tss.um.entity.ResourceType; import com.boubei.tss.um.entity.ResourceTypeRoot; import com.boubei.tss.um.helper.ApplicationTreeParser; import com.boubei.tss.um.service.IResourceService; /** * 应用资源管理相关Action对象 */ @Controller @RequestMapping("/auth/resource") public class ResourceAction extends BaseActionSupport { @Autowired private IResourceService resourceService; /** * 获取所有的Applicaton对象并转换成Tree相应的xml数据格式 */ @RequestMapping("/apps") public void getAllApplication2Tree(HttpServletResponse response) { Object applications = resourceService.findApplicationAndResourceType(); TreeEncoder treeEncoder = new TreeEncoder(applications, new ApplicationTreeParser()); treeEncoder.setNeedRootNode(false); print("AppSource", treeEncoder); } /** * 获取一个Application对象的明细信息 */ @RequestMapping(value = "/app/{id}", method = RequestMethod.GET) public void getOtherAppInfo(HttpServletResponse response, @PathVariable("id") Long id) { Application application; if(UMConstants.DEFAULT_NEW_ID.equals(id)) { application = new Application(); application.setApplicationType(UMConstants.OTHER_SYSTEM_APP); } else { application = resourceService.getApplicationById(id); } XFormEncoder xEncoder = new XFormEncoder(UMConstants.OTHER_APPLICATION_XFORM, application); print("AppDetail", xEncoder); } /** * 获取一个ResourceType对象的明细信息 */ @RequestMapping(value = "/resourceType/{id}", method = RequestMethod.GET) public void getResourceTypeInfo(HttpServletResponse response, @PathVariable("id") Long id) { ResourceType resourceType = resourceService.getResourceTypeById(id); String applicationId = resourceType.getApplicationId(); String resourceTypeId = resourceType.getResourceTypeId(); ResourceTypeRoot rtRoot = resourceService.findResourceTypeRoot(applicationId, resourceTypeId); resourceType.setRootId(rtRoot.getRootId()); XFormEncoder xEncoder = new XFormEncoder(UMConstants.RESOURCETYPE_XFORM, resourceType); print("ResourceTypeDetail", xEncoder); } /** * 获取一个Operation对象的明细信息 */ @RequestMapping(value = "/operation/{id}", method = RequestMethod.GET) public void getOperationInfo(HttpServletResponse response, @PathVariable("id") Long id) { // 编辑操作选项 Operation operation = resourceService.getOperationById(id); XFormEncoder xformEncoder = new XFormEncoder(UMConstants.OPERATION_XFORM, operation); print("PermissionOption", xformEncoder); } /** * 编辑一个Application对象的明细信息 */ @RequestMapping(value = "/app", method = RequestMethod.POST) public void editApplication(HttpServletResponse response, Application application) { boolean isNew = application.getId() == null; resourceService.saveApplication(application); doAfterSave(isNew, application, "AppSource"); } /** * 编辑一个ResourceType对象的明细信息 */ @RequestMapping(value = "/resource", method = RequestMethod.POST) public void editResourceType(HttpServletResponse response, ResourceType resourceType) { boolean isNew = resourceType.getId() == null; if( isNew ) { // 新建 resourceService.createResourceType(resourceType); } else{ // 编辑 resourceService.updateResourceType(resourceType); } doAfterSave(isNew, resourceType, "AppSource"); } /** * 编辑一个Operation对象的明细信息 */ @RequestMapping(value = "/operation", method = RequestMethod.POST) public void editOperation(HttpServletResponse response, Operation operation) { boolean isNew = operation.getId() == null; if( isNew ) { // 新建,新建的权限选项要将该权限选项赋予管理员角色(id==-1) resourceService.saveOperation(operation); } else { // 编辑 resourceService.updateOperation(operation); } doAfterSave(isNew, operation, "AppSource"); } /** * 删除应用系统 */ @RequestMapping(value = "/application/{id}", method = RequestMethod.DELETE) public void deleteApplication(HttpServletResponse response, @PathVariable Long id) { resourceService.removeApplication(id); printSuccessMessage(); } /** * 删除资源类型 */ @RequestMapping(value = "/resource/{id}", method = RequestMethod.DELETE) public void deleteResourceType(HttpServletResponse response, @PathVariable Long id) { resourceService.removeResourceType(id); printSuccessMessage(); } /** * 删除操作选项 */ @RequestMapping(value = "/operation/{id}", method = RequestMethod.DELETE) public void deleteOperation(HttpServletResponse response, @PathVariable Long id) { resourceService.removeOperation(id); printSuccessMessage(); } }
BlackBeltPanda/ViaVersion
common/src/main/java/us/myles/ViaVersion/protocols/protocol1_10to1_9_3/storage/ResourcePackTracker.java
<reponame>BlackBeltPanda/ViaVersion package us.myles.ViaVersion.protocols.protocol1_10to1_9_3.storage; import lombok.Getter; import lombok.Setter; import lombok.ToString; import us.myles.ViaVersion.api.data.StoredObject; import us.myles.ViaVersion.api.data.UserConnection; @Getter @Setter @ToString public class ResourcePackTracker extends StoredObject { private String lastHash = ""; public ResourcePackTracker(UserConnection user) { super(user); } }
rcjetpilot/Mobile-UILibrary-iOS
Framework/DJIUILibrary.framework/Headers/DULLeadingBarViewController.h
<filename>Framework/DJIUILibrary.framework/Headers/DULLeadingBarViewController.h // // DULLeadingBarViewController.h // DJIUILibrary // // Copyright © 2016 DJI. All rights reserved. // #import <DJIUILibrary/DULSideBarViewController.h> /** * Subclass of DULSideBarViewController which manages the logic for pre-populating * the leading side bar view with widgets similar to DJI Go. */ @interface DULLeadingBarViewController : DULSideBarViewController @end
zbzbhahae/androidworks
app/src/main/java/com/zb/review/rxj/bean/StudentModel.java
package com.zb.review.rxj.bean; import java.util.ArrayList; import java.util.List; public class StudentModel { static List<Student> students; public static void init() { students = new ArrayList<>(); for(int i=0; i<10; i++) { List<Course> list = new ArrayList<>(); list.add(new Course("语文")); list.add(new Course("数学")); list.add(new Course("英语")); list.add(new Course("物理")); Student s = new Student("stu" + i, list); students.add(s); } } public static List<Student> getStudents() { return students; } public static void setStudents(List<Student> students) { StudentModel.students = students; } }
viyadb/viyadb
src/query/stats.cc
/* * Copyright (c) 2017-present ViyaDB Group * * 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 "query/stats.h" #include "util/statsd.h" #include <glog/logging.h> #include <sstream> namespace viya { namespace query { void QueryStats::OnBegin(const std::string &query_type, const std::string &table) { query_type_ = query_type; table_ = table; begin_work_ = cr::steady_clock::now(); } void QueryStats::OnCompile() { compile_time = cr::steady_clock::now() - begin_work_; } void QueryStats::OnEnd() { whole_time = cr::steady_clock::now() - begin_work_; auto query_time = cr::duration_cast<cr::milliseconds>(whole_time).count(); LOG(INFO) << "Query time " << query_time << " ms (" << "ss=" << std::to_string(scanned_segments) << ",sr=" << std::to_string(scanned_recs) << ",ar=" << std::to_string(aggregated_recs) << ",or=" << std::to_string(output_recs) << ")" << std::endl; std::ostringstream prefix; prefix << "query." << query_type_ << "." << table_ << "."; statsd_.Timing(prefix.str() + "time", query_time); statsd_.Count(prefix.str() + "rows", output_recs); } } // namespace query } // namespace viya
chris-blanks-mf/find
webapp/core/src/test/js/spec/app/model/dependent-parametric-collection.js
/* * Copyright 2016-2017 Hewlett Packard Enterprise Development Company, L.P. * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. */ define([ 'find/app/model/dependent-parametric-collection', 'resources/sunburst_test_data/dependent-parametric-collection-input-data-1', 'resources/sunburst_test_data/dependent-parametric-collection-output-data-1', 'resources/sunburst_test_data/dependent-parametric-collection-input-data-2', 'resources/sunburst_test_data/dependent-parametric-collection-output-data-2' ], function(DependentParametricCollection, inputData1, outputData1, inputData2, outputData2) { 'use strict'; describe('DependentParametricCollection', function () { describe('parse method', function () { it('should split values into segments with correct padding', function () { const output = DependentParametricCollection.prototype.parse(inputData1); expect(output).toEqual(outputData1); }); it('should split values and children into segments with correct padding', function () { const output = DependentParametricCollection.prototype.parse(inputData2); expect(output).toEqual(outputData2); }); it('returns an empty array when given an empty array', function () { expect(DependentParametricCollection.prototype.parse([])).toEqual([]); }); }); }); });
ldj01/espa-surface-reflectance
ledaps/ledapsSrc/src/include/header.h
<gh_stars>1-10 #ifndef HEADER_H #define HEADER_H #include "edips.h" #include "jsc.h" #include "ltwg.h" #include "tipsp.h" #include "siat.h" /* * ANSI X3.27-1978 American National Standard Magnetic * Tape Labels and File Structure for Information Interchange * pp 13-22 */ /* * Label #1 Information */ typedef struct { char file_ident[17]; /* file identifier */ char file_set_ident[6]; /* file-set identifier */ char file_sect_no[4]; /* file section number */ char file_seq_no[4]; /* file sequence number */ char gener_no[4]; /* generation number */ char gener_ver_no[2]; /* generation version number */ char create_date[6]; /* creation date " yyddd" */ char expire_date[6]; /* expiration date " yyddd" */ char accessibility; /* accessability */ char blk_count[6]; /* block count */ char system_code[13]; /* system code */ char hdr1_spaces[7]; /* spaces */ } INFO1; /* each field is dimensioned to be one char longer than is written to to tape, in order to allow them to be null-terminated strings */ /* * Label #2 Information */ typedef struct { char rec_format; /* "F" - fixed length */ /* "D" - variable length */ /* "S" - spanned */ char blk_length[5]; /* block length in characters */ char rec_length[5]; /* record length in characters */ char timestamp[11]; /* file create date YYDDDHHMMSS */ char hdr2_spaces1[24]; /* spaces */ char buffer_offset_length[2];/* buffer-offset length */ char hdr2_spaces2[28]; /* spaces */ } INFO2; /* * File-Header #1 Layout */ struct HDR1 { char label_id[3]; /* "HDR" */ char label_no; /* "1" */ INFO1 info; } ; /* * File-Header #2 Layout */ struct HDR2 { char label_id[3]; /* "HDR" */ char label_no; /* "2" */ INFO2 info; } ; /* * File-Header #n Layout */ struct HDRN { char label_id[3]; /* "HDR" */ char label_no; /* "3", "4", ... "9" */ char hdrn_data[76]; /* reserved for system use */ } ; /* * User Header Labels */ struct UHLA { char label_id[3]; /* "UHL" */ char label_no; /* "a" character */ char uhla_data[76]; /* reserved for user application */ } ; int c_edips_anc ( char *outh, /* image host file name */ long outsys, /* output system */ struct EDPSAC *anc, /* EDIPS ancillary structure */ struct EDPSAC_EPH *anceph, /* EDIPS ancillary structure--Ephemeris Data */ struct EDPSAC_ATT *ancatt, /* EDIPS ancillary structure--Attitude Data */ struct EDPSAC_RS *ancutm, /* EDIPS ancillary structure--Horizontal and Vertical resampling for UTM/PS data */ struct EDPSAC_RS *ancsom /* EDIPS ancillary structure--Horizontal and Vertical resampling for SOM/HOM data */ ); int c_convertab ( char *header_a, /* fast format a header bfer */ char *header_b /* fast format b header buffer */ ); int c_edips_ann ( char *outh, struct EDIPSA *annot ); int c_edips_hdr ( char *outh, /* host image name */ long outsys, /* output system */ struct EDIPSH *hdr /* EDIPS header structure */ ); int c_edips_trl ( char *outh, struct EDIPST *trl ); int c_fhdrrd ( char *header, /* the pointer to the fast fmt header */ long field, /* the field to be read */ char *data /* address to place the data read */ ); int c_fhdrup ( char *header, /* the pointer to the fast fmt header */ long field, /* the field to be updated */ char *data /* pointer to the data to place in the field*/ ); int c_jsc_anc ( struct JSCIN *jscin, /* TIPSP sturcture declaration */ char *name, /* image name */ long *nl /* line number to seek to */ ); int c_jsc_lhdr ( char *outh, /* image host file name */ struct JSCLH *lhdr /* JSC Landsat header structure */ ); int c_ltwg_eaa ( struct LTWGEAA *eaa, /* OUTPUT - LTWG ephomeris volume descriptor */ /* attitude ancillary rec structure */ FILE *fin, /* INPUT - File pointer */ int *size /* INPUT - record size in bytes */ ); int c_ltwg_fpr ( struct LTWGFPR *fpr, /* OUTPUT - LTWG volume descriptor rec structure*/ FILE *fin /* INPUT - File pointer */ ); int c_ltwg_idr ( struct LTWGIDR *idr, /* OUTPUT - LTWG image data rec structure */ FILE *fin /* INPUT - File pointer */ ); int c_ltwg_ifd ( struct LTWGIFD *ifd, /* OUTPUT - LTWG imagery file descriptor */ FILE *fin /* INPUT - File pointer */ ); int c_ltwg_lfd ( struct LTWGLFD *lfd, /* OUTPUT - LTWG leader file descriptor */ FILE *fin /* INPUT - File pointer */ ); int c_ltwg_mpr ( struct LTWGMPR *mpr, /* OUTPUT - LTWG map projection rec structure */ FILE *fin, /* INPUT - File pointer */ long *size /* INPUT - number of bytes to read for file */ ); int c_ltwg_mtr ( struct LTWGMTR *mtr, /* OUTPUT - LTWG mission telemetry anc rec structure */ FILE *fin, /* INPUT - File pointer */ long *size /* INPUT - record size in bytes */ ); int c_ltwg_rcr ( struct LTWGRCR *rcr, /* OUTPUT - LTWG radiometric calibration rec struct */ FILE *fin, /* INPUT - File pointer */ long *size /* INPUT - Record size in bytes */ ); int c_ltwg_rjr ( struct LTWGRJR *rjr, /* OUTPUT - LTWG raw jitter meas rec structure */ FILE *fin, /* INPUT - File pointer */ long *size /* INPUT - record size in bytes */ ); int c_ltwg_sfd ( struct LTWGSFD *sfd, /* OUTPUT - LTWG supplemental file descriptor */ FILE *fin /* INPUT - File pointer */ ); int c_ltwg_shr ( struct LTWGSHR *shr, /* OUTPUT - LTWG volume descriptor rec structure */ FILE *fin, /* INPUT - File pointer */ long *size /* INPUT - number of bytes to read in for file */ ); int c_ltwg_sih ( struct LTWGSIH *sih, /* OUTPUT - LTWG interval header rec structure */ FILE *fin, /* INPUT - File pointer */ long *size /* INPUT - record size in bytes */ ); int c_ltwg_str ( struct LTWGSTR *str, /* OUTPUT - LTWG supplemental text rec structure */ FILE *fin /* INPUT - File pointer */ ); int c_ltwg_tfd ( struct LTWGTFD *tfd, /* OUTPUT - LTWG trailer file des rec structure */ FILE *fin /* INPUT - File pointer */ ); int c_ltwg_tmhk ( struct LTWGTMHK *tmhk, /* OUTPUT - LTWG TM house keeping rec structure */ FILE *fin, /* INPUT - File pointer */ long *size /* INPUT - record size in bytes */ ); int c_ltwg_tr ( struct LTWGTR *tr, /* OUTPUT - LTWG trailer rec structure */ FILE *fin, /* INIPUT - File pointer */ long *size /* INIPUT - record size in bytes */ ); int c_ltwg_triv ( struct LTWGTRIV *triv, /* OUTPUT - LTWG volume descriptor rec structure */ FILE *fin /* INPUT - File pointer */ ); int c_ltwg_vdr ( struct LTWGVDR *vdr, /* OUTPUT - LTWG volume descriptor rec structure */ FILE *fin /* INPUT - File pointer */ ); int c_jsc_radtran ( char *outh, /* image host file name */ struct JSCRT *jscrt4,/* JSC Landsat header Radiometric Transformation band 4 */ struct JSCRT *jscrt5,/* JSC Landsat header Radiometric Transformation band 5 */ struct JSCRT *jscrt6,/* JSC Landsat header Radiometric Transformation band 6 */ struct JSCRT *jscrt7,/* JSC Landsat header Radiometric Transformation band 7 */ struct JSCRT *jscrt8 /* JSC Landsat header Radiometric Transformation band 8 */ ); int c_jsc_uhdr ( char *outh, /* image host file name */ struct JSCUH *uhdr /* JSC Universal header structure */ ); long get_long_var ( unsigned char *val ); int c_open_header ( char *buf, /* header buffer */ char *name, /* image name */ long *flag /* flag to determine read or write acc */ ); int c_read_annot ( struct TIPSP *tipsp, /* TIPSP sturcture declaration */ char *name /* image name */ ); int c_read_head ( struct TIPSP *tipsp, char *name /* image name */ ); int c_read_siat ( struct SIAT *siat, /* SIAT sturcture declaration */ char *name /* image name */ ); int c_read_trail ( struct TIPSP *tipsp, /* TIPSP sturcture declaration */ char *name /* image name */ ); int c_readfpg ( unsigned char *buf, /* value in FPG format */ double *tempdbl /* converted value of double */ ); int cdbl2ftn ( char *buffer, /* the buffer to print the string to */ double value /* the value to convert */ ); int fstr2cdbl ( char *buffer, /* the buffer to with the string */ double *value /* the return address */ ); int convert_dms ( char **strings, /* pointer to strings */ long proj_number, /* USGS projection number */ long method /* converstion method. 0 = old->new, !0 = new->old */ ); int deg2dms ( char *buffer, /* the buffer to write the string to */ double value, /* the value to convert */ long mode /* latitude = 0, longitude = 1 */ ); int dms2deg ( char *buffer, /* the buffer that contains the string */ double *value, /* the address to place the result */ long mode /* latitude = 0, longitude = 1 */ ); int c_fhdfld ( long field, /* field to get information about */ long fdata[5] /* array to fill with the information */ ); int meta_init ( char *file ); int meta_insert ( int field, char *data ); char *meta_getfield ( int field ); void meta_setfile ( char *file ); int meta_write(void); void meta_writearchv ( char *tapeloc[], char *format, int file_number ); void meta_read(void); int meta_cleanup(void); /* NOTE: template_header used to be template, but since template is a reserved word it was changed */ void template_header ( char *buf /* header buffer */ ); #endif
pivotalexperimental/screw-unit-server
spec/functional/functional_spec_server_starter.rb
require "rubygems" require "timeout" require "lsof" dir = File.dirname(__FILE__) $LOAD_PATH.unshift "#{dir}/../../lib" require "screw_unit" require "nokogiri" module WaitFor extend self def wait_for(time=5) Timeout.timeout(time) do loop do value = yield return value if value end end end end class FunctionalSpecServerStarter class << self include WaitFor def call(threaded=true) return if $screw_unit_server_started Lsof.kill(8080) wait_for do !Lsof.running?(8080) end dir = File.dirname(__FILE__) Dir.chdir("#{dir}/../../") do Thread.start do start_thin_server end end wait_for do Lsof.running?(8080) end $screw_unit_server_started = true end def start_thin_server at_exit do Lsof.kill(8080) end system("bin/screw_unit_server --spec-path=#{spec_root_path} --root-path=#{public_path}") end def spec_root_path File.expand_path("#{dir}/../example_specs") end def public_path File.expand_path("#{dir}/../example_public") end def dir dir = File.dirname(__FILE__) end end end if $0 == __FILE__ FunctionalSpecServerStarter.call(false) end
ScarfZapdos/conan-bge-questgen
src/downward/experiments/issue213/base-opt.py
#! /usr/bin/env python # -*- coding: utf-8 -*- import itertools import os from lab.environments import LocalEnvironment, MaiaEnvironment from downward.reports.compare import ComparativeReport import common_setup from common_setup import IssueConfig, IssueExperiment BENCHMARKS_DIR = os.environ["DOWNWARD_BENCHMARKS"] REVISION = "issue213-base" BUILDS = ["release32", "release64"] SEARCHES = [ ("bjolp", "astar(lmcount(lm_merged([lm_rhw(), lm_hm(m=1)]), admissible=true), mpd=true)"), ("blind", "astar(blind())"), ("cegar", "astar(cegar())"), ("divpot", "astar(diverse_potentials())"), ("ipdb", "astar(ipdb(max_time=900))"), ("lmcut", "astar(lmcut())"), ("mas", "astar(merge_and_shrink(shrink_strategy=shrink_bisimulation(greedy=false), " "merge_strategy=merge_dfp(), " "label_reduction=exact(before_shrinking=true, before_merging=false), max_states=100000, threshold_before_merge=1))"), ("seq", "astar(operatorcounting([state_equation_constraints()]))"), ] CONFIGS = [ IssueConfig( "{nick}-{build}".format(**locals()), ["--search", search], build_options=[build], driver_options=["--build", build]) for nick, search in SEARCHES for build in BUILDS ] SUITE = common_setup.DEFAULT_OPTIMAL_SUITE ENVIRONMENT = MaiaEnvironment( priority=0, email="<EMAIL>") if common_setup.is_test_run(): SUITE = IssueExperiment.DEFAULT_TEST_SUITE ENVIRONMENT = LocalEnvironment(processes=1) exp = IssueExperiment( revisions=[REVISION], configs=CONFIGS, environment=ENVIRONMENT, ) exp.add_suite(BENCHMARKS_DIR, SUITE) exp.add_absolute_report_step() algorithm_pairs = [] for build1, build2 in itertools.combinations(BUILDS, 2): for config_nick, search in SEARCHES: algorithm_pairs.append( ("{REVISION}-{config_nick}-{build1}".format(**locals()), "{REVISION}-{config_nick}-{build2}".format(**locals()), "Diff ({})".format(config_nick))) exp.add_report( ComparativeReport( algorithm_pairs, attributes=IssueExperiment.DEFAULT_TABLE_ATTRIBUTES), name="issue213-opt-comparison") #exp.add_scatter_plot_step(attributes=["total_time", "memory"]) exp.run_steps()
avalonmediasystem/react-structural-metadata-editor
dist/containers/WaveformContainer.js
<reponame>avalonmediasystem/react-structural-metadata-editor "use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _react = _interopRequireWildcard(require("react")); var _Utils = _interopRequireDefault(require("../api/Utils")); var _reactRedux = require("react-redux"); var _peaksInstance = require("../actions/peaks-instance"); var _forms = require("../actions/forms"); var _Waveform = _interopRequireDefault(require("../components/Waveform")); var _alertStatus = require("../services/alert-status"); var apiUtils = new _Utils["default"](); // Peaks options var peaksOptions = { container: null, mediaElement: null, dataUri: null, dataUriDefaultFormat: 'json', keyboard: true, pointMarkerColor: '#006eb0', showPlayheadTime: true, zoomWaveformColor: 'rgba(117, 117, 117, 1)', overviewWaveformColor: 'rgba(117, 117, 117, 1)', timeLabelPrecision: 3 }; var WaveformContainer = /*#__PURE__*/ function (_Component) { (0, _inherits2["default"])(WaveformContainer, _Component); function WaveformContainer(props) { var _this; (0, _classCallCheck2["default"])(this, WaveformContainer); _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(WaveformContainer).call(this, props)); (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "state", { // alertObj: { alert: this.props.alert, showAlert: false }, streamAlert: {}, masterFileID: _this.props.masterFileID, baseURL: _this.props.baseURL, initStructure: _this.props.initStructure, streamLength: _this.props.streamDuration, dataUri: null }); _this.zoomView = null; _this.overView = null; _this.mediaPlayer = null; return _this; } (0, _createClass2["default"])(WaveformContainer, [{ key: "componentDidMount", value: function componentDidMount() { peaksOptions.containers = { zoomview: this.zoomView, overview: this.overView }; peaksOptions.mediaElement = this.mediaPlayer; this.initializePeaksInstance(); } }, { key: "initializePeaksInstance", value: function () { var _initializePeaksInstance = (0, _asyncToGenerator2["default"])( /*#__PURE__*/ _regenerator["default"].mark(function _callee() { var _this$state, baseURL, masterFileID, initStructure, streamLength; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _this$state = this.state, baseURL = _this$state.baseURL, masterFileID = _this$state.masterFileID, initStructure = _this$state.initStructure, streamLength = _this$state.streamLength; _context.prev = 1; _context.next = 4; return apiUtils.headRequest(baseURL, masterFileID, 'waveform.json'); case 4: // Set waveform URI peaksOptions.dataUri = "".concat(baseURL, "/master_files/").concat(masterFileID, "/waveform.json"); // Update redux-store flag for waveform file retrieval this.props.retrieveWaveformSuccess(); _context.next = 11; break; case 8: _context.prev = 8; _context.t0 = _context["catch"](1); // Enable the flash message alert this.handleError(_context.t0); case 11: // Fetch structure.json and build Peaks this.props.fetchDataAndBuildPeaks(baseURL, masterFileID, initStructure, peaksOptions, streamLength); case 12: case "end": return _context.stop(); } } }, _callee, this, [[1, 8]]); })); function initializePeaksInstance() { return _initializePeaksInstance.apply(this, arguments); } return initializePeaksInstance; }() }, { key: "handleError", value: function handleError(error) { console.log('TCL: WaveformContainer -> handleError -> error', error); var status = null; var _this$state2 = this.state, baseURL = _this$state2.baseURL, masterFileID = _this$state2.masterFileID; // Pull status code out of error response/request if (error.response !== undefined) { status = error.response.status; if (status == 404) { peaksOptions.dataUri = "".concat(baseURL, "/master_files/").concat(masterFileID, "/waveform.json?empty=true"); status = -7; // for persistent missing waveform data alert } } else if (error.request !== undefined) { status = -3; } var alert = (0, _alertStatus.configureAlert)(status); this.props.setAlert(alert); } }, { key: "render", value: function render() { var _this2 = this; var audioStreamURL = this.props.audioStreamURL; return _react["default"].createElement("section", { className: "waveform-section", "data-testid": "waveform-container" }, _react["default"].createElement(_Waveform["default"], { zoomViewRef: function zoomViewRef(ref) { return _this2.zoomView = ref; }, overViewRef: function overViewRef(ref) { return _this2.overView = ref; }, mediaPlayerRef: function mediaPlayerRef(ref) { return _this2.mediaPlayer = ref; }, audioStreamURL: audioStreamURL, withCredentials: this.props.withCredentials }), ' '); } }]); return WaveformContainer; }(_react.Component); var mapStateToProps = function mapStateToProps(state) { return { smData: state.structuralMetadata.smData, alert: state.forms.alert }; }; var mapDispatchToProps = { fetchDataAndBuildPeaks: _peaksInstance.initializeSMDataPeaks, peaksReady: _peaksInstance.peaksReady, retrieveWaveformSuccess: _forms.retrieveWaveformSuccess, setAlert: _forms.setAlert }; var _default = (0, _reactRedux.connect)(mapStateToProps, mapDispatchToProps)(WaveformContainer); exports["default"] = _default;
masud-technope/ACER-Replication-Package-ASE2017
corpus/class/eclipse.pde.ui/3261.java
<filename>corpus/class/eclipse.pde.ui/3261.java /******************************************************************************* * Copyright (c) 2007, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.pde.internal.ua.ui.wizards.toc; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.osgi.util.NLS; import org.eclipse.pde.internal.ua.ui.PDEUserAssistanceUIPlugin; import org.eclipse.pde.internal.ua.ui.editor.toc.HelpEditorUtil; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.dialogs.WizardNewFileCreationPage; /** * PDEWizardNewFileCreationPage */ public class TocHTMLWizardPage extends WizardNewFileCreationPage { private String fLastFilename; /** * @param pageName * @param selection */ public TocHTMLWizardPage(String pageName, IStructuredSelection selection) { super(pageName, selection); } /* (non-Javadoc) * @see org.eclipse.ui.dialogs.WizardNewFileCreationPage#validatePage() */ protected boolean validatePage() { fLastFilename = getFileName().trim(); // Verify the filename is non-empty if (fLastFilename.length() == 0) { // Reset previous error message set if any setErrorMessage(null); return false; } // Verify the file name does not begin with a dot if (fLastFilename.charAt(0) == '.') { setErrorMessage(TocWizardMessages.TocHTMLWizardPage_errorMessage1); return false; } if (!HelpEditorUtil.hasValidPageExtension(new Path(fLastFilename))) { String message = NLS.bind(TocWizardMessages.TocHTMLWizardPage_errorMessage2, HelpEditorUtil.getPageExtensionList()); setErrorMessage(message); return false; } // Perform default validation return super.validatePage(); } /* (non-Javadoc) * @see org.eclipse.ui.dialogs.WizardNewFileCreationPage#validateLinkedResource() */ protected IStatus validateLinkedResource() { //$NON-NLS-1$ return new Status(IStatus.OK, PDEUserAssistanceUIPlugin.PLUGIN_ID, IStatus.OK, "", null); } /* (non-Javadoc) * @see org.eclipse.ui.dialogs.WizardNewFileCreationPage#createLinkTarget() */ protected void createLinkTarget() { // NO-OP } protected void createAdvancedControls(Composite parent) { // NO-OP } public String getFileName() { if (getControl() != null && getControl().isDisposed()) { return fLastFilename; } return super.getFileName(); } }
eaglelzy/myglide
library/src/main/java/com/lizy/myglide/load/resource/bitmap/BitmapDrawableDecoder.java
<reponame>eaglelzy/myglide<filename>library/src/main/java/com/lizy/myglide/load/resource/bitmap/BitmapDrawableDecoder.java package com.lizy.myglide.load.resource.bitmap; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import com.lizy.myglide.load.Options; import com.lizy.myglide.load.ResourceDecoder; import com.lizy.myglide.load.engine.Resource; import com.lizy.myglide.load.engine.bitmap_recycle.BitmapPool; import com.lizy.myglide.util.Preconditions; import java.io.IOException; /** * Created by lizy on 16-4-29. */ public class BitmapDrawableDecoder<DataType> implements ResourceDecoder<DataType, BitmapDrawable> { private final ResourceDecoder<DataType, Bitmap> decoder; private final Resources resources; private final BitmapPool bitmapPool; public BitmapDrawableDecoder(Resources resources, BitmapPool bitmapPool, ResourceDecoder<DataType, Bitmap> decoder) { this.resources = Preconditions.checkNotNull(resources); this.bitmapPool = Preconditions.checkNotNull(bitmapPool); this.decoder = Preconditions.checkNotNull(decoder); } @Override public boolean handles(DataType source, Options options) throws IOException { return decoder.handles(source, options); } @Override public Resource<BitmapDrawable> decode(DataType source, int width, int height, Options options) throws IOException { Resource<Bitmap> bitmapResource = decoder.decode(source, width, height, options); if (bitmapResource == null) { return null; } return LazyBitmapDrawableResource.obtain(resources, bitmapPool, bitmapResource.get()); } }
tmatsuo/google-cloud-java
google-cloud-core/src/test/java/com/google/cloud/RetryParamsTest.java
<gh_stars>0 /* * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud; import static com.google.cloud.RetryParams.DEFAULT_INITIAL_RETRY_DELAY_MILLIS; import static com.google.cloud.RetryParams.DEFAULT_MAX_RETRY_DELAY_MILLIS; import static com.google.cloud.RetryParams.DEFAULT_RETRY_DELAY_BACKOFF_FACTOR; import static com.google.cloud.RetryParams.DEFAULT_RETRY_MAX_ATTEMPTS; import static com.google.cloud.RetryParams.DEFAULT_RETRY_MIN_ATTEMPTS; import static com.google.cloud.RetryParams.DEFAULT_TOTAL_RETRY_PERIOD_MILLIS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.google.cloud.RetryParams.Builder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.util.Arrays; /** * Tests for {@link RetryParams}. */ @RunWith(JUnit4.class) public class RetryParamsTest { @Test public void testDefaults() { RetryParams params1 = RetryParams.defaultInstance(); RetryParams params2 = RetryParams.builder().build(); for (RetryParams params : Arrays.asList(params1, params2)) { assertEquals(DEFAULT_INITIAL_RETRY_DELAY_MILLIS, params.initialRetryDelayMillis()); assertEquals(DEFAULT_MAX_RETRY_DELAY_MILLIS, params.maxRetryDelayMillis()); assertEquals(DEFAULT_RETRY_DELAY_BACKOFF_FACTOR, params.retryDelayBackoffFactor(), 0); assertEquals(DEFAULT_RETRY_MAX_ATTEMPTS, params.retryMaxAttempts()); assertEquals(DEFAULT_RETRY_MIN_ATTEMPTS, params.retryMinAttempts()); assertEquals(DEFAULT_TOTAL_RETRY_PERIOD_MILLIS, params.totalRetryPeriodMillis()); } } @Test public void testSetAndCopy() { RetryParams.Builder builder = RetryParams.builder(); builder.initialRetryDelayMillis(101); builder.maxRetryDelayMillis(102); builder.retryDelayBackoffFactor(103); builder.retryMinAttempts(107); builder.retryMaxAttempts(108); builder.totalRetryPeriodMillis(109); RetryParams params1 = builder.build(); RetryParams params2 = new RetryParams.Builder(params1).build(); for (RetryParams params : Arrays.asList(params1, params2)) { assertEquals(101, params.initialRetryDelayMillis()); assertEquals(102, params.maxRetryDelayMillis()); assertEquals(103, params.retryDelayBackoffFactor(), 0); assertEquals(107, params.retryMinAttempts()); assertEquals(108, params.retryMaxAttempts()); assertEquals(109, params.totalRetryPeriodMillis()); } } @Test public void testBadSettings() { RetryParams.Builder builder = RetryParams.builder(); builder.initialRetryDelayMillis(-1); builder = assertFailure(builder); builder.maxRetryDelayMillis(RetryParams.defaultInstance().initialRetryDelayMillis() - 1); builder = assertFailure(builder); builder.retryDelayBackoffFactor(-1); builder = assertFailure(builder); builder.retryMinAttempts(-1); builder = assertFailure(builder); builder.retryMaxAttempts(RetryParams.defaultInstance().retryMinAttempts() - 1); builder = assertFailure(builder); builder.totalRetryPeriodMillis(-1); builder = assertFailure(builder); // verify that it is OK for min and max to be equal builder.retryMaxAttempts(RetryParams.defaultInstance().retryMinAttempts()); builder.maxRetryDelayMillis(RetryParams.defaultInstance().initialRetryDelayMillis()); builder.build(); } private static Builder assertFailure(Builder builder) { try { builder.build(); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException ex) { // expected } return RetryParams.builder(); } }
prezi/kannotator
testData/interpreter/primitiveParamsAndReturn/Test.java
package interpreter.primitiveParamsAndReturn; public class Test { public int intReturn(Object p1, Object p2) { return 0; } public void voidReturn(Object p1, Object p2) { } public Object objectReturn(Object p1, Object p2) { return null; } public void intParam(Object p1, int p2, Object p3) { } public int intParamAndReturn(Object p1, int p2, Object p3) { return 0; } }
CaddyDz/Ruby
p1/ch6/exception.rb
class MyNewException < Exception end begin puts "About to raise exception..." raise MyNewException rescue MyNewException => e puts "Just raised an exception : #{e}" end
TheMrButcher/opengl_lessons
src/design_editor/dvb/SharedContext.cpp
/** * Copyright (c) 2018 <NAME> * This file is licensed under the terms of the MIT license. */ #include "SharedContext.h" #include <gamebase/serial/LoadObj.h> #include <gamebase/tools/MakeRaw.h> namespace gamebase { namespace editor { SharedContext::SharedContext( TreeView& treeView, Selector propertiesMenu, DesignModel& model) : treeView(treeView) , propertiesMenu(propertiesMenu) , model(model) , currentNodeID(-1) {} void SharedContext::select(int id) { sync(); toolBar->clear(); propertiesMenu.select(-1); auto itOld = nodes.find(currentNodeID); if (itOld != nodes.end() && itOld->second.props) { itOld->second.props->detach(); propertiesMenu.remove(currentNodeID); } currentNodeID = id; auto it = nodes.find(id); if (it == nodes.end() || !it->second.props) { propertiesMenuArea.update(); return; } if (!propertiesMenu.has(id)) { Layout layout = loadObj<Layout>("ui\\PropertiesLayout.json"); const auto& props = nodes[id].props; nodes[id].props->attach(makeRaw(layout)); propertiesMenu.insert(props->id, layout); } propertiesMenu.select(id); for (const auto& keyAndButton : it->second.callbacks) toolBar->addButton(keyAndButton.first, keyAndButton.second); propertiesMenuArea.update(); } void SharedContext::onSelection() { select(switchsGroup.selected()); } void SharedContext::sync() { auto it = nodes.find(currentNodeID); if (it != nodes.end() && it->second.props) it->second.props->sync(); } } }
JLLeitschuh/vid
vid-app-common/src/test/java/org/onap/vid/services/VersionServiceTest.java
/*- * ============LICENSE_START======================================================= * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.onap.vid.services; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.net.MalformedURLException; import java.net.URL; import javax.servlet.ServletContext; import org.jetbrains.annotations.NotNull; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.portalsdk.core.util.SystemProperties; import org.onap.vid.model.VersionAndFeatures; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @ContextConfiguration(classes = {SystemProperties.class}) public class VersionServiceTest extends AbstractTestNGSpringContextTests { private static final String VERSION_FILE_PATH = "/app/vid/scripts/constants/version.json"; @Mock ServletContext servletContext; VersionService versionService; @BeforeClass public void initMocks() { MockitoAnnotations.initMocks(this); } @BeforeMethod public void resetMocks() { Mockito.reset(servletContext); versionService = new VersionService(servletContext); } @DataProvider public static Object[][] majorVersionContainer() { return new Object[][]{ {"features.properties", "1.0.2000", "features.properties.2000"}, {"", "1.0.2000", ".2000"}, {"kuku", "1.0.2000", "kuku.2000"}, {"/kuku", "1.0.2000", "kuku.2000"}, {"1810p.features.properties", "1.0.2000", "1810p.2000"}, {"/opt/app/dev.features.properties", "1.0.2000", "dev.2000"}, {"foo", "2000", "foo.2000"}, }; } @Test(dataProvider = "majorVersionContainer") public void testGetDisplayVersion(String majorVersionContainer, String buildNumberContainer, String expected) { assertThat(versionService.buildDisplayVersion(majorVersionContainer, buildNumberContainer), is(expected)); } @Test public void testReadFeatureSet() { assertEquals("onap.features.properties", versionService.readFeatureSet()); } @Test public void whenReadBuildNumber_thenTheRightBuildIsReturn_andReadOnlyOnce() throws MalformedURLException { mockForVersionFile(); assertEquals("1.0.151", versionService.retrieveBuildNumber()); //second call shall not read resource assertEquals("1.0.151", versionService.retrieveBuildNumber()); verify(servletContext).getResource(any()); } private void mockForVersionFile() throws MalformedURLException { URL versionFileExample = this.getClass().getResource("/version.example.json"); when(servletContext.getResource(eq(VERSION_FILE_PATH))).thenReturn(versionFileExample); } @NotNull protected VersionAndFeatures retrieveAndAssertVersionWithGoodResult() throws MalformedURLException { mockForVersionFile(); VersionAndFeatures expected = new VersionAndFeatures("onap.features.properties", "1.0.151", "onap.151"); assertEquals(expected, versionService.retrieveVersionAndFeatures()); return expected; } @Test(expectedExceptions = RuntimeException.class, expectedExceptionsMessageRegExp = "abc") public void whenExceptionThrownDuringGetBuildNumber_thenExceptionIsThrown() throws MalformedURLException { when(servletContext.getResource(any())).thenThrow(new RuntimeException("abc")); versionService.retrieveBuildNumber(); } @Test public void whenExceptionThrownDuringVersionAndFeatures_thenUnknownIsReturn() throws MalformedURLException { //exception is thrown during retrieveVersionAndFeatures, so expect to "unknown" result when(servletContext.getResource(eq(VERSION_FILE_PATH))).thenThrow(new RuntimeException()); assertEquals(VersionAndFeatures.Companion.getUnknown(), versionService.retrieveVersionAndFeatures()); //retrieveVersionAndFeatures going smoothly, so expecting to good result retrieveAndAssertVersionWithGoodResult(); } @Test public void whenRetrieveVersionAndFeatures_expectedValuesReturn_andExecuteOnce() throws MalformedURLException { VersionAndFeatures expected = retrieveAndAssertVersionWithGoodResult(); //second call shall not read resource assertEquals(expected, versionService.retrieveVersionAndFeatures()); verify(servletContext).getResource(eq(VERSION_FILE_PATH)); } }
Ernestyj/JStudy
src/main/java/onlinealgo/CoverPoints.java
<reponame>Ernestyj/JStudy package onlinealgo; import java.math.BigDecimal; /** * Created by v_yangjian02 on 2016/9/8. */ public class CoverPoints { public static void main(String[] args) { System.out.println("*****RESULT*****"); double[] nums = {0.1, 0.2, 0.3, 1.5, 1.6, 1.61, 9.8}; int res = maxCover(nums, 0.2); System.out.println(res); } //求满足a[j]-a[i]<=L && a[j+1]-a[i]>L这两个条件的j与i中间的所有点个数中的最大值,即j-i+1最大 public static int maxCover(double nums[], double L) { int n = nums.length; int count = 2, maxCount = 1, start = 0; int i = 0, j = 1; while(i<n && j<n) { while(j<n && (new BigDecimal(String.valueOf(nums[j])).subtract(new BigDecimal(String.valueOf(nums[i])))) .compareTo(new BigDecimal(String.valueOf(L)))<=0) { j++; count++; } j--; count--; //退回到满足条件的j if(maxCount<count) { start = i; //记录起始覆盖点 maxCount = count; } i++; //收缩 j++; //TODO 注意j也++ } return maxCount; } }
riversy/golang-course-training
level-004/exercise-003/main.go
package main import "fmt" func main() { x := [][]int{ {42, 43, 44, 45, 46}, {47, 48, 49, 50, 51}, {44, 45, 46, 47, 48}, {43, 44, 45, 46, 47}, } for i, v := range x { fmt.Println(i, v, len(v), cap(v)) } fmt.Printf("%T\t\t%v\t%v\n", x, len(x), cap(x)) fmt.Printf("%T\t\t%v\t%v\n", x, len(x), cap(x)) }
CodingLuoye/mianshizhongdian
src/main/java/com/self/bianlimap/UnsafeCurrentHashMap.java
<reponame>CodingLuoye/mianshizhongdian package com.self.bianlimap; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; /** * hashMap是线程不安全的,在多个线程同时对其进行读写的时候,会造成死循环 * Hashtable的大小增加到一定的时候,性能会急剧下降,因为迭代时需要被锁定很长的时间。 * 因为ConcurrentHashMap引入了分割(segmentation),不论它变得多么大,仅仅需要锁定map的某个部分,而其它的线程不需要等到迭代完成才能访问map。 * 简而言之,在迭代的过程中,ConcurrentHashMap仅仅锁定map的某个部分,而Hashtable则会锁定整个map * * HashTable的线程安全使用的是一个单独的全部Map范围的锁,ConcurrentHashMap抛弃了HashTable的单锁机制,使用了锁分离技术,使得多个修改操作能够并发进行,只有进行SIZE()操作时ConcurrentHashMap会锁住整张表。 * HashTable的put和get方法都是同步方法,而ConcurrentHashMap的get方法多数情况都不用锁,put方法需要锁。 * 但是ConcurrentHashMap不能替代HashTable,因为两者的迭代器的一致性不同的,hashTable的迭代器是强一致性的,而concurrentHashmap是弱一致的。 * ConcurrentHashMap的get,clear,iterator 都是弱一致性的 * * Hashtable继承于 Dictionary 类,实现了 Map, Cloneable, java.io.Serializable接口。存储的是内容是键值对,通过拉链法实现哈希表。 * HashTable容器使用synchronized来保证线程安全,但在线程竞争激烈的情况下HashTable的效率非常低下 * * @author Administrator * */ public class UnsafeCurrentHashMap { public static void main(String[] args) { final Map<Integer,Integer> map = new HashMap<>(); // final Map<Integer,Integer> map = new ConcurrentHashMap<>(); for (int i = 0; i < 1000; i++) { Thread t = new Thread(){ Random rnd = new Random(); @Override public void run() { for (int i = 0; i < 1000; i++) { map.put(rnd.nextInt(), 1); } } }; t.start(); } final Map<Integer,Integer> map2 = new Hashtable<>(); for (int i = 0; i < 1000; i++) { Thread t = new Thread(){ Random rnd = new Random(); @Override public void run() { for (int i = 0; i < 1000; i++) { map2.put(rnd.nextInt(), 1); } } }; t.start(); } final Map<Integer,Integer> map3 = new ConcurrentHashMap<>(); for (int i = 0; i < 1000; i++) { Thread t = new Thread(){ Random rnd = new Random(); @Override public void run() { for (int i = 0; i < 1000; i++) { map3.put(rnd.nextInt(), 1); } } }; t.start(); } } }
ErhardSiegl/galleon
testsuite/src/test/java/org/jboss/galleon/universe/maven/test/MavenProducerInstallTestCase.java
/* * Copyright 2016-2019 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.galleon.universe.maven.test; import static org.jboss.galleon.universe.TestConstants.*; import java.util.Collection; import org.jboss.galleon.universe.UniverseRepoTestBase; import org.jboss.galleon.universe.maven.MavenArtifact; import org.jboss.galleon.universe.maven.MavenProducer; import org.jboss.galleon.universe.maven.MavenChannel; import org.jboss.galleon.universe.maven.MavenProducerInstaller; import org.jboss.galleon.universe.maven.MavenErrors; import org.jboss.galleon.universe.maven.MavenUniverseException; import org.junit.Assert; import org.junit.Test; /** * * @author <NAME> */ public class MavenProducerInstallTestCase extends UniverseRepoTestBase { private MavenArtifact producerArtifact; @Override protected void doInit() { producerArtifact = new MavenArtifact(); producerArtifact.setGroupId(GROUP_ID); producerArtifact.setArtifactId("test-producer"); producerArtifact.setVersion("1.0.0.Final"); } @Test public void testMain() throws Exception { final String fpGroupId = "fp-group1"; final String fpArtifactId = "fp-artifact1"; final MavenProducerInstaller producerInstaller = new MavenProducerInstaller("producer1", repo, producerArtifact, fpGroupId, fpArtifactId); producerInstaller.addFrequencies("alpha", "beta"); producerInstaller.addChannel("1.0", "[1.0.0,2.0.0)"); producerInstaller.addChannel("2.0", "[2.0.0,3.0.0)", false, ".*-ext-[0-9][0-9]", ".*-ext-11"); producerInstaller.install(); producerArtifact.setPath(null); MavenProducer producer = new MavenProducer("producer1", repo, producerArtifact); Assert.assertEquals(fpGroupId, producer.getFeaturePackGroupId()); Assert.assertEquals(fpArtifactId, producer.getFeaturePackArtifactId()); Collection<String> frequencies = producer.getFrequencies(); Assert.assertEquals(3, frequencies.size()); Assert.assertTrue(frequencies.contains("alpha")); Assert.assertTrue(frequencies.contains("beta")); Assert.assertTrue(frequencies.contains("final")); Assert.assertTrue(producer.hasChannel("1.0")); MavenChannel channel = producer.getChannel("1.0"); Assert.assertEquals(fpGroupId, channel.getFeaturePackGroupId()); Assert.assertEquals(fpArtifactId, channel.getFeaturePackArtifactId()); Assert.assertEquals("[1.0.0,2.0.0)", channel.getVersionRange()); frequencies = channel.getFrequencies(); Assert.assertEquals(3, frequencies.size()); Assert.assertTrue(frequencies.contains("alpha")); Assert.assertTrue(frequencies.contains("beta")); Assert.assertTrue(frequencies.contains("final")); channel = producer.getChannel("2.0"); Assert.assertEquals(fpGroupId, channel.getFeaturePackGroupId()); Assert.assertEquals(fpArtifactId, channel.getFeaturePackArtifactId()); Assert.assertEquals("[2.0.0,3.0.0)", channel.getVersionRange()); Assert.assertEquals(".*-ext-[0-9][0-9]", channel.getVersionIncludeRegex()); Assert.assertEquals(".*-ext-11", channel.getVersionExcludeRegex()); frequencies = channel.getFrequencies(); Assert.assertEquals(3, frequencies.size()); Assert.assertTrue(frequencies.contains("alpha")); Assert.assertTrue(frequencies.contains("beta")); Assert.assertTrue(frequencies.contains("final")); Assert.assertTrue(producer.hasChannel("2.0")); Assert.assertFalse(producer.hasChannel("3.0")); try { producer.getChannel("3.0"); } catch(MavenUniverseException e) { Assert.assertEquals(MavenErrors.channelNotFound(producer.getName(), "3.0").getLocalizedMessage(), e.getLocalizedMessage()); } Assert.assertEquals(2, producer.getChannels().size()); } }
amc8391/mage
Mage.Sets/src/mage/cards/g/GuidedStrike.java
<gh_stars>1-10 package mage.cards.g; import java.util.UUID; import mage.abilities.effects.Effect; import mage.abilities.effects.common.DrawCardSourceControllerEffect; import mage.abilities.effects.common.continuous.BoostTargetEffect; import mage.abilities.effects.common.continuous.GainAbilityTargetEffect; import mage.abilities.keyword.FirstStrikeAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.target.common.TargetCreaturePermanent; /** * * @author LoneFox * */ public final class GuidedStrike extends CardImpl { public GuidedStrike(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.INSTANT}, "{1}{W}"); // Target creature gets +1/+0 and gains first strike until end of turn. this.getSpellAbility().addTarget(new TargetCreaturePermanent()); Effect effect = new BoostTargetEffect(1, 0, Duration.EndOfTurn); effect.setText("Target creature gets +1/+0"); this.getSpellAbility().addEffect(effect); effect = new GainAbilityTargetEffect(FirstStrikeAbility.getInstance(), Duration.EndOfTurn); effect.setText("and gains first strike until end of turn"); this.getSpellAbility().addEffect(effect); // Draw a card. this.getSpellAbility().addEffect(new DrawCardSourceControllerEffect(1)); } public GuidedStrike(final GuidedStrike card) { super(card); } @Override public GuidedStrike copy() { return new GuidedStrike(this); } }
siertech/stapi
src/main/java/request/RequestService.java
<gh_stars>0 package request; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.siertech.stapi.model.GenericService; @Service public class RequestService extends GenericService<Request> { @Autowired private RequestDAO requestDAO; }
codegymdanang/CGDN-Demo-DigitalCubeRN
App/Containers/SignIn/index.js
<reponame>codegymdanang/CGDN-Demo-DigitalCubeRN import React, { Component } from 'react' import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { TouchableWithoutFeedback, View, Image, Text } from 'react-native' import LinearGradient from 'react-native-linear-gradient' import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view' import validator from 'validator' import { Colors, Images } from '@theme' import styles from './styles' import { RubikText, FontWeight, CustomTextInput, RoundedButton, Link } from '@components' import I18N from '@services/i18n' import UserActions from '@actions/user' class SignIn extends Component { constructor(props) { super(props) this.state = { email: '', password: '', emailError: '', passwordError: '', } } validateLogin = () => { const { email, password } = this.state; if (validator.isEmpty(email)) { return { type: 'email', errorMsg: 'Email required' }; } if (!validator.isEmail(email)) { return { type: 'email', errorMsg: 'Email invalid' }; } if (validator.isEmpty(password)) { return { type: 'password', errorMsg: 'Password required' }; } return null; } signIn = () => { const { navigation, userLogin, fetchLogin } = this.props; const { email, password } = this.state; this.setState({ emailError: '', passwordError: '' }); const error = this.validateLogin(); if (!error) { fetchLogin({email, password}) } else if (error.type === 'email') { this.setState({ emailError: error.errorMsg }); } else { this.setState({ passwordError: error.errorMsg }); } } renderSocial() { return ( <View style={styles.socialWrapper}> {/* TODO: onPress facebook */} <TouchableWithoutFeedback > <Image source={Images.icon.facebook} style={styles.imageSocial} /> </TouchableWithoutFeedback> {/* TODO: onPress google */} <TouchableWithoutFeedback> <Image source={Images.icon.google} style={styles.imageSocial} /> </TouchableWithoutFeedback> </View> ) } renderLogo() { return ( <View style={styles.logoWrapper}> <Image source={Images.stackedBookIcon} style={styles.logo} /> <Image source={Images.bookLoverBackground} style={styles.bookLoverLogo} /> <RubikText fontWeight={FontWeight.BOLD} text={I18N.t('signIn.header')} size={24} /> </View> ) } renderLoginByEmail() { const { passwordError, emailError, } = this.state; const { userLogin } = this.props return ( <View style={styles.loginByEmailWrapper}> <RubikText text={I18N.t('signIn.byEmail.header')} color={Colors.bodyText} style={{ textAlign: 'center' }} /> <CustomTextInput placeholder={I18N.t('signIn.byEmail.placeholder.email')} containerStyle={styles.textInput} onChangeText={text => this.setState({ email: text })} errorMessage={emailError} /> <CustomTextInput placeholder={I18N.t('signIn.byEmail.placeholder.password')} containerStyle={styles.textInput} secureTextEntry onChangeText={text => this.setState({ password: text })} errorMessage={passwordError} /> { userLogin.error && <Text style={styles.lbSystemError}>Incorrect email or password.</Text> } <Link text={I18N.t('signIn.forgotPassword')} fontWeight={FontWeight.BOLD} color={Colors.secondary} style={styles.forgotLink} /> {/* TODO: onPress to login */} <RoundedButton title={I18N.t('signIn.btnLoginLabel')} onPress={this.signIn} isLoading={userLogin.requesting} /> <View style={styles.rigesterLink}> <RubikText text={I18N.t('signIn.noAccountQuestion')} color={Colors.bodyText} size={12} /> {/* TODO: link to register page */} <Link text={I18N.t('signIn.registerLink')} fontWeight={FontWeight.BOLD} color={Colors.primary} onPress={() => this.props.navigation.navigate('InscriptionStep')} /> </View> </View> ) } render() { return ( <KeyboardAwareScrollView enableOnAndroid> <LinearGradient colors={[Colors.background, Colors.white]} start={{ x: 0, y: 0 }} end={{ x: 0, y: 1 }} style={styles.container}> {this.renderLogo()} {this.renderSocial()} {this.renderLoginByEmail()} </LinearGradient> </KeyboardAwareScrollView> ) } } export default connect( state => ({ userLogin: state.user.login, }), dispatch => bindActionCreators({ fetchLogin: UserActions.fetchLogin, }, dispatch) )(SignIn)
jackyluo/ilune-cas
PBX-Asterisk-Java/src/org/asteriskjava/manager/action/SipShowPeerAction.java
/* * Copyright 2004-2006 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.asteriskjava.manager.action; import org.asteriskjava.manager.ExpectedResponse; import org.asteriskjava.manager.response.SipShowPeerResponse; /** * Retrieves a the details about a given SIP peer.<p> * The result is returned in the response received in reply to this action.<p> * Use {@link org.asteriskjava.manager.response.ManagerResponse#getAttribute(String)} * to retrieve the properties. Consider using {@link org.asteriskjava.manager.action.SipPeersAction} * instead.<p> * Available since Asterisk 1.2 * * @author srt * @version $Id: SipShowPeerAction.java 1142 2008-08-20 12:02:59Z srt $ * @since 0.2 * @see org.asteriskjava.manager.action.SipPeersAction * @see org.asteriskjava.manager.response.SipShowPeerResponse */ @ExpectedResponse(SipShowPeerResponse.class) public class SipShowPeerAction extends AbstractManagerAction { /** * Serial version identifier. */ private static final long serialVersionUID = 1L; private String peer; /** * Creates a new empty SipShowPeerAction. */ public SipShowPeerAction() { } /** * Creates a new SipShowPeerAction that requests the details about the given * SIP peer. * <p> * This is just the peer name without the channel type prefix. For example * if your channel is called "SIP/john", the peer name is just "john". * * @param peer the name of the SIP peer to retrieve details for. * @since 0.2 */ public SipShowPeerAction(String peer) { this.peer = peer; } @Override public String getAction() { return "SIPShowPeer"; } /** * Returns the name of the peer to retrieve.<p> * This parameter is mandatory. * * @return the name of the peer to retrieve without the channel type prefix. */ public String getPeer() { return peer; } /** * Sets the name of the peer to retrieve. * <p> * This is just the peer name without the channel type prefix. For example * if your channel is called "SIP/john", the peer name is just "john". * <p> * This parameter is mandatory. * * @param peer the name of the peer to retrieve without the channel type prefix. */ public void setPeer(String peer) { this.peer = peer; } }
Kirishikesan/haiku
src/tests/servers/app/lock_focus/LockFocusTest.cpp
/* * Copyright 2005-2007, Haiku Inc. * Distributed under the terms of the MIT License. * * Authors: * <NAME>, <EMAIL> */ #include <Application.h> #include <MessageRunner.h> #include <Window.h> #include <View.h> #include <stdio.h> static const uint32 kMsgUpdate = 'updt'; class View : public BView { public: View(BRect rect); virtual ~View(); virtual void AttachedToWindow(); virtual void DetachedFromWindow(); virtual void Draw(BRect updateRect); virtual void KeyDown(const char* bytes, int32 numBytes); virtual void KeyUp(const char* bytes, int32 numBytes); virtual void MessageReceived(BMessage* message); virtual void MouseDown(BPoint where); private: void _Update(); BMessageRunner* fRunner; char fLastKey; bool fPressed; uint8 fLastColor; }; class Window : public BWindow { public: Window(int32 offset = 0); virtual ~Window(); virtual bool QuitRequested(); }; class Application : public BApplication { public: Application(); virtual void ReadyToRun(); }; View::View(BRect rect) : BView(rect, "lock focus", B_FOLLOW_ALL, B_WILL_DRAW), fRunner(NULL), fLastKey('\0'), fPressed(false), fLastColor(255) { } View::~View() { } void View::AttachedToWindow() { MakeFocus(this); BMessage update(kMsgUpdate); fRunner = new BMessageRunner(this, &update, 16667); BFont font; font.SetSize(72); SetFont(&font); } void View::DetachedFromWindow() { delete fRunner; fRunner = NULL; } void View::MouseDown(BPoint where) { SetMouseEventMask(0, B_LOCK_WINDOW_FOCUS | B_SUSPEND_VIEW_FOCUS | B_NO_POINTER_HISTORY); ::Window* window = new ::Window(100); window->Show(); } void View::MessageReceived(BMessage* message) { switch (message->what) { case kMsgUpdate: _Update(); break; default: BView::MessageReceived(message); break; } } void View::_Update() { if (fPressed) return; if (fLastColor < 255) { fLastColor += 15; Invalidate(); } } void View::KeyUp(const char* bytes, int32 numBytes) { fPressed = false; } void View::KeyDown(const char* bytes, int32 numBytes) { fLastKey = bytes[0]; fLastColor = 0; fPressed = true; Invalidate(); } void View::Draw(BRect updateRect) { SetHighColor(fLastColor, fLastColor, fLastColor); DrawString(&fLastKey, 1, BPoint(20, 70)); } // #pragma mark - Window::Window(int32 offset) : BWindow(BRect(100 + offset, 100 + offset, 400 + offset, 400 + offset), "LockFocus-Test", B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS) { BView *view = new View(Bounds()); AddChild(view); } Window::~Window() { } bool Window::QuitRequested() { be_app->PostMessage(B_QUIT_REQUESTED); return true; } // #pragma mark - Application::Application() : BApplication("application/x-vnd.haiku-lock_focus") { } void Application::ReadyToRun(void) { Window* window = new Window(); window->Show(); } // #pragma mark - int main(int argc, char** argv) { Application app; app.Run(); return 0; }
blendsdk/blendjs-sdk
etc/postinstall.js
var fs = require('fs'); var path = require('path'); var root = __dirname + '/../'; var mroot = root + '/node_modules'; var bcsroot = mroot + "/blend-class-system/lib"; var srcroot = root + "/src"; /** * Fixed the path per OS * @param {type} pth */ var fixPath = function (pth) { return pth.replace(/\\/g, path.sep); }; /** * Helper copy function * @param {type} srcFile * @param {type} destFile */ var copyFile = function (srcFile, destFile) { console.log("Installing " + path.basename(srcFile)); var srcContent = fs.readFileSync(fixPath(srcFile)).toString(); fs.writeFileSync(fixPath(destFile), srcContent); }; /** * Start copy files; */ copyFile(bcsroot + "/Blend.js", srcroot + "/js/core/Blend.js"); copyFile(bcsroot + "/ClassBuilder.js", srcroot + "/js/core/ClassBuilder.js"); copyFile(root + '/bin/builder/src/Builder/utils/String.js', srcroot + "/js/utils/String.js");
josehu07/SplitFS
kernel/linux-5.4/drivers/hwmon/lm80.c
// SPDX-License-Identifier: GPL-2.0-or-later /* * lm80.c - From lm_sensors, Linux kernel modules for hardware * monitoring * Copyright (C) 1998, 1999 <NAME> <<EMAIL>> * and <NAME> <<EMAIL>> * * Ported to Linux 2.6 by <NAME> <<EMAIL>> */ #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/jiffies.h> #include <linux/i2c.h> #include <linux/hwmon.h> #include <linux/hwmon-sysfs.h> #include <linux/err.h> #include <linux/mutex.h> /* Addresses to scan */ static const unsigned short normal_i2c[] = { 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, I2C_CLIENT_END }; /* Many LM80 constants specified below */ /* The LM80 registers */ #define LM80_REG_IN_MAX(nr) (0x2a + (nr) * 2) #define LM80_REG_IN_MIN(nr) (0x2b + (nr) * 2) #define LM80_REG_IN(nr) (0x20 + (nr)) #define LM80_REG_FAN1 0x28 #define LM80_REG_FAN2 0x29 #define LM80_REG_FAN_MIN(nr) (0x3b + (nr)) #define LM80_REG_TEMP 0x27 #define LM80_REG_TEMP_HOT_MAX 0x38 #define LM80_REG_TEMP_HOT_HYST 0x39 #define LM80_REG_TEMP_OS_MAX 0x3a #define LM80_REG_TEMP_OS_HYST 0x3b #define LM80_REG_CONFIG 0x00 #define LM80_REG_ALARM1 0x01 #define LM80_REG_ALARM2 0x02 #define LM80_REG_MASK1 0x03 #define LM80_REG_MASK2 0x04 #define LM80_REG_FANDIV 0x05 #define LM80_REG_RES 0x06 #define LM96080_REG_CONV_RATE 0x07 #define LM96080_REG_MAN_ID 0x3e #define LM96080_REG_DEV_ID 0x3f /* * Conversions. Rounding and limit checking is only done on the TO_REG * variants. Note that you should be a bit careful with which arguments * these macros are called: arguments may be evaluated more than once. * Fixing this is just not worth it. */ #define IN_TO_REG(val) (clamp_val(((val) + 5) / 10, 0, 255)) #define IN_FROM_REG(val) ((val) * 10) static inline unsigned char FAN_TO_REG(unsigned rpm, unsigned div) { if (rpm == 0) return 255; rpm = clamp_val(rpm, 1, 1000000); return clamp_val((1350000 + rpm * div / 2) / (rpm * div), 1, 254); } #define FAN_FROM_REG(val, div) ((val) == 0 ? -1 : \ (val) == 255 ? 0 : 1350000/((div) * (val))) #define TEMP_FROM_REG(reg) ((reg) * 125 / 32) #define TEMP_TO_REG(temp) (DIV_ROUND_CLOSEST(clamp_val((temp), \ -128000, 127000), 1000) << 8) #define DIV_FROM_REG(val) (1 << (val)) enum temp_index { t_input = 0, t_hot_max, t_hot_hyst, t_os_max, t_os_hyst, t_num_temp }; static const u8 temp_regs[t_num_temp] = { [t_input] = LM80_REG_TEMP, [t_hot_max] = LM80_REG_TEMP_HOT_MAX, [t_hot_hyst] = LM80_REG_TEMP_HOT_HYST, [t_os_max] = LM80_REG_TEMP_OS_MAX, [t_os_hyst] = LM80_REG_TEMP_OS_HYST, }; enum in_index { i_input = 0, i_max, i_min, i_num_in }; enum fan_index { f_input, f_min, f_num_fan }; /* * Client data (each client gets its own) */ struct lm80_data { struct i2c_client *client; struct mutex update_lock; char error; /* !=0 if error occurred during last update */ char valid; /* !=0 if following fields are valid */ unsigned long last_updated; /* In jiffies */ u8 in[i_num_in][7]; /* Register value, 1st index is enum in_index */ u8 fan[f_num_fan][2]; /* Register value, 1st index enum fan_index */ u8 fan_div[2]; /* Register encoding, shifted right */ s16 temp[t_num_temp]; /* Register values, normalized to 16 bit */ u16 alarms; /* Register encoding, combined */ }; static int lm80_read_value(struct i2c_client *client, u8 reg) { return i2c_smbus_read_byte_data(client, reg); } static int lm80_write_value(struct i2c_client *client, u8 reg, u8 value) { return i2c_smbus_write_byte_data(client, reg, value); } /* Called when we have found a new LM80 and after read errors */ static void lm80_init_client(struct i2c_client *client) { /* * Reset all except Watchdog values and last conversion values * This sets fan-divs to 2, among others. This makes most other * initializations unnecessary */ lm80_write_value(client, LM80_REG_CONFIG, 0x80); /* Set 11-bit temperature resolution */ lm80_write_value(client, LM80_REG_RES, 0x08); /* Start monitoring */ lm80_write_value(client, LM80_REG_CONFIG, 0x01); } static struct lm80_data *lm80_update_device(struct device *dev) { struct lm80_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; int i; int rv; int prev_rv; struct lm80_data *ret = data; mutex_lock(&data->update_lock); if (data->error) lm80_init_client(client); if (time_after(jiffies, data->last_updated + 2 * HZ) || !data->valid) { dev_dbg(dev, "Starting lm80 update\n"); for (i = 0; i <= 6; i++) { rv = lm80_read_value(client, LM80_REG_IN(i)); if (rv < 0) goto abort; data->in[i_input][i] = rv; rv = lm80_read_value(client, LM80_REG_IN_MIN(i)); if (rv < 0) goto abort; data->in[i_min][i] = rv; rv = lm80_read_value(client, LM80_REG_IN_MAX(i)); if (rv < 0) goto abort; data->in[i_max][i] = rv; } rv = lm80_read_value(client, LM80_REG_FAN1); if (rv < 0) goto abort; data->fan[f_input][0] = rv; rv = lm80_read_value(client, LM80_REG_FAN_MIN(1)); if (rv < 0) goto abort; data->fan[f_min][0] = rv; rv = lm80_read_value(client, LM80_REG_FAN2); if (rv < 0) goto abort; data->fan[f_input][1] = rv; rv = lm80_read_value(client, LM80_REG_FAN_MIN(2)); if (rv < 0) goto abort; data->fan[f_min][1] = rv; prev_rv = rv = lm80_read_value(client, LM80_REG_TEMP); if (rv < 0) goto abort; rv = lm80_read_value(client, LM80_REG_RES); if (rv < 0) goto abort; data->temp[t_input] = (prev_rv << 8) | (rv & 0xf0); for (i = t_input + 1; i < t_num_temp; i++) { rv = lm80_read_value(client, temp_regs[i]); if (rv < 0) goto abort; data->temp[i] = rv << 8; } rv = lm80_read_value(client, LM80_REG_FANDIV); if (rv < 0) goto abort; data->fan_div[0] = (rv >> 2) & 0x03; data->fan_div[1] = (rv >> 4) & 0x03; prev_rv = rv = lm80_read_value(client, LM80_REG_ALARM1); if (rv < 0) goto abort; rv = lm80_read_value(client, LM80_REG_ALARM2); if (rv < 0) goto abort; data->alarms = prev_rv + (rv << 8); data->last_updated = jiffies; data->valid = 1; data->error = 0; } goto done; abort: ret = ERR_PTR(rv); data->valid = 0; data->error = 1; done: mutex_unlock(&data->update_lock); return ret; } /* * Sysfs stuff */ static ssize_t in_show(struct device *dev, struct device_attribute *attr, char *buf) { struct lm80_data *data = lm80_update_device(dev); int index = to_sensor_dev_attr_2(attr)->index; int nr = to_sensor_dev_attr_2(attr)->nr; if (IS_ERR(data)) return PTR_ERR(data); return sprintf(buf, "%d\n", IN_FROM_REG(data->in[nr][index])); } static ssize_t in_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct lm80_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; int index = to_sensor_dev_attr_2(attr)->index; int nr = to_sensor_dev_attr_2(attr)->nr; long val; u8 reg; int err = kstrtol(buf, 10, &val); if (err < 0) return err; reg = nr == i_min ? LM80_REG_IN_MIN(index) : LM80_REG_IN_MAX(index); mutex_lock(&data->update_lock); data->in[nr][index] = IN_TO_REG(val); lm80_write_value(client, reg, data->in[nr][index]); mutex_unlock(&data->update_lock); return count; } static ssize_t fan_show(struct device *dev, struct device_attribute *attr, char *buf) { int index = to_sensor_dev_attr_2(attr)->index; int nr = to_sensor_dev_attr_2(attr)->nr; struct lm80_data *data = lm80_update_device(dev); if (IS_ERR(data)) return PTR_ERR(data); return sprintf(buf, "%d\n", FAN_FROM_REG(data->fan[nr][index], DIV_FROM_REG(data->fan_div[index]))); } static ssize_t fan_div_show(struct device *dev, struct device_attribute *attr, char *buf) { int nr = to_sensor_dev_attr(attr)->index; struct lm80_data *data = lm80_update_device(dev); if (IS_ERR(data)) return PTR_ERR(data); return sprintf(buf, "%d\n", DIV_FROM_REG(data->fan_div[nr])); } static ssize_t fan_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int index = to_sensor_dev_attr_2(attr)->index; int nr = to_sensor_dev_attr_2(attr)->nr; struct lm80_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; unsigned long val; int err = kstrtoul(buf, 10, &val); if (err < 0) return err; mutex_lock(&data->update_lock); data->fan[nr][index] = FAN_TO_REG(val, DIV_FROM_REG(data->fan_div[index])); lm80_write_value(client, LM80_REG_FAN_MIN(index + 1), data->fan[nr][index]); mutex_unlock(&data->update_lock); return count; } /* * Note: we save and restore the fan minimum here, because its value is * determined in part by the fan divisor. This follows the principle of * least surprise; the user doesn't expect the fan minimum to change just * because the divisor changed. */ static ssize_t fan_div_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { int nr = to_sensor_dev_attr(attr)->index; struct lm80_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; unsigned long min, val; u8 reg; int rv; rv = kstrtoul(buf, 10, &val); if (rv < 0) return rv; /* Save fan_min */ mutex_lock(&data->update_lock); min = FAN_FROM_REG(data->fan[f_min][nr], DIV_FROM_REG(data->fan_div[nr])); switch (val) { case 1: data->fan_div[nr] = 0; break; case 2: data->fan_div[nr] = 1; break; case 4: data->fan_div[nr] = 2; break; case 8: data->fan_div[nr] = 3; break; default: dev_err(dev, "fan_div value %ld not supported. Choose one of 1, 2, 4 or 8!\n", val); mutex_unlock(&data->update_lock); return -EINVAL; } rv = lm80_read_value(client, LM80_REG_FANDIV); if (rv < 0) { mutex_unlock(&data->update_lock); return rv; } reg = (rv & ~(3 << (2 * (nr + 1)))) | (data->fan_div[nr] << (2 * (nr + 1))); lm80_write_value(client, LM80_REG_FANDIV, reg); /* Restore fan_min */ data->fan[f_min][nr] = FAN_TO_REG(min, DIV_FROM_REG(data->fan_div[nr])); lm80_write_value(client, LM80_REG_FAN_MIN(nr + 1), data->fan[f_min][nr]); mutex_unlock(&data->update_lock); return count; } static ssize_t temp_show(struct device *dev, struct device_attribute *devattr, char *buf) { struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr); struct lm80_data *data = lm80_update_device(dev); if (IS_ERR(data)) return PTR_ERR(data); return sprintf(buf, "%d\n", TEMP_FROM_REG(data->temp[attr->index])); } static ssize_t temp_store(struct device *dev, struct device_attribute *devattr, const char *buf, size_t count) { struct sensor_device_attribute *attr = to_sensor_dev_attr(devattr); struct lm80_data *data = dev_get_drvdata(dev); struct i2c_client *client = data->client; int nr = attr->index; long val; int err = kstrtol(buf, 10, &val); if (err < 0) return err; mutex_lock(&data->update_lock); data->temp[nr] = TEMP_TO_REG(val); lm80_write_value(client, temp_regs[nr], data->temp[nr] >> 8); mutex_unlock(&data->update_lock); return count; } static ssize_t alarms_show(struct device *dev, struct device_attribute *attr, char *buf) { struct lm80_data *data = lm80_update_device(dev); if (IS_ERR(data)) return PTR_ERR(data); return sprintf(buf, "%u\n", data->alarms); } static ssize_t alarm_show(struct device *dev, struct device_attribute *attr, char *buf) { int bitnr = to_sensor_dev_attr(attr)->index; struct lm80_data *data = lm80_update_device(dev); if (IS_ERR(data)) return PTR_ERR(data); return sprintf(buf, "%u\n", (data->alarms >> bitnr) & 1); } static SENSOR_DEVICE_ATTR_2_RW(in0_min, in, i_min, 0); static SENSOR_DEVICE_ATTR_2_RW(in1_min, in, i_min, 1); static SENSOR_DEVICE_ATTR_2_RW(in2_min, in, i_min, 2); static SENSOR_DEVICE_ATTR_2_RW(in3_min, in, i_min, 3); static SENSOR_DEVICE_ATTR_2_RW(in4_min, in, i_min, 4); static SENSOR_DEVICE_ATTR_2_RW(in5_min, in, i_min, 5); static SENSOR_DEVICE_ATTR_2_RW(in6_min, in, i_min, 6); static SENSOR_DEVICE_ATTR_2_RW(in0_max, in, i_max, 0); static SENSOR_DEVICE_ATTR_2_RW(in1_max, in, i_max, 1); static SENSOR_DEVICE_ATTR_2_RW(in2_max, in, i_max, 2); static SENSOR_DEVICE_ATTR_2_RW(in3_max, in, i_max, 3); static SENSOR_DEVICE_ATTR_2_RW(in4_max, in, i_max, 4); static SENSOR_DEVICE_ATTR_2_RW(in5_max, in, i_max, 5); static SENSOR_DEVICE_ATTR_2_RW(in6_max, in, i_max, 6); static SENSOR_DEVICE_ATTR_2_RO(in0_input, in, i_input, 0); static SENSOR_DEVICE_ATTR_2_RO(in1_input, in, i_input, 1); static SENSOR_DEVICE_ATTR_2_RO(in2_input, in, i_input, 2); static SENSOR_DEVICE_ATTR_2_RO(in3_input, in, i_input, 3); static SENSOR_DEVICE_ATTR_2_RO(in4_input, in, i_input, 4); static SENSOR_DEVICE_ATTR_2_RO(in5_input, in, i_input, 5); static SENSOR_DEVICE_ATTR_2_RO(in6_input, in, i_input, 6); static SENSOR_DEVICE_ATTR_2_RW(fan1_min, fan, f_min, 0); static SENSOR_DEVICE_ATTR_2_RW(fan2_min, fan, f_min, 1); static SENSOR_DEVICE_ATTR_2_RO(fan1_input, fan, f_input, 0); static SENSOR_DEVICE_ATTR_2_RO(fan2_input, fan, f_input, 1); static SENSOR_DEVICE_ATTR_RW(fan1_div, fan_div, 0); static SENSOR_DEVICE_ATTR_RW(fan2_div, fan_div, 1); static SENSOR_DEVICE_ATTR_RO(temp1_input, temp, t_input); static SENSOR_DEVICE_ATTR_RW(temp1_max, temp, t_hot_max); static SENSOR_DEVICE_ATTR_RW(temp1_max_hyst, temp, t_hot_hyst); static SENSOR_DEVICE_ATTR_RW(temp1_crit, temp, t_os_max); static SENSOR_DEVICE_ATTR_RW(temp1_crit_hyst, temp, t_os_hyst); static DEVICE_ATTR_RO(alarms); static SENSOR_DEVICE_ATTR_RO(in0_alarm, alarm, 0); static SENSOR_DEVICE_ATTR_RO(in1_alarm, alarm, 1); static SENSOR_DEVICE_ATTR_RO(in2_alarm, alarm, 2); static SENSOR_DEVICE_ATTR_RO(in3_alarm, alarm, 3); static SENSOR_DEVICE_ATTR_RO(in4_alarm, alarm, 4); static SENSOR_DEVICE_ATTR_RO(in5_alarm, alarm, 5); static SENSOR_DEVICE_ATTR_RO(in6_alarm, alarm, 6); static SENSOR_DEVICE_ATTR_RO(fan1_alarm, alarm, 10); static SENSOR_DEVICE_ATTR_RO(fan2_alarm, alarm, 11); static SENSOR_DEVICE_ATTR_RO(temp1_max_alarm, alarm, 8); static SENSOR_DEVICE_ATTR_RO(temp1_crit_alarm, alarm, 13); /* * Real code */ static struct attribute *lm80_attrs[] = { &sensor_dev_attr_in0_min.dev_attr.attr, &sensor_dev_attr_in1_min.dev_attr.attr, &sensor_dev_attr_in2_min.dev_attr.attr, &sensor_dev_attr_in3_min.dev_attr.attr, &sensor_dev_attr_in4_min.dev_attr.attr, &sensor_dev_attr_in5_min.dev_attr.attr, &sensor_dev_attr_in6_min.dev_attr.attr, &sensor_dev_attr_in0_max.dev_attr.attr, &sensor_dev_attr_in1_max.dev_attr.attr, &sensor_dev_attr_in2_max.dev_attr.attr, &sensor_dev_attr_in3_max.dev_attr.attr, &sensor_dev_attr_in4_max.dev_attr.attr, &sensor_dev_attr_in5_max.dev_attr.attr, &sensor_dev_attr_in6_max.dev_attr.attr, &sensor_dev_attr_in0_input.dev_attr.attr, &sensor_dev_attr_in1_input.dev_attr.attr, &sensor_dev_attr_in2_input.dev_attr.attr, &sensor_dev_attr_in3_input.dev_attr.attr, &sensor_dev_attr_in4_input.dev_attr.attr, &sensor_dev_attr_in5_input.dev_attr.attr, &sensor_dev_attr_in6_input.dev_attr.attr, &sensor_dev_attr_fan1_min.dev_attr.attr, &sensor_dev_attr_fan2_min.dev_attr.attr, &sensor_dev_attr_fan1_input.dev_attr.attr, &sensor_dev_attr_fan2_input.dev_attr.attr, &sensor_dev_attr_fan1_div.dev_attr.attr, &sensor_dev_attr_fan2_div.dev_attr.attr, &sensor_dev_attr_temp1_input.dev_attr.attr, &sensor_dev_attr_temp1_max.dev_attr.attr, &sensor_dev_attr_temp1_max_hyst.dev_attr.attr, &sensor_dev_attr_temp1_crit.dev_attr.attr, &sensor_dev_attr_temp1_crit_hyst.dev_attr.attr, &dev_attr_alarms.attr, &sensor_dev_attr_in0_alarm.dev_attr.attr, &sensor_dev_attr_in1_alarm.dev_attr.attr, &sensor_dev_attr_in2_alarm.dev_attr.attr, &sensor_dev_attr_in3_alarm.dev_attr.attr, &sensor_dev_attr_in4_alarm.dev_attr.attr, &sensor_dev_attr_in5_alarm.dev_attr.attr, &sensor_dev_attr_in6_alarm.dev_attr.attr, &sensor_dev_attr_fan1_alarm.dev_attr.attr, &sensor_dev_attr_fan2_alarm.dev_attr.attr, &sensor_dev_attr_temp1_max_alarm.dev_attr.attr, &sensor_dev_attr_temp1_crit_alarm.dev_attr.attr, NULL }; ATTRIBUTE_GROUPS(lm80); /* Return 0 if detection is successful, -ENODEV otherwise */ static int lm80_detect(struct i2c_client *client, struct i2c_board_info *info) { struct i2c_adapter *adapter = client->adapter; int i, cur, man_id, dev_id; const char *name = NULL; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) return -ENODEV; /* First check for unused bits, common to both chip types */ if ((lm80_read_value(client, LM80_REG_ALARM2) & 0xc0) || (lm80_read_value(client, LM80_REG_CONFIG) & 0x80)) return -ENODEV; /* * The LM96080 has manufacturer and stepping/die rev registers so we * can just check that. The LM80 does not have such registers so we * have to use a more expensive trick. */ man_id = lm80_read_value(client, LM96080_REG_MAN_ID); dev_id = lm80_read_value(client, LM96080_REG_DEV_ID); if (man_id == 0x01 && dev_id == 0x08) { /* Check more unused bits for confirmation */ if (lm80_read_value(client, LM96080_REG_CONV_RATE) & 0xfe) return -ENODEV; name = "lm96080"; } else { /* Check 6-bit addressing */ for (i = 0x2a; i <= 0x3d; i++) { cur = i2c_smbus_read_byte_data(client, i); if ((i2c_smbus_read_byte_data(client, i + 0x40) != cur) || (i2c_smbus_read_byte_data(client, i + 0x80) != cur) || (i2c_smbus_read_byte_data(client, i + 0xc0) != cur)) return -ENODEV; } name = "lm80"; } strlcpy(info->type, name, I2C_NAME_SIZE); return 0; } static int lm80_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct device *dev = &client->dev; struct device *hwmon_dev; struct lm80_data *data; int rv; data = devm_kzalloc(dev, sizeof(struct lm80_data), GFP_KERNEL); if (!data) return -ENOMEM; data->client = client; mutex_init(&data->update_lock); /* Initialize the LM80 chip */ lm80_init_client(client); /* A few vars need to be filled upon startup */ rv = lm80_read_value(client, LM80_REG_FAN_MIN(1)); if (rv < 0) return rv; data->fan[f_min][0] = rv; rv = lm80_read_value(client, LM80_REG_FAN_MIN(2)); if (rv < 0) return rv; data->fan[f_min][1] = rv; hwmon_dev = devm_hwmon_device_register_with_groups(dev, client->name, data, lm80_groups); return PTR_ERR_OR_ZERO(hwmon_dev); } /* * Driver data (common to all clients) */ static const struct i2c_device_id lm80_id[] = { { "lm80", 0 }, { "lm96080", 1 }, { } }; MODULE_DEVICE_TABLE(i2c, lm80_id); static struct i2c_driver lm80_driver = { .class = I2C_CLASS_HWMON, .driver = { .name = "lm80", }, .probe = lm80_probe, .id_table = lm80_id, .detect = lm80_detect, .address_list = normal_i2c, }; module_i2c_driver(lm80_driver); MODULE_AUTHOR("<NAME> <<EMAIL>> and " "<NAME> <<EMAIL>>"); MODULE_DESCRIPTION("LM80 driver"); MODULE_LICENSE("GPL");
Dbevan/SunderingShadows
d/laerad/outpost/rooms/1.c
<gh_stars>10-100 #include <std.h> #include "../outpost.h" inherit STORAGE"coastline"; void create(){ ::create(); set_exits(([ "south" : "d/laerad/wasteland/waste2", "northeast" : ROOMS"2", ])); } void reset(){ ::reset(); if(!present("anton")){new(MOBS"anton")->move(TO);} if(!present("gateguard")){new(MOBS"gateguard")->move(TO);} }
tejasvinu/hetu-core
presto-main/src/main/java/io/prestosql/execution/CachePredicate.java
/* * Copyright (C) 2018-2020. Huawei Technologies Co., Ltd. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.prestosql.execution; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.prestosql.spi.connector.ColumnMetadata; import io.prestosql.spi.predicate.TupleDomain; import java.util.Objects; public class CachePredicate { private final TupleDomain<ColumnMetadata> columnMetadataTupleDomain; private final String cachePredicateString; // For storing human readable predicate input as it cannot be extracted from a TupleDomain @JsonCreator public CachePredicate( @JsonProperty("columnMetadataTupleDomain") TupleDomain<ColumnMetadata> columnMetadataTupleDomain, @JsonProperty("cachePredicateString") String cachePredicateString) { this.columnMetadataTupleDomain = columnMetadataTupleDomain; this.cachePredicateString = cachePredicateString; } @JsonProperty public TupleDomain<ColumnMetadata> getColumnMetadataTupleDomain() { return columnMetadataTupleDomain; } @JsonProperty public String getCachePredicateString() { return cachePredicateString; } @Override public String toString() { return "CachePredicate{" + "columnMetadataTupleDomain=" + columnMetadataTupleDomain + ", cachePredicateString='" + cachePredicateString + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof CachePredicate)) { return false; } CachePredicate that = (CachePredicate) o; return Objects.equals(columnMetadataTupleDomain, that.columnMetadataTupleDomain) && Objects.equals(cachePredicateString, that.cachePredicateString); } @Override public int hashCode() { return Objects.hash(columnMetadataTupleDomain, cachePredicateString); } }
xlf19/PurchasingCenter
jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/contract/jingfen/service/impl/JingFengServiceImpl.java
<filename>jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/contract/jingfen/service/impl/JingFengServiceImpl.java package org.jeecg.modules.contract.jingfen.service.impl; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.apache.poi.ss.formula.functions.T; import org.jeecg.modules.contract.jingfen.mapper.JingFengMapper; import org.jeecg.modules.contract.jingfen.service.IJingFengService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Map; @Service public class JingFengServiceImpl extends ServiceImpl<JingFengMapper, T> implements IJingFengService { @Autowired JingFengMapper jf; public void addjqlist(String pgdh,String htbh) { jf.addjqlist(pgdh,htbh); } public void addjqlistat(String startTime, String endTime, String gudw,String htbh) { jf.addjqlistat(startTime,endTime,gudw,htbh); } public IPage<Map<Object, String>> selectjfdy(IPage<Map<Object, String>> page, String htbh, Integer pzh) { return jf.selectjfdy(page,htbh,pzh); } public Map<Object, Object> updatejsd(String id) { return jf.updatejsd(id); } }
FANsZL/hive
ql/src/java/org/apache/hadoop/hive/ql/exec/vector/ptf/VectorPTFEvaluatorAbstractLeadLag.java
<gh_stars>1000+ /* * 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.hadoop.hive.ql.exec.vector.ptf; import java.util.stream.IntStream; import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch; import org.apache.hadoop.hive.ql.exec.vector.ColumnVector.Type; import org.apache.hadoop.hive.ql.exec.vector.expressions.ConstantVectorExpression; import org.apache.hadoop.hive.ql.exec.vector.expressions.IdentityExpression; import org.apache.hadoop.hive.ql.exec.vector.expressions.VectorExpression; import org.apache.hadoop.hive.ql.exec.vector.ptf.VectorPTFEvaluatorBase; import org.apache.hadoop.hive.ql.exec.vector.ptf.VectorPTFGroupBatches; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.plan.ptf.WindowFrameDef; import org.apache.hadoop.hive.ql.udf.ptf.Range; import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable; public abstract class VectorPTFEvaluatorAbstractLeadLag extends VectorPTFEvaluatorBase { protected int amt; protected Object defaultValue; protected int defaultValueColumn = -1; protected Type type; public VectorPTFEvaluatorAbstractLeadLag(WindowFrameDef windowFrameDef, VectorExpression inputVecExpr, int outputColumnNum, Type type, int amt, VectorExpression defaultValueExpression) { super(windowFrameDef, inputVecExpr, outputColumnNum); this.type = type; this.amt = amt; initDefaultValue(defaultValueExpression); } private void initDefaultValue(VectorExpression defaultValueExpression) { if (defaultValueExpression == null) { defaultValue = null; return; } else if (defaultValueExpression instanceof ConstantVectorExpression) { // FIXME: always getLongValue()? check if other type is given in 3rd argument long longValue = ((ConstantVectorExpression) defaultValueExpression).getLongValue(); switch (type) { case LONG: defaultValue = longValue; break; case DOUBLE: defaultValue = Double.valueOf(longValue); break; case DECIMAL: defaultValue = new HiveDecimalWritable(longValue); break; default: throw new RuntimeException("Unexpected column vector type " + type + " for lag function"); } } else if (defaultValueExpression instanceof IdentityExpression) { defaultValueColumn = ((IdentityExpression) defaultValueExpression).getOutputColumnNum(); } else { throw new RuntimeException( "Unexpected vector expression type for default value in lag function: " + defaultValueExpression.getClass().getName()); } } @Override public boolean canRunOptimizedCalculation(int rowNum, Range range) { return true; } protected Object getDefaultValue(int rowNum, VectorPTFGroupBatches batches) throws HiveException { if (defaultValueColumn > -1) { return batches.getValue(rowNum, defaultValueColumn); } else { return defaultValue; } } @Override public void evaluateGroupBatch(VectorizedRowBatch batch) throws HiveException { } // TODO: HIVE-25123: Implement vectorized streaming lead/lag @Override public boolean streamsResult() { return false; } @Override public Type getResultColumnVectorType() { return type; } @Override public void resetEvaluator() { } @Override public boolean isCacheableForRange() { return false; } @Override public void mapCustomColumns(int[] bufferedColumnMap) { if (defaultValueColumn > -1) { defaultValueColumn = IntStream.range(0, bufferedColumnMap.length) .filter(j -> bufferedColumnMap[j] == defaultValueColumn).findFirst() .orElseGet(() -> defaultValueColumn); } } }
tramwayjs/cli
dev/config/services/templates.js
import { indexing, dependencies, classes, config, methods, routes, server, } from "../../services/templates"; const { ConvergenceTemplate, DependencyExposure, MultiClassDirectory, SingleClassDirectory, UnificationTemplate, } = indexing; const { DependencyTemplate, } = dependencies; const { ClassTemplate, } = classes; const { ConfigTemplate, } = config; const { MethodTemplate, GetterSetterTemplate, } = methods; const { RouteBuilder, versions, } = routes; const { V1Builder, V3Builder, } = versions; const { ServerTemplate, } = server; export default { "template.index:convergence": { "class": ConvergenceTemplate, "constructor": [ {"type": "service", "key": "service.module_generation"}, ] }, "template.index:multiclass": { "class": MultiClassDirectory, "constructor": [ {"type": "service", "key": "service.module_generation"}, ] }, "template.index:unification": { "class": UnificationTemplate, "constructor": [ {"type": "service", "key": "service.module_generation"}, ] }, "template.index:dependency_exposure": { "class": DependencyExposure, "constructor": [ {"type": "service", "key": "service.module_generation"}, ] }, "template.dependency": { "class": DependencyTemplate, "constructor": [ {"type": "service", "key": "provider.file"}, {"type": "parameter", "key": "dependency_dirname"}, ] }, "template.class": { "class": ClassTemplate, "constructor": [ {"type": "service", "key": "provider.file"}, {"type": "parameter", "key": "class_versions"}, {"type": "parameter", "key": "class_dirname"}, ] }, "template.config": { "class": ConfigTemplate, "constructor": [ {"type": "service", "key": "provider.file"}, {"type": "parameter", "key": "config_versions"}, {"type": "parameter", "key": "config_dirname"}, ] }, "template.method": { "class": MethodTemplate, "constructor": [ {"type": "service", "key": "provider.file"}, {"type": "parameter", "key": "method_versions"}, {"type": "parameter", "key": "method_dirname"}, ] }, "template.method:getter_setter": { "class": GetterSetterTemplate, "constructor": [ {"type": "service", "key": "provider.file"}, {"type": "parameter", "key": "method_versions"}, {"type": "parameter", "key": "method_dirname"}, ] }, "template.route:v1": { "class": RouteBuilder, "constructor": [ {"type": "service", "key": "builder.route:v1"}, ] }, "template.route:v2": { "class": RouteBuilder, "constructor": [ {"type": "service", "key": "builder.route:v1"}, ] }, "template.route:v3": { "class": RouteBuilder, "constructor": [ {"type": "service", "key": "builder.route:v3"}, ] }, "builder.route:v1": { "class": V1Builder, "constructor": [ {"type": "parameter", "key": "format"}, ] }, "builder.route:v3": { "class": V3Builder, "constructor": [ {"type": "parameter", "key": "format"}, ] }, "template.server": { "class": ServerTemplate, "constructor": [ {"type": "service", "key": "provider.file"}, {"type": "parameter", "key": "server_versions"}, {"type": "parameter", "key": "server_dirname"}, ] }, }
KarlCyan/zeus
src/main/java/com/harmonycloud/zeus/bean/user/BeanResourceMenu.java
<reponame>KarlCyan/zeus package com.harmonycloud.zeus.bean.user; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import lombok.EqualsAndHashCode; import java.io.Serializable; /** * @author xutianhong * @Date 2021/7/28 11:18 上午 */ @Data @EqualsAndHashCode(callSuper = false) @TableName("resource_menu") public class BeanResourceMenu implements Serializable { private static final long serialVersionUID = -678893223L; /** * 自增id */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 字段名称 */ @TableField("name") private String name; /** * 字段名称 */ @TableField("alias_name") private String aliasName; /** * 字段名称 */ @TableField("url") private String url; /** * 字段名称 */ @TableField("weight") private Integer weight; /** * 字段名称 */ @TableField("icon_name") private String iconName; /** * 字段名称 */ @TableField("parent_id") private Integer parentId; /** * 字段名称 */ @TableField("module") private String module; }
ihltx/spring-boot-starter-ihltx
src/main/java/com/ihltx/utility/redis/exception/RedisException.java
package com.ihltx.utility.redis.exception; public class RedisException extends Exception { /** * */ private static final long serialVersionUID = -203518099579136285L; public RedisException(String message) { super(message); } }
khamutov/intellij-scala
scala/scala-impl/testdata/resolve/class/dependent2/a.scala
<gh_stars>100-1000 trait CompilationUnits { self : Global => class CompilationUnit } class Global extends CompilationUnits { } class MainXMLExporter { class XMLExporter() { val global = new Global import global._ val units: <ref>CompilationUnit = null } }
Markoy8/Foundry
Components/LearningCore/Source/gov/sandia/cognition/learning/function/scalar/HardTanHFunction.java
<gh_stars>100-1000 /* * File: HardTanHFunction.java * Authors: <NAME> * Project: Cognitive Foundry * * Copyright 2016 Cognitive Foundry. All rights reserved. */ package gov.sandia.cognition.learning.function.scalar; import gov.sandia.cognition.math.AbstractDifferentiableUnivariateScalarFunction; /** * A hard sigmoid function, which is an approximation of a tanh sigmoid * whose output is between -1 and 1. The function also maps values between * -1 and 1 linearly between -1 and 1 and for values outside that range it is * capped. Unlike the soft tanh it actually ends up producing values of -1 * and 1 for inputs outside of that range, where it is saturated. * * The functional form is: f(x) = min(1.0, max(-1.0, x)) * * @author <NAME> * @since 4.0.0 * @see TanHFunction */ public class HardTanHFunction extends AbstractDifferentiableUnivariateScalarFunction { /** * Creates a new {@link HardTanHFunction}. */ public HardTanHFunction() { super(); } @Override public HardTanHFunction clone() { return (HardTanHFunction) super.clone(); } @Override public double evaluate( final double input) { return hardTanH(input); } @Override public double differentiate( final double input) { if (input >= 1.0 || input <= -1.0) { return 0.0; } else { return 1.0; } } /** * Computes the hard sigmoid function. The functional form is: * f(x) = min(1.0, max(-1.0, x)) * * @param input * The input value to apply the hard sigmoid to. * @return * The output, which is between -1.0 and 1.0. If NaN is given, NaN will * be returned. */ public static double hardTanH( final double input) { if (input <= -1.0) { return -1.0; } else if (input >= 1.0) { return 1.0; } else { return input; } } }
mdyd-dev/pos-cli
bin/pos-cli-init.js
#!/usr/bin/env node const program = require('commander'), degit = require('degit'), inquirer = require('inquirer'); const logger = require('../lib/logger'), report = require('../lib/logger/report'); const repos = { empty: 'mdyd-dev/directory-structure', 'Hello world': 'mdyd-dev/hello-world', 'Todo app': 'mdyd-dev/todo-app', 'Product Marketplace Template': 'mdyd-dev/product-marketplace-template', }; function createStructure(url, branch) { branch = branch ? `#${branch}` : ''; degit(`${url}${branch}`, { force: true, cache: false, verbose: false }) .clone('.') .then(() => { report('[OK] Init', { extras: [ { key: 'status', value: 'Success' }, { key: 'hasBranch', value: !!branch }, ], }); logger.Success('Directory structure sucessfully created.'); }) .catch((error) => { report('[ERR] Init', { extras: [ { key: 'status', value: 'Error' }, { key: 'hasBranch', value: !!branch }, ], }); logger.Error(`Cloning failed. Reason: ${error.message}`); }); } program .name('pos-cli init') .option( '--url <url>', 'structure source repository url (github, bitbucket, gitlab). \nRead more on accepted formats: https://github.com/Rich-Harris/degit#usage \n' ) .option('--branch <branch>', 'branch where the structure is located') .option('-w, --wizard', 'Start repo wizard') .action(async (params) => { if (params.wizard) { inquirer .prompt([ { type: 'list', name: 'repo', message: 'Example app', default: 'empty', choices: Object.keys(repos), }, { type: 'string', name: 'branch', message: 'Branch', default: 'master', }, ]) .then((answers) => { createStructure(repos[answers.repo], answers.branch); report('Init: Wizard', { extras: [ { key: 'status', value: 'Success' }, { key: 'repo', value: repos[answers.repo] }, ], }); }) return; } const url = params.url || repos.empty; createStructure(url, params.branch); }); program.parse(process.argv);
Kowalski1337/softwareDesign
hw7/src/main/java/com/ifmo/vnaydyuk/animal/TextAnimal.java
package com.ifmo.vnaydyuk.animal; public abstract class TextAnimal implements Animal { private final String sound; private final String name; protected TextAnimal(String name, String sound) { this.name = name; this.sound = sound; } @Override public String getName() { return name; } @Override public String saySomething() { return sound; } }
sunshengfei/workflow-corex
lib/src/main/java/com/fuwafuwa/workflow/agent/IViewProxy.java
package com.fuwafuwa.workflow.agent; import android.content.Context; import android.view.ViewGroup; import com.fuwafuwa.workflow.adapter.BaseFlowRecyclerViewHolder; import com.fuwafuwa.workflow.adapter.BaseRecyclerViewHolder; import com.fuwafuwa.workflow.adapter.IWorkFlowAdapter; import com.fuwafuwa.workflow.bean.IWorkFlowAdapterItem; import com.fuwafuwa.workflow.bean.WorkFlowTypeItem; import java.lang.ref.SoftReference; public interface IViewProxy { //region Adapter 重构 void setCurrentItemViewType(int currentItemViewType); String getFlowItemTypeDescription(); int acceptItemViewType(); int[] acceptItemViewTypes(); boolean canDrag(); boolean canDrop(); BaseFlowRecyclerViewHolder<IWorkFlowAdapterItem> onRenderHolder(ViewGroup parent, int viewType, ISimpleFlowAction iWorkFlowActionHandler); //endregion //Flow Item boolean slotValueHasBeenSet(SoftReference<Context> mContextRef, BaseRecyclerViewHolder<? extends IWorkFlowAdapterItem> holder, String urlTag); void onClickFlowItem(SoftReference<Context> mContextRef, BaseRecyclerViewHolder<? extends IWorkFlowAdapterItem> holder, String urlTag); // View Bean void onCreateSkeleton(IWorkFlowAdapter adapter, WorkFlowTypeItem workFlowTypeItem); }
Douglasdsm/web-css-html-javascript
array.js/atividade02.js
<reponame>Douglasdsm/web-css-html-javascript //Escreva uma função que receba a idade de uma pessoa em anos e retorne a mesma idade em dias. function idadeEmDias(idade){ dias = 365*idade return dias } const Douglas = idadeEmDias(24) const Deivid = idadeEmDias(23) console.log(Douglas); console.log(Deivid);
kanety/enum_ish
lib/enum_ish/dictionary_lookup.rb
module EnumIsh class DictionaryLookup def initialize(klass, enum, options = {}) @klass = klass @enum = enum @options = options end def call i18n = lookup_for(@klass).transform_keys { |k| k.to_s.to_sym } dict = {} if @enum.use?(:accessor) @enum.mapping.each { |k, v| dict[k] = i18n[k] } else @enum.mapping.each { |k, v| dict[v] = i18n[k] } end filter(dict) end private def lookup_for(klass) if klass.name.blank? || !klass.is_a?(Class) return lookup_for(klass.superclass) end key = [@enum.name, @options[:format]].compact.join('/') options = (@options[:i18n_options] || {}).merge(default: nil) if klass.name.to_s.in?(['ActiveRecord::Base', 'Object']) I18n.t(:"enum_ish.defaults.#{key}", **options) || @enum.mapping else I18n.t(:"enum_ish.#{klass.name.underscore}.#{key}", **options) || lookup_for(klass.superclass) end end def filter(dict) if @options[:except] except = Array(@options[:except]) dict.reject! { |k, v| except.include?(k) } end if @options[:only] only = Array(@options[:only]) dict.select! { |k, v| only.include?(k) } end dict end end end
oneHook/onehook_android_general_library
onehookinclibrary/src/main/java/com/onehook/view/confetti/ConfettiView.java
<gh_stars>10-100 package com.onehook.view.confetti; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Path; import android.graphics.PathMeasure; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.widget.TextView; import com.onehook.util.animator.AnimationEndListener; import com.onehookinc.androidlib.R; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.Collection; /** * Created by <NAME> on 2016-04-04. */ public class ConfettiView extends ViewGroup { private static final String TAG = "OHConfettiView"; private static final boolean DEBUG = true; public interface IConfettiViewCustomizationListener { View createConfettiCell(final ConfettiCellBuilder builder, final int index); } public ConfettiView(Context context) { super(context); commonInit(context, null); } public ConfettiView(Context context, AttributeSet attrs) { super(context, attrs); commonInit(context, attrs); } public ConfettiView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); commonInit(context, attrs); } @TargetApi(21) public ConfettiView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); commonInit(context, attrs); } private int mMinDuration = 1500; private int mMaxDuration = 3000; private int mConfettiCellCount = 50; private int mConfettiSize = 128; private int mConfettiDelayRatio = 8; private int mConfettiRotation = 180; private float mSizeDiffRatio = 1.0f; private ArrayList<View> mConfettiViewCells; /** * Common Init. * * @param context context * @param attrs attributes */ private void commonInit(@NonNull final Context context, @Nullable final AttributeSet attrs) { mConfettiViewCells = new ArrayList<>(); if (attrs != null) { final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ConfettiView); mMinDuration = a.getInteger(R.styleable.ConfettiView_oh_confetti_view_min_duration, mMinDuration); mMaxDuration = a.getInteger(R.styleable.ConfettiView_oh_confetti_view_max_duration, mMaxDuration); mConfettiCellCount = a.getInteger(R.styleable.ConfettiView_oh_confetti_view_count, mConfettiCellCount); mConfettiSize = a.getDimensionPixelSize(R.styleable.ConfettiView_oh_confetti_view_size, mConfettiSize); mConfettiDelayRatio = a.getInteger(R.styleable.ConfettiView_oh_confetti_view_delay, mConfettiDelayRatio); mConfettiRotation = a.getInteger(R.styleable.ConfettiView_oh_confetti_view_rotation, mConfettiRotation); mSizeDiffRatio = a.getFloat(R.styleable.ConfettiView_oh_confetti_view_size_diff_ratio, mSizeDiffRatio); } } @Override protected void onLayout(boolean b, int i, int i1, int i2, int i3) { /* do nothing */ } public void start(@NonNull final IConfettiViewCustomizationListener customizationListener) { if (mConfettiViewCells != null && mConfettiViewCells.size() > 0) { return; } final int width = getMeasuredWidth(); final int height = getMeasuredHeight(); /* Create and customize each cell */ final ConfettiCellBuilder builder = new ConfettiCellBuilder(getContext()); for (int i = 0; i < mConfettiCellCount; i++) { final View cell = customizationListener.createConfettiCell(builder, i); final int size = getCalculatedConfettiSize(); if (cell instanceof TextView) { ((TextView) cell).setTextSize(size / 4); } cell.measure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY)); final int x = generateRandomX(); cell.layout(x, -size, x + size, 0); addView(cell); mConfettiViewCells.add(cell); } /* Setup Animators */ final Collection<Animator> animators = new ArrayList<>(); for (int i = 0; i < mConfettiViewCells.size(); i++) { final View cell = mConfettiViewCells.get(i); final int cellSize = cell.getMeasuredHeight(); final long duration = generateRandomDuration(); final long delay = generateRandomDelay(i); final int endingX = generateRandomX(); final int controlX = (endingX > width / 2) ? width : 0; final int endingY = height + cellSize; final int controlY = (int) (Math.random() * endingY); final Path path = new Path(); path.moveTo(width / 2, -cellSize); path.quadTo(controlX, controlY, endingX, endingY); final ValueAnimator pathAnimator = ValueAnimator.ofFloat(1.0f, 1.0f); pathAnimator.setDuration(duration); pathAnimator.setInterpolator(new AccelerateInterpolator()); final PathMeasure pathMeasure = new PathMeasure(path, false); pathAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { float[] point = new float[2]; @Override public void onAnimationUpdate(ValueAnimator animation) { float val = animation.getAnimatedFraction(); pathMeasure.getPosTan(pathMeasure.getLength() * val, point, null); cell.setX(point[0]); cell.setY(point[1]); } }); final ObjectAnimator rotationAnimator = ObjectAnimator.ofFloat(cell, "rotation", 0f, mConfettiRotation); rotationAnimator.setDuration(duration); final AnimatorSet animatorSet = new AnimatorSet(); animatorSet.playTogether(rotationAnimator, pathAnimator); animatorSet.setStartDelay(delay); animators.add(animatorSet); } final AnimatorSet allSets = new AnimatorSet(); allSets.playTogether(animators); allSets.start(); allSets.addListener(new AnimationEndListener() { @Override public void onAnimationEndOrCanceled(Animator animation) { for (View view : mConfettiViewCells) { removeView(view); } mConfettiViewCells.clear(); if (DEBUG) { Log.d(TAG, "confetti finished"); } } }); } /** * Helper function to generate a random drop down time. * * @return drop time */ private long generateRandomDuration() { return (long) (Math.random() * (mMaxDuration - mMinDuration) + mMinDuration); } /** * Helper function to generate a random delay time for given confetti. * * @param index index of confetti * @return random delay time */ private long generateRandomDelay(final int index) { return (long) ((Math.random() * mConfettiDelayRatio) * 500); } /** * Generate a start x position. * * @return random x position */ private int generateRandomX() { return (int) (getMeasuredWidth() * Math.random()); } private int getCalculatedConfettiSize() { return (int) (mConfettiSize - (mConfettiSize - (mConfettiSize * mSizeDiffRatio)) * Math.random()); } /* Public accessors */ public boolean isAnimating() { return mConfettiViewCells != null && mConfettiViewCells.size() > 0; } /* Public setting */ public void setMinDuration(int minDuration) { this.mMinDuration = minDuration; } public void setMaxDuration(int maxDuration) { this.mMaxDuration = maxDuration; } public void setConfettiCellCount(int confettiCellCount) { this.mConfettiCellCount = confettiCellCount; } public void setConfettiSize(int confettiSize) { this.mConfettiSize = confettiSize; } public void setConfettiDelayRatio(int confettiDelayRatio) { this.mConfettiDelayRatio = confettiDelayRatio; } public void setConfettiRotation(int confettiRotation) { this.mConfettiRotation = confettiRotation; } public void setSizeDiffRatio(float sizeDiffRatio) { this.mSizeDiffRatio = sizeDiffRatio; } }
DhairyaDoc/TelegramApi
src/main/java/org/telegram/api/input/sticker/set/TLInputStickerSetId.java
<reponame>DhairyaDoc/TelegramApi package org.telegram.api.input.sticker.set; import org.telegram.tl.StreamingUtils; import org.telegram.tl.TLContext; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * @author <NAME> * @version 1.0 * @brief TODO * @date 07 of July of 2015 */ public class TLInputStickerSetId extends TLAbsInputStickerSet { public static final int CLASS_ID = 0x9de7a269; private long id; private long accessHash; @Override public int getClassId() { return CLASS_ID; } public long getId() { return this.id; } public void setId(long id) { this.id = id; } public long getAccessHash() { return this.accessHash; } public void setAccessHash(long accessHash) { this.accessHash = accessHash; } @Override public void serializeBody(OutputStream stream) throws IOException { StreamingUtils.writeLong(this.id, stream); StreamingUtils.writeLong(this.accessHash, stream); } @Override public void deserializeBody(InputStream stream, TLContext context) throws IOException { this.id = StreamingUtils.readLong(stream); this.accessHash = StreamingUtils.readLong(stream); } @Override public String toString() { return "sticker.set.inputStickerSetId#9de7a269"; } }
OxanaPeregud/Course-Java-Enterprise-Maven
src/main/java/com/peregud/sessionfactory/dao/impl/DAOPersonImpl.java
package com.peregud.sessionfactory.dao.impl; import com.peregud.sessionfactory.dao.DAOPerson; import com.peregud.sessionfactory.exceptions.DaoException; import com.peregud.sessionfactory.model.Person; import org.hibernate.ReplicationMode; import java.sql.SQLException; public class DAOPersonImpl extends AbstractDAO<Person> implements DAOPerson { @Override public Person save(Person person) throws DaoException, SQLException { return super.save(person); } @Override public Person get(Class<Person> clazz, int id) throws DaoException, SQLException { return super.get(Person.class, id); } @Override public void update(Class<Person> clazz, int id, String fieldName, int value) throws DaoException, NoSuchFieldException, IllegalAccessException, SQLException { super.update(Person.class, id, fieldName, value); } @Override public void delete(Class<Person> clazz, int id) throws DaoException, SQLException { super.delete(Person.class, id); } @Override public void callProcedure(String procedure, int id) throws DaoException { super.callProcedure(procedure, id); } @Override public void replicate(Person person, ReplicationMode replicationMode) throws DaoException { super.replicate(person, replicationMode); } }
baracil/perobobbot
lib/perobobbot.twitch/perobobbot.twitch.eventsub.api/src/main/java/perobobbot/twitch/eventsub/api/event/PollChoices.java
package perobobbot.twitch.eventsub.api.event; import com.fasterxml.jackson.annotation.JsonAlias; import lombok.NonNull; import lombok.Value; @Value public class PollChoices { @NonNull String id; @NonNull String title; @JsonAlias("bits_votes") int bitsVotes; @JsonAlias("channel_points_votes") int channelPointVotes; int votes; }
reels-research/iOS-Private-Frameworks
CalendarNotification.framework/EKTravelEngineAgendaEntry.h
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/CalendarNotification.framework/CalendarNotification */ @interface EKTravelEngineAgendaEntry : NSObject { NSString * _agendaEntryIdentifier; NSObject<OS_dispatch_queue> * _callbackQueue; bool _dismissed; id /* block */ _entrySignificantlyChangedBlock; CLLocation * _geoLocation; bool _geocodedEventEncountered; CalGeocoder * _geocoder; GEORouteHypothesizer * _hypothesizer; bool _hypothesizerSentAtLeastOneHypothesis; EKTravelEngineHypothesis * _latestHypothesis; NSData * _mapKitHandle; double _maximumTravelDurationEncountered; EKTravelEngineOriginalEvent * _originalEventInternal; EKTravelEngineThrottle * _throttle; long long _travelTimeThresholdExceededState; id /* block */ _updateBlock; NSObject<OS_dispatch_queue> * _workQueue; } @property (nonatomic, retain) NSString *agendaEntryIdentifier; @property (nonatomic, retain) NSObject<OS_dispatch_queue> *callbackQueue; @property (nonatomic) bool dismissed; @property (nonatomic, copy) id /* block */ entrySignificantlyChangedBlock; @property (nonatomic, retain) CLLocation *geoLocation; @property (nonatomic) bool geocodedEventEncountered; @property (nonatomic, retain) CalGeocoder *geocoder; @property (nonatomic, retain) GEORouteHypothesizer *hypothesizer; @property (nonatomic) bool hypothesizerSentAtLeastOneHypothesis; @property (nonatomic, retain) EKTravelEngineHypothesis *latestHypothesis; @property (nonatomic, retain) NSData *mapKitHandle; @property (nonatomic) double maximumTravelDurationEncountered; @property (nonatomic, readonly) EKTravelEngineOriginalEvent *originalEvent; @property (nonatomic, retain) EKTravelEngineOriginalEvent *originalEventInternal; @property (nonatomic, retain) EKTravelEngineThrottle *throttle; @property (nonatomic) long long travelTimeThresholdExceededState; @property (nonatomic, copy) id /* block */ updateBlock; @property (nonatomic, retain) NSObject<OS_dispatch_queue> *workQueue; + (void)_accountForGeocodingFailureWithError:(id)arg1; + (void)_accountForHypothesizerNeverHavingSentHypothesis; + (void)_accountForHypothesizerSendingHypothesis; + (void)_accountForLocationEnhancementSuccess; + (void)_accountForNoLocationEnhancementNeeded; + (double)fuzzyMaximumInitialUpdateIntervalBeforeStartDate; - (void).cxx_destruct; - (void)_accountForGeocodedEventEncounter; - (void)_accountForMaximumTravelDuration; - (void)_accountForTravelDurationThresholdExceededState; - (void)_clearEverything; - (void)_createEmissionHypothesisRefreshTimerWithDate:(id)arg1; - (void)_createHypothesisRequestRefreshTimerWithDate:(id)arg1; - (void)_createHypothesizerForDestination:(id)arg1; - (id)_createSyntheticHypothesis; - (void)_emissionHypothesisRefreshTimerFired; - (void)_enhanceLocation; - (id)_generateDestination; - (void)_hypothesisRefreshTimerFired; - (void)_performAnalyticsPostProcessing; - (void)_requestHypothesisRefreshTimerFired:(id)arg1; - (void)_sendFeedbackToHypothesizerForPostingNotification:(unsigned long long)arg1; - (void)_setUpRouteMonitoring; - (void)_trackTTLCandidateEvent:(id)arg1; - (void)_uninstallEmissionHypothesisRefreshTimer; - (void)_uninstallRequestHypothesisRefreshTimer; - (void)_updateTravelTimeExceededThresholdStateUsingExceededValue:(bool)arg1; - (void)_updateWithHypothesis:(id)arg1; - (id)agendaEntryIdentifier; - (id)callbackQueue; - (void)cancelEmissionHypothesisRefresh; - (void)cancelHypothesisRefreshRequest; - (void)createBTAJobWithName:(id)arg1 atDate:(id)arg2; - (void)dealloc; - (bool)dismissed; - (id)emissionHypothesisRefreshBTAJobName; - (id /* block */)entrySignificantlyChangedBlock; - (id)geoLocation; - (bool)geocodedEventEncountered; - (id)geocoder; - (void)handleBTAJob:(id)arg1 named:(const char *)arg2; - (id)hypothesizer; - (bool)hypothesizerSentAtLeastOneHypothesis; - (id)init; - (id)latestHypothesis; - (id)mapKitHandle; - (double)maximumTravelDurationEncountered; - (id)originalEvent; - (id)originalEventInternal; - (void)removeBTAJobWithName:(id)arg1; - (void)requestHypothesisRefreshAtDate:(id)arg1; - (id)requestHypothesisRefreshBTAJobName; - (void)reset; - (void)sendFeedbackForPostingLeaveByNotification; - (void)sendFeedbackForPostingLeaveNowNotification; - (void)setAgendaEntryIdentifier:(id)arg1; - (void)setCallbackQueue:(id)arg1; - (void)setDismissed:(bool)arg1; - (void)setEntrySignificantlyChangedBlock:(id /* block */)arg1; - (void)setGeoLocation:(id)arg1; - (void)setGeocodedEventEncountered:(bool)arg1; - (void)setGeocoder:(id)arg1; - (void)setHypothesizer:(id)arg1; - (void)setHypothesizerSentAtLeastOneHypothesis:(bool)arg1; - (void)setLatestHypothesis:(id)arg1; - (void)setMapKitHandle:(id)arg1; - (void)setMaximumTravelDurationEncountered:(double)arg1; - (void)setOriginalEventInternal:(id)arg1; - (void)setThrottle:(id)arg1; - (void)setTravelTimeThresholdExceededState:(long long)arg1; - (void)setUpdateBlock:(id /* block */)arg1; - (void)setWorkQueue:(id)arg1; - (id)throttle; - (long long)travelTimeThresholdExceededState; - (id /* block */)updateBlock; - (void)updateWithOriginalEvent:(id)arg1; - (id)workQueue; @end
tizenorg/framework.web.web-ui-fw
tests/unit-tests/virtuallist/virtuallist-tests.js
<filename>tests/unit-tests/virtuallist/virtuallist-tests.js /* * Unit Test: Virtual list * * <NAME> <<EMAIL>> */ $( document ).ready( function () { module( "Virtual List"); function startVirtualListTest(){ var $vlContainer = $( "ul.ui-virtual-list-container" ), $vlElements = $( "ul.ui-virtual-list-container li" ), vlHeight = $vlContainer.css( "height" ), vlOptions = $( "#virtuallist-normal_1line_ul" ).virtuallistview( "option" ); test( "Virtual list test", function () { /* Initialize and create method */ ok( $vlContainer ); equal( $vlElements.length, 100 ); ok( parseInt( vlHeight, 10 ) > 3000 ); /* Options */ equal( vlOptions.id, "#virtuallist-normal_1line_ul" ); equal( vlOptions.childSelector, " li" ); equal( vlOptions.dbtable, "JSON_DATA" ); equal( vlOptions.template, "tmp-1line" ); equal( vlOptions.row, 100 ); equal( vlOptions.dbkey, false ); equal( vlOptions.scrollview, true ); /* Destroy method */ ok ( ( function () { /* Call destroy */ $( "#virtuallist-normal_1line_ul" ).virtuallistview( "destroy" ); destoyedVlElements = $( "ul.ui-virtual-list-container li" ); console.log( destoyedVlElements.length ); try { equal ( destoyedVlElements.length, 0 ); } catch ( exception ) { console.log( "destroy : " + exception ); return false; } return true; }() ), "destroy()" ); } ); } /* Load Dummy Data and Init Virtual List widget*/ if ( window.JSON_DATA ) { $( "ul" ).filter( function () { return $( this ).data( "role" ) == "virtuallistview"; } ).addClass( "vlLoadSuccess" ); // trigger pagecreate $( "#virtuallist-unit-test" ).page(); $( "ul.ui-virtual-list-container" ).virtuallistview( "create" ); startVirtualListTest(); } else { console.log ( "Virtual List Init Fail." ); } } );
jianlilu/thooo
apache-tomcat-6.0.44ForThoPM/work/Catalina/localhost/_/org/apache/jsp/WEB_002dINF/views/modules/act/actModelList_jsp.java
<filename>apache-tomcat-6.0.44ForThoPM/work/Catalina/localhost/_/org/apache/jsp/WEB_002dINF/views/modules/act/actModelList_jsp.java<gh_stars>0 package org.apache.jsp.WEB_002dINF.views.modules.act; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class actModelList_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { static private org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_0; static private org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_1; static private org.apache.jasper.runtime.ProtectedFunctionMapper _jspx_fnmap_2; static { _jspx_fnmap_0= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fns:getAdminPath", com.shark.base.common.config.Global.class, "getAdminPath", new Class[] {}); _jspx_fnmap_1= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fns:getDictList", com.shark.base.modules.sys.utils.DictUtils.class, "getDictList", new Class[] {java.lang.String.class}); _jspx_fnmap_2= org.apache.jasper.runtime.ProtectedFunctionMapper.getMapForFunction("fns:getDictLabel", com.shark.base.modules.sys.utils.DictUtils.class, "getDictLabel", new Class[] {java.lang.String.class, java.lang.String.class, java.lang.String.class}); } private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List _jspx_dependants; static { _jspx_dependants = new java.util.ArrayList(5); _jspx_dependants.add("/WEB-INF/views/include/taglib.jsp"); _jspx_dependants.add("/WEB-INF/tlds/shiros.tld"); _jspx_dependants.add("/WEB-INF/tlds/fns.tld"); _jspx_dependants.add("/WEB-INF/tlds/fnc.tld"); _jspx_dependants.add("/WEB-INF/tags/sys/message.tag"); } private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems; private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody; private javax.el.ExpressionFactory _el_expressionfactory; private org.apache.AnnotationProcessor _jsp_annotationprocessor; public Object getDependants() { return _jspx_dependants; } public void _jspInit() { _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig()); _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory(); _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName()); } public void _jspDestroy() { _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.release(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.release(); _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.release(); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; out.write('\n'); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("\n"); out.write(" \n"); out.write("\n"); out.write("\n"); if (_jspx_meth_c_005fset_005f0(_jspx_page_context)) return; out.write('\n'); if (_jspx_meth_c_005fset_005f1(_jspx_page_context)) return; out.write("\n"); out.write("<html>\n"); out.write("<head>\n"); out.write("\t<title>模型管理</title>\n"); out.write("\t<meta name=\"decorator\" content=\"default\"/>\n"); out.write("\t<script type=\"text/javascript\">\n"); out.write("\t\t$(document).ready(function(){\n"); out.write("\t\t\ttop.$.jBox.tip.mess = null; \n"); out.write("\t\t});\n"); out.write("\t\tfunction page(n,s){\n"); out.write(" \tlocation = '"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("/act/model/?pageNo='+n+'&pageSize='+s;\n"); out.write(" }\n"); out.write("\t\tfunction updateCategory(id, category){\n"); out.write("\t\t\t$.jBox($(\"#categoryBox\").html(), {title:\"设置分类\", buttons:{\"关闭\":true}, submit: function(){}});\n"); out.write("\t\t\t$(\"#categoryBoxId\").val(id);\n"); out.write("\t\t\t$(\"#categoryBoxCategory\").val(category);\n"); out.write("\t\t}\n"); out.write("\t</script>\n"); out.write("\t<script type=\"text/template\" id=\"categoryBox\">\n"); out.write("\t\t<form id=\"categoryForm\" action=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("/act/model/updateCategory\" method=\"post\" enctype=\"multipart/form-data\"\n"); out.write("\t\t\tstyle=\"text-align:center;\" class=\"form-search\" onsubmit=\"loading('正在分类,请稍等...');\"><br/>\n"); out.write("\t\t\t<input id=\"categoryBoxId\" type=\"hidden\" name=\"id\" value=\"\" />\n"); out.write("\t\t\t<select id=\"categoryBoxCategory\" name=\"category\">\n"); out.write("\t\t\t\t"); if (_jspx_meth_c_005fforEach_005f0(_jspx_page_context)) return; out.write("\n"); out.write("\t\t\t</select>\n"); out.write("\t\t\t<br/><br/>  \n"); out.write("\t\t\t<input id=\"categorySubmit\" class=\"btn btn-primary\" type=\"submit\" value=\" 保 存 \"/>  \n"); out.write("\t\t</form>\n"); out.write("\t</script>\n"); out.write("</head>\n"); out.write("<body>\n"); out.write("\t<ul class=\"nav nav-tabs\">\n"); out.write("\t\t<li class=\"active\"><a href=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("/act/model/\">模型管理</a></li>\n"); out.write("\t\t<li><a href=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("/act/model/create\">新建模型</a></li>\n"); out.write("\t</ul>\n"); out.write("\t<form id=\"searchForm\" action=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("/act/model/\" method=\"post\" class=\"breadcrumb form-search\">\n"); out.write("\t\t<select id=\"category\" name=\"category\" class=\"input-medium\">\n"); out.write("\t\t\t<option value=\"\">全部分类</option>\n"); out.write("\t\t\t"); if (_jspx_meth_c_005fforEach_005f1(_jspx_page_context)) return; out.write("\n"); out.write("\t\t</select>\n"); out.write("\t\t&nbsp;<input id=\"btnSubmit\" class=\"btn btn-primary\" type=\"submit\" value=\"查询\"/>\n"); out.write("\t</form>\n"); out.write("\t"); if (_jspx_meth_sys_005fmessage_005f0(_jspx_page_context)) return; out.write("\n"); out.write("\t<table class=\"table table-striped table-bordered table-condensed\">\n"); out.write("\t\t<thead>\n"); out.write("\t\t\t<tr>\n"); out.write("\t\t\t\t<th>流程分类</th>\n"); out.write("\t\t\t\t<th>模型ID</th>\n"); out.write("\t\t\t\t<th>模型标识</th>\n"); out.write("\t\t\t\t<th>模型名称</th>\n"); out.write("\t\t\t\t<th>版本号</th>\n"); out.write("\t\t\t\t<th>创建时间</th>\n"); out.write("\t\t\t\t<th>最后更新时间</th>\n"); out.write("\t\t\t\t<th>操作</th>\n"); out.write("\t\t\t</tr>\n"); out.write("\t\t</thead>\n"); out.write("\t\t<tbody>\n"); out.write("\t\t\t"); if (_jspx_meth_c_005fforEach_005f2(_jspx_page_context)) return; out.write("\n"); out.write("\t\t</tbody>\n"); out.write("\t</table>\n"); out.write("\t<div class=\"pagination\">"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${page}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("</div>\n"); out.write("</body>\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) try { out.clearBuffer(); } catch (java.io.IOException e) {} if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else log(t.getMessage(), t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } private boolean _jspx_meth_c_005fset_005f0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:set org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f0 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class); _jspx_th_c_005fset_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fset_005f0.setParent(null); // /WEB-INF/views/include/taglib.jsp(11,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null _jspx_th_c_005fset_005f0.setVar("ctx"); // /WEB-INF/views/include/taglib.jsp(11,0) name = value type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true deferredMethod = false expectedTypeName = java.lang.Object methodSignature = null _jspx_th_c_005fset_005f0.setValue(new org.apache.jasper.el.JspValueExpression("/WEB-INF/views/include/taglib.jsp(11,0) '${pageContext.request.contextPath}${fns:getAdminPath()}'",_el_expressionfactory.createValueExpression(new org.apache.jasper.el.ELContextWrapper(_jspx_page_context.getELContext(),_jspx_fnmap_0),"${pageContext.request.contextPath}${fns:getAdminPath()}",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); int _jspx_eval_c_005fset_005f0 = _jspx_th_c_005fset_005f0.doStartTag(); if (_jspx_th_c_005fset_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0); return true; } _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f0); return false; } private boolean _jspx_meth_c_005fset_005f1(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:set org.apache.taglibs.standard.tag.rt.core.SetTag _jspx_th_c_005fset_005f1 = (org.apache.taglibs.standard.tag.rt.core.SetTag) _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.get(org.apache.taglibs.standard.tag.rt.core.SetTag.class); _jspx_th_c_005fset_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fset_005f1.setParent(null); // /WEB-INF/views/include/taglib.jsp(12,0) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null _jspx_th_c_005fset_005f1.setVar("ctxStatic"); // /WEB-INF/views/include/taglib.jsp(12,0) name = value type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true deferredMethod = false expectedTypeName = java.lang.Object methodSignature = null _jspx_th_c_005fset_005f1.setValue(new org.apache.jasper.el.JspValueExpression("/WEB-INF/views/include/taglib.jsp(12,0) '${pageContext.request.contextPath}/static'",_el_expressionfactory.createValueExpression(_jspx_page_context.getELContext(),"${pageContext.request.contextPath}/static",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); int _jspx_eval_c_005fset_005f1 = _jspx_th_c_005fset_005f1.doStartTag(); if (_jspx_th_c_005fset_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1); return true; } _005fjspx_005ftagPool_005fc_005fset_0026_005fvar_005fvalue_005fnobody.reuse(_jspx_th_c_005fset_005f1); return false; } private boolean _jspx_meth_c_005fforEach_005f0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f0 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_005fforEach_005f0.setPageContext(_jspx_page_context); _jspx_th_c_005fforEach_005f0.setParent(null); // /WEB-INF/views/modules/act/actModelList.jsp(25,4) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true deferredMethod = false expectedTypeName = java.lang.Object methodSignature = null _jspx_th_c_005fforEach_005f0.setItems(new org.apache.jasper.el.JspValueExpression("/WEB-INF/views/modules/act/actModelList.jsp(25,4) '${fns:getDictList('act_category')}'",_el_expressionfactory.createValueExpression(new org.apache.jasper.el.ELContextWrapper(_jspx_page_context.getELContext(),_jspx_fnmap_1),"${fns:getDictList('act_category')}",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); // /WEB-INF/views/modules/act/actModelList.jsp(25,4) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null _jspx_th_c_005fforEach_005f0.setVar("dict"); int[] _jspx_push_body_count_c_005fforEach_005f0 = new int[] { 0 }; try { int _jspx_eval_c_005fforEach_005f0 = _jspx_th_c_005fforEach_005f0.doStartTag(); if (_jspx_eval_c_005fforEach_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t\t\t\t\t<option value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${dict.value}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write('"'); out.write('>'); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${dict.label}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("</option>\n"); out.write("\t\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fforEach_005f0.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fforEach_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fforEach_005f0[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fforEach_005f0.doCatch(_jspx_exception); } finally { _jspx_th_c_005fforEach_005f0.doFinally(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f0); } return false; } private boolean _jspx_meth_c_005fforEach_005f1(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f1 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_005fforEach_005f1.setPageContext(_jspx_page_context); _jspx_th_c_005fforEach_005f1.setParent(null); // /WEB-INF/views/modules/act/actModelList.jsp(42,3) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true deferredMethod = false expectedTypeName = java.lang.Object methodSignature = null _jspx_th_c_005fforEach_005f1.setItems(new org.apache.jasper.el.JspValueExpression("/WEB-INF/views/modules/act/actModelList.jsp(42,3) '${fns:getDictList('act_category')}'",_el_expressionfactory.createValueExpression(new org.apache.jasper.el.ELContextWrapper(_jspx_page_context.getELContext(),_jspx_fnmap_1),"${fns:getDictList('act_category')}",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); // /WEB-INF/views/modules/act/actModelList.jsp(42,3) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null _jspx_th_c_005fforEach_005f1.setVar("dict"); int[] _jspx_push_body_count_c_005fforEach_005f1 = new int[] { 0 }; try { int _jspx_eval_c_005fforEach_005f1 = _jspx_th_c_005fforEach_005f1.doStartTag(); if (_jspx_eval_c_005fforEach_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t\t\t\t<option value=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${dict.value}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write('"'); out.write(' '); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${dict.value==category?'selected':''}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write('>'); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${dict.label}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("</option>\n"); out.write("\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fforEach_005f1.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fforEach_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fforEach_005f1[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fforEach_005f1.doCatch(_jspx_exception); } finally { _jspx_th_c_005fforEach_005f1.doFinally(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f1); } return false; } private boolean _jspx_meth_sys_005fmessage_005f0(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // sys:message org.apache.jsp.tag.web.sys.message_tag _jspx_th_sys_005fmessage_005f0 = new org.apache.jsp.tag.web.sys.message_tag(); org.apache.jasper.runtime.AnnotationHelper.postConstruct(_jsp_annotationprocessor, _jspx_th_sys_005fmessage_005f0); _jspx_th_sys_005fmessage_005f0.setJspContext(_jspx_page_context); // /WEB-INF/views/modules/act/actModelList.jsp(48,1) name = content type = java.lang.String reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = java.lang.String methodSignature = null _jspx_th_sys_005fmessage_005f0.setContent((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${message}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); _jspx_th_sys_005fmessage_005f0.doTag(); org.apache.jasper.runtime.AnnotationHelper.preDestroy(_jsp_annotationprocessor, _jspx_th_sys_005fmessage_005f0); return false; } private boolean _jspx_meth_c_005fforEach_005f2(PageContext _jspx_page_context) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // c:forEach org.apache.taglibs.standard.tag.rt.core.ForEachTag _jspx_th_c_005fforEach_005f2 = (org.apache.taglibs.standard.tag.rt.core.ForEachTag) _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.get(org.apache.taglibs.standard.tag.rt.core.ForEachTag.class); _jspx_th_c_005fforEach_005f2.setPageContext(_jspx_page_context); _jspx_th_c_005fforEach_005f2.setParent(null); // /WEB-INF/views/modules/act/actModelList.jsp(63,3) name = items type = javax.el.ValueExpression reqTime = true required = false fragment = false deferredValue = true deferredMethod = false expectedTypeName = java.lang.Object methodSignature = null _jspx_th_c_005fforEach_005f2.setItems(new org.apache.jasper.el.JspValueExpression("/WEB-INF/views/modules/act/actModelList.jsp(63,3) '${page.list}'",_el_expressionfactory.createValueExpression(_jspx_page_context.getELContext(),"${page.list}",java.lang.Object.class)).getValue(_jspx_page_context.getELContext())); // /WEB-INF/views/modules/act/actModelList.jsp(63,3) name = var type = java.lang.String reqTime = false required = false fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null _jspx_th_c_005fforEach_005f2.setVar("model"); int[] _jspx_push_body_count_c_005fforEach_005f2 = new int[] { 0 }; try { int _jspx_eval_c_005fforEach_005f2 = _jspx_th_c_005fforEach_005f2.doStartTag(); if (_jspx_eval_c_005fforEach_005f2 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) { do { out.write("\n"); out.write("\t\t\t\t<tr>\n"); out.write("\t\t\t\t\t<td><a href=\"javascript:updateCategory('"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.id}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("', '"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.category}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("')\" title=\"设置分类\">"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${fns:getDictLabel(model.category,'act_category','无分类')}", java.lang.String.class, (PageContext)_jspx_page_context, _jspx_fnmap_2, false)); out.write("</a></td>\n"); out.write("\t\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.id}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("</td>\n"); out.write("\t\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.key}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("</td>\n"); out.write("\t\t\t\t\t<td>"); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.name}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("</td>\n"); out.write("\t\t\t\t\t<td><b title='流程版本号'>V: "); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.version}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("</b></td>\n"); out.write("\t\t\t\t\t<td>"); if (_jspx_meth_fmt_005fformatDate_005f0(_jspx_th_c_005fforEach_005f2, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f2)) return true; out.write("</td>\n"); out.write("\t\t\t\t\t<td>"); if (_jspx_meth_fmt_005fformatDate_005f1(_jspx_th_c_005fforEach_005f2, _jspx_page_context, _jspx_push_body_count_c_005fforEach_005f2)) return true; out.write("</td>\n"); out.write("\t\t\t\t\t<td>\n"); out.write("\t\t\t\t\t\t<a href=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${pageContext.request.contextPath}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("/act/rest/service/editor?id="); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.id}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("\" target=\"_blank\">编辑</a>\n"); out.write("\t\t\t\t\t\t<a href=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("/act/model/deploy?id="); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.id}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("\" onclick=\"return confirmx('确认要部署该模型吗?', this.href)\">部署</a>\n"); out.write("\t\t\t\t\t\t<a href=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("/act/model/export?id="); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.id}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("\" target=\"_blank\">导出</a>\n"); out.write("\t <a href=\""); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${ctx}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("/act/model/delete?id="); out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.id}", java.lang.String.class, (PageContext)_jspx_page_context, null, false)); out.write("\" onclick=\"return confirmx('确认要删除该模型吗?', this.href)\">删除</a>\n"); out.write("\t\t\t\t\t</td>\n"); out.write("\t\t\t\t</tr>\n"); out.write("\t\t\t"); int evalDoAfterBody = _jspx_th_c_005fforEach_005f2.doAfterBody(); if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN) break; } while (true); } if (_jspx_th_c_005fforEach_005f2.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { return true; } } catch (Throwable _jspx_exception) { while (_jspx_push_body_count_c_005fforEach_005f2[0]-- > 0) out = _jspx_page_context.popBody(); _jspx_th_c_005fforEach_005f2.doCatch(_jspx_exception); } finally { _jspx_th_c_005fforEach_005f2.doFinally(); _005fjspx_005ftagPool_005fc_005fforEach_0026_005fvar_005fitems.reuse(_jspx_th_c_005fforEach_005f2); } return false; } private boolean _jspx_meth_fmt_005fformatDate_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f2, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f2) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:formatDate org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag _jspx_th_fmt_005fformatDate_005f0 = (org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag) _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag.class); _jspx_th_fmt_005fformatDate_005f0.setPageContext(_jspx_page_context); _jspx_th_fmt_005fformatDate_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f2); // /WEB-INF/views/modules/act/actModelList.jsp(70,9) name = value type = null reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null _jspx_th_fmt_005fformatDate_005f0.setValue((java.util.Date) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.createTime}", java.util.Date.class, (PageContext)_jspx_page_context, null, false)); // /WEB-INF/views/modules/act/actModelList.jsp(70,9) name = pattern type = null reqTime = true required = false fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null _jspx_th_fmt_005fformatDate_005f0.setPattern("yyyy-MM-dd HH:mm:ss"); int _jspx_eval_fmt_005fformatDate_005f0 = _jspx_th_fmt_005fformatDate_005f0.doStartTag(); if (_jspx_th_fmt_005fformatDate_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f0); return true; } _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f0); return false; } private boolean _jspx_meth_fmt_005fformatDate_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_c_005fforEach_005f2, PageContext _jspx_page_context, int[] _jspx_push_body_count_c_005fforEach_005f2) throws Throwable { PageContext pageContext = _jspx_page_context; JspWriter out = _jspx_page_context.getOut(); // fmt:formatDate org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag _jspx_th_fmt_005fformatDate_005f1 = (org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag) _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.get(org.apache.taglibs.standard.tag.rt.fmt.FormatDateTag.class); _jspx_th_fmt_005fformatDate_005f1.setPageContext(_jspx_page_context); _jspx_th_fmt_005fformatDate_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_005fforEach_005f2); // /WEB-INF/views/modules/act/actModelList.jsp(71,9) name = value type = null reqTime = true required = true fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null _jspx_th_fmt_005fformatDate_005f1.setValue((java.util.Date) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${model.lastUpdateTime}", java.util.Date.class, (PageContext)_jspx_page_context, null, false)); // /WEB-INF/views/modules/act/actModelList.jsp(71,9) name = pattern type = null reqTime = true required = false fragment = false deferredValue = false deferredMethod = false expectedTypeName = null methodSignature = null _jspx_th_fmt_005fformatDate_005f1.setPattern("yyyy-MM-dd HH:mm:ss"); int _jspx_eval_fmt_005fformatDate_005f1 = _jspx_th_fmt_005fformatDate_005f1.doStartTag(); if (_jspx_th_fmt_005fformatDate_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) { _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f1); return true; } _005fjspx_005ftagPool_005ffmt_005fformatDate_0026_005fvalue_005fpattern_005fnobody.reuse(_jspx_th_fmt_005fformatDate_005f1); return false; } }
katarineaid/admin-BGS-E
client/src/common/components/map/router/createMapRouter.js
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { matchPath } from 'react-router-dom'; function createMapRouter(ComposedComponent) { const rootPath = '/admin/view'; class MapRouter extends Component { static propTypes = { children: PropTypes.node, history: PropTypes.objectOf(PropTypes.any).isRequired, }; static defaultProps = { children: undefined, }; constructor(props) { super(props); this.state = { currentSourceName: MapRouter.getSourceCurrentName(this.props), }; } static getDerivedStateFromProps(nextProps) { return { currentSourceName: MapRouter.getSourceCurrentName(nextProps), }; } static getSourceCurrentName(props) { const { location, match } = props; const pathname = location.pathname; const matched = matchPath(pathname, { path: `${rootPath}/:item` }, match); return matched && matched.params.item || ''; } render() { const { children, ...other } = this.props; const { currentSourceName } = this.state; return ( <ComposedComponent currentSourceName={currentSourceName} {...other} > {children} </ComposedComponent> ); } } return MapRouter } export default createMapRouter;
ScalablyTyped/SlinkyTyped
r/react-notifications-component/src/main/scala/typingsSlinky/reactNotificationsComponent/components/ReactNotificationsComponent.scala
package typingsSlinky.reactNotificationsComponent.components import slinky.web.html.`*`.tag import typingsSlinky.StBuildingComponent import typingsSlinky.reactNotificationsComponent.mod.ReactNotificationProps import typingsSlinky.reactNotificationsComponent.mod.default import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object ReactNotificationsComponent { @JSImport("react-notifications-component", JSImport.Default) @js.native val component: js.Object = js.native @scala.inline class Builder (val args: js.Array[js.Any]) extends AnyVal with StBuildingComponent[tag.type, default] { @scala.inline def breakpoint(value: Double): this.type = set("breakpoint", value.asInstanceOf[js.Any]) @scala.inline def className(value: String): this.type = set("className", value.asInstanceOf[js.Any]) @scala.inline def id(value: String): this.type = set("id", value.asInstanceOf[js.Any]) @scala.inline def isMobile(value: Boolean): this.type = set("isMobile", value.asInstanceOf[js.Any]) @scala.inline def types(value: js.Array[String]): this.type = set("types", value.asInstanceOf[js.Any]) @scala.inline def typesVarargs(value: String*): this.type = set("types", js.Array(value :_*)) } implicit def make(companion: ReactNotificationsComponent.type): Builder = new Builder(js.Array(this.component, js.Dictionary.empty))() def withProps(p: ReactNotificationProps): Builder = new Builder(js.Array(this.component, p.asInstanceOf[js.Any])) }
bbbart/pyfmodex
pyfmodex/channel_group.py
"""A submix in the mixing hierarchy akin to a bus that can contain both :py:class:`~pyfmodex.channel.Channel` and :py:class:`~pyfmodex.channel_group.ChannelGroup` objects. """ from ctypes import * from .channel_control import ChannelControl from .globalvars import DLL as _dll from .globalvars import get_class from .utils import check_type, ckresult class ChannelGroup(ChannelControl): """A submix in the mixing hierarchy akin to a bus that can contain both :py:class:`~pyfmodex.channel.Channel` and :py:class:`~pyfmodex.channel_group.ChannelGroup` objects. """ def add_group(self, group, propagate_dsp_clock=True): """Add a ChannelGroup as an input to this group. :param ChannelGroup group: Group to add. :param bool propagate_dsp_clock: Recursively propagate this object's clock values to `group`. :returns: Connection between the head :py:class:`~pyfmodex.dsp.DSP` of `group` and the tail :py:class:`~pyfmodex.dsp.DSP` of this object. :rtype: DSPConnection """ check_type(group, ChannelGroup) conn_ptr = c_void_p() self._call_fmod( "FMOD_ChannelGroup_AddGroup", group._ptr, propagate_dsp_clock, byref(conn_ptr), ) return get_class("DSP_Connection")(conn_ptr) def get_channel(self, idx): """Retrieve the Channel at the specified index in the list of Channel inputs. :param int idx: Offset into the list of Channel inputs. :returns: Channel at the specified index. :rtype: Channel """ c_ptr = c_void_p() self._call_fmod("FMOD_ChannelGroup_GetChannel", idx, byref(c_ptr)) return get_class("Channel")(c_ptr) def get_group(self, idx): """Retrieve the ChannelGroup at the specified index in the list of group inputs. :param int idx: Offset into the list of group inputs. :returns: Group at the specified index. :rtype: ChannelGroup """ grp_ptr = c_void_p() ckresult(_dll.FMOD_ChannelGroup_GetGroup(self._ptr, idx, byref(grp_ptr))) return ChannelGroup(grp_ptr) @property def name(self): """The name set when the group was created. :type: str """ buf = create_string_buffer(512) self._call_fmod("FMOD_ChannelGroup_GetName", buf, 512) return buf.value @property def num_channels(self): """The number of Channels that feed into to this group. :type: int """ num = c_int() self._call_fmod("FMOD_ChannelGroup_GetNumChannels", byref(num)) return num.value @property def num_groups(self): """The number of ChannelGroups that feed into to this group. :type: int """ num = c_int() self._call_fmod("FMOD_ChannelGroup_GetNumGroups", byref(num)) return num.value @property def parent_group(self): """The ChannelGroup this object outputs to. :type: ChannelGroup """ grp_ptr = c_void_p() self._call_fmod("FMOD_ChannelGroup_GetParentGroup", byref(grp_ptr)) return ChannelGroup(grp_ptr) if grp_ptr.value else None def release(self): """Free the memory for the group. Any :py:class:`Channels <pyfmodex.channel.Channel>` or :py:class:`ChannelGrous <pyfmodex.channel_group.ChannelGroup>` feeding into this group are moved to the master :py:class:`~pyfmodex.channel_group.ChannelGroup`. """ self._call_fmod("FMOD_ChannelGroup_Release")
elix22/Urho3D
Source/ThirdParty/angle/src/libANGLE/validationGL31_autogen.h
// GENERATED FILE - DO NOT EDIT. // Generated by generate_entry_points.py using data from gl.xml and wgl.xml. // // Copyright 2019 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // validationGL31_autogen.h: // Validation functions for the OpenGL 3.1 entry points. #ifndef LIBANGLE_VALIDATION_GL31_AUTOGEN_H_ #define LIBANGLE_VALIDATION_GL31_AUTOGEN_H_ #include "common/PackedEnums.h" namespace gl { class Context; bool ValidateGetActiveUniformName(Context *context, ShaderProgramID programPacked, GLuint uniformIndex, GLsizei bufSize, GLsizei *length, GLchar *uniformName); bool ValidatePrimitiveRestartIndex(Context *context, GLuint index); bool ValidateTexBuffer(Context *context, GLenum target, GLenum internalformat, BufferID bufferPacked); } // namespace gl #endif // LIBANGLE_VALIDATION_GL31_AUTOGEN_H_
blc-cruise/ggongsul-api
ggongsul/core/renderers.py
<gh_stars>1-10 from django.shortcuts import resolve_url from django.template import loader from rest_framework import serializers from rest_framework.renderers import HTMLFormRenderer class ImageHTMLFormRenderer(HTMLFormRenderer): def render_field(self, field, parent_style): if isinstance(field._field, serializers.HiddenField): return "" style = {} if hasattr(field, "_proxy_class"): if field._proxy_class is serializers.ImageField: style = {"template": "image_input.html", "input_type": "file"} elif field._proxy_class is serializers.ChoiceField: style = {"template": "radio_input.html"} if field.name == "offer_type": style["choice_help_text"] = { 1: "1회원 당, 술 1병 무료제공", 2: "2회원 당, 술 1병 무료제공 (안주 가격이 평균 15,000원 이하인 매장만 권장드립니다.)", 3: "전체 회원 인증 시, 술 무제한 제공 (홍보 효과가 가장 좋습니다. 안주로 승부하시는 매장에 추천드립니다.)", } elif ( field._proxy_class is serializers.BooleanField and field.name.startswith("policy") ): style = { "template": "checkbox_input.html", "policy_url": f"{resolve_url('partner-agreement')}", } if not style: style = self.default_style[field].copy() style.update(field.style) if "template_pack" not in style: style["template_pack"] = parent_style.get( "template_pack", self.template_pack ) style["renderer"] = self # Get a clone of the field with text-only value representation. field = field.as_form_field() if style.get("input_type") == "datetime-local" and isinstance(field.value, str): field.value = field.value.rstrip("Z") if "template" in style: template_name = style["template"] else: template_name = ( style["template_pack"].strip("/") + "/" + style["base_template"] ) template = loader.get_template(template_name) context = {"field": field, "style": style} return template.render(context) def render(self, data, accepted_media_type=None, renderer_context=None): """ Render serializer data and return an HTML form, as a string. """ renderer_context = renderer_context or {} form = data.serializer style = renderer_context.get("style", {}) if "template_pack" not in style: style["template_pack"] = self.template_pack style["renderer"] = self template_pack = style["template_pack"].strip("/") template_name = template_pack + "/" + self.base_template template = loader.get_template(template_name) context = {"form": form, "style": style} return template.render(context)
algostack/risk-engine
mmap/src/main/java/io/algostack/mmap/MMDoubleArrayImpl.java
package io.algostack.mmap; import java.nio.DoubleBuffer; public class MMDoubleArrayImpl implements DoubleArray { private final DoubleBuffer buffer; private final int size; public MMDoubleArrayImpl(DoubleBuffer buffer, int size) { this.buffer = buffer; this.size = size; } @Override public double get(int index) { return buffer.get(index); } @Override public int size() { return size; } }
doumKim/surf-client-repo
src/postApi.js
import { baseUrl } from "./constants/GlobalVariables"; // 글 상세 페이지 데이터 조회 export function getWaveDetail(id) { return fetch(`${baseUrl}/post/wave/${id}`, { method: "GET", credentials: "include", mode: "cors", }); } export const getPhase = (id, cur) => fetch(`${baseUrl}/post/phaseWave/${id}/?phase=${cur}`, { method: "GET", credentials: "include", mode: "cors", }); export const sendLike = id => fetch(`${baseUrl}/post/like/${id}`, { method: "POST", credentials: "include", mode: "cors", headers: { "Content-Type": "application/json", }, }); export const postPhaseWave = (id, phaseId, data) => fetch(`${baseUrl}/post/createPhaseWave/${id}?currentPhase=${phaseId}`, { method: "POST", credentials: "include", mode: "cors", headers: { "Content-Type": "application/json", }, body: data, }); export const createWave = data => fetch(`${baseUrl}/post/createWave`, { method: "POST", credentials: "include", mode: "cors", // headers: { // "Content-Type": "multipart/form-data", // }, body: data, }); export const searchWave = (category, sort = "created_at", offset = 0) => fetch( `${baseUrl}/post/allWave?category=${category}&sort=${sort}&offset=${offset}`, { method: "GET", credentials: "include", mode: "cors", } ); // /post/id/id -> 갔을 떄 권한 부여 export const createCurrentJoinUser = id => fetch(`${baseUrl}/post/createCurrentJoinUser/${id}`, { method: "GET", credentials: "include", mode: "cors", }); export const removeCurrentJoinUser = id => fetch(`${baseUrl}/post/removeCurrentJoinUser/${id}`, { method: "GET", credentials: "include", mode: "cors", }); export const getLikeWave = () => fetch(`${baseUrl}/post/likeWave`, { method: "GET", credentials: "include", mode: "cors", });
brunolauze/openpegasus-providers-old
src/Providers/UNIXProviders/StorageRedundancyGroup/UNIX_StorageRedundancyGroup_DARWIN.hxx
#ifdef PEGASUS_OS_DARWIN #ifndef __UNIX_STORAGEREDUNDANCYGROUP_PRIVATE_H #define __UNIX_STORAGEREDUNDANCYGROUP_PRIVATE_H #endif #endif
fjacobs/spring-data-examples
jpa/deferred/src/main/java/example/service/Customer1149Service.java
package example.service; import example.repo.Customer1149Repository; import org.springframework.stereotype.Service; @Service public class Customer1149Service { public Customer1149Service(Customer1149Repository repo) { } }
ankurshukla1993/IOT-test
coeey/com/google/android/gms/internal/zzfij.java
<gh_stars>1-10 package com.google.android.gms.internal; import java.io.IOException; public final class zzfij extends zzfhe<zzfij> implements Cloneable { private static volatile zzfij[] zzpkz; private String key; private String value; public zzfij() { this.key = ""; this.value = ""; this.zzpgy = null; this.zzpai = -1; } public static zzfij[] zzcxz() { if (zzpkz == null) { synchronized (zzfhi.zzphg) { if (zzpkz == null) { zzpkz = new zzfij[0]; } } } return zzpkz; } private zzfij zzcya() { try { return (zzfij) super.zzcxe(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } public final /* synthetic */ Object clone() throws CloneNotSupportedException { return zzcya(); } public final boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof zzfij)) { return false; } zzfij com_google_android_gms_internal_zzfij = (zzfij) obj; if (this.key == null) { if (com_google_android_gms_internal_zzfij.key != null) { return false; } } else if (!this.key.equals(com_google_android_gms_internal_zzfij.key)) { return false; } if (this.value == null) { if (com_google_android_gms_internal_zzfij.value != null) { return false; } } else if (!this.value.equals(com_google_android_gms_internal_zzfij.value)) { return false; } return (this.zzpgy == null || this.zzpgy.isEmpty()) ? com_google_android_gms_internal_zzfij.zzpgy == null || com_google_android_gms_internal_zzfij.zzpgy.isEmpty() : this.zzpgy.equals(com_google_android_gms_internal_zzfij.zzpgy); } public final int hashCode() { int i = 0; int hashCode = ((this.value == null ? 0 : this.value.hashCode()) + (((this.key == null ? 0 : this.key.hashCode()) + ((getClass().getName().hashCode() + 527) * 31)) * 31)) * 31; if (!(this.zzpgy == null || this.zzpgy.isEmpty())) { i = this.zzpgy.hashCode(); } return hashCode + i; } public final /* synthetic */ zzfhk zza(zzfhb com_google_android_gms_internal_zzfhb) throws IOException { while (true) { int zzcts = com_google_android_gms_internal_zzfhb.zzcts(); switch (zzcts) { case 0: break; case 10: this.key = com_google_android_gms_internal_zzfhb.readString(); continue; case 18: this.value = com_google_android_gms_internal_zzfhb.readString(); continue; default: if (!super.zza(com_google_android_gms_internal_zzfhb, zzcts)) { break; } continue; } return this; } } public final void zza(zzfhc com_google_android_gms_internal_zzfhc) throws IOException { if (!(this.key == null || this.key.equals(""))) { com_google_android_gms_internal_zzfhc.zzn(1, this.key); } if (!(this.value == null || this.value.equals(""))) { com_google_android_gms_internal_zzfhc.zzn(2, this.value); } super.zza(com_google_android_gms_internal_zzfhc); } public final /* synthetic */ zzfhe zzcxe() throws CloneNotSupportedException { return (zzfij) clone(); } public final /* synthetic */ zzfhk zzcxf() throws CloneNotSupportedException { return (zzfij) clone(); } protected final int zzo() { int zzo = super.zzo(); if (!(this.key == null || this.key.equals(""))) { zzo += zzfhc.zzo(1, this.key); } return (this.value == null || this.value.equals("")) ? zzo : zzo + zzfhc.zzo(2, this.value); } }
gedestroy/gateleen
gateleen-delta/src/test/java/org/swisspush/gateleen/delta/DeltaHandlerTest.java
package org.swisspush.gateleen.delta; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.MultiMap; import io.vertx.core.http.CaseInsensitiveHeaders; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerRequest; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.redis.RedisClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.swisspush.gateleen.core.http.DummyHttpServerRequest; import org.swisspush.gateleen.core.http.DummyHttpServerResponse; import org.swisspush.gateleen.core.util.StatusCode; import org.swisspush.gateleen.routing.Router; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.*; @RunWith(VertxUnitRunner.class) public class DeltaHandlerTest { private RedisClient redisClient; private Router router = mock(Router.class); private HttpServerRequest request; private CaseInsensitiveHeaders requestHeaders = new CaseInsensitiveHeaders(); @Before public void before() { redisClient = mock(RedisClient.class); doAnswer(invocation -> { Handler<AsyncResult<Long>> handler = (Handler<AsyncResult<Long>>) invocation.getArguments()[1]; handler.handle(Future.succeededFuture(555L)); return null; }).when(redisClient).incr(eq("delta:sequence"), any()); requestHeaders = new CaseInsensitiveHeaders(); requestHeaders.add("x-delta", "auto"); request = mock(HttpServerRequest.class); when(request.method()).thenReturn(HttpMethod.PUT); when(request.path()).thenReturn("/a/b/c"); when(request.headers()).thenReturn(requestHeaders); } @Test public void testDeltaNoExpiry() { DeltaHandler deltaHandler = new DeltaHandler(redisClient, null); deltaHandler.handle(request, router); verify(redisClient, times(1)).set(eq("delta:resources:a:b:c"), eq("555"), any()); verify(redisClient, never()).setex(any(), anyLong(), any(), any()); } @Test public void testDeltaWithExpiry() { requestHeaders.add("x-expire-after", "123"); DeltaHandler deltaHandler = new DeltaHandler(redisClient, null); deltaHandler.handle(request, router); verify(redisClient, times(1)).setex(eq("delta:resources:a:b:c"), eq(123L), eq("555"), any()); verify(redisClient, never()).set(any(), any(), any()); } @Test public void testRejectLimitOffsetParameters(TestContext context) { DeltaHandler deltaHandler = new DeltaHandler(redisClient, null, true); final DummyHttpServerResponse response = new DummyHttpServerResponse(); DeltaRequest request = new DeltaRequest(new CaseInsensitiveHeaders() .add("delta", "0") .add("limit", "2"), response); deltaHandler.handle(request, router); context.assertEquals(StatusCode.BAD_REQUEST.getStatusCode(), request.response().getStatusCode(), "StatusCode should be 400"); request = new DeltaRequest(new CaseInsensitiveHeaders() .add("delta", "0") .add("offset", "55"), response); deltaHandler.handle(request, router); context.assertEquals(StatusCode.BAD_REQUEST.getStatusCode(), request.response().getStatusCode(), "StatusCode should be 400"); request = new DeltaRequest(new CaseInsensitiveHeaders() .add("delta", "0") .add("limit", "10") .add("offset", "55"), response); deltaHandler.handle(request, router); context.assertEquals(StatusCode.BAD_REQUEST.getStatusCode(), request.response().getStatusCode(), "StatusCode should be 400"); } class DeltaRequest extends DummyHttpServerRequest { private final MultiMap params; private final DummyHttpServerResponse response; public DeltaRequest(MultiMap params, DummyHttpServerResponse response) { this.params = params; this.response = response; } @Override public HttpMethod method() { return HttpMethod.GET; } @Override public String uri() { return "/gateleen/server/deltaResources"; } @Override public MultiMap params() { return params; } @Override public DummyHttpServerResponse response() { return response; } @Override public MultiMap headers() { return new CaseInsensitiveHeaders(); } } }
rhalbersma/gravon
src/scripts/transform/parse.py
<reponame>rhalbersma/gravon<filename>src/scripts/transform/parse.py # Copyright <NAME> 2018-2021. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) import os import re from typing import Callable, Iterable, Optional, Tuple import lxml.etree import numpy as np import pandas as pd from tqdm import tqdm import gravon.package as pkg GameHeader = Tuple[int, int, str, str, int, int, int, Optional[str]] GameBody = pd.DataFrame def _gsn(gid: int, basename: str) -> Tuple[GameHeader, GameBody]: filename = os.path.join(pkg.txt_dir, basename) with open(filename, 'r', encoding='utf-8-sig') as src: lines = src.read().splitlines() assert lines[0][:-1] == '#X38FA11 Stratego-Notation v' assert int(lines[0][-1]) in range(1, 3) assert lines[1].startswith('type') type = int(lines[1][-1]) assert lines[-2] == 'END' field_content = lines[2] if lines[2:-2] else None game_body = pd.DataFrame( data=[ (gid, mid, line[:2], line[3:]) for mid, line in enumerate(lines[3:-2]) if line[2] != ':' ], columns=[ 'gid', 'mid', 'source', 'target' ], dtype=int ) num_moves = game_body.shape[0] players, result = lines[-1].split(' result ') player_red, player_blue = players.split(' vs ') ending, winner = ( int(attrib) for attrib in result.split(' winner ') ) return (gid, type, player_red, player_blue, winner, ending, num_moves, field_content), game_body def _xml(gid: int, basename: str) -> Tuple[GameHeader, GameBody]: filename = os.path.join(pkg.txt_dir, basename) tree = lxml.etree.parse(filename) type = { 'classic' : 0, 'barrage' : 1, 'classicfree' : 2, 'ultimate lightning': 3, 'duell' : 4 }[tree.find('//game').attrib['type']] try: field_content = tree.find('//field').attrib['content'] except: field_content = None game_body = pd.DataFrame( data=[ (gid, mid, move.attrib['source'], move.attrib['target']) for mid, move in enumerate(tree.findall('//move')) ], columns=[ 'gid', 'mid', 'source', 'target' ], dtype=int ) num_moves = game_body.shape[0] player_red, player_blue = ( p.text for p in tree.findall('//player') ) winner, ending = ( int(tree.find('//result').attrib[a]) for a in ('winner', 'type') ) winner -= 1 return (gid, type, player_red, player_blue, winner, ending, num_moves, field_content), game_body def _concatter(index: Iterable[GameHeader], games: Iterable[GameBody]) -> Tuple[pd.DataFrame, pd.DataFrame]: return pd.DataFrame( data=index, columns=[ 'gid', 'type', 'player_red', 'player_blue', 'winner', 'ending', 'num_moves', 'field_content' ] ), pd.concat(games) def _selection(files: pd.DataFrame, parser: Callable[[int, str], Tuple[GameHeader, GameBody]]) -> Tuple[pd.DataFrame, pd.DataFrame]: return _concatter(*zip(*[ parser(row.gid, row.filename) for row in tqdm(files.itertuples(), total=files.shape[0]) ])) def txt_files(df: pd.DataFrame) -> pd.DataFrame: return (df .assign( splitext = lambda r: r.filename.apply(lambda x: os.path.splitext(x)), root = lambda r: r.splitext.apply(lambda x: x[0]), splitroot = lambda r: r.apply(lambda x: re.split(r'[-.]', x.root), axis=1), prefix = lambda r: r.splitroot.apply(lambda x: x[0]), period = lambda r: r.splitroot.apply(lambda x: '-'.join( np.where( x[2] == '0', [ str(int(x[1]) - 1), '12' ] + x[3:-1], # transform 20xy-0 to 20xz-12 with z = y - 1 [ x[1], str(x[2]).zfill(2) ] + x[3:-1] # transform 20xy-z to 20xy-0z if z < 10 ) )), freq = lambda r: r.period.apply(lambda x: np.where(len(x) == 10, 'D', 'M')), no = lambda r: r.splitroot.apply(lambda x: int(x[-1])), ext = lambda r: r.splitext.apply(lambda x: x[1]), type = lambda r: r.prefix ) .replace({'type': { 'classic' : 0, 'barrage' : 1, 'freesetup' : 2, 'classicfree' : 2, 'ultimate' : 3, 'ultimate lightning': 3, 'duell' : 4, }}) .drop(columns=['splitext', 'root', 'splitroot']) .sort_values(['type', 'period', 'no']) .reset_index(drop=True) .reset_index() .rename(columns={'index': 'gid'}) .loc[:, [ 'gid', 'url', 'name', 'last_modified', 'modified', 'filename', 'prefix', 'period', 'freq', 'no', 'ext', 'type' ]] ) def index_games(df: pd.DataFrame) -> Tuple[pd.DataFrame, pd.DataFrame]: index, games = ( pd.concat(list(t), sort=False, ignore_index=True) for t in zip(*[ _selection(df.query('filename.str.endswith(@ext)'), parser) for ext, parser in [ ('.gsn', _gsn), ('.xml', _xml) ] ]) ) return index, games
defeo/ff_compositum
flint/pq_nmod/embeddings.c
<reponame>defeo/ff_compositum #include "pq_nmod.h" #include "nmod_poly_extra.h" #include <flint/nmod_poly.h> #include <flint/nmod_vec.h> /************** EMBEDDING *****************/ /* Given x in A=k[X]/P and y in B=k[X]/Q, computes the image of xy in the compositum AB. x, y and the result are in dual form. M is the product of deg P and deg Q. res must have enough memory to hold M limbs. res must not be equal to P->coeffs. You would be crazy to do so. */ void _pq_nmod_embed(mp_ptr res, mp_srcptr x, const nmod_poly_t P, mp_srcptr y, const nmod_poly_t Q, slong M) { mp_ptr tmp = _nmod_vec_init(M); nmod_poly_trem(tmp, y, Q, M); nmod_poly_trem(res, x, P, M); __COEFF_PROD(res, res, tmp, P->mod, M); _nmod_vec_clear(tmp); } /* Given x in A=k[X]/P and y in B=k[X]/Q, computes the image of xy in the compositum AB. P and Q must be monic and normalized. */ void pq_nmod_embed(pq_nmod_elt_t res, const pq_nmod_elt_t x, const pq_nmod_t A, const pq_nmod_elt_t y, const pq_nmod_t B) { slong m = nmod_poly_degree(A->M), n = nmod_poly_degree(B->M), M = m*n; _pq_nmod_insure_dual(x, A); _pq_nmod_insure_dual(y, B); if (!nmod_poly_is_zero(x->dual) && !nmod_poly_is_zero(y->dual)) { nmod_poly_fit_length(res->dual, M); _pq_nmod_embed(res->dual->coeffs, x->dual->coeffs, A->M, y->dual->coeffs, B->M, M); res->dual->length = M; } else { nmod_poly_zero(res->dual); } nmod_poly_zero(res->mono); } /************** PROJECTION *****************/ /* Project x onto the space (k[X]/P)y*, where y* is any element dual to y. x is in monomial form, y is in dual form. Result is in monomial form. */ void _pq_nmod_project(nmod_poly_t res, const nmod_poly_t P, const nmod_poly_t x, mp_srcptr y, const nmod_poly_t Q) { slong m = nmod_poly_degree(P), n = nmod_poly_degree(Q), M = FLINT_MIN(x->length, m*n); mp_ptr tmp = _nmod_vec_init(M); nmod_poly_trem(tmp, y, Q, M); nmod_poly_fit_length(res, M); res->length = M; __COEFF_PROD(res->coeffs, x->coeffs, tmp, P->mod, M); _nmod_poly_normalise(res); _nmod_vec_clear(tmp); nmod_poly_rem(res, res, P); } void pq_nmod_project(pq_nmod_elt_t res, const pq_nmod_t A, const pq_nmod_elt_t x, const pq_nmod_t AB, const pq_nmod_elt_t y, const pq_nmod_t B) { _pq_nmod_insure_mono(x, AB); _pq_nmod_insure_dual(y, B); if (!nmod_poly_is_zero(y->dual) && !nmod_poly_is_zero(x->mono)) _pq_nmod_project(res->mono, A->M, x->mono, y->dual->coeffs, B->M); else nmod_poly_zero(res->mono); nmod_poly_zero(res->dual); } /* Relative trace of AB/A */ void pq_nmod_trace(pq_nmod_elt_t res, const pq_nmod_t A, const pq_nmod_elt_t x, const pq_nmod_t AB, const pq_nmod_t B) { _pq_nmod_insure_mono(x, AB); if (!nmod_poly_is_zero(x->mono)) _pq_nmod_project(res->mono, A->M, x->mono, B->newton->coeffs, B->M); else nmod_poly_zero(res->mono); nmod_poly_zero(res->dual); }
havettaa/aurelhavetta.eu
samples/3/usag/morepository/MOREPOSITORY/WebContent/ui5_routing/Detail.controller.js
jQuery.sap.require("com.tutorial.controllers.Detail" + m_urlVersion);
datdoan/jss
scripts/clean-canary-tags.js
<filename>scripts/clean-canary-tags.js const { execSync } = require('child_process'); // prune local tags execSync('git fetch origin --prune --prune-tags', { stdio: 'inherit' }); // fetch all tags from repository execSync('git fetch --all --tags -f', { stdio: 'inherit' }); const output = execSync('git tag', { encoding: 'utf-8', }); const tags = output .split('\n') .filter((tag) => tag.includes('-canary')) .join(' '); if (!tags.length) { console.log('No tags to remove!'); return; } // remove local tags execSync(`git tag -d ${tags}`, { stdio: 'inherit', }); // remove remote tags execSync(`git push -d origin ${tags}`, { stdio: 'inherit' });
Watch-Later/mfcmapi
core/sortlistdata/commentData.h
<filename>core/sortlistdata/commentData.h<gh_stars>100-1000 #pragma once #include <core/sortlistdata/data.h> namespace sortlistdata { class sortListData; class commentData : public IData { public: commentData(_In_opt_ const _SPropValue* lpOldProp) noexcept; static void init(sortListData* data, _In_opt_ const _SPropValue* lpOldProp); _Check_return_ const SPropValue* getCurrentProp() { return m_lpNewProp ? m_lpNewProp : m_lpOldProp; } void setCurrentProp(_In_ SPropValue* prop) { m_lpNewProp = prop; } private: const SPropValue* m_lpOldProp; // not allocated - just a pointer LPSPropValue m_lpNewProp; // Owned by an alloc parent - do not free }; } // namespace sortlistdata
matias-rivera/restobar
frontend/src/reducers/__tests__/table/tableUpdateReducer.test.js
import { TABLE_UPDATE_REQUEST, TABLE_UPDATE_SUCCESS, TABLE_UPDATE_FAIL, TABLE_UPDATE_RESET, } from "../../../constants/tableConstants"; import { tableUpdateReducer } from "../../tableReducers"; /* DATA */ const table = { id: 1, name: "<NAME>", occupied: false, createdAt: "2021-05-19T03:54:18.000Z", updatedAt: "2021-05-19T05:28:26.000Z", }; /* TESTS */ it("handles actions of type TABLE_UPDATE_REQUEST", () => { const action = { type: TABLE_UPDATE_REQUEST, }; const newState = tableUpdateReducer({}, action); expect(newState).toEqual({ loading: true }); }); it("handles actions of type TABLE_UPDATE_SUCCESS", () => { const action = { type: TABLE_UPDATE_SUCCESS, payload: table, }; const newState = tableUpdateReducer({}, action); expect(newState).toEqual({ loading: false, success: true, table: table }); }); it("handles actions of type TABLE_UPDATE_FAIL", () => { const action = { type: TABLE_UPDATE_FAIL, payload: "Request failed with status code 500", }; const newState = tableUpdateReducer({}, action); expect(newState).toEqual({ loading: false, error: "Request failed with status code 500", }); }); it("handles actions of type TABLE_UPDATE_RESET", () => { const action = { type: TABLE_UPDATE_RESET, }; const newState = tableUpdateReducer({}, action); expect(newState).toEqual({ table: {} }); }); it("handles action with unknown type", () => { const action = { type: "UNKNOWN", }; const newState = tableUpdateReducer({}, action); expect(newState).toEqual({}); });
side-projects-42/INTERVIEW-PREP-COMPLETE
notes-n-resources/Data-Structures-N-Algo/_DS-n-Algos/__MY_OPRIGINAL_DS/_Extra-Practice/03_recursion/python/02_greet.py
def greet2(name): print("how are you, ", name, "?") def bye(): print("ok bye!") def greet(name): print("hello, ", name, "!") greet2(name) print("getting ready to say bye...") bye() greet("adit")
io7m/cantoria
com.io7m.cantoria.changes.vanilla/src/main/java/com/io7m/cantoria/changes/vanilla/CMethodChangedFinality.java
/* * Copyright © 2017 <<EMAIL>> http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.cantoria.changes.vanilla; import com.io7m.cantoria.api.CAccessibility; import com.io7m.cantoria.api.CClass; import com.io7m.cantoria.api.CClassModifiers; import com.io7m.cantoria.api.CClassRegistryType; import com.io7m.cantoria.api.CMethod; import com.io7m.cantoria.api.CModifier; import com.io7m.cantoria.changes.spi.CChangeReceiverType; import com.io7m.cantoria.changes.spi.CMethodOverloadComparatorType; import com.io7m.cantoria.changes.vanilla.api.CChangeClassMethodBecameFinal; import com.io7m.cantoria.changes.vanilla.api.CChangeClassMethodBecameNonFinal; import io.vavr.collection.List; /** * Compare the finality of methods. * * <blockquote>Changing a method that is declared final to no longer be declared * final does not break compatibility with pre-existing binaries. * * Changing an instance method that is not declared final to be declared final * may break compatibility with existing binaries that depend on the ability to * override the method.</blockquote> * * JLS 9 §13.4.17 * * @see CChangeClassMethodBecameFinal * @see CChangeClassMethodBecameNonFinal */ public final class CMethodChangedFinality extends LocalizedCheck implements CMethodOverloadComparatorType { /** * Construct a comparator */ public CMethodChangedFinality() { super(CMethodChangedFinality.class.getCanonicalName()); } @Override public String name() { return this.getClass().getCanonicalName(); } @Override public List<String> jlsReferences() { return List.of("JLS 9 §13.4.17"); } @Override public void compareMethodOverload( final CChangeReceiverType receiver, final CClassRegistryType registry, final CClass class_old, final CMethod method_old, final CClass class_new, final CMethod method_new) { /* * If a class is final, then changes to the finality of individual methods * are irrelevant. */ if (CClassModifiers.classIsFinal(class_new.node())) { return; } /* * Private methods are effectively final, because they cannot be overridden. */ if (method_new.accessibility() == CAccessibility.PRIVATE) { return; } final boolean final_old = method_old.modifiers().contains(CModifier.FINAL); final boolean final_new = method_new.modifiers().contains(CModifier.FINAL); if (final_old && !final_new) { receiver.onChange( this, CChangeClassMethodBecameNonFinal.builder() .setMethodPrevious(method_old) .setMethod(method_new) .build()); } if (!final_old && final_new) { receiver.onChange( this, CChangeClassMethodBecameFinal.builder() .setMethodPrevious(method_old) .setMethod(method_new) .build()); } } }
knmcguire/gap_sdk
gvsoc/gvsoc/models/cpu/iss/include/rvXgap9.hpp
<reponame>knmcguire/gap_sdk<gh_stars>1-10 /* * Copyright (C) 2018 ETH Zurich and University of Bologna * * 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. */ /* * Authors: <NAME>, ETH (<EMAIL>) */ #ifndef __CPU_ISS_RVXCPLX_HPP #define __CPU_ISS_RVXCPLX_HPP #include "iss_core.hpp" #include "isa_lib/int.h" #include "isa_lib/macros.h" static inline iss_insn_t *gap9_CPLXMUL_H_I_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL4(lib_CPLXMUL_H_I, REG_GET(0), REG_GET(1), REG_GET(2), 0)); return insn->next; } static inline iss_insn_t *gap9_CPLXMUL_H_I_DIV2_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL4(lib_CPLXMUL_H_I, REG_GET(0), REG_GET(1), REG_GET(2), 1)); return insn->next; } static inline iss_insn_t *gap9_CPLXMUL_H_I_DIV4_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL4(lib_CPLXMUL_H_I, REG_GET(0), REG_GET(1), REG_GET(2), 2)); return insn->next; } static inline iss_insn_t *gap9_CPLXMUL_H_I_DIV8_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL4(lib_CPLXMUL_H_I, REG_GET(0), REG_GET(1), REG_GET(2), 3)); return insn->next; } static inline iss_insn_t *gap9_CPLXMUL_H_R_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL4(lib_CPLXMUL_H_R, REG_GET(0), REG_GET(1), REG_GET(2), 0)); return insn->next; } static inline iss_insn_t *gap9_CPLXMUL_H_R_DIV2_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL4(lib_CPLXMUL_H_R, REG_GET(0), REG_GET(1), REG_GET(2), 1)); return insn->next; } static inline iss_insn_t *gap9_CPLXMUL_H_R_DIV4_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL4(lib_CPLXMUL_H_R, REG_GET(0), REG_GET(1), REG_GET(2), 2)); return insn->next; } static inline iss_insn_t *gap9_CPLXMUL_H_R_DIV8_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL4(lib_CPLXMUL_H_R, REG_GET(0), REG_GET(1), REG_GET(2), 3)); return insn->next; } static inline iss_insn_t *gap9_CPLX_CONJ_16_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL1(lib_CPLX_CONJ_16, REG_GET(0))); return insn->next; } static inline iss_insn_t *gap9_VEC_ADD_16_ROTMJ_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_ADD_16_ROTMJ, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_ADD_16_ROTMJ_DIV2_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_ADD_16_ROTMJ_DIV2, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_ADD_16_ROTMJ_DIV4_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_ADD_16_ROTMJ_DIV4, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_ADD_16_ROTMJ_DIV8_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_ADD_16_ROTMJ_DIV8, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_ADD_16_DIV2_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_ADD_int16_t_to_int32_t_div2, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_ADD_16_DIV4_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_ADD_int16_t_to_int32_t_div4, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_ADD_16_DIV8_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_ADD_int16_t_to_int32_t_div8, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_SUB_16_DIV2_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_SUB_int16_t_to_int32_t_div2, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_SUB_16_DIV4_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_SUB_int16_t_to_int32_t_div4, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_SUB_16_DIV8_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_SUB_int16_t_to_int32_t_div8, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_VEC_PACK_SC_H_16_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL2(lib_VEC_PACK_SC_H_16, REG_GET(0), REG_GET(1))); return insn->next; } static inline iss_insn_t *gap9_BITREV_exec(iss_t *iss, iss_insn_t *insn) { REG_SET(0, LIB_CALL3(lib_BITREV, REG_GET(0), UIM_GET(0), UIM_GET(1)+1)); return insn->next; } #endif
PayalSasmal10/datastructures-algorithms
thread/singleThread.py
import threading def print_cube(num): print("cube:", num*num*num) def print_square(num): print("square:", num*num) t1 = threading.Thread(target=print_cube, args=(10,)) t2 = threading.Thread(target=print_square, args=(10,)) t1.start() t2.start()
ScalablyTyped/SlinkyTyped
o/office-js-preview/src/main/scala/typingsSlinky/officeJsPreview/Visio/Interfaces/DocumentData.scala
<gh_stars>10-100 package typingsSlinky.officeJsPreview.Visio.Interfaces import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} /** An interface describing the data returned by calling "document.toJSON()". */ @js.native trait DocumentData extends StObject { /** * * Represents a Visio application instance that contains this document. Read-only. * * [Api set: 1.1] */ var application: js.UndefOr[ApplicationData] = js.native /** * * Represents a collection of pages associated with the document. Read-only. * * [Api set: 1.1] */ var pages: js.UndefOr[js.Array[PageData]] = js.native /** * * Returns the DocumentView object. Read-only. * * [Api set: 1.1] */ var view: js.UndefOr[DocumentViewData] = js.native } object DocumentData { @scala.inline def apply(): DocumentData = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[DocumentData] } @scala.inline implicit class DocumentDataMutableBuilder[Self <: DocumentData] (val x: Self) extends AnyVal { @scala.inline def setApplication(value: ApplicationData): Self = StObject.set(x, "application", value.asInstanceOf[js.Any]) @scala.inline def setApplicationUndefined: Self = StObject.set(x, "application", js.undefined) @scala.inline def setPages(value: js.Array[PageData]): Self = StObject.set(x, "pages", value.asInstanceOf[js.Any]) @scala.inline def setPagesUndefined: Self = StObject.set(x, "pages", js.undefined) @scala.inline def setPagesVarargs(value: PageData*): Self = StObject.set(x, "pages", js.Array(value :_*)) @scala.inline def setView(value: DocumentViewData): Self = StObject.set(x, "view", value.asInstanceOf[js.Any]) @scala.inline def setViewUndefined: Self = StObject.set(x, "view", js.undefined) } }
sul-dlss/sul_pub
lib/my_app_utf8.rb
# frozen_string_literal: true module MyAppUtf8 class SetNamesUtf8 def self.filter(_controller) suppress(ActiveRecord::StatementInvalid) do ActiveRecord::Base.connection.execute 'SET NAMES UTF8' end true end end end
JULIELab/jcore-dependencies
jcore-mallet-2.0.9/src/main/java/cc/mallet/classify/tui/Text2Vectors.java
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept. This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit). http://www.cs.umass.edu/~mccallum/mallet This software is provided under the terms of the Common Public License, version 1.0, as published by http://www.opensource.org. For further information, see the file `LICENSE' included with this distribution. */ package cc.mallet.classify.tui; import cc.mallet.pipe.*; import cc.mallet.pipe.iterator.FileIterator; import cc.mallet.types.InstanceList; import cc.mallet.util.CharSequenceLexer; import cc.mallet.util.CommandOption; import cc.mallet.util.MalletLogger; import cc.mallet.util.Strings; import java.io.*; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Convert document files into vectors (a persistent instance list). * @author <NAME> <a href="mailto:<EMAIL>"><EMAIL></a> */ public class Text2Vectors { private static Logger logger = MalletLogger.getLogger(Text2Vectors.class.getName()); public static String defaultTokenRegex = "\\p{L}[\\p{L}\\p{P}]+\\p{L}"; static CommandOption.SpacedStrings classDirs = new CommandOption.SpacedStrings(Text2Vectors.class, "input", "DIR...", true, null, "The directories containing text files to be classified, one directory per class", null); static CommandOption.File outputFile = new CommandOption.File(Text2Vectors.class, "output", "FILE", true, new File("text.vectors"), "Write the instance list to this file; Using - indicates stdout.", null); static CommandOption.File usePipeFromVectorsFile = new CommandOption.File(Text2Vectors.class, "use-pipe-from", "FILE", true, new File("text.vectors"), "Use the pipe and alphabets from a previously created vectors file. " + "Allows the creation, for example, of a test set of vectors that are " + "compatible with a previously created set of training vectors", null); static CommandOption.Boolean preserveCase = new CommandOption.Boolean(Text2Vectors.class, "preserve-case", "[TRUE|FALSE]", false, false, "If true, do not force all strings to lowercase.", null); static CommandOption.SpacedStrings replacementFiles = new CommandOption.SpacedStrings(Text2Vectors.class, "replacement-files", "FILE [FILE ...]", true, null, "files containing string replacements, one per line:\n 'A B [tab] C' replaces A B with C,\n 'A B' replaces A B with A_B", null); static CommandOption.SpacedStrings deletionFiles = new CommandOption.SpacedStrings(Text2Vectors.class, "deletion-files", "FILE [FILE ...]", true, null, "files containing strings to delete after replacements but before tokenization (ie multiword stop terms)", null); static CommandOption.Boolean removeStopWords = new CommandOption.Boolean(Text2Vectors.class, "remove-stopwords", "[TRUE|FALSE]", false, false, "If true, remove a default list of common English \"stop words\" from the text.", null); static CommandOption.File stoplistFile = new CommandOption.File(Text2Vectors.class, "stoplist-file", "FILE", true, null, "Instead of the default list, read stop words from a file, one per line. Implies --remove-stopwords", null); static CommandOption.File extraStopwordsFile = new CommandOption.File(Text2Vectors.class, "extra-stopwords", "FILE", true, null, "Read whitespace-separated words from this file, and add them to either\n" + " the default English stoplist or the list specified by --stoplist-file.", null); static CommandOption.File stopPatternFile = new CommandOption.File(Text2Vectors.class, "stop-pattern-file", "FILE", true, null, "Read regular expressions from a file, one per line. Tokens matching these regexps will be removed.", null); static CommandOption.Boolean skipHeader = new CommandOption.Boolean(Text2Vectors.class, "skip-header", "[TRUE|FALSE]", false, false, "If true, in each document, remove text occurring before a blank line."+ " This is useful for removing email or UseNet headers", null); static CommandOption.Boolean skipHtml = new CommandOption.Boolean(Text2Vectors.class, "skip-html", "[TRUE|FALSE]", false, false, "If true, remove text occurring inside <...>, as in HTML or SGML.", null); static CommandOption.Boolean binaryFeatures = new CommandOption.Boolean(Text2Vectors.class, "binary-features", "[TRUE|FALSE]", false, false, "If true, features will be binary.", null); static CommandOption.IntegerArray gramSizes = new CommandOption.IntegerArray(Text2Vectors.class, "gram-sizes", "INTEGER,[INTEGER,...]", true, new int[] {1}, "Include among the features all n-grams of sizes specified. "+ "For example, to get all unigrams and bigrams, use --gram-sizes 1,2. "+ "This option occurs after the removal of stop words, if removed.", null); static CommandOption.Boolean keepSequence = new CommandOption.Boolean(Text2Vectors.class, "keep-sequence", "[TRUE|FALSE]", false, false, "If true, final data will be a FeatureSequence rather than a FeatureVector.", null); static CommandOption.Boolean keepSequenceBigrams = new CommandOption.Boolean(Text2Vectors.class, "keep-sequence-bigrams", "[TRUE|FALSE]", false, false, "If true, final data will be a FeatureSequenceWithBigrams rather than a FeatureVector.", null); static CommandOption.Boolean saveTextInSource = new CommandOption.Boolean(Text2Vectors.class, "save-text-in-source", "[TRUE|FALSE]", false, false, "If true, save original text of document in source.", null); static CommandOption.ObjectFromBean stringPipe = new CommandOption.ObjectFromBean(Text2Vectors.class, "string-pipe", "Pipe constructor", true, null, "Java code for the constructor of a Pipe to be run as soon as input becomes a CharSequence", null); static CommandOption.ObjectFromBean tokenPipe = new CommandOption.ObjectFromBean(Text2Vectors.class, "token-pipe", "Pipe constructor", true, null, "Java code for the constructor of a Pipe to be run as soon as input becomes a TokenSequence", null); static CommandOption.ObjectFromBean featureVectorPipe = new CommandOption.ObjectFromBean(Text2Vectors.class, "fv-pipe", "Pipe constructor", true, null, "Java code for the constructor of a Pipe to be run as soon as input becomes a FeatureVector", null); static CommandOption.String encoding = new CommandOption.String(Text2Vectors.class, "encoding", "STRING", true, Charset.defaultCharset().displayName(), "Character encoding for input file", null); static CommandOption.String tokenRegex = new CommandOption.String(Text2Vectors.class, "token-regex", "REGEX", true, defaultTokenRegex, "Regular expression used for tokenization.\n" + " Example: \"[\\p{L}\\p{N}_]+|[\\p{P}]+\" (unicode letters, numbers and underscore OR all punctuation) ", null); static CommandOption.Boolean printOutput = new CommandOption.Boolean(Text2Vectors.class, "print-output", "[TRUE|FALSE]", false, false, "If true, print a representation of the processed data\n" + " to standard output. This option is intended for debugging.", null); public static void main (String[] args) throws FileNotFoundException, IOException { // Process the command-line options CommandOption.setSummary (Text2Vectors.class, "A tool for creating instance lists of FeatureVectors or FeatureSequences from text documents.\n"); CommandOption.process (Text2Vectors.class, args); //String[] classDirs = CommandOption.process (Text2Vectors.class, args); // Print some helpful messages for error cases if (args.length == 0) { CommandOption.getList(Text2Vectors.class).printUsage(false); System.exit (-1); } if (classDirs.value.length == 0) { throw new IllegalArgumentException ("You must include --input DIR1 DIR2 ...' in order to specify a " + "list of directories containing the documents for each class."); } // Remove common prefix from all the input class directories int commonPrefixIndex = Strings.commonPrefixIndex (classDirs.value); logger.info ("Labels = "); File[] directories = new File[classDirs.value.length]; for (int i = 0; i < classDirs.value.length; i++) { directories[i] = new File (classDirs.value[i]); if (commonPrefixIndex < classDirs.value.length) { logger.info (" "+classDirs.value[i].substring(commonPrefixIndex)); } else { logger.info (" "+classDirs.value[i]); } } Pipe instancePipe; InstanceList previousInstanceList = null; if (usePipeFromVectorsFile.wasInvoked()) { previousInstanceList = InstanceList.load (usePipeFromVectorsFile.value); instancePipe = previousInstanceList.getPipe(); } else { // Build a new pipe // Create a list of pipes that will be added to a SerialPipes object later ArrayList<Pipe> pipeList = new ArrayList<Pipe>(); // Convert the "target" object into a numeric index // into a LabelAlphabet. pipeList.add(new Target2Label()); // The "data" field is currently a filename. Save it as "source". pipeList.add( new SaveDataInSource() ); // Set "data" to the file's contents. "data" is now a String. pipeList.add( new Input2CharSequence(encoding.value) ); // Optionally save the text to "source" -- not recommended if memory is scarce. if (saveTextInSource.wasInvoked()) { pipeList.add( new SaveDataInSource() ); } // Allow the user to specify an arbitrary Pipe object // that operates on Strings if (stringPipe.wasInvoked()) { pipeList.add( (Pipe) stringPipe.value ); } // Remove all content before the first empty line. // Useful for email and usenet news posts. if (skipHeader.value) { pipeList.add( new CharSubsequence(CharSubsequence.SKIP_HEADER) ); } // Remove HTML tags. Suitable for SGML and XML. if (skipHtml.value) { pipeList.add( new CharSequenceRemoveHTML() ); } // String replacements if (! preserveCase.value()) { pipeList.add(new CharSequenceLowercase()); } if (replacementFiles.value != null || deletionFiles.value != null) { NGramPreprocessor preprocessor = new NGramPreprocessor(); if (replacementFiles.value != null) { for (String filename: replacementFiles.value) { preprocessor.loadReplacements(filename); } } if (deletionFiles.value != null) { for (String filename: deletionFiles.value) { preprocessor.loadDeletions(filename); } } pipeList.add(preprocessor); } // // Tokenize the input: first compile the tokenization pattern // Pattern tokenPattern = null; if (keepSequenceBigrams.value) { // We do not want to record bigrams across punctuation, // so we need to keep non-word tokens. tokenPattern = CharSequenceLexer.LEX_NONWHITESPACE_CLASSES; } else { // Otherwise, try to compile the regular expression pattern. try { tokenPattern = Pattern.compile(tokenRegex.value); } catch (PatternSyntaxException pse) { throw new IllegalArgumentException("The token regular expression (" + tokenRegex.value + ") was invalid: " + pse.getMessage()); } } // Add the tokenizer pipeList.add(new CharSequence2TokenSequence(tokenPattern)); // Allow user to specify an arbitrary Pipe object // that operates on TokenSequence objects. if (tokenPipe.wasInvoked()) { pipeList.add( (Pipe) tokenPipe.value ); } if (keepSequenceBigrams.value) { // Remove non-word tokens, but record the fact that they // were there. pipeList.add(new TokenSequenceRemoveNonAlpha(true)); } // Stopword removal. if (stoplistFile.wasInvoked()) { // The user specified a new list TokenSequenceRemoveStopwords stopwordFilter = new TokenSequenceRemoveStopwords(stoplistFile.value, encoding.value, false, // don't include default list false, keepSequenceBigrams.value); if (extraStopwordsFile.wasInvoked()) { stopwordFilter.addStopWords(extraStopwordsFile.value); } pipeList.add(stopwordFilter); } else if (removeStopWords.value) { // The user did not specify a new list, so use the default // built-in English list, possibly adding extra words. TokenSequenceRemoveStopwords stopwordFilter = new TokenSequenceRemoveStopwords(false, keepSequenceBigrams.value); if (extraStopwordsFile.wasInvoked()) { stopwordFilter.addStopWords(extraStopwordsFile.value); } pipeList.add(stopwordFilter); } if (stopPatternFile.wasInvoked()) { TokenSequenceRemoveStopPatterns stopPatternFilter = new TokenSequenceRemoveStopPatterns(stopPatternFile.value); pipeList.add(stopPatternFilter); } // gramSizes is an integer array, with default value [1]. // Check if we have a non-default value. if (! (gramSizes.value.length == 1 && gramSizes.value[0] == 1)) { pipeList.add( new TokenSequenceNGrams(gramSizes.value) ); } // So far we have a sequence of Token objects that contain // String values. Look these up in an alphabet and store integer IDs // ("features") instead of Strings. if (keepSequenceBigrams.value) { pipeList.add( new TokenSequence2FeatureSequenceWithBigrams() ); } else { pipeList.add( new TokenSequence2FeatureSequence() ); } // For many applications, we do not need to preserve the sequence of features, // only the number of times times a feature occurs. if (! (keepSequence.value || keepSequenceBigrams.value)) { pipeList.add( new FeatureSequence2AugmentableFeatureVector(binaryFeatures.value) ); } // Allow users to specify an arbitrary Pipe object that operates on // feature vectors. if (featureVectorPipe.wasInvoked()) { pipeList.add( (Pipe) featureVectorPipe.value ); } if (printOutput.value) { pipeList.add(new PrintInputAndTarget()); } instancePipe = new SerialPipes(pipeList); } InstanceList instances = new InstanceList (instancePipe); boolean removeCommonPrefix = true; instances.addThruPipe (new FileIterator (directories, FileIterator.STARTING_DIRECTORIES, removeCommonPrefix)); // write vector file ObjectOutputStream oos; if (outputFile.value.toString().equals ("-")) { oos = new ObjectOutputStream(System.out); } else { oos = new ObjectOutputStream(new FileOutputStream(outputFile.value)); } oos.writeObject(instances); oos.close(); // *rewrite* vector file used as source of pipe in case we changed the alphabet(!) if (usePipeFromVectorsFile.wasInvoked()) { logger.info(" rewriting previous instance list, with ID = " + previousInstanceList.getPipe().getInstanceId()); oos = new ObjectOutputStream(new FileOutputStream(usePipeFromVectorsFile.value)); oos.writeObject(previousInstanceList); oos.close(); } } }
MyPureCloud/platform-client-sdk-cli
build/gc/models/fieldlist.go
package models import ( "encoding/json" "strconv" "strings" ) var ( FieldlistMarshalled = false ) // This struct is here to use the useless readonly properties so that their required imports don't throw an unused error (time, etc.) type FieldlistDud struct { } // Fieldlist type Fieldlist struct { // CustomLabels CustomLabels bool `json:"customLabels"` // InstructionText InstructionText string `json:"instructionText"` // Key Key string `json:"key"` // LabelKeys LabelKeys []string `json:"labelKeys"` // Params Params map[string]interface{} `json:"params"` // Repeatable Repeatable bool `json:"repeatable"` // State State string `json:"state"` // VarType VarType string `json:"type"` // Required Required bool `json:"required"` // Gdpr Gdpr bool `json:"gdpr"` } // String returns a JSON representation of the model func (o *Fieldlist) String() string { o.LabelKeys = []string{""} o.Params = map[string]interface{}{"": Interface{}} j, _ := json.Marshal(o) str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\u`, `\u`, -1)) return str } func (u *Fieldlist) MarshalJSON() ([]byte, error) { type Alias Fieldlist if FieldlistMarshalled { return []byte("{}"), nil } FieldlistMarshalled = true return json.Marshal(&struct { CustomLabels bool `json:"customLabels"` InstructionText string `json:"instructionText"` Key string `json:"key"` LabelKeys []string `json:"labelKeys"` Params map[string]interface{} `json:"params"` Repeatable bool `json:"repeatable"` State string `json:"state"` VarType string `json:"type"` Required bool `json:"required"` Gdpr bool `json:"gdpr"` *Alias }{ LabelKeys: []string{""}, Params: map[string]interface{}{"": Interface{}}, Alias: (*Alias)(u), }) }
JaneMandy/CS
sleep/engine/Block.java
package sleep.engine; import java.io.File; import java.io.Serializable; import java.util.ConcurrentModificationException; import sleep.engine.atoms.Goto; import sleep.runtime.Scalar; import sleep.runtime.ScriptEnvironment; import sleep.runtime.SleepUtils; public class Block implements Serializable { protected Step first; protected Step last; protected String source = "unknown"; public Block(String var1) { this.source = var1; } public String toString(String var1) { StringBuffer var2 = new StringBuffer(); for(Step var3 = this.first; var3 != null; var3 = var3.next) { var2.append(var3.toString(var1)); } return var2.toString(); } public String toString() { return this.toString(""); } public String getSource() { return this.source; } public int getApproximateLineNumber() { return this.first != null ? this.first.getLineNumber() : -1; } public int getHighLineNumber() { int var1 = 0; for(Step var3 = this.first; var3 != null; var3 = var3.next) { int var2 = var3.getHighLineNumber(); if (var2 > var1) { var1 = var2; } } return var1; } public int getLowLineNumber() { int var1 = Integer.MAX_VALUE; for(Step var3 = this.first; var3 != null; var3 = var3.next) { int var2 = var3.getLowLineNumber(); if (var2 < var1) { var1 = var2; } } return var1; } public String getApproximateLineRange() { int var1 = this.getLowLineNumber(); int var2 = this.getHighLineNumber(); return var1 == var2 ? var1.makeConcatWithConstants<invokedynamic>(var1) : var1 + "-" + var2; } public String getSourceLocation() { String var10000 = (new File(this.source)).getName(); return var10000 + ":" + this.getApproximateLineRange(); } public void add(Step var1) { if (this.first == null) { this.first = var1; } else { this.last.next = var1; } this.last = var1; } public Scalar evaluate(ScriptEnvironment var1) { return this.evaluate(var1, this.first); } private void handleException(ScriptEnvironment var1) { if (var1.isResponsible(this)) { Block var2 = var1.getExceptionHandler(); var2.evaluate(var1); var1.getScriptInstance().clearStackTrace(); } } private void cleanupEnvironment(ScriptEnvironment var1) { var1.popSource(); if (var1.isResponsible(this)) { var1.popExceptionContext(); } } public Scalar evaluate(ScriptEnvironment var1, Step var2) { if (var1.isReturn()) { if (var1.isThrownValue()) { var1.pushSource(this.source); this.handleException(var1); this.cleanupEnvironment(var1); } return var1.getReturnValue(); } else { var1.pushSource(this.source); for(Step var3 = var2; var3 != null; var3 = var3.next) { try { var3.evaluate(var1); } catch (Exception var5) { if (var5 instanceof IllegalArgumentException) { var1.getScriptInstance().fireWarning(var5.getMessage(), var3.getLineNumber()); } else if (var5 instanceof IndexOutOfBoundsException) { if (var5.getMessage() != null) { var1.getScriptInstance().fireWarning("attempted an invalid index: " + var5.getMessage(), var3.getLineNumber()); } else { var1.getScriptInstance().fireWarning("attempted an invalid index", var3.getLineNumber()); } } else if (var5 instanceof ClassCastException) { var1.getScriptInstance().fireWarning("attempted an invalid cast: " + var5.getMessage(), var3.getLineNumber()); } else if (var5 instanceof NullPointerException) { var1.getScriptInstance().fireWarning("null value error", var3.getLineNumber()); } else if (var5 instanceof ConcurrentModificationException) { if (var5.getMessage() != null) { var1.getScriptInstance().fireWarning("unsafe data modification: " + var5.getMessage(), var3.getLineNumber()); } else { var1.getScriptInstance().fireWarning("detected unsafe data modification", var3.getLineNumber()); } } else if (var5 instanceof RuntimeException) { if (var5.getMessage() == null) { var1.getScriptInstance().fireWarning("internal error - " + var5.getClass(), var3.getLineNumber()); } else { var1.getScriptInstance().fireWarning(var5.getMessage(), var3.getLineNumber()); } } else { var1.getScriptInstance().fireWarning(var5.toString(), var3.getLineNumber()); } this.cleanupEnvironment(var1); return SleepUtils.getEmptyScalar(); } catch (Error var6) { var1.getScriptInstance().fireWarning("critical internal error - " + var6.toString(), var3.getLineNumber()); this.cleanupEnvironment(var1); throw var6; } while(var1.isReturn()) { if (var1.isYield()) { if (var3 instanceof Goto) { var1.addToContext(this, var3); } else { var1.addToContext(this, var3.next); } } if (var1.isCallCC()) { var1.getCurrentFrame().push(this.source); var1.getCurrentFrame().push(new Integer(var3.getLineNumber())); } if (var1.isThrownValue()) { if (!var1.isExceptionHandlerInstalled()) { if (!SleepUtils.isEmptyScalar(var1.getReturnValue())) { var1.getScriptInstance().fireWarning("Uncaught exception: " + var1.getExceptionMessage(), var3.getLineNumber()); var1.flagReturn((Scalar)null, 16); } } else if (!SleepUtils.isEmptyScalar(var1.getReturnValue())) { this.handleException(var1); } this.cleanupEnvironment(var1); return var1.getReturnValue(); } if (!var1.isDebugInterrupt()) { this.cleanupEnvironment(var1); return var1.getReturnValue(); } var1.getScriptInstance().fireWarning(var1.getDebugString(), var3.getLineNumber()); } } this.cleanupEnvironment(var1); return SleepUtils.getEmptyScalar(); } } }
RedaMastouri/marvis
11 - Extra-- sonos snips voice app/tests/use_cases/test_resume_music_use_case.py
import pytest from mock import mock from snipssonos.entities.device import Device from snipssonos.use_cases.resume_music import ResumeMusicUseCase from snipssonos.use_cases.request_objects import ResumeMusicRequestObject from snipssonos.exceptions import NoReachableDeviceException @pytest.fixture def connected_device(): return Device( name="Anthony's Sonos", identifier="RINCON_XXXX", volume=10 ) def test_use_case_empty_parameters(connected_device): device_discovery_service = mock.Mock() device_discovery_service.get.return_value = connected_device # We mock the device discovery service device_transport_control_service = mock.Mock() resume_music_uc = ResumeMusicUseCase(device_discovery_service, device_transport_control_service) resume_music_request = ResumeMusicRequestObject.from_dict({}) result_object = resume_music_uc.execute(resume_music_request) device_discovery_service.get.assert_called() device_transport_control_service.resume.assert_called() assert bool(result_object) is True def test_use_case_no_reachable_device(): device_discovery_service = mock.Mock() device_discovery_service.get.side_effect = NoReachableDeviceException( "No reachable Sonos devices") # We mock the device discovery service device_transport_control_service = mock.Mock() resume_music_uc = ResumeMusicUseCase(device_discovery_service, device_transport_control_service) resume_music_request = ResumeMusicRequestObject() result_obj = resume_music_uc.execute(resume_music_request) assert bool(result_obj) is False assert result_obj.message == "NoReachableDeviceException: No reachable Sonos devices"
BackboneBootstrap/backbonebootstrap-core
utils/html.js
<reponame>BackboneBootstrap/backbonebootstrap-core /*globals define*/ define( [ 'jquery' ], function( $ ) { 'use strict'; var html = {}; html.enable = function(selector, value) { if (value === undefined) value = true; var elem = $(selector); if (value === true ) { elem.removeAttr('disabled'); elem.removeClass('disabled'); if (selector.prop('tagName') === 'A') { selector.unbind('click'); } } else { elem.attr('disabled', 'disabled'); elem.addClass('disabled'); if (selector.prop('tagName') === 'A') { selector.click(function(e) { e.preventDefault(); }); } } }; html.disable = function(selector) { html.enable(selector, false); }; // check http://stackoverflow.com/questions/1354064/how-to-convert-characters-to-html-entities-using-plain-javascript html.encode = function(text) { var escaped = text.replace(/[\u00A0-\u00FF\u2022-\u2135]/g, function(c) { return '&#' + c.charCodeAt(0) + ';'; }); return escaped; }; return html; });
DevInsideYou/tagless-final
todo/02-core/src/test/scala/com/devinsideyou/todo/crud/BoundarySuite.scala
package com.devinsideyou package todo package crud import cats._ final class BoundarySuite extends TestSuite { import BoundarySuite._ private type F[A] = Id[A] test("description should be trimmed") { val entityGateway: EntityGateway[F, Unit] = new FakeEntityGateway[F, Unit] { override def writeMany( todos: Vector[Todo[Unit]] ): F[Vector[Todo.Existing[Unit]]] = todos.map { case data: Todo.Data => Todo.Existing((), data) case existing: Todo.Existing[Unit] => existing } } val boundary: Boundary[F, Unit] = Boundary.dsl(entityGateway) forAll { data: Todo.Data => boundary.createOne(data).description shouldBe data.description.trim } } test("readByDescription should not always call gateway.readByDescription") { var wasCalled = false val entityGateway: EntityGateway[F, Unit] = new FakeEntityGateway[F, Unit] { override def readManyByPartialDescription( partialDescription: String ): F[Vector[Todo.Existing[Unit]]] = { wasCalled = true Vector.empty } } val boundary: Boundary[F, Unit] = Boundary.dsl(entityGateway) When("the description is empty") boundary.readManyByPartialDescription("") Then("gateway.readByDescription should NOT be called") wasCalled shouldBe false forAll(MinSuccessful(1)) { description: String => whenever(description.nonEmpty) { When("the description is NOT empty") boundary.readManyByPartialDescription(description) Then("gateway.readByDescription should be called") wasCalled shouldBe true } } } } object BoundarySuite { private class FakeEntityGateway[F[_], TodoId] extends EntityGateway[F, TodoId] { override def writeMany( todos: Vector[Todo[TodoId]] ): F[Vector[Todo.Existing[TodoId]]] = ??? override def readManyById( ids: Vector[TodoId] ): F[Vector[Todo.Existing[TodoId]]] = ??? override def readManyByPartialDescription( partialDescription: String ): F[Vector[Todo.Existing[TodoId]]] = ??? override def readAll: F[Vector[Todo.Existing[TodoId]]] = ??? override def deleteMany(todos: Vector[Todo.Existing[TodoId]]): F[Unit] = ??? override def deleteAll: F[Unit] = ??? } }
runvs/1hgj_352
impl/jamtemplate/common/tweens/tween_position.cpp
#include "tween_position.hpp" #include "linterp.hpp" namespace jt { Tween::Sptr TweenPosition::create(std::weak_ptr<DrawableInterface> obj, float time, jt::Vector2f valueStart, jt::Vector2f valueEnd) { return std::make_shared<TweenPosition>(obj, time, valueStart, valueEnd); } TweenPosition::TweenPosition(std::weak_ptr<DrawableInterface> obj, float time, jt::Vector2f valueStart, jt::Vector2f valueEnd) : Tween { obj, time } , m_initialValue { valueStart } , m_finalValue { valueEnd } { } void TweenPosition::doUpdateObject( std::shared_ptr<DrawableInterface> const& sptr, float agePercent) const { auto pos = sptr->getPosition(); pos.x = Lerp::linear( static_cast<float>(m_initialValue.x), static_cast<float>(m_finalValue.x), agePercent); pos.y = Lerp::linear( static_cast<float>(m_initialValue.y), static_cast<float>(m_finalValue.y), agePercent); sptr->setPosition(pos); } } // namespace jt
minhvip2001/pythonproject
Week1_PyThonBasic/List/Ex1.py
<gh_stars>0 aLsit = [100, 200, 300, 400, 500] print(aLsit[::-1])
maciejg-git/vue-bootstrap-icons
dist-mdi/mdi/source-fork.js
<filename>dist-mdi/mdi/source-fork.js import { h } from 'vue' export default { name: "SourceFork", vendor: "Mdi", type: "", tags: ["source","fork"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-source-fork","innerHTML":"<path d='M6,2A3,3 0 0,1 9,5C9,6.28 8.19,7.38 7.06,7.81C7.15,8.27 7.39,8.83 8,9.63C9,10.92 11,12.83 12,14.17C13,12.83 15,10.92 16,9.63C16.61,8.83 16.85,8.27 16.94,7.81C15.81,7.38 15,6.28 15,5A3,3 0 0,1 18,2A3,3 0 0,1 21,5C21,6.32 20.14,7.45 18.95,7.85C18.87,8.37 18.64,9 18,9.83C17,11.17 15,13.08 14,14.38C13.39,15.17 13.15,15.73 13.06,16.19C14.19,16.62 15,17.72 15,19A3,3 0 0,1 12,22A3,3 0 0,1 9,19C9,17.72 9.81,16.62 10.94,16.19C10.85,15.73 10.61,15.17 10,14.38C9,13.08 7,11.17 6,9.83C5.36,9 5.13,8.37 5.05,7.85C3.86,7.45 3,6.32 3,5A3,3 0 0,1 6,2M6,4A1,1 0 0,0 5,5A1,1 0 0,0 6,6A1,1 0 0,0 7,5A1,1 0 0,0 6,4M18,4A1,1 0 0,0 17,5A1,1 0 0,0 18,6A1,1 0 0,0 19,5A1,1 0 0,0 18,4M12,18A1,1 0 0,0 11,19A1,1 0 0,0 12,20A1,1 0 0,0 13,19A1,1 0 0,0 12,18Z' />"}, ) } }
goutomroy/uva.onlinejudge
solved/10931.cpp
<filename>solved/10931.cpp<gh_stars>0 #include<stdio.h> #include<string.h> void main( ) { long n,i,a[500],j,m,k,sum; while(scanf("%ld",&n)==1 &&n!=0) { if(n==1) printf("The parity of %ld is %ld (mod 2).\n",n,n); else { k=0;sum=0;m=n; while(n!=1) { if(n%2==0) a[k++]=0; else a[k++]=1; n=n/2; } a[k++]=1; for(i=0;i<k;i++) sum=sum+a[i]; printf("The parity of "); for(i=k-1;i>=0;i--) printf("%ld",a[i]); printf(" is %ld (mod 2).\n",sum); } } }
cacheflowe/haxademic
src/com/haxademic/demo/hardware/serial/Demo_LedStripLPD8806.java
package com.haxademic.demo.hardware.serial; import com.haxademic.core.app.P; import com.haxademic.core.app.PAppletHax; import com.haxademic.core.app.config.AppSettings; import com.haxademic.core.app.config.Config; import com.haxademic.core.debug.DebugView; import com.haxademic.core.draw.filters.pshader.BrightnessFilter; import com.haxademic.core.draw.textures.SimplexNoise3dTexture; import com.haxademic.core.draw.textures.pshader.TextureShader; import com.haxademic.core.hardware.mouse.Mouse; import com.haxademic.core.hardware.serial.LedStripLPD8806; import com.haxademic.core.hardware.serial.SerialDevice; import com.haxademic.core.hardware.serial.SerialDevice.ISerialDeviceDelegate; import processing.serial.Serial; public class Demo_LedStripLPD8806 extends PAppletHax implements ISerialDeviceDelegate { public static void main(String args[]) { arguments = args; PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); } protected SimplexNoise3dTexture noiseTexture; protected TextureShader textureShader; protected LedStripLPD8806 ledStrip; protected void config() { Config.setProperty( AppSettings.WIDTH, 640 ); Config.setProperty( AppSettings.HEIGHT, 640 ); Config.setProperty( AppSettings.SHOW_FPS_IN_TITLE, true ); // Config.setProperty( AppSettings.FPS, 30 ); } protected void firstFrame() { SerialDevice.printDevices(); ledStrip = new LedStripLPD8806(this, 0, 115200, 12); noiseTexture = new SimplexNoise3dTexture(p.width, p.height); textureShader = new TextureShader(TextureShader.light_leak); } protected void drawApp() { background(0); updateLedLights(); } protected void updateLedLights() { // update texture textureShader.setTime((float) p.frameCount * 0.03f); pg.filter(textureShader.shader()); BrightnessFilter.instance(p).setBrightness(Mouse.xNorm); BrightnessFilter.instance(p).applyTo(pg); // copy to device buffer & send to hardware ledStrip.update(pg, 0.4f, 0.85f); p.image(pg, 0, 0); } @Override public void newDataAvailable(Serial serialDevice) { // log incoming messages String inputStr = serialDevice.readString(); DebugView.setValue("[Serial in]", inputStr); P.out(inputStr); } } // ARDUINO CODE /** // Controls LPD8806-based RGB LED Modules in a strip // Wiring diagram: https://learn.adafruit.com/digital-led-strip/wiring // -5V = 5V // -GND = GND // -DI = Digital 2 // -CI = Digital 3 // For led chips like WS2812, which have a data line, ground, and power, you just // need to define DATA_PIN. For led chipsets that are SPI based (four wires - data, clock, // ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN // Clock pin only needed for SPI based chipsets when not using hardware SPI ///////////////////////////////////////////////////////////////////////////// // hardware setup #include <FastLED.h> #define DATA_PIN 2 #define CLOCK_PIN 3 // lights config #define NUM_LEDS 32 CRGB leds[NUM_LEDS]; // state-machine for bufferless serial input typedef enum { NONE, GOT_COLOR, GOT_OTHER } states; states state = NONE; unsigned int currentValue; int colorArrSize = 4; int curRgbInput[] = {0, 0, 0, 0}; // [led_index, r, g, b] int rgbInputValIndex = 0; // start void setup() { // ## Clocked (SPI) initializer ## FastLED.addLeds<LPD8806, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS); // GRB ordering is typical // Start serial for input Serial.begin(115200); Serial.setTimeout(0); Serial.println("<Arduino is ready>"); state = NONE; } int byteToInt(byte b) { return b;// & 0xFF; } void loop() { // runSingleDotPulseDemo(); runRgbSerial(); } ///////////////////////////// // Serial input mode ///////////////////////////// void runRgbSerial() { while (Serial.available()) { processIncomingByte(Serial.read()); } // Serial.flush(); FastLED.show(); // delay(16); } void processIncomingByte (byte c) { // check for numeric values or new mode characters // idea from: http://www.gammon.com.au/forum/?id=11425&reply=1#reply1 if (isCmd (c)) { processCmdByte(c); } else { processNumericByte(c); } } boolean isCmd(byte c) { return(c == 'c' || c == 's'); } void processNumericByte (byte c) { // Serial.println (c); int val = byteToInt(c); switch (state) { case GOT_COLOR: processColorVal(val); break; case GOT_OTHER: processNumericVal(val); break; default: break; } } void processCmdByte (const unsigned int c) { switch (c) { case 'c': newColorMode(); break; case 's': numericAddMode(); break; default: state = NONE; break; } } void processColorVal (int val) { // set value in index curRgbInput[rgbInputValIndex] = val; // advance rgb array index // and write to LEDs when the array is filled rgbInputValIndex++; if(rgbInputValIndex >= colorArrSize) { int ledIndex = curRgbInput[0]; if(ledIndex < NUM_LEDS) { leds[ledIndex] = CRGB(curRgbInput[1], curRgbInput[2], curRgbInput[3]); rgbInputValIndex = 0; } } } void newColorMode() { state = GOT_COLOR; rgbInputValIndex = 0; } void numericAddMode() { state = GOT_OTHER; } void processNumericVal (int val) { currentValue *= 10; currentValue += val - '0'; } ///////////////////////////// // Demo mode ///////////////////////////// void runSingleDotPulseDemo() { for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed = whiteLed + 1) { // Turn our current led on to white, then show the leds leds[whiteLed] = CRGB::White; // Show the leds (only one of which is set to white, from above) FastLED.show(); // Wait a little bit (60fps) delay(16); // Turn our current led back to black for the next loop around leds[whiteLed] = CRGB::Black; } } */