text
stringlengths
1
1.05M
import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import { Azureblob } from '../models/azureblob'; import {environment} from "../../environments/environment"; import {Observable} from 'rxjs/Observable'; @Injectable() export class AzureblobService { constructor(private httpClient: HttpClient) { } serverUrl : string = environment.BACKEND_URL + "/service/blobservice/azure/fetch"; thumbnailFetchUrl : string = "https://southcentralus.api.cognitive.microsoft.com/vision/v2.0/generateThumbnail?width=100&height=100&smartCropp"; value: any; getAllBlobs() { console.log("....AzureblobService.getAllBlobs()"); const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept' : 'application/json' }); return this.httpClient.post<Azureblob[]>(this.serverUrl, JSON.stringify({ "azureAcountName": "acsazurestore", "azureAcountKey": "<KEY> "azureContainer":"acsazurecontainer" }),{headers: headers}); } getBlobThumbnail(): Observable<Blob> { console.log("....AzureblobService.getBlobThumbnail()"); const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', 'Ocp-Apim-Subscription-Key': 'f78fdd51de304d99862c4a50c9a0ec0c' }); return this.httpClient.post<Blob>(this.thumbnailFetchUrl, { "url": "http://acsazurestore.blob.core.windows.net/acsazurecontainer/Git-Logo-1788C.png" }, {headers: headers, responseType: 'blob' as 'json' }); } }
items = [ {"name": "widget", "price": 10, "quantity": 5 }, {"name": "thingy", "price": 7, "quantity": 3 }, {"name": "doodad", "price": 5, "quantity": 2 }, ] taxRate = 0.095 shippingCost = 7.50 totalCost = 0 for item in items: totalCost += item['price'] * item['quantity'] totalCost += totalCost * taxRate totalCost += shippingCost print('Total cost:', totalCost)
/* * C compiler file mcdep.h * Copyright (C) Acorn Computers Ltd., 1988. * SPDX-Licence-Identifier: Apache-2.0 */ /* * RCS $Revision$ Codemist 4 * Checkin $Date$ * Revising $Author$ */ /* * (Interface for target-dependent part of local code generation). */ #ifndef _mcdep_h #define _mcdep_h 1 #ifndef _globals_LOADED #error include "mcdep.h" out of place /* We need globals.h loaded first (host/options/target/defaults). */ #endif #ifndef _cgdefs_LOADED # include "cgdefs.h" #endif #ifndef _jopcode_LOADED # include "jopcode.h" #endif #include "toolenv.h" /***************************************************************************/ /* Interface to the target code generator */ /***************************************************************************/ #ifdef TARGET_HAS_FP_LITERALS # ifndef fpliteral extern bool fpliteral(FloatCon const *val, J_OPCODE op); /* Returns true if the argument value can be represented as a literal operand * in the expansion of the argument operation (passing this allows for the * possibility of changing the operation, eg ADD to SUB, to allow use of a * literal). */ # endif #endif #ifndef immed_cmp extern bool immed_cmp(int32 n); /* False if this integer is to be a candidate to be held in a register through * loop optimisation. */ #endif #ifndef immed_op /* target.h may define this otherwise, to return 1 if n may be an immediate * operand in the expansion of J_OPCODE op. If the value is 0, CSE is more * enthusiastic about making a load of the value into a CSE or hoisting it * out of loops. * immed_cmp is a special case, sensibly defined as immed_op(n, J_CMPK) where * immed_op has a non-default value. */ # define immed_op(n, op) 1 #endif #ifndef TARGET_DOESNT_CHECK_SWIS int32 CheckSWIValue(int32); #else #define CheckSWIValue(n) (n) #endif #ifdef TARGET_INLINES_MONADS extern int32 target_inlinable(Binder const *b, int32 nargs); #endif #ifndef alterscc #define alterscc(ic) (sets_psr(ic) || corrupts_psr(ic)) #endif extern bool sets_psr(Icode const *ic); extern bool reads_psr(Icode const *ic); extern bool uses_psr(Icode const *ic); extern bool corrupts_psr(Icode const *ic); extern bool corrupts_r1(Icode const* ic); extern bool corrupts_r2(Icode const* ic); extern bool has_side_effects(Icode const *ic); extern void remove_writeback(Icode *ic); extern RealRegister local_base(Binder const *b); /* Returns the base register to be used in accessing the object b (must be * local). */ extern int32 local_address(Binder const *b); /* Returns the offset from local_base(b) to be used in accessing object b. */ extern void setlabel(LabelNumber *l); /* Sets the argument label at the current code position. * Although the idea of setlabel is target independent, it is in the mc-dep * interface because it back-patches code. * In the long term it should be in codebuf.c and call a target dependent * backpatch routine. */ extern void branch_round_literals(LabelNumber *m); /* Encouraged by a comment that only ARM used mustlitby, it has been removed from the codebuf interface, and the initialisations of it which used to happen in codebuf.c turned into calls of the following function. Targets which don't care will just refrain from setting localcg_newliteralpool_exists */ #ifdef localcg_newliteralpool_exists extern void localcg_newliteralpool(void); #else #define localcg_newliteralpool() 0 #endif #ifdef TARGET_HAS_MULTIPLE_CODE_AREAS void localcg_endcode(void); #endif extern void show_instruction(Icode const *const ic); extern void localcg_reinit(void); /* under threat (use J_ENTER) */ extern void localcg_tidy(void); /* ditto (use J_ENDPROC) */ typedef struct { RealRegSet use, /* registers read */ def, /* registers written */ c_in, /* registers corrupted on entry (clash with input regs) */ c_out; /* registers corrupted on exit (clash with output regs) */ } RealRegUse; /* returns the physical register usage of ic */ extern void RealRegisterUse(Icode const *ic, RealRegUse *u); #ifdef TARGET_IS_ARM_OR_THUMB bool UnalignedLoadMayUse(RealRegister r); /* A special purpose version of RealRegisterUse, but called before it's */ /* known what Icode the load is going to expand into. */ #endif /* Return the minimum/maximum offset a certain load/store can have (inclusive). Larger offsets require either IP to be reserved or a seperate base pointer. */ extern int32 MinMemOffset(J_OPCODE op); extern int32 MaxMemOffset(J_OPCODE op); /* Return the granularity of memory addresses for op. */ extern int32 MemQuantum(J_OPCODE op); typedef enum { JCHK_MEM = 1, JCHK_REGS = 2, JCHK_SYSERR = 256 } CheckJopcode_flags; extern char *CheckJopcode(const Icode *ic, CheckJopcode_flags flags); extern int multiply_cycles(int val, bool accumulate); /* return #cycles for a multiply */ /***************************************************************************/ /* Interface to the object code formatter */ /***************************************************************************/ extern void obj_codewrite(Symstr *name); /* (name == 0 && codep == 0) => called from just after the creation of a */ /* new code segment. bindsym_(codesegment) is the name of */ /* a symbol to be set at the base of the area (not */ /* the area name) */ /* (name == 0 && codep != 0) => called generation of a string literal */ /* (name != 0) => called after generation of code for a function */ extern void obj_init(void); extern void obj_header(void); extern void obj_trailer(void); extern void obj_common_start(Symstr *name); extern void obj_common_end(void); #define obj_setcommoncode() (var_cc_private_flags |= 0x40000000) /* set COMDEF attribute */ #define obj_clearcommoncode() (var_cc_private_flags &= ~0x40000000) #define obj_iscommoncode() (var_cc_private_flags & 0x40000000) #define obj_setvtable() (var_cc_private_flags |= 0x20000000) /* set COMDEF attribute */ #define obj_clearvtable() (var_cc_private_flags &= ~0x20000000) #define obj_isvtable() (var_cc_private_flags & 0x20000000) #ifdef TARGET_HAS_AOUT extern void obj_stabentry(struct nlist const *p); #endif #ifndef NO_ASSEMBLER_OUTPUT /***************************************************************************/ /* Interface to the assembly code generator */ /***************************************************************************/ extern void asm_header(void); extern void asm_trailer(void); extern void asm_setregname(int regno, char const *name); extern void display_assembly_code(Symstr const *); /* Entry conditions as for obj_codewrite. */ #endif /***************************************************************************/ /* Interface to the debug table generator */ /***************************************************************************/ #define DBG_LINE 1 /* line info -- reduces peepholing */ #define DBG_PROC 2 /* top level info -- no change to code */ #define DBG_VAR 4 /* local var info -- no leaf procs */ #define DBG_PP 8 #define DBG_OPT_CSE 0x10 #define DBG_OPT_REG 0x20 #define DBG_OPT_DEAD 0x40 #define DBG_OPT_ALL (DBG_OPT_CSE|DBG_OPT_REG|DBG_OPT_DEAD) #ifdef TARGET_DEBUGGER_WANTS_MACROS # define DBG_ANY (DBG_LINE|DBG_PROC|DBG_VAR|DBG_PP) #else # define DBG_ANY (DBG_LINE|DBG_PROC|DBG_VAR) #endif #ifdef TARGET_HAS_DEBUGGER /* Language independent type number, to be passed to dbg_tableindex */ #define DT_QINT 1 #define DT_HINT 2 #define DT_INT 3 #define DT_LINT 4 #define DT_UQINT 5 #define DT_UHINT 6 #define DT_UINT 7 #define DT_ULINT 8 #define DT_FLOAT 9 #define DT_DOUBLE 10 #define DT_EXTENDED 11 #define DT_COMPLEX 12 #define DT_LCOMPLEX 13 #define DT_QBOOL 14 #define DT_HBOOL 15 #define DT_BOOL 16 #define DT_LBOOL 17 #define DT_CHAR 18 #define DT_UCHAR 19 #define DT_MAX 19 extern char dbg_name[]; extern int usrdbgmask; # define usrdbg(DBG_WHAT) (usrdbgmask & (DBG_WHAT)) extern int32 dbg_tablesize(void); extern int32 dbg_tableindex(int32 dt_number); extern void *dbg_notefileline(FileLine fl); extern void dbg_addcodep(void *debaddr, int32 codeaddr); extern bool dbg_scope(BindListList *, BindListList *); extern void dbg_final_src_codeaddr(int32, int32); # ifdef DEBUGGER_NEEDS_NO_FRAMEPOINTER extern bool dbg_needsframepointer(void); # else # define dbg_needsframepointer() 1 # endif # ifdef TARGET_HAS_BSS # define DS_EXT 1 /* bits in stgclass argument of dbg_topvar */ # define DS_BSS 2 # define DS_CODE 4 # define DS_REG 8 # define DS_UNDEF 16 extern void dbg_topvar(Symstr *name, int32 addr, TypeExpr *t, int stgclass, FileLine fl); # else extern void dbg_topvar(Symstr *name, int32 addr, TypeExpr *t, bool ext, FileLine fl); # endif extern void dbg_type(Symstr *name, TypeExpr *t, FileLine fl); #ifndef NEW_DBG_PROC_INTERFACE extern void dbg_proc(Symstr *name, TypeExpr *t, bool ext, FileLine fl); #else extern void dbg_proc(Binder *b, TagBinder *parent, bool ext, FileLine fl); #endif extern void dbg_locvar(Binder *name, FileLine fl); extern void dbg_locvar1(Binder *name); /* used by F77 front-end */ extern void dbg_commblock(Binder *name, SynBindList *members, FileLine fl); extern void dbg_enterproc(void); extern void dbg_bodyproc(void); extern void dbg_return(int32 addr); extern void dbg_xendproc(FileLine fl); # ifdef TARGET_DEBUGGER_WANTS_MACROS typedef struct dbg_ArgList dbg_ArgList; struct dbg_ArgList { char const *name; dbg_ArgList *next; }; extern void dbg_define(char const *name, bool objectmacro, char const *body, dbg_ArgList const *args, FileLine fl); extern void dbg_undef(char const *name, FileLine fl); extern void dbg_include(char const *filename, char const *path, FileLine fl); extern void dbg_notepath(char const *pathname); # else # define dbg_undef(a, b) # define dbg_define(a, b, c, d, e) # define dbg_include(a, b, c) # define dbg_notepath(a) # endif extern void dbg_init(void); #else # define usrdbg(DBG_WHAT) ((int)0) # define dbg_tablesize() ((int32)0) # define dbg_tableindex(a) ((int32)0) # define dbg_notefileline(a) ((void *)0) # define dbg_init() ((void)0) # define dbg_scope(a,b) ((bool)0) # define dbg_addcodep(debaddr,codeaddr) ((void)0) # define dbg_enterproc() ((void)0) # define dbg_bodyproc() ((void)0) # define dbg_return(a) ((void)0) # define dbg_xendproc(a) ((void)0) # define dbg_type(a,b,c) ((void)0) # define dbg_proc(a,b,c,d) ((void)0) # define dbg_topvar(a,b,c,d,e) ((void)0) # define dbg_locvar(a,b) ((void)0) # define dbg_locvar1(a) ((void)0) # define dbg_commblock(a, b, c) ((void)0) # define dbg_undef(a, b) ((void)0) # define dbg_define(a, b, c, d, e) ((void)0) # define dbg_include(a, b,c) ((void)0) # define dbg_notepath(a) ((void)0) # define dbg_finalise() ((void)0) # define dbg_setformat(a) ((void)0) # define dbg_debugareaexists(a) ((bool)0) # define dbg_final_src_codeaddr(a, b) ((void)0) # define dbg_needsframepointer() 0 #endif /***************************************************************************/ /* Interface between debug table generator, object formatter and target */ /* code generator */ /***************************************************************************/ #ifdef TARGET_HAS_DEBUGGER #include "xrefs.h" int32 local_fpaddress(Binder const *b); /* Returns the offset of the object from the fp (assuming that fp and sp * have not been split in the frame containing the object ...). */ #define R_NOFPREG ((RealRegister)-1) RealRegister local_fpbase(Binder const *b); void dbg_writedebug(void); /* Call from the object formatter to the debug table generator to * cause tables to be output */ void obj_writedebug(void const *, int32); #define DBG_INTFLAG 0x80000000L /* flag in the size argument to obj_writedebug indicating that the things * being written are 4-byte ints (to be byte reversed if appropriate); */ #define DBG_SHORTFLAG 0x40000000L /* flag in the size argument to obj_writedebug indicating that the things * being written are 2-byte ints (to be byte reversed if appropriate); * If neither flag is present, they are byte strings to be written as * presented. */ void dbg_finalise(void); # ifdef TARGET_HAS_FP_OFFSET_TABLES typedef struct FPList FPList; typedef struct { FPList *fplist; int32 startaddr, endaddr, saveaddr; Symstr *codeseg; int32 initoffset; } ProcFPDesc; struct FPList { FPList *cdr; int32 addr; int32 change; }; void obj_notefpdesc(ProcFPDesc const *); # endif void dbg_setformat(char const *format); bool dbg_debugareaexists(char const *name); Symstr *obj_notedebugarea(char const *name); void obj_startdebugarea(char const *name); void obj_enddebugarea(char const *name, DataXref *relocs); #endif /***************************************************************************/ /* Target-dependent argument processing */ /***************************************************************************/ typedef enum { KW_NONE, KW_OK, KW_MISSINGARG, KW_BADARG, KW_OKNEXT, KW_BADNEXT } KW_Status; void mcdep_init(void); #ifdef TARGET_HAS_DATA_VTABLES bool mcdep_data_vtables(void); #endif #ifdef TARGET_SUPPORTS_TOOLENVS int mcdep_toolenv_insertdefaults(ToolEnv *t); extern KW_Status mcdep_keyword(char const *key, char const *nextarg, ToolEnv *t); void config_init(ToolEnv *t); void mcdep_set_options(ToolEnv *); #ifdef CALLABLE_COMPILER #define mcdep_config_option(n,t,e) ((bool)0) #else bool mcdep_config_option(char name, char const tail[], ToolEnv *t); #endif #else extern KW_Status mcdep_keyword(char const *key, int *argp, char **argv); void config_init(void); # ifdef CALLABLE_COMPILER #define mcdep_config_option(n,t) ((bool)0) # else bool mcdep_config_option(char name, char tail[]); void mcdep_debug_option(char name, char tail[]); # endif #endif #endif /* end of mcdep.h */
#!/bin/bash install_package htop
CREATE TABLE user_scores ( user_id INT UNSIGNED NOT NULL, score INT UNSIGNED NOT NULL, last_updated DATETIME NOT NULL, PRIMARY KEY (user_id) );
<filename>OSS13 Client/Sources/Graphics/UI/Widget/GameProcess/TileContextMenu.cpp<gh_stars>10-100 #include "TileContextMenu.h" #include <imgui.h> #include <Client.hpp> #include <Network/Connection.h> #include <Shared/Network/Protocol/ClientToServer/Commands.h> void TileContextMenu::Update(sf::Time /*timeElapsed*/) { openPopupIfNeeded(); drawContent(); } void TileContextMenu::Open() { askedOpen = true; } void TileContextMenu::SetContent(network::protocol::ContextMenuData &&data) { this->data = std::make_unique<network::protocol::ContextMenuData>(std::move(data)); dataUpdated = true; } void TileContextMenu::openPopupIfNeeded() { if (askedOpen && dataUpdated) { askedOpen = false; dataUpdated = false; ImGui::OpenPopup("TileContextMenu"); } } void drawNode(const network::protocol::ContextMenuNode &node, uint8_t nodeIndex) { if (ImGui::BeginMenu(node.title.c_str())) { uint8_t verbsCounter = 0; for (auto &verb : node.verbs) { if (ImGui::MenuItem(verb.c_str())) { auto command = std::make_unique<network::protocol::client::ContextMenuClickCommand>(); command->node = nodeIndex; command->verb = verbsCounter; Connection::commandQueue.Push(command.release()); } verbsCounter++; } ImGui::EndMenu(); } } void TileContextMenu::drawContent() { if (ImGui::BeginPopup("TileContextMenu")) { uint8_t nodeCounter = 0; for (auto &node : data->nodes) drawNode(*node, nodeCounter++); ImGui::EndPopup(); } }
import { __assign, __extends } from "tslib"; import { each } from '@antv/util'; import GridBase from './base'; var Line = /** @class */ (function (_super) { __extends(Line, _super); function Line() { return _super !== null && _super.apply(this, arguments) || this; } Line.prototype.getDefaultCfg = function () { var cfg = _super.prototype.getDefaultCfg.call(this); return __assign(__assign({}, cfg), { type: 'line' }); }; Line.prototype.getGridPath = function (points) { var path = []; each(points, function (point, index) { if (index === 0) { path.push(['M', point.x, point.y]); } else { path.push(['L', point.x, point.y]); } }); return path; }; return Line; }(GridBase)); export default Line; //# sourceMappingURL=line.js.map
#!/bin/bash ###################################################################### function print_header { cat <<EOF This is `basename $0` part of the RegCM version 4 SVN Revision: `svnversion` : this run start at : `date '+%Y-%m-%d %H:%M:%S%z'` : it is submitted by : `whoami` : it is running on : $HOST : in directory : $PWD EOF } ###################################################################### function help { more <<EOF NAME: `basename $0` SYNOPSIS: `basename $0` [-i] namelist [options] MANDATORY ARGUMENTS: namelist: set namelist OTHER OPTIONS -i (, --input=) namelist: set namelist [for compatibility reasons] -e (, --emissions=) name: set path to emissions inventories [default: RCP database] -v (, --verbose=) level: set verbose level (values are 0; 1 [default]; 2, 3; 4) -c (, --cdo=) path: set cdo path name if unusual -o (, --output=) outout: set path to interpolated emissions file [default: "dirter" directory] -h (,--help): print this help EOF exit 0 } ###################################################################### ###################################################################### function get_args { while [ "$#" -ge 1 ] do case $1 in "-h"|"--help") help; exit; ;; "-v"|"--verbose=") if [ -n "$2" ]; then shift 1 ; VERBOSE=$1 ; fi ;; "-i"|"--input=") if [ -n "$2" ]; then shift 1 ; NAMELIST=$1 ; fi ;; "-e"|"--emissions=") if [ -n "$2" ]; then shift 1 ; data_dir=$1 ; fi ;; "-o"|"--output=") if [ -n "$2" ]; then shift 1 ; out_dir=$1 ; fi ;; "-c"|"--cdo=") if [ -n "$2" ]; then shift 1 ; CDO=$1 ; fi ;; -*) echo -e "ERROR: unknown option. Use -h for help\n"; exit; ;; *) NAMELIST=$1 ; ;; esac shift done # set default values VERBOSE=${VERBOSE:=1} CDO=${CDO:=`which cdo 2> /dev/null`} } ###################################################################### ###################################################################### function test_settings { # set verbose options (default is 1) case ${VERBOSE} in "0") CDOOPTIONS="-s" ;; "2") set -v ;; "3") set -x; ;; "4") set -x; CDOOPTIONS="-v" ;; esac # test namelist if [ ! -f "${NAMELIST}" ] ; then echo "Cannot find namelist ${NAMELIST}: no such file or directory." echo "Please set it with -i option. Use -h for help" exit 1 else # set domain name DOMNAME=`cat $NAMELIST | grep domname | grep -v coarse_domname | \ cut -d "=" -f 2 | tr "'" " " | \ cut -d "," -f 1 | sed -e 's/ //g' ` # set model simulation input directory REGCM_dir=`cat $NAMELIST | grep dirter | cut -d "=" -f 2 | tr "'" " " | \ cut -d "," -f 1 | sed -e 's/ //g' ` out_dir=${out_dir:="${REGCM_dir}"} # set emission inventories path (default directory is global RCP directory) EMISSDIR=`cat $NAMELIST | grep inpglob | cut -d "=" -f 2 | tr "'" " " | \ cut -d "," -f 1 | sed -e 's/ //g' ` data_dir=${data_dir:="${EMISSDIR}/RCP_EMGLOB_PROCESSED/iiasa/"} # set model chemistry type CHEMTYPE=`cat $NAMELIST | grep chemsimtype | cut -d "=" -f 2 | tr "'" " " | \ cut -d "," -f 1 | sed -e 's/ //g' ` fi # test CDO availability if [ x${CDO}x == "xx" ] ; then echo "Cannot find a cdo executable in your path." echo echo 'Please install cdo (https://code.zmaw.de/projects/cdo)' echo exit 1 fi # test model domain name if [ x${DOMNAME}x == "xx" ] ; then echo "model input path is not set." echo "Please check out your namelist." exit 1 fi # test model simulation path if [ ! -d "${REGCM_dir}" ] ; then echo "Cannot find model input path ${REGCM_dir}: no such file or directory." echo "Please check out your namelist." exit 1 fi # test emission data path if [ ! -d "${data_dir}" ] ; then echo "Cannot find emission data path ${data_dir}: no such file or directory." echo "Please check out your namelist or rerun -d option. Use -h for help" exit 1 fi # test interpolated data path if [ ! -d "${out_dir}" ] ; then echo "Cannot find interpolated emission data path ${out_dir}: no such file or directory." echo "Please check out your namelist or rerun -o option. Use -h for help" exit 1 fi if [ ${VERBOSE} -ge 1 ] ; then echo "EMISSION INTERPOLATION SCRIPT READY." fi } ###################################################################### ###################################################################### function set_filelist { # define species for chemistry mode case $CHEMTYPE in "DUST") echo "WARNING: no need to interpolate emissions for $CHEMTYPE simulation, abort computation" exit 0 ;; "DU12") echo "WARNING: no need to interpolate emissions for $CHEMTYPE simulation, abort computation" exit 0 ;; "SSLT") echo "WARNING: no need to interpolate emissions for $CHEMTYPE simulation, abort computation" exit 0 ;; "SULF") SPECIELIST=(SO2) ;; "CARB") SPECIELIST=(BC OC) ;; "SUCA") SPECIELIST=(BC OC SO2) ;; "SUCE") SPECIELIST=(BC OC SO2) ;; "AERO") SPECIELIST=(BC OC SO2) ;; "CBMZ") SPECIELIST=(ALD2 AONE BC C2H6 CH3OH CH4 CO ETH HCHO NH3 NOx OC OLEI OLET PAR RCOOH SO2 TOL XYL ISOP_BIO) ;; "DCCB") SPECIELIST=(ALD2 AONE BC C2H6 CH3OH CH4 CO ETH HCHO NH3 NOx OC OLEI OLET PAR RCOOH SO2 TOL XYL ISOP_BIO) ;; *) echo "Cannot find chemistry simulation type: \"${CHEMTYPE}\"" echo "Please check out your namelist" exit 1 ;; esac # set emissions file list n=${#SPECIELIST[@]} file_list=() for (( i = 0; i < $n; i++ )) ; do file_list+=(`ls ${data_dir}/*_"${SPECIELIST[i]}"[._]*nc 2> /dev/null`) done } ###################################################################### ###################################################################### function init_timeframe { # set model starting date for emission processing START=`cat $NAMELIST | grep gdate1 | cut -d "=" -f 2 | tr "'" " " | \ cut -d "," -f 1 | sed -e 's/ //g' ` START=${START:0:4}-${START:4:2}-${START:6:2}T00:00:00 # set model ending date END=`cat $NAMELIST | grep gdate2 | cut -d "=" -f 2 | tr "'" " " | \ cut -d "," -f 1 | sed -e 's/ //g' ` END=${END:0:4}-${END:4:2}-${END:6:2}T00:00:00 } ###################################################################### ###################################################################### function emissions_interpolate { # set file list set_filelist # create weights from first specie file $CDO gencon,$REGCM_dir/${DOMNAME}_grid.nc -setgrid,${file_list[0]} \ ${file_list[0]} remapweights.nc # interpolate all species onto model grid init_timeframe chfiles="" for file in ${file_list[*]}; do ofile=`basename $file` if [ ${VERBOSE} -ge 1 ] ; then echo "Producing $ofile..." fi # adjust data to simulation time period $CDO $CDOOPTIONS seldate,$START,$END $file $out_dir/tfile # grid interpolation $CDO -O $CDOOPTIONS remap,$REGCM_dir/${DOMNAME}_grid.nc,remapweights.nc $out_dir/tfile $out_dir/$ofile chfiles+="$out_dir/$ofile " done rm -f $out_dir/${DOMNAME}_CHEMISS.nc #REMAP_EXTRAPOLATE="on" $CDO $CDOOPTIONS -O merge $chfiles $out_dir/${DOMNAME}_CHEMISS.nc } ###################################################################### ###################################################################### function cleanup { if [ ${VERBOSE} -ge 1 ] ; then echo 'Cleanup...' fi for file in ${file_list[*]} do ofile=`basename $file` rm -f $out_dir/$ofile done rm -f remapweights.nc $out_dir/tfile if [ ${VERBOSE} -ge 1 ] ; then echo 'Done' fi } ###################################################################### ############################################################################### # This is the master script for pre-processing the emissions ############################################################################### get_args "$@" print_header test_settings emissions_interpolate cleanup exit 0
tf_model="https://modelzoo-train-atc.obs.cn-north-4.myhuaweicloud.com/003_Atc_Models/AE/ATC%20Model/human_segmentation/human_segmentation.pb" aipp_cfg="https://modelzoo-train-atc.obs.cn-north-4.myhuaweicloud.com/003_Atc_Models/AE/ATC%20Model/human_segmentation/insert_op.cfg" model_name="human_segmentation" presenter_server_name="human_segmentation" data_source="https://c7xcode.obs.cn-north-4.myhuaweicloud.com/models/human_segmentation/person.mp4" project_name="cplusplus_human_segmentation_video" version=$1 script_path="$( cd "$(dirname $BASH_SOURCE)" ; pwd -P)" project_path=${script_path}/.. declare -i success=0 declare -i inferenceError=1 declare -i verifyResError=2 function downloadData() { mkdir -p ${project_path}/data/ wget -O ${project_path}/data/"person.mp4" ${data_source} --no-check-certificate if [ $? -ne 0 ];then echo "download person.mp4 failed, please check Network." return 1 fi return 0 } function setAtcEnv() { # 设置模型转换时需要的环境变量 if [[ ${version} = "c73" ]] || [[ ${version} = "C73" ]];then export install_path=/home/HwHiAiUser/Ascend/ascend-toolkit/latest export PATH=/usr/local/python3.7.5/bin:${install_path}/atc/ccec_compiler/bin:${install_path}/atc/bin:$PATH export PYTHONPATH=${install_path}/atc/python/site-packages/te:${install_path}/atc/python/site-packages/topi:$PYTHONPATH export ASCEND_OPP_PATH=${install_path}/opp export LD_LIBRARY_PATH=${install_path}/atc/lib64:${LD_LIBRARY_PATH} elif [[ ${version} = "c75" ]] || [[ ${version} = "C75" ]];then export install_path=$HOME/Ascend/ascend-toolkit/latest export PATH=/usr/local/python3.7.5/bin:${install_path}/atc/ccec_compiler/bin:${install_path}/atc/bin:$PATH export ASCEND_OPP_PATH=${install_path}/opp export PYTHONPATH=${install_path}/atc/python/site-packages:${install_path}/atc/python/site-packages/auto_tune.egg/auto_tune:${install_path}/atc/python/site-packages/schedule_search.egg:$PYTHONPATH export LD_LIBRARY_PATH=${install_path}/atc/lib64:${LD_LIBRARY_PATH} fi return 0 } function setBuildEnv() { # 设置代码编译时需要的环境变量 if [[ ${version} = "c73" ]] || [[ ${version} = "C73" ]];then export DDK_PATH=/home/HwHiAiUser/Ascend/ascend-toolkit/latest/arm64-linux_gcc7.3.0 export NPU_HOST_LIB=${DDK_PATH}/acllib/lib64/stub elif [[ ${version} = "c75" ]] || [[ ${version} = "C75" ]];then export DDK_PATH=/home/HwHiAiUser/Ascend/ascend-toolkit/latest/arm64-linux export NPU_HOST_LIB=${DDK_PATH}/acllib/lib64/stub fi return 0 } function downloadOriginalModel() { mkdir -p ${project_path}/model/ wget -O ${project_path}/model/${tf_model##*/} ${tf_model} --no-check-certificate if [ $? -ne 0 ];then echo "install tf_model failed, please check Network." return 1 fi wget -O ${project_path}/model/${aipp_cfg##*/} ${aipp_cfg} --no-check-certificate if [ $? -ne 0 ];then echo "install aipp_cfg failed, please check Network." return 1 fi return 0 } function main() { if [[ ${version}"x" = "x" ]];then echo "ERROR: version is invalid" return ${inferenceError} fi # 下载测试集 downloadData if [ $? -ne 0 ];then echo "ERROR: download test images failed" return ${inferenceError} fi mkdir -p ${HOME}/models/${project_name} if [[ $(find ${HOME}/models/${project_name} -name ${model_name}".om")"x" = "x" ]];then downloadOriginalModel if [ $? -ne 0 ];then echo "ERROR: download original model failed" return ${inferenceError} fi # 设置模型转换的环境变量 setAtcEnv if [ $? -ne 0 ];then echo "ERROR: set atc environment failed" return ${inferenceError} fi # 转模型 cd ${project_path}/model/ atc --input_shape="input_rgb:1,512,512,3" --output=${HOME}/models/${project_name}/${model_name} --insert_op_conf=${project_path}/model/insert_op.cfg --framework=3 --model=${project_path}/model/${tf_model##*/} --soc_version=Ascend310 --input_format=NHWC if [ $? -ne 0 ];then echo "ERROR: convert model failed" return ${inferenceError} fi ln -s ${HOME}/models/${project_name}/${model_name}".om" ${project_path}/model/${model_name}".om" if [ $? -ne 0 ];then echo "ERROR: failed to set model soft connection" return ${inferenceError} fi else ln -s ${HOME}/models/${project_name}/${model_name}".om" ${project_path}/model/${model_name}".om" if [ $? -ne 0 ];then echo "ERROR: failed to set model soft connection" return ${inferenceError} fi fi # 创建目录用于存放编译文件 mkdir -p ${project_path}/build/intermediates/host if [ $? -ne 0 ];then echo "ERROR: mkdir build folder failed. please check your project" return ${inferenceError} fi cd ${project_path}/build/intermediates/host setBuildEnv if [ $? -ne 0 ];then echo "ERROR: set build environment failed" return ${inferenceError} fi # 产生Makefile cmake ${project_path}/src -DCMAKE_CXX_COMPILER=aarch64-linux-gnu-g++ -DCMAKE_SKIP_RPATH=TRUE if [ $? -ne 0 ];then echo "ERROR: cmake failed. please check your project" return ${inferenceError} fi make if [ $? -ne 0 ];then echo "ERROR: make failed. please check your project" return ${inferenceError} fi cd ${project_path}/out # 重新配置程序运行所需的环境变量 export LD_LIBRARY_PATH= export LD_LIBRARY_PATH=/home/HwHiAiUser/Ascend/acllib/lib64:/home/HwHiAiUser/ascend_ddk/arm/lib:${LD_LIBRARY_PATH} # 开启presenter server cd ${script_path}/ cd ../../../../common/ bash run_presenter_server.sh ${script_path}/human_segmentation.conf if [ $? -ne 0 ];then echo "ERROR: run presenter server failed. please check your project" return ${inferenceError} fi sleep 2 # 运行程序 mv ${project_path}/out/main ${project_path}/out/${project_name} cd ${project_path}/out/ ./${project_name} ${project_path}/data/person.mp4 & sleep 8 project_pid=`ps -ef | grep "${project_name}" | grep "data" | awk -F ' ' '{print $2}'` if [[ ${project_pid}"X" != "X" ]];then echo -e "\033[33m kill existing project process: kill -9 ${project_pid}.\033[0m" kill -9 ${project_pid} if [ $? -ne 0 ];then echo "ERROR: kill project process failed." return ${inferenceError} fi presenter_server_pid=`ps -ef | grep "presenter_server\.py" | grep "${presenter_server_name}" | awk -F ' ' '{print $2}'` if [[ ${presenter_server_pid}"X" != "X" ]];then echo -e "\033[33mNow do presenter server configuration, kill existing presenter process: kill -9 ${presenter_server_pid}.\033[0m" kill -9 ${presenter_server_pid} if [ $? -ne 0 ];then echo "ERROR: kill presenter server process failed." return ${inferenceError} fi fi else echo "ERROR: run failed. please check your project" return ${inferenceError} fi echo "run success" return ${success} } main
<reponame>qishabisi/javaScript<gh_stars>0 (function(window,undefined) { var $ = function(args) { return new Yin.prototype.init(args); }; var Yin = function(){}; Yin.prototype = { constructor: $, init: function(args) { this.elements = []; if (typeof args == 'string') { //css模拟 if (args.indexOf(' ') != -1) { var elements = args.split(' '); var childElements = []; var node = []; for (var i = 0; i < elements.length; i ++) { if (node.length == 0) node.push(document); switch (elements[i].charAt(0)) { case '#' : childElements = []; childElements.push(this.getId(elements[i].substring(1))); node = childElements; break; case '.' : childElements = []; for (var j = 0; j < node.length; j ++) { var temps = this.getClass(elements[i].substring(1), node[j]); for (var k = 0; k < temps.length; k ++) { childElements.push(temps[k]); } } node = childElements; break; default : childElements = []; for (var j = 0; j < node.length; j ++) { var temps = this.getTagName(elements[i], node[j]); for (var k = 0; k < temps.length; k ++) { childElements.push(temps[k]); } } node = childElements; } } this.elements = childElements; } else { //find模拟 switch (args.charAt(0)) { case '#' : this.elements.push(this.getId(args.substring(1))); break; case '.' : this.elements = this.getClass(args.substring(1)); break; default : this.elements = this.getTagName(args); } } } else if (typeof args == 'object') { if (args != undefined) { this.elements[0] = args; } } else if (typeof args == 'function') { this.ready(args); } }, ready:function (fn) { addDomLoaded(fn); }, getId:function (id) { return document.getElementById(id); }, getTagName:function (tag, parentNode) { var node = null; var temps = []; if (parentNode != undefined) { node = parentNode; } else { node = document; } var tags = node.getElementsByTagName(tag); for (var i = 0; i < tags.length; i ++) { temps.push(tags[i]); } return temps; }, getClass:function (className, parentNode) { var node = null; var temps = []; if (parentNode != undefined) { node = parentNode; } else { node = document; } var all = node.getElementsByTagName('*'); for (var i = 0; i < all.length; i ++) { if ((new RegExp('(\\s|^)' +className +'(\\s|$)')).test(all[i].className)) { temps.push(all[i]); } } return temps; }, find:function (str) { var childElements = []; for (var i = 0; i < this.elements.length; i ++) { switch (str.charAt(0)) { case '#' : childElements.push(this.getId(str.substring(1))); break; case '.' : var temps = this.getClass(str.substring(1), this.elements[i]); for (var j = 0; j < temps.length; j ++) { childElements.push(temps[j]); } break; default : var temps = this.getTagName(str, this.elements[i]); for (var j = 0; j < temps.length; j ++) { childElements.push(temps[j]); } } } this.elements = childElements; return this; }, get:function (num) { return this.elements[num]; }, first:function () { return this.elements[0]; }, last:function () { return this.elements[this.elements.length - 1]; }, length:function () { return this.elements.length; }, attr:function (attr, value) { for (var i = 0; i < this.elements.length; i ++) { if (arguments.length == 1) { return this.elements[i].getAttribute(attr); } else if (arguments.length == 2) { this.elements[i].setAttribute(attr, value); } } return this; }, index:function () { var children = this.elements[0].parentNode.children; for (var i = 0; i < children.length; i ++) { if (this.elements[0] == children[i]) return i; } }, opacity:function (num) { for (var i = 0; i < this.elements.length; i ++) { this.elements[i].style.opacity = num / 100; this.elements[i].style.filter = 'alpha(opacity=' + num + ')'; } return this; }, eq:function (num) { var element = this.elements[num]; this.elements = []; this.elements[0] = element; return this; }, next:function () { for (var i = 0; i < this.elements.length; i ++) { this.elements[i] = this.elements[i].nextSibling; if (this.elements[i] == null) throw new Error('找不到下一个同级元素节点!'); if (this.elements[i].nodeType == 3) this.next(); } return this; }, prev:function () { for (var i = 0; i < this.elements.length; i ++) { this.elements[i] = this.elements[i].previousSibling; if (this.elements[i] == null) throw new Error('找不到上一个同级元素节点!'); if (this.elements[i].nodeType == 3) this.prev(); } return this; }, css:function (attr, value) { for (var i = 0; i < this.elements.length; i ++) { if (arguments.length == 1) { return getStyle(this.elements[i], attr); } this.elements[i].style[attr] = value; } return this; }, addClass:function (className) { for (var i = 0; i < this.elements.length; i ++) { if (!hasClass(this.elements[i], className)) { // 加个空格,防止添加的多个class相连; // 这样就可以添加多个class了; this.elements[i].className += ' ' + className; } } return this; }, removeClass:function (className) { for (var i = 0; i < this.elements.length; i ++) { if (hasClass(this.elements[i], className)) { this.elements[i].className = this.elements[i].className.replace(new RegExp('(\\s|^)' + className + '(\\s|$)'), ' '); } } return this; }, html:function (str) { for (var i = 0; i < this.elements.length; i ++) { if (arguments.length == 0) { return this.elements[i].innerHTML; } this.elements[i].innerHTML = str; } return this; }, text:function (str) { for (var i = 0; i < this.elements.length; i ++) { if (arguments.length == 0) { return getInnerText(this.elements[i]); } setInnerText(this.elements[i], text); } return this; }, bind:function (event, fn) { for (var i = 0; i < this.elements.length; i ++) { addEvent(this.elements[i], event, fn); } return this; }, hover:function (over, out) { for (var i = 0; i < this.elements.length; i ++) { addEvent(this.elements[i], 'mouseover', over); addEvent(this.elements[i], 'mouseout', out); } return this; }, click:function (fn) { for (var i = 0; i < this.elements.length; i ++) { this.elements[i].onclick = fn; } return this; }, hasClass:function(element, className) { return element.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)')); } }; $.fn = Yin.prototype.init.prototype = Yin.prototype; window.$ = $; })(window,undefined);
find . -name "*.re" -type f -exec refmt --in-place {} \;
<reponame>MarcelBraghetto/AndroidNanoDegree2016<gh_stars>0 package com.lilarcor.popularmovies.framework.foundation.network.dagger; import android.content.Context; import android.support.annotation.NonNull; import com.lilarcor.popularmovies.framework.foundation.network.DefaultNetworkRequestProvider; import com.lilarcor.popularmovies.framework.foundation.network.contracts.NetworkRequestProvider; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; /** * Created by <NAME> on 30/07/15. * * This is the main network request provider * Dagger mapping module to construct a network * request provider when needed. * * Other build variants can choose a different * module implementation to effectively swap * out the default network request provider * implementation. For example, in the * Espresso automation tests, we want canned * network responses to be delivered when * running tests, so the network request * provider has a completely different * implementation while running the suite of * automated Espresso tests. */ @Module public class NetworkRequestProviderModule { @Provides @Singleton @NonNull public NetworkRequestProvider provideNetworkRequestProvider(@NonNull Context applicationContext) { return new DefaultNetworkRequestProvider(applicationContext); } }
<gh_stars>1-10 package elasta.composer.state.handlers.impl; import elasta.composer.Events; import elasta.composer.Msg; import elasta.composer.state.handlers.GenerateIdStateHandler; import elasta.core.flow.Flow; import elasta.core.flow.StateTrigger; import elasta.core.promise.intfs.Promise; import elasta.orm.idgenerator.ObjectIdGenerator; import io.vertx.core.json.JsonObject; import java.util.Objects; /** * Created by sohan on 6/30/2017. */ final public class GenerateIdStateHandlerImpl implements GenerateIdStateHandler<JsonObject, JsonObject> { final String entity; final ObjectIdGenerator<Object> objectIdGenerator; public GenerateIdStateHandlerImpl(String entity, ObjectIdGenerator objectIdGenerator) { Objects.requireNonNull(entity); Objects.requireNonNull(objectIdGenerator); this.entity = entity; this.objectIdGenerator = objectIdGenerator; } @Override public Promise<StateTrigger<Msg<JsonObject>>> handle(Msg<JsonObject> msg) throws Throwable { return objectIdGenerator.generateId(entity, msg.body()) .map(jsonObject -> Flow.trigger( Events.next, msg.withBody(jsonObject) )); } }
#!/bin/sh echo Configuring Git for pushing to GH... git config user.email "4financebot@gmail.com" git config user.name "4Finance Bot" git config push.default simple git remote set-url origin "https://github.com/${TRAVIS_REPO_SLUG}.git" echo Git configured
SELECT product_id, SUM(quantity) as sales FROM Sales GROUP BY product_id;
import {ChallengeFromFile} from "./challenge"; import {ChallengeRegistry} from "./challenge_registry"; import {runIntcode} from "./intcode"; const STAR2_TARGET = 19690720; class ChallengeD02 extends ChallengeFromFile { private input: number[] | null = null; constructor() { super("d02"); } public async solveFirstStar(): Promise<string> { const input = this.getInput(); input[1] = 12; input[2] = 2; runIntcode(input); return input[0].toString(); } public async solveSecondStar(): Promise<string> { const baseInput = this.getInput(); for (let noun = 0; noun < 100; noun++) { for (let verb = 0; verb < 100; verb++) { const input = [...baseInput]; input[1] = noun; input[2] = verb; runIntcode(input); if (input[0] === STAR2_TARGET) { return (100 * noun + verb).toString(); } } } return "Not Found"; } private getInput(): number[] { if (this.input === null) { this.input = this.loadInputFile(1) .split(",") .filter((m) => m) .map((m) => parseInt(m, 10)); } return [...this.input]; } } ChallengeRegistry.getInstance().registerChallenge(new ChallengeD02());
<gh_stars>0 $.validator.addMethod("dateFA",function(t,a){return this.optional(a)||/^[1-4]\d{3}\/((0?[1-6]\/((3[0-1])|([1-2][0-9])|(0?[1-9])))|((1[0-2]|(0?[7-9]))\/(30|([1-2][0-9])|(0?[1-9]))))$/.test(t)},$.validator.messages.date); //# sourceMappingURL=dateFA.min.js.map
<filename>16PWMLedDriverOpenMRN/targets/bbb.linux.armv7a/Hardware.hxx #ifndef __HARDWARE_HXX #define __HARDWARE_HXX #include <os/LinuxGpio.hxx> #include <os/LinuxPWM.hxx> #include "utils/GpioInitializer.hxx" #define HARDWARE_IMPL "BBB 16 Channel PWM LED Driver" // On chip GPIO: #define OEPin GpioOutputSafeLow GPIO_PIN(OE, OEPin, (32*1)+12); // GPIO1_12: P8-12 typedef GpioInitializer<OE_Pin> GpioInit; static constexpr uint32_t PWMCHIP = 0; static constexpr uint32_t A0 = 0; extern LinuxPWM A0_Pin; static constexpr uint32_t A1 = 1; extern LinuxPWM A1_Pin; static constexpr uint32_t A2 = 2; extern LinuxPWM A2_Pin; static constexpr uint32_t A3 = 3; extern LinuxPWM A3_Pin; static constexpr uint32_t A4 = 4; extern LinuxPWM A4_Pin; static constexpr uint32_t A5 = 5; extern LinuxPWM A5_Pin; static constexpr uint32_t A6 = 6; extern LinuxPWM A6_Pin; static constexpr uint32_t A7 = 7; extern LinuxPWM A7_Pin; static constexpr uint32_t B0 = 8; extern LinuxPWM B0_Pin; static constexpr uint32_t B1 = 9; extern LinuxPWM B1_Pin; static constexpr uint32_t B2 = 10; extern LinuxPWM B2_Pin; static constexpr uint32_t B3 = 11; extern LinuxPWM B3_Pin; static constexpr uint32_t B4 = 12; extern LinuxPWM B4_Pin; static constexpr uint32_t B5 = 13; extern LinuxPWM B5_Pin; static constexpr uint32_t B6 = 14; extern LinuxPWM B6_Pin; static constexpr uint32_t B7 = 15; extern LinuxPWM B7_Pin; //#define HAVE_TCP_GRIDCONNECT_HOST //#define TCP_GRIDCONNECT_HOST "127.0.0.1" //#define TCP_GRIDCONNECT_PORT 12021 #define PRINT_ALL_PACKETS #define HAVE_SOCKET_CAN_PORT #define SOCKET_CAN_PORT "can1" #endif // __HARDWARE_HXX
#!/bin/sh # # Wrapper for batch-crop.scm gimp-script. # # if no arguments are given, use alls png-files in the directory. if [ $# -lt 1 ] then ARGS='*.png' else ARGS="$*" fi echo Adjusting/Converting "${ARGS}" gimp -i --batch-interpreter='plug-in-script-fu-eval' -b "(batch-crop \"${ARGS}\")(gimp-quit 0)"
package io.github.marcelbraghetto.dailydeviations.framework.artworks.content; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.util.Xml; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import io.github.marcelbraghetto.dailydeviations.framework.artworks.models.Artwork; /** * Created by <NAME> on 21/02/16. * * Helper class to take an XML RSS feed from the Deviant Art web site and parse it into * a collection of Artwork models. */ public class ArtworksParser { private static final String ns = null; private ArtworksParser() { } /** * Take the given source string which should be in the Deviant Art RSS format and attempt to * parse it into a collection of Artwork models. * @param source xml to parse. * @return list of artworks that were parsed, or null if an error occurred while parsing. */ @Nullable public static List<Artwork> parse(@Nullable String source) { if(TextUtils.isEmpty(source)) { return null; } InputStream inputStream = new ByteArrayInputStream(source.getBytes()); try { XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(inputStream, null); parser.nextTag(); parser.nextTag(); return readFeed(parser); } catch(Exception e) { Log.e("ARTWORKS", e.getMessage()); return null; } finally { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } private static List<Artwork> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException { List<Artwork> entries = new ArrayList<>(); long now = System.currentTimeMillis(); parser.require(XmlPullParser.START_TAG, ns, "channel"); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); // Starts by looking for the entry tag if (name.equals("item")) { now++; Artwork entry = readEntry(parser, now); // Only keep artworks that are 'valid' which may have parsed successfully // but also have all our required fields. if(entry.isValid()) { entries.add(entry); } } else { skip(parser); } } return entries; } // Parses the contents of an entry. If it encounters a title, summary, or link tag, hands them // off to their respective methods for processing. Otherwise, skips the tag. private static Artwork readEntry(XmlPullParser parser, long timestamp) throws XmlPullParserException, IOException { Artwork artwork = new Artwork(); artwork.setTimestamp(timestamp); parser.require(XmlPullParser.START_TAG, ns, "item"); while (parser.next() != XmlPullParser.END_TAG) { if (parser.getEventType() != XmlPullParser.START_TAG) { continue; } String name = parser.getName(); switch (name) { case "guid": // The guid doubles as both an id and the url to open to view the artwork. String url = readTextNode(parser, name); artwork.setGuid(url); artwork.setWebUrl(url); break; case "title": artwork.setTitle(readTextNode(parser, name)); break; case "media:credit": String author = readTextNode(parser, name); // This is the author's profile link if(author.startsWith("http:")) { artwork.setAuthorImageUrl(author); } else { artwork.setAuthor(author); } break; case "media:description": artwork.setDescription(readTextNode(parser, name)); break; case "media:content": parser.require(XmlPullParser.START_TAG, ns, name); String mediaType = parser.getAttributeValue(ns, "medium"); // There are media types other than images which we don't want. if("image".equals(mediaType)) { artwork.setImageUrl(parser.getAttributeValue(ns, "url")); artwork.setImageWidth(Integer.parseInt(parser.getAttributeValue(ns, "width"))); artwork.setImageHeight(Integer.parseInt(parser.getAttributeValue(ns, "height"))); } skip(parser); break; case "pubDate": artwork.setPublishDate(readTextNode(parser, name)); break; case "media:copyright": artwork.setCopyright(readTextNode(parser, name)); break; default: skip(parser); break; } } return artwork; } private static String readTextNode(XmlPullParser parser, String nodeName) throws IOException, XmlPullParserException { parser.require(XmlPullParser.START_TAG, ns, nodeName); String result = extractTextValue(parser); parser.require(XmlPullParser.END_TAG, ns, nodeName); return result; } // For the tags title and summary, extracts their text values. private static String extractTextValue(XmlPullParser parser) throws IOException, XmlPullParserException { String result = ""; if (parser.next() == XmlPullParser.TEXT) { result = parser.getText(); parser.nextTag(); } return result; } // Skips tags the parser isn't interested in. Uses depth to handle nested tags. i.e., // if the next tag after a START_TAG isn't a matching END_TAG, it keeps going until it // finds the matching END_TAG (as indicated by the value of "depth" being 0). private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException { if (parser.getEventType() != XmlPullParser.START_TAG) { throw new IllegalStateException(); } int depth = 1; while (depth != 0) { switch (parser.next()) { case XmlPullParser.END_TAG: depth--; break; case XmlPullParser.START_TAG: depth++; break; } } } }
exit_code=0 if [[ "$TRAVIS_PULL_REQUEST" != "false" ]]; then exit $exit_code; fi; # Deploy to the the content server if its a "develop" or "release/version" branch # The "develop_doc" branch is reserved to test full deploy process without impacting the real content. if [ "$TRAVIS_BRANCH" == "develop_doc" ]; then PPO_SCRIPT_BRANCH=develop elif [[ "$TRAVIS_BRANCH" == "develop" || "$TRAVIS_BRANCH" =~ ^v|release/[[:digit:]]+\.[[:digit:]]+(\.[[:digit:]]+)?(-\S*)?$ ]]; then PPO_SCRIPT_BRANCH=master else # Early exit, this branch doesn't require documentation build exit $exit_code; fi export DEPLOY_DOCS_SH=https://raw.githubusercontent.com/PaddlePaddle/PaddlePaddle.org/$PPO_SCRIPT_BRANCH/scripts/deploy/deploy_docs.sh docker run -it \ -e CONTENT_DEC_PASSWD=$CONTENT_DEC_PASSWD \ -e TRAVIS_BRANCH=$TRAVIS_BRANCH \ -e DEPLOY_DOCS_SH=$DEPLOY_DOCS_SH \ -e TRAVIS_PULL_REQUEST=$TRAVIS_PULL_REQUEST \ -e PPO_SCRIPT_BRANCH=$PPO_SCRIPT_BRANCH \ -e PADDLE_ROOT=/models \ -v "$PWD:/models" \ -w /models \ paddlepaddle/paddle:latest-dev \ /bin/bash -c 'curl $DEPLOY_DOCS_SH | bash -s $CONTENT_DEC_PASSWD $TRAVIS_BRANCH /models models/build/doc/ $PPO_SCRIPT_BRANCH' || exit_code=$(( exit_code | $? ))
public class FileFormatMatcher { public boolean applies(String filename) { if (filename.endsWith(".txt") || filename.endsWith(".csv") || filename.endsWith(".json")) { return true; } return false; } }
<gh_stars>0 export * from '@src/app/resources/events/events.resource'; export * from '@src/app/resources/events/events.model'; export * from '@src/app/resources/events/events-get.mapper';
# Install conda case "$(uname -s)" in 'Darwin') MINICONDA_FILENAME="Miniconda3-latest-MacOSX-x86_64.sh" ;; 'Linux') MINICONDA_FILENAME="Miniconda3-latest-Linux-x86_64.sh" ;; *) ;; esac wget https://repo.continuum.io/miniconda/$MINICONDA_FILENAME -O miniconda.sh bash miniconda.sh -b -p $HOME/miniconda export PATH="$HOME/miniconda/bin:$PATH" conda config --set always_yes yes --set changeps1 no # Create conda environment conda create -q -n test-environment python=$PYTHON source activate test-environment # Pin matrix items # Please see PR ( https://github.com/dask/dask/pull/2185 ) for details. touch $CONDA_PREFIX/conda-meta/pinned echo "numpy $NUMPY" >> $CONDA_PREFIX/conda-meta/pinned echo "pandas $PANDAS" >> $CONDA_PREFIX/conda-meta/pinned # Install dependencies. conda install -q -c conda-forge \ numpy \ pandas \ bcolz \ blosc \ bokeh \ boto3 \ chest \ cloudpickle \ coverage \ cytoolz \ distributed \ graphviz \ h5py \ ipython \ partd \ psutil \ pytables \ "pytest<=3.1.1" \ scikit-image \ scikit-learn \ scipy \ sqlalchemy \ toolz pip install -q git+https://github.com/dask/partd --upgrade --no-deps pip install -q git+https://github.com/dask/zict --upgrade --no-deps pip install -q git+https://github.com/dask/distributed --upgrade --no-deps pip install -q git+https://github.com/mrocklin/sparse --upgrade --no-deps pip install -q git+https://github.com/dask/s3fs --upgrade --no-deps if [[ $PYTHONOPTIMIZE != '2' ]] && [[ $NUMPY > '1.11.0' ]] && [[ $NUMPY < '1.13.0' ]]; then conda install -q -c conda-forge numba cython pip install -q git+https://github.com/dask/fastparquet fi if [[ $PYTHON == '2.7' ]]; then pip install -q backports.lzma mock fi pip install -q \ cachey \ graphviz \ moto \ pyarrow \ --upgrade --no-deps pip install -q \ cityhash \ flake8 \ mmh3 \ pandas_datareader \ pytest-xdist \ xxhash \ pycodestyle # Install dask pip install -q --no-deps -e .[complete] echo pip freeze pip freeze
#!/bin/bash if [[ `uname` == "Darwin" ]]; then THIS_SCRIPT=`python -c 'import os,sys; print os.path.realpath(sys.argv[1])' $0` else THIS_SCRIPT=`readlink -f $0` fi THIS_DIR="${THIS_SCRIPT%/*}" BASE_DIR=$(cd $THIS_DIR/.. && pwd) LIB_DIR="${BASE_DIR}/lib" NUM_SERVER_THREADS=4 CONF_DIR="${BASE_DIR}/conf" if [ -z ${TIMELY_HOST+x} ]; then echo "TIMELY_HOST is unset, using 127.0.0.1" TIMELY_HOST="127.0.0.1" else echo "TIMELY_HOST is set to '$TIMELY_HOST'" fi if [ -z ${TIMELY_PORT+x} ]; then echo "TIMELY_PORT is unset, using 54321" TIMELY_PORT=54321 else echo "TIMELY_PORT is set to '$TIMELY_PORT'" fi CP="" SEP="" for j in ${LIB_DIR}/*.jar; do CP="${CP}${SEP}${j}" SEP=":" done JVM_ARGS="-Xmx128m -Xms128m -Dio.netty.eventLoopThreads=${NUM_SERVER_THREADS} -Dlog4j.configurationFile=${CONF_DIR}/log4j2-spring.xml" echo "$JAVA_HOME/bin/java -classpath ${CP} ${JVM_ARGS} timely.util.InsertTestData ${TIMELY_HOST} ${TIMELY_PORT}" exec $JAVA_HOME/bin/java -classpath ${CP} ${JVM_ARGS} timely.util.InsertTestData ${TIMELY_HOST} ${TIMELY_PORT}
package main import ( "context" "encoding/json" "html/template" "log" "net/http" "os" "time" "github.com/Luzifer/go_helpers/github" "github.com/gorilla/mux" "github.com/gorilla/websocket" "github.com/nicksnyder/go-i18n/i18n" ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Maximum message size allowed from peer. maxMessageSize = 8192 // Time allowed to read the next pong message from the peer. pongWait = 60 * time.Second // Send pings to peer with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Number of concurrent calculations per socket calculationPoolSize = 3 ) var upgrader = websocket.Upgrader{} type routeRequest struct { StartSystemID int64 `json:"start_system_id"` TargetSystemID int64 `json:"target_system_id"` RouteRequestID string `json:"route_request_id"` StopDistance float64 `json:"stop_distance"` } type routeResponse struct { Counter int64 `json:"counter"` Success bool `json:"success"` ErrorMessage string `json:"error_message"` RouteRequestID string `json:"route_request_id"` Result traceResult `json:"result"` } type jsonResponse struct { Success bool `json:"success"` ErrorMessage string `json:"error_message"` Data map[string]interface{} `json:"data"` } func (j jsonResponse) Send(res http.ResponseWriter, cachingAllowed bool) error { res.Header().Set("Content-Type", "application/json") if cachingAllowed { res.Header().Set("Cache-Control", "public, max-age=3600") } else { res.Header().Set("Cache-Control", "no-cache") } return json.NewEncoder(res).Encode(j) } func startWebService() { r := mux.NewRouter() r.HandleFunc("/", handleFrontend) r.HandleFunc("/assets/application.js", handleJS) r.HandleFunc("/api/system-by-name", handleSystemByName) r.HandleFunc("/api/route", handleRouteSocket) r.HandleFunc("/api/control/shutdown", handleShutdown) r.HandleFunc("/api/control/update", handleUpdate) r.HandleFunc("/api/control/update-database", handleUpdateDatabase) verboseLog("Webserver started and listening on %s", cfg.Listen) log.Fatalf("Unable to listen for web connections: %s", http.ListenAndServe(cfg.Listen, r)) } func getTranslator(r *http.Request) i18n.TranslateFunc { c, _ := r.Cookie("lang") var cookieLang string if c != nil { cookieLang = c.Value } acceptLang := r.Header.Get("Accept-Language") defaultLang := "en-US" // known valid language T, _ := i18n.Tfunc(cookieLang, acceptLang, defaultLang) return T } func handleFrontend(res http.ResponseWriter, r *http.Request) { T := getTranslator(r) frontend, err := Asset("assets/frontend.html") if err != nil { http.Error(res, "Could not load frontend: "+err.Error(), http.StatusInternalServerError) return } tpl, err := template.New("frontend").Funcs(template.FuncMap{"T": T}).Parse(string(frontend)) if err != nil { http.Error(res, "Could not parse frontend: "+err.Error(), http.StatusInternalServerError) return } if err := tpl.Execute(res, map[string]interface{}{ "version": version, "disableSoftwareControl": cfg.DisableSoftwareControl, }); err != nil { http.Error(res, "Could not execute frontend: "+err.Error(), http.StatusInternalServerError) return } } func handleJS(res http.ResponseWriter, r *http.Request) { js, _ := Asset("assets/application.js") res.Header().Set("Content-Type", "application/javascript") res.Write(js) } func handleShutdown(res http.ResponseWriter, r *http.Request) { T := getTranslator(r) if cfg.DisableSoftwareControl { http.Error(res, "Controls are disabled", http.StatusForbidden) return } defer os.Exit(0) jsonResponse{ Success: true, ErrorMessage: T("warn_service_will_shutdown"), }.Send(res, false) <-time.After(time.Second) // Give the response a second to send } func handleUpdate(res http.ResponseWriter, r *http.Request) { T := getTranslator(r) if cfg.DisableSoftwareControl { http.Error(res, "Controls are disabled", http.StatusForbidden) return } updater, err := github.NewUpdater(autoUpdateRepo, version) if err != nil { jsonResponse{ Success: false, ErrorMessage: T("warn_no_new_version_found"), }.Send(res, false) log.Printf("Could not initialize update engine: %s", err) return } if hasUpdate, err := updater.HasUpdate(true); err != nil { jsonResponse{ Success: false, ErrorMessage: err.Error(), }.Send(res, false) return } else { if !hasUpdate { jsonResponse{ Success: false, ErrorMessage: T("warn_no_new_version_found"), }.Send(res, false) return } } if err := updater.Apply(); err != nil { jsonResponse{ Success: false, ErrorMessage: err.Error(), }.Send(res, false) } else { jsonResponse{ Success: true, ErrorMessage: T("warn_service_update_success"), }.Send(res, false) } } func handleUpdateDatabase(res http.ResponseWriter, r *http.Request) { T := getTranslator(r) if cfg.DisableSoftwareControl { http.Error(res, "Controls are disabled", http.StatusForbidden) return } if err := refreshEDSMData(); err != nil { jsonResponse{ Success: false, ErrorMessage: T("warn_database_update_failed"), }.Send(res, false) log.Printf("Database update failed: %s", err) return } jsonResponse{ Success: true, ErrorMessage: T("warn_database_update_success"), }.Send(res, false) } func handleSystemByName(res http.ResponseWriter, r *http.Request) { T := getTranslator(r) search := r.URL.Query().Get("system_name") if len(search) < 3 { jsonResponse{ Success: false, ErrorMessage: T("warn_too_few_characers"), }.Send(res, true) return } if sys := starSystems.GetSystemByName(search); sys != nil { jsonResponse{ Success: true, Data: map[string]interface{}{ "system": sys, }, }.Send(res, true) } else { jsonResponse{ Success: false, ErrorMessage: T("warn_no_matching_system_found"), }.Send(res, true) return } } func handleRouteSocket(res http.ResponseWriter, r *http.Request) { T := getTranslator(r) // In case socket quits also quit all child operations ctx, cancel := context.WithCancel(context.Background()) defer cancel() ws, err := upgrader.Upgrade(res, r, nil) if err != nil { http.Error(res, "Could not open socket", http.StatusInternalServerError) return } defer ws.Close() doneChan := make(chan struct{}) defer close(doneChan) go pingSocket(ws, doneChan) messageChan := make(chan routeResponse, 500) defer close(messageChan) go func(ws *websocket.Conn, m chan routeResponse) { for msg := range m { ws.WriteJSON(msg) } }(ws, messageChan) ws.SetReadLimit(maxMessageSize) ws.SetReadDeadline(time.Now().Add(pongWait)) ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil }) calculationPool := make(chan *struct{}, calculationPoolSize) for { msg := routeRequest{} if err := ws.ReadJSON(&msg); err != nil { log.Printf("Experienced error: %s", err) break } if msg.RouteRequestID == "" || msg.StartSystemID == 0 || msg.TargetSystemID == 0 { messageChan <- routeResponse{ Success: false, ErrorMessage: T("warn_required_field_missing"), } continue } if msg.StopDistance < cfg.WebRouteStopMin { messageChan <- routeResponse{ Success: false, ErrorMessage: T("warn_stop_distance_too_small", cfg), } continue } go processSocketRouting(ctx, messageChan, msg, calculationPool) } cancel() } func processSocketRouting(parentCtx context.Context, msgChan chan routeResponse, r routeRequest, calculationPool chan *struct{}) { start := starSystems.GetSystemByID(r.StartSystemID) target := starSystems.GetSystemByID(r.TargetSystemID) calculationPool <- nil defer func() { <-calculationPool }() ctx, cancel := context.WithTimeout(parentCtx, cfg.WebRouteTimeout) defer cancel() rChan, eChan := starSystems.CalculateRoute(ctx, start, target, r.StopDistance) var counter int64 for { select { case stop, ok := <-rChan: if ok { msgChan <- routeResponse{ Counter: counter, Success: true, RouteRequestID: r.RouteRequestID, Result: stop, } if stop.TraceType == traceTypeFlightStop { counter++ } } else { return } case err := <-eChan: if err != nil { msgChan <- routeResponse{ Success: false, ErrorMessage: err.Error(), } return } } } } func pingSocket(ws *websocket.Conn, done chan struct{}) { ticker := time.NewTicker(pingPeriod) defer ticker.Stop() for { select { case <-ticker.C: ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(writeWait)) case <-done: return } } }
<filename>src/main/java/com/github/chen0040/leetcode/day06/easy/LengthOfLastWord.java<gh_stars>1-10 package com.github.chen0040.leetcode.day06.easy; /** * Created by xschen on 1/8/2017. * * link: https://leetcode.com/problems/length-of-last-word/description/ */ public class LengthOfLastWord { public class Solution { public int lengthOfLastWord(String s) { int count = 0; int prevCount = 0; for(int i=0; i < s.length(); ++i) { if(s.charAt(i) == ' ') { if(count != 0) prevCount = count; count = 0; } else { count++; } } return count == 0 ? prevCount : count; } } }
//-------------------------------------------------------------------------------------- // File: DyanmicShaderLinkageFX11.cpp // // This sample shows a simple example of the Microsoft Direct3D's High-Level // Shader Language (HLSL) using Dynamic Shader Linkage in conjunction // with Effects 11. // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTcamera.h" #include "DXUTgui.h" #include "DXUTsettingsDlg.h" #include "SDKmisc.h" #include "SDKMesh.h" #include "resource.h" #include <d3dx11effect.h> #include <strsafe.h> // We show two ways of handling dynamic linkage binding. // This #define selects between a single technique where // bindings are done via effect variables and multiple // techniques where the bindings are done with BindInterfaces // in the technqiues. #define USE_BIND_INTERFACES 0 //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs CModelViewerCamera g_Camera; // A model viewing camera CDXUTDirectionWidget g_LightControl; CD3DSettingsDlg g_D3DSettingsDlg; // Device settings dialog CDXUTDialog g_HUD; // manages the 3D CDXUTDialog g_SampleUI; // dialog for sample specific controls D3DXMATRIXA16 g_mCenterMesh; float g_fLightScale; int g_nNumActiveLights; int g_nActiveLight; bool g_bShowHelp = false; // If true, it renders the UI control text // Lighting Settings bool g_bHemiAmbientLighting = false; bool g_bDirectLighting = false; bool g_bLightingOnly = false; bool g_bWireFrame = false; // Resources CDXUTTextHelper* g_pTxtHelper = NULL; CDXUTSDKMesh g_Mesh11; ID3D11Buffer* g_pVertexBuffer = NULL; ID3D11Buffer* g_pIndexBuffer = NULL; ID3D11InputLayout* g_pVertexLayout11 = NULL; ID3DX11Effect* g_pEffect = NULL; ID3DX11EffectTechnique* g_pTechnique = NULL; ID3DX11EffectMatrixVariable* g_pWorldViewProjection = NULL; ID3DX11EffectMatrixVariable* g_pWorld = NULL; ID3DX11EffectScalarVariable* g_pFillMode = NULL; ID3D11ShaderResourceView* g_pEnvironmentMapSRV = NULL; ID3DX11EffectShaderResourceVariable* g_pEnvironmentMapVar = NULL; // Shader Linkage Interface and Class variables ID3DX11EffectInterfaceVariable* g_pAmbientLightIface = NULL; ID3DX11EffectInterfaceVariable* g_pDirectionalLightIface = NULL; ID3DX11EffectInterfaceVariable* g_pEnvironmentLightIface = NULL; ID3DX11EffectInterfaceVariable* g_pMaterialIface = NULL; ID3DX11EffectClassInstanceVariable* g_pAmbientLightClass = NULL; ID3DX11EffectVectorVariable* g_pAmbientLightColor = NULL; ID3DX11EffectScalarVariable* g_pAmbientLightEnable = NULL; ID3DX11EffectClassInstanceVariable* g_pHemiAmbientLightClass = NULL; ID3DX11EffectVectorVariable* g_pHemiAmbientLightColor = NULL; ID3DX11EffectScalarVariable* g_pHemiAmbientLightEnable = NULL; ID3DX11EffectVectorVariable* g_pHemiAmbientLightGroundColor = NULL; ID3DX11EffectVectorVariable* g_pHemiAmbientLightDirUp = NULL; ID3DX11EffectClassInstanceVariable* g_pDirectionalLightClass = NULL; ID3DX11EffectVectorVariable* g_pDirectionalLightColor = NULL; ID3DX11EffectScalarVariable* g_pDirectionalLightEnable = NULL; ID3DX11EffectVectorVariable* g_pDirectionalLightDir = NULL; ID3DX11EffectClassInstanceVariable* g_pEnvironmentLightClass = NULL; ID3DX11EffectVectorVariable* g_pEnvironmentLightColor = NULL; ID3DX11EffectScalarVariable* g_pEnvironmentLightEnable = NULL; ID3DX11EffectVectorVariable* g_pEyeDir = NULL; // Material Dynamic Permutation enum E_MATERIAL_TYPES { MATERIAL_PLASTIC, MATERIAL_PLASTIC_TEXTURED, MATERIAL_PLASTIC_LIGHTING_ONLY, MATERIAL_ROUGH, MATERIAL_ROUGH_TEXTURED, MATERIAL_ROUGH_LIGHTING_ONLY, MATERIAL_TYPE_COUNT }; char* g_pMaterialClassNames[ MATERIAL_TYPE_COUNT ] = { "g_plasticMaterial", // cPlasticMaterial "g_plasticTexturedMaterial", // cPlasticTexturedMaterial "g_plasticLightingOnlyMaterial", // cPlasticLightingOnlyMaterial "g_roughMaterial", // cRoughMaterial "g_roughTexturedMaterial", // cRoughTexturedMaterial "g_roughLightingOnlyMaterial" // cRoughLightingOnlyMaterial }; E_MATERIAL_TYPES g_iMaterial = MATERIAL_PLASTIC_TEXTURED; struct MaterialVars { ID3DX11EffectTechnique* pTechnique; ID3DX11EffectClassInstanceVariable* pClass; ID3DX11EffectVectorVariable* pColor; ID3DX11EffectScalarVariable* pSpecPower; }; MaterialVars g_MaterialClasses[ MATERIAL_TYPE_COUNT ] = { NULL }; //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 3 #define IDC_CHANGEDEVICE 4 #define IDC_TOGGLEWIRE 5 // Lighting Controls #define IDC_AMBIENT_LIGHTING_GROUP 6 #define IDC_LIGHT_CONST_AMBIENT 7 #define IDC_LIGHT_HEMI_AMBIENT 8 #define IDC_LIGHT_DIRECT 9 #define IDC_LIGHTING_ONLY 10 // Material Controls #define IDC_MATERIAL_GROUP 11 #define IDC_MATERIAL_PLASTIC 12 #define IDC_MATERIAL_PLASTIC_TEXTURED 13 #define IDC_MATERIAL_ROUGH 14 #define IDC_MATERIAL_ROUGH_TEXTURED 15 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ); void CALLBACK OnD3D11DestroyDevice( void* pUserContext ); void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ); void InitApp(); void RenderText(); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // DXUT will create and use the best device feature level available // that is available on the system depending on which D3D callbacks are set below // Set DXUT callbacks DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( OnKeyboard ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackD3D11DeviceAcceptable( IsD3D11DeviceAcceptable ); DXUTSetCallbackD3D11DeviceCreated( OnD3D11CreateDevice ); DXUTSetCallbackD3D11SwapChainResized( OnD3D11ResizedSwapChain ); DXUTSetCallbackD3D11FrameRender( OnD3D11FrameRender ); DXUTSetCallbackD3D11SwapChainReleasing( OnD3D11ReleasingSwapChain ); DXUTSetCallbackD3D11DeviceDestroyed( OnD3D11DestroyDevice ); InitApp(); DXUTInit( true, true, NULL ); // Parse the command line, show msgboxes on error, no extra command line params DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"DynamicShaderLinkageFX11" ); DXUTCreateDevice(D3D_FEATURE_LEVEL_11_0, true, 640, 480 ); DXUTMainLoop(); // Enter into the DXUT render loop return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { D3DXVECTOR3 vLightDir( -1, 1, -1 ); D3DXVec3Normalize( &vLightDir, &vLightDir ); g_LightControl.SetLightDirection( vLightDir ); // Initialize dialogs g_D3DSettingsDlg.Init( &g_DialogResourceManager ); g_HUD.Init( &g_DialogResourceManager ); g_SampleUI.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 25; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 0, iY, 170, 22 ); g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 0, iY += 26, 170, 22, VK_F3 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 0, iY += 26, 170, 22, VK_F2 ); g_HUD.AddButton( IDC_TOGGLEWIRE, L"Toggle Wires (F4)", 0, iY += 26, 170, 22, VK_F4 ); // Material Controls iY = 10; g_SampleUI.AddRadioButton( IDC_MATERIAL_PLASTIC, IDC_MATERIAL_GROUP, L"Plastic", 0, iY += 26, 170, 22 ); g_SampleUI.AddRadioButton( IDC_MATERIAL_PLASTIC_TEXTURED, IDC_MATERIAL_GROUP, L"Plastic Textured", 0, iY += 26, 170, 22 ); g_SampleUI.AddRadioButton( IDC_MATERIAL_ROUGH, IDC_MATERIAL_GROUP, L"Rough", 0, iY += 26, 170, 22 ); g_SampleUI.AddRadioButton( IDC_MATERIAL_ROUGH_TEXTURED, IDC_MATERIAL_GROUP, L"Rough Textured", 0, iY += 26, 170, 22 ); CDXUTRadioButton* pRadioButton = g_SampleUI.GetRadioButton( IDC_MATERIAL_PLASTIC_TEXTURED ); pRadioButton->SetChecked( true ); iY += 24; // Lighting Controls g_SampleUI.AddRadioButton( IDC_LIGHT_CONST_AMBIENT, IDC_AMBIENT_LIGHTING_GROUP, L"Constant Ambient", 0, iY += 26, 170, 22 ); g_SampleUI.AddRadioButton( IDC_LIGHT_HEMI_AMBIENT, IDC_AMBIENT_LIGHTING_GROUP, L"Hemi Ambient", 0, iY += 26, 170, 22 ); pRadioButton = g_SampleUI.GetRadioButton( IDC_LIGHT_CONST_AMBIENT ); pRadioButton->SetChecked( true ); g_SampleUI.AddCheckBox( IDC_LIGHT_DIRECT, L"Direct Lighting", 0, iY += 26, 170, 22, g_bDirectLighting ); g_SampleUI.AddCheckBox( IDC_LIGHTING_ONLY, L"Lighting Only", 0, iY += 26, 170, 22, g_bLightingOnly ); g_SampleUI.SetCallback( OnGUIEvent ); } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; if( s_bFirstTime ) { s_bFirstTime = false; if( ( DXUT_D3D11_DEVICE == pDeviceSettings->ver && pDeviceSettings->d3d11.DriverType == D3D_DRIVER_TYPE_REFERENCE ) ) { DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } } return true; } //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { // Update the camera's position based on user input g_Camera.FrameMove( fElapsedTime ); } //-------------------------------------------------------------------------------------- // Render the help and statistics text //-------------------------------------------------------------------------------------- void RenderText() { UINT nBackBufferHeight = ( DXUTIsAppRenderingWithD3D9() ) ? DXUTGetD3D9BackBufferSurfaceDesc()->Height : DXUTGetDXGIBackBufferSurfaceDesc()->Height; g_pTxtHelper->Begin(); g_pTxtHelper->SetInsertionPos( 2, 0 ); g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) ); g_pTxtHelper->DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) ); g_pTxtHelper->DrawTextLine( DXUTGetDeviceStats() ); // Draw help if( g_bShowHelp ) { g_pTxtHelper->SetInsertionPos( 2, nBackBufferHeight - 20 * 6 ); g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 0.75f, 0.0f, 1.0f ) ); g_pTxtHelper->DrawTextLine( L"Controls:" ); g_pTxtHelper->SetInsertionPos( 20, nBackBufferHeight - 20 * 5 ); g_pTxtHelper->DrawTextLine( L"Rotate model: Left mouse button\n" L"Rotate light: Right mouse button\n" L"Rotate camera: Middle mouse button\n" L"Zoom camera: Mouse wheel scroll\n" ); g_pTxtHelper->SetInsertionPos( 350, nBackBufferHeight - 20 * 5 ); g_pTxtHelper->DrawTextLine( L"Hide help: F1\n" L"Quit: ESC\n" ); } else { g_pTxtHelper->SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); g_pTxtHelper->DrawTextLine( L"Press F1 for help" ); } g_pTxtHelper->End(); } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Pass messages to dialog resource manager calls so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass messages to settings dialog if its active if( g_D3DSettingsDlg.IsActive() ) { g_D3DSettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; g_LightControl.HandleMessages( hWnd, uMsg, wParam, lParam ); // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); return 0; } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK OnKeyboard( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { if( bKeyDown ) { switch( nChar ) { case VK_F1: g_bShowHelp = !g_bShowHelp; break; } } } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_TOGGLEREF: DXUTToggleREF(); break; case IDC_CHANGEDEVICE: g_D3DSettingsDlg.SetActive( !g_D3DSettingsDlg.IsActive() ); break; case IDC_TOGGLEWIRE: g_bWireFrame = !g_bWireFrame; break; // Lighting Controls case IDC_LIGHT_CONST_AMBIENT: g_bHemiAmbientLighting = false; break; case IDC_LIGHT_HEMI_AMBIENT: g_bHemiAmbientLighting = true; break; case IDC_LIGHT_DIRECT: g_bDirectLighting = !g_bDirectLighting; break; case IDC_LIGHTING_ONLY: g_bLightingOnly = !g_bLightingOnly; break; // Material Controls case IDC_MATERIAL_PLASTIC: g_iMaterial = MATERIAL_PLASTIC; break; case IDC_MATERIAL_PLASTIC_TEXTURED: g_iMaterial = MATERIAL_PLASTIC_TEXTURED; break; case IDC_MATERIAL_ROUGH: g_iMaterial = MATERIAL_ROUGH; break; case IDC_MATERIAL_ROUGH_TEXTURED: g_iMaterial = MATERIAL_ROUGH_TEXTURED; break; } } //-------------------------------------------------------------------------------------- // Reject any D3D10 devices that aren't acceptable by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsD3D11DeviceAcceptable( const CD3D11EnumAdapterInfo *AdapterInfo, UINT Output, const CD3D11EnumDeviceInfo *DeviceInfo, DXGI_FORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { return true; } //-------------------------------------------------------------------------------------- // Use this until D3DX11 comes online and we get some compilation helpers //-------------------------------------------------------------------------------------- static const unsigned int MAX_INCLUDES = 9; struct sInclude { HANDLE hFile; HANDLE hFileMap; LARGE_INTEGER FileSize; void *pMapData; }; class CIncludeHandler : public ID3DInclude { private: struct sInclude m_includeFiles[MAX_INCLUDES]; unsigned int m_nIncludes; public: CIncludeHandler() { // array initialization for ( unsigned int i=0; i<MAX_INCLUDES; i++) { m_includeFiles[i].hFile = INVALID_HANDLE_VALUE; m_includeFiles[i].hFileMap = INVALID_HANDLE_VALUE; m_includeFiles[i].pMapData = NULL; } m_nIncludes = 0; } ~CIncludeHandler() { for (unsigned int i=0; i<m_nIncludes; i++) { UnmapViewOfFile( m_includeFiles[i].pMapData ); if ( m_includeFiles[i].hFileMap != INVALID_HANDLE_VALUE) CloseHandle( m_includeFiles[i].hFileMap ); if ( m_includeFiles[i].hFile != INVALID_HANDLE_VALUE) CloseHandle( m_includeFiles[i].hFile ); } m_nIncludes = 0; } STDMETHOD(Open( D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes )) { unsigned int incIndex = m_nIncludes+1; // Make sure we have enough room for this include file if ( incIndex >= MAX_INCLUDES ) return E_FAIL; // try to open the file m_includeFiles[incIndex].hFile = CreateFileA( pFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL ); if( INVALID_HANDLE_VALUE == m_includeFiles[incIndex].hFile ) { return E_FAIL; } // Get the file size GetFileSizeEx( m_includeFiles[incIndex].hFile, &m_includeFiles[incIndex].FileSize ); // Use Memory Mapped File I/O for the header data m_includeFiles[incIndex].hFileMap = CreateFileMappingA( m_includeFiles[incIndex].hFile, NULL, PAGE_READONLY, m_includeFiles[incIndex].FileSize.HighPart, m_includeFiles[incIndex].FileSize.LowPart, pFileName); if( m_includeFiles[incIndex].hFileMap == NULL ) { if (m_includeFiles[incIndex].hFile != INVALID_HANDLE_VALUE) CloseHandle( m_includeFiles[incIndex].hFile ); return E_FAIL; } // Create Map view *ppData = MapViewOfFile( m_includeFiles[incIndex].hFileMap, FILE_MAP_READ, 0, 0, 0 ); *pBytes = m_includeFiles[incIndex].FileSize.LowPart; // Success - Increment the include file count m_nIncludes= incIndex; return S_OK; } STDMETHOD(Close( LPCVOID pData )) { // Defer Closure until the container destructor return S_OK; } }; HRESULT CompileShaderFromFile( WCHAR* szFileName, DWORD flags, LPCSTR szEntryPoint, LPCSTR szShaderModel, ID3DBlob** ppBlobOut ) { HRESULT hr = S_OK; // find the file WCHAR str[MAX_PATH]; WCHAR workingPath[MAX_PATH], filePath[MAX_PATH]; WCHAR *strLastSlash = NULL; bool resetCurrentDir = false; // Get the current working directory so we can restore it later UINT nBytes = GetCurrentDirectory( MAX_PATH, workingPath ); if (nBytes==MAX_PATH) { return E_FAIL; } // Check we can find the file first V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, szFileName ) ); // Check if the file is in the current working directory wcscpy_s( filePath, MAX_PATH, str ); strLastSlash = wcsrchr( filePath, TEXT( '\\' ) ); if( strLastSlash ) { // Chop the exe name from the exe path *strLastSlash = 0; SetCurrentDirectory( filePath ); resetCurrentDir = true; } // open the file HANDLE hFile = CreateFile( str, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL ); if( INVALID_HANDLE_VALUE == hFile ) return E_FAIL; // Get the file size LARGE_INTEGER FileSize; GetFileSizeEx( hFile, &FileSize ); // create enough space for the file data BYTE* pFileData = new BYTE[ FileSize.LowPart ]; if( !pFileData ) return E_OUTOFMEMORY; // read the data in DWORD BytesRead; if( !ReadFile( hFile, pFileData, FileSize.LowPart, &BytesRead, NULL ) ) return E_FAIL; CloseHandle( hFile ); // Create an Include handler instance CIncludeHandler* pIncludeHandler = new CIncludeHandler; // Compile the shader using optional defines and an include handler for header processing ID3DBlob* pErrorBlob; hr = D3DCompile( pFileData, FileSize.LowPart, "none", NULL, static_cast< ID3DInclude* > (pIncludeHandler), szEntryPoint, szShaderModel, flags, D3DCOMPILE_EFFECT_ALLOW_SLOW_OPS, ppBlobOut, &pErrorBlob ); delete pIncludeHandler; delete []pFileData; // Restore the current working directory if we need to if ( resetCurrentDir ) { SetCurrentDirectory( workingPath ); } if( FAILED(hr) ) { OutputDebugStringA( (char*)pErrorBlob->GetBufferPointer() ); SAFE_RELEASE( pErrorBlob ); return hr; } SAFE_RELEASE( pErrorBlob ); return hr; } //-------------------------------------------------------------------------------------- // Create any D3D10 resources that aren't dependant on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr = S_OK; ID3D11DeviceContext* pd3dImmediateContext = DXUTGetD3D11DeviceContext(); V_RETURN( g_DialogResourceManager.OnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) ); V_RETURN( g_D3DSettingsDlg.OnD3D11CreateDevice( pd3dDevice ) ); g_pTxtHelper = new CDXUTTextHelper( pd3dDevice, pd3dImmediateContext, &g_DialogResourceManager, 15 ); D3DXVECTOR3 vCenter( 0.25767413f, -28.503521f, 111.00689f ); FLOAT fObjectRadius = 378.15607f; D3DXMatrixTranslation( &g_mCenterMesh, -vCenter.x, -vCenter.y, -vCenter.z ); D3DXMATRIXA16 m; D3DXMatrixRotationY( &m, D3DX_PI ); g_mCenterMesh *= m; D3DXMatrixRotationX( &m, D3DX_PI / 2.0f ); g_mCenterMesh *= m; // Init the UI widget for directional lighting V_RETURN( CDXUTDirectionWidget::StaticOnD3D11CreateDevice( pd3dDevice, pd3dImmediateContext ) ); g_LightControl.SetRadius( fObjectRadius ); // Compile and create the effect. ID3DBlob* pEffectBuffer = NULL; V_RETURN( CompileShaderFromFile( L"DynamicShaderLinkageFX11.fx", 0, NULL, "fx_5_0", &pEffectBuffer ) ); V_RETURN( D3DX11CreateEffectFromMemory( pEffectBuffer->GetBufferPointer(), pEffectBuffer->GetBufferSize(), 0, pd3dDevice, &g_pEffect ) ); // Get the light Class Interfaces for setting values // and as potential binding sources. g_pAmbientLightClass = g_pEffect->GetVariableByName( "g_ambientLight" )->AsClassInstance(); g_pAmbientLightColor = g_pAmbientLightClass->GetMemberByName( "m_vLightColor" )->AsVector(); g_pAmbientLightEnable = g_pAmbientLightClass->GetMemberByName( "m_bEnable" )->AsScalar(); g_pHemiAmbientLightClass = g_pEffect->GetVariableByName( "g_hemiAmbientLight" )->AsClassInstance(); g_pHemiAmbientLightColor = g_pHemiAmbientLightClass->GetMemberByName( "m_vLightColor" )->AsVector(); g_pHemiAmbientLightEnable = g_pHemiAmbientLightClass->GetMemberByName( "m_bEnable" )->AsScalar(); g_pHemiAmbientLightGroundColor = g_pHemiAmbientLightClass->GetMemberByName( "m_vGroundColor" )->AsVector(); g_pHemiAmbientLightDirUp = g_pHemiAmbientLightClass->GetMemberByName( "m_vDirUp" )->AsVector(); g_pDirectionalLightClass = g_pEffect->GetVariableByName( "g_directionalLight")->AsClassInstance(); g_pDirectionalLightColor = g_pDirectionalLightClass->GetMemberByName( "m_vLightColor" )->AsVector(); g_pDirectionalLightEnable = g_pDirectionalLightClass->GetMemberByName( "m_bEnable" )->AsScalar(); g_pDirectionalLightDir = g_pDirectionalLightClass->GetMemberByName( "m_vLightDir" )->AsVector(); g_pEnvironmentLightClass = g_pEffect->GetVariableByName( "g_environmentLight")->AsClassInstance(); g_pEnvironmentLightColor = g_pEnvironmentLightClass->GetMemberByName( "m_vLightColor" )->AsVector(); g_pEnvironmentLightEnable = g_pEnvironmentLightClass->GetMemberByName( "m_bEnable" )->AsScalar(); g_pEyeDir = g_pEffect->GetVariableByName( "g_vEyeDir" )->AsVector(); // Acquire the material Class Instances for all possible material settings for( UINT i=0; i < MATERIAL_TYPE_COUNT; i++) { char pTechName[50]; StringCbPrintfA( pTechName, sizeof(pTechName), "FeatureLevel11_%s", g_pMaterialClassNames[ i ] ); g_MaterialClasses[i].pTechnique = g_pEffect->GetTechniqueByName( pTechName ); g_MaterialClasses[i].pClass = g_pEffect->GetVariableByName( g_pMaterialClassNames[i] )->AsClassInstance(); g_MaterialClasses[i].pColor = g_MaterialClasses[i].pClass->GetMemberByName( "m_vColor" )->AsVector(); g_MaterialClasses[i].pSpecPower = g_MaterialClasses[i].pClass->GetMemberByName( "m_iSpecPower" )->AsScalar(); } // Select which technique to use based on the feature level we acquired D3D_FEATURE_LEVEL supportedFeatureLevel = DXUTGetD3D11DeviceFeatureLevel(); if (supportedFeatureLevel >= D3D_FEATURE_LEVEL_11_0) { // We are going to use Dynamic shader linkage with SM5 so we need to look up interface and class instance variables // Get the abstract class interfaces so we can dynamically permute and assign linkages g_pAmbientLightIface = g_pEffect->GetVariableByName( "g_abstractAmbientLighting" )->AsInterface(); g_pDirectionalLightIface = g_pEffect->GetVariableByName( "g_abstractDirectLighting" )->AsInterface(); g_pEnvironmentLightIface = g_pEffect->GetVariableByName( "g_abstractEnvironmentLighting" )->AsInterface(); g_pMaterialIface = g_pEffect->GetVariableByName( "g_abstractMaterial" )->AsInterface(); g_pTechnique = g_pEffect->GetTechniqueByName( "FeatureLevel11" ); } else // Lower feature levels than 11 have no support for Dynamic Shader Linkage - need to use a statically specialized shaders { LPCSTR pTechniqueName; switch( supportedFeatureLevel ) { case D3D_FEATURE_LEVEL_10_1: pTechniqueName = "FeatureLevel10_1"; break; case D3D_FEATURE_LEVEL_10_0: pTechniqueName = "FeatureLevel10"; break; case D3D_FEATURE_LEVEL_9_3: pTechniqueName = "FeatureLevel9_3"; break; case D3D_FEATURE_LEVEL_9_2: // Shader model 2 fits feature level 9_1 case D3D_FEATURE_LEVEL_9_1: pTechniqueName = "FeatureLevel9_1"; break; default: return E_FAIL; } g_pTechnique = g_pEffect->GetTechniqueByName( pTechniqueName ); } SAFE_RELEASE( pEffectBuffer ); // Create our vertex input layout const D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R10G10B10A2_UNORM, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R16G16_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TANGENT", 0, DXGI_FORMAT_R10G10B10A2_UNORM, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "BINORMAL", 0, DXGI_FORMAT_R10G10B10A2_UNORM, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; D3DX11_PASS_SHADER_DESC VsPassDesc; D3DX11_EFFECT_SHADER_DESC VsDesc; g_pTechnique->GetPassByIndex(0)->GetVertexShaderDesc(&VsPassDesc); VsPassDesc.pShaderVariable->GetShaderDesc(VsPassDesc.ShaderIndex, &VsDesc); V_RETURN( pd3dDevice->CreateInputLayout( layout, ARRAYSIZE( layout ), VsDesc.pBytecode, VsDesc.BytecodeLength, &g_pVertexLayout11 ) ); DXUT_SetDebugName( g_pVertexLayout11, "Primary" ); // Load the mesh V_RETURN( g_Mesh11.Create( pd3dDevice, L"Squid\\squid.sdkmesh", false ) ); g_pWorldViewProjection = g_pEffect->GetVariableByName( "g_mWorldViewProjection" )->AsMatrix(); g_pWorld = g_pEffect->GetVariableByName( "g_mWorld" )->AsMatrix(); // Load a HDR Environment for reflections WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"Light Probes\\uffizi_cross.dds" ) ); V_RETURN( D3DX11CreateShaderResourceViewFromFile( pd3dDevice, str, NULL, NULL, &g_pEnvironmentMapSRV, NULL )); g_pEnvironmentMapVar = g_pEffect->GetVariableByName( "g_txEnvironmentMap" )->AsShaderResource(); g_pEnvironmentMapVar->SetResource( g_pEnvironmentMapSRV ); // Setup the camera's view parameters D3DXVECTOR3 vecEye( 0.0f, 0.0f, -50.0f ); D3DXVECTOR3 vecAt ( 0.0f, 0.0f, -0.0f ); g_Camera.SetViewParams( &vecEye, &vecAt ); g_Camera.SetRadius( fObjectRadius , fObjectRadius , fObjectRadius ); // Find Rasterizer State Object index for WireFrame / Solid rendering g_pFillMode = g_pEffect->GetVariableByName( "g_fillMode" )->AsScalar(); return hr; } //-------------------------------------------------------------------------------------- // Create any D3D11 resources that depend on the back buffer //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D11ResizedSwapChain( ID3D11Device* pd3dDevice, IDXGISwapChain* pSwapChain, const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr = S_OK; V_RETURN( g_DialogResourceManager.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); V_RETURN( g_D3DSettingsDlg.OnD3D11ResizedSwapChain( pd3dDevice, pBackBufferSurfaceDesc ) ); // Setup the camera's projection parameters float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; g_Camera.SetProjParams( D3DX_PI / 4, fAspectRatio, 2.0f, 4000.0f ); g_Camera.SetWindow( pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height ); g_Camera.SetButtonMasks( MOUSE_LEFT_BUTTON, MOUSE_WHEEL, MOUSE_MIDDLE_BUTTON ); g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, 170 ); g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 ); g_SampleUI.SetSize( 170, 300 ); return hr; } //-------------------------------------------------------------------------------------- // Render the scene using the D3D11 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11FrameRender( ID3D11Device* pd3dDevice, ID3D11DeviceContext* pd3dImmediateContext, double fTime, float fElapsedTime, void* pUserContext ) { HRESULT hr; // If the settings dialog is being shown, then render it instead of rendering the app's scene if( g_D3DSettingsDlg.IsActive() ) { g_D3DSettingsDlg.OnRender( fElapsedTime ); return; } // Clear the render target and depth stencil float ClearColor[4] = { 0.0f, 0.25f, 0.25f, 0.55f }; ID3D11RenderTargetView* pRTV = DXUTGetD3D11RenderTargetView(); pd3dImmediateContext->ClearRenderTargetView( pRTV, ClearColor ); ID3D11DepthStencilView* pDSV = DXUTGetD3D11DepthStencilView(); pd3dImmediateContext->ClearDepthStencilView( pDSV, D3D11_CLEAR_DEPTH, 1.0, 0 ); D3DXMATRIX mWorldViewProjection; D3DXVECTOR3 vLightDir; D3DXMATRIX mWorld; D3DXMATRIX mView; D3DXMATRIX mProj; // Get the projection & view matrix from the camera class mWorld = *g_Camera.GetWorldMatrix(); mProj = *g_Camera.GetProjMatrix(); mView = *g_Camera.GetViewMatrix(); // Get the light direction vLightDir = g_LightControl.GetLightDirection(); // Render the light arrow so the user can visually see the light dir //D3DXCOLOR arrowColor = ( i == g_nActiveLight ) ? D3DXVECTOR4( 1, 1, 0, 1 ) : D3DXVECTOR4( 1, 1, 1, 1 ); D3DXCOLOR arrowColor = D3DXVECTOR4( 1, 1, 0, 1 ); V( g_LightControl.OnRender11( arrowColor, &mView, &mProj, g_Camera.GetEyePt() ) ); // Ambient Light D3DXVECTOR4 vLightColor(0.1f, 0.1f, 0.1f, 1.0f); g_pAmbientLightColor->SetFloatVector(vLightColor); g_pAmbientLightEnable->SetBool(true); // Hemi Ambient Light vLightColor.x = 0.3f; vLightColor.y = 0.3f; vLightColor.z = 0.4f; g_pHemiAmbientLightColor->SetFloatVector(vLightColor); g_pHemiAmbientLightEnable->SetBool(true); vLightColor.x = 0.05f; vLightColor.y = 0.05f; vLightColor.z = 0.05f; vLightColor.w = 1.0f; g_pHemiAmbientLightGroundColor->SetFloatVector(vLightColor); D3DXVECTOR4 vVec(0.0f, 1.0f, 0.0f, 1.0f); g_pHemiAmbientLightDirUp->SetFloatVector(vVec); // Directional Light vLightColor.x = 1.0f; vLightColor.y = 1.0f; vLightColor.z = 1.0f; g_pDirectionalLightColor->SetFloatVector(vLightColor); g_pDirectionalLightEnable->SetBool(true); vVec.x = vLightDir.x; vVec.y = vLightDir.y; vVec.z = vLightDir.z; vVec.w = 1.0f; g_pDirectionalLightDir->SetFloatVector(vVec); // Environment Light - color comes from the texture vLightColor.x = 0.0f; vLightColor.y = 0.0f; vLightColor.z = 0.0f; g_pEnvironmentLightColor->SetFloatVector(vLightColor); g_pEnvironmentLightEnable->SetBool(true); // Setup the Eye based on the DXUT camera D3DXVECTOR3 vEyePt = *g_Camera.GetEyePt(); D3DXVECTOR3 vDir = *g_Camera.GetLookAtPt() - vEyePt; g_pEyeDir->SetFloatVector(D3DXVECTOR4( vDir.x, vDir.y, vDir.z, 1.0f )); //Get the mesh //IA setup pd3dImmediateContext->IASetInputLayout( g_pVertexLayout11 ); UINT Strides[1]; UINT Offsets[1]; ID3D11Buffer* pVB[1]; pVB[0] = g_Mesh11.GetVB11( 0, 0 ); Strides[0] = ( UINT )g_Mesh11.GetVertexStride( 0, 0 ); Offsets[0] = 0; pd3dImmediateContext->IASetVertexBuffers( 0, 1, pVB, Strides, Offsets ); pd3dImmediateContext->IASetIndexBuffer( g_Mesh11.GetIB11( 0 ), g_Mesh11.GetIBFormat11( 0 ), 0 ); // Set the per object constant data mWorldViewProjection = mWorld * mView * mProj; // VS Per object g_pWorldViewProjection->SetMatrix(mWorldViewProjection); g_pWorld->SetMatrix(mWorld); // Setup the Shader Linkage based on the user settings for Lighting ID3DX11EffectClassInstanceVariable* pLightClassVar; // Ambient Lighting First - Constant or Hemi? if ( g_bHemiAmbientLighting ) { pLightClassVar = g_pHemiAmbientLightClass; } else { pLightClassVar = g_pAmbientLightClass; } if (g_pAmbientLightIface) { g_pAmbientLightIface->SetClassInstance(pLightClassVar); } // Direct Light - None or Directional if (g_bDirectLighting) { pLightClassVar = g_pDirectionalLightClass; } else { // Disable ALL Direct Lighting pLightClassVar = g_pAmbientLightClass; } if (g_pDirectionalLightIface) { g_pDirectionalLightIface->SetClassInstance(pLightClassVar); } // Setup the selected material class instance E_MATERIAL_TYPES iMaterialTech = g_iMaterial; switch( g_iMaterial ) { case MATERIAL_PLASTIC: case MATERIAL_PLASTIC_TEXTURED: // Bind the Environment light for reflections pLightClassVar = g_pEnvironmentLightClass; if (g_bLightingOnly) { iMaterialTech = MATERIAL_PLASTIC_LIGHTING_ONLY; } break; case MATERIAL_ROUGH: case MATERIAL_ROUGH_TEXTURED: // UnBind the Environment light pLightClassVar = g_pAmbientLightClass; if (g_bLightingOnly) { iMaterialTech = MATERIAL_ROUGH_LIGHTING_ONLY; } break; } if (g_pEnvironmentLightIface) { g_pEnvironmentLightIface->SetClassInstance(pLightClassVar); } ID3DX11EffectTechnique* pTechnique = g_pTechnique; if (g_pMaterialIface) { #if USE_BIND_INTERFACES // We're using the techniques with pre-bound materials, // so select the appropriate technique. pTechnique = g_MaterialClasses[ iMaterialTech ].pTechnique; #else // We're using a single technique and need to explicitly // bind a concrete material instance. g_pMaterialIface->SetClassInstance( g_MaterialClasses[ iMaterialTech ].pClass ); #endif } // PS Per Prim // Shiny Plastic g_MaterialClasses[MATERIAL_PLASTIC].pColor->SetFloatVector(D3DXVECTOR3(1, 0, 0.5f)); g_MaterialClasses[MATERIAL_PLASTIC].pSpecPower->SetInt(255); // Shiny Plastic with Textures g_MaterialClasses[MATERIAL_PLASTIC_TEXTURED].pColor->SetFloatVector(D3DXVECTOR3(1, 0, 0.5f)); g_MaterialClasses[MATERIAL_PLASTIC_TEXTURED].pSpecPower->SetInt(128); // Lighting Only Plastic g_MaterialClasses[MATERIAL_PLASTIC_LIGHTING_ONLY].pColor->SetFloatVector(D3DXVECTOR3(1, 1, 1)); g_MaterialClasses[MATERIAL_PLASTIC_LIGHTING_ONLY].pSpecPower->SetInt(128); // Rough Material g_MaterialClasses[MATERIAL_ROUGH].pColor->SetFloatVector(D3DXVECTOR3(0, 0.5f, 1)); g_MaterialClasses[MATERIAL_ROUGH].pSpecPower->SetInt(6); // Rough Material with Textures g_MaterialClasses[MATERIAL_ROUGH_TEXTURED].pColor->SetFloatVector(D3DXVECTOR3(0, 0.5f, 1)); g_MaterialClasses[MATERIAL_ROUGH_TEXTURED].pSpecPower->SetInt(6); // Lighting Only Rough g_MaterialClasses[MATERIAL_ROUGH_LIGHTING_ONLY].pColor->SetFloatVector(D3DXVECTOR3(1, 1, 1)); g_MaterialClasses[MATERIAL_ROUGH_LIGHTING_ONLY].pSpecPower->SetInt(6); if (g_bWireFrame) g_pFillMode->SetInt(1); else g_pFillMode->SetInt(0); // Apply the technique to update state. pTechnique->GetPassByIndex(0)->Apply(0, pd3dImmediateContext); //Render g_Mesh11.Render( pd3dImmediateContext, 0, 1, INVALID_SAMPLER_SLOT); // Tell the UI items to render DXUT_BeginPerfEvent( DXUT_PERFEVENTCOLOR, L"HUD / Stats" ); g_HUD.OnRender( fElapsedTime ); g_SampleUI.OnRender( fElapsedTime ); RenderText(); DXUT_EndPerfEvent(); } //-------------------------------------------------------------------------------------- // Release D3D11 resources created in OnD3D10ResizedSwapChain //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11ReleasingSwapChain( void* pUserContext ) { g_DialogResourceManager.OnD3D11ReleasingSwapChain(); } //-------------------------------------------------------------------------------------- // Release D3D11 resources created in OnD3D10CreateDevice //-------------------------------------------------------------------------------------- void CALLBACK OnD3D11DestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D11DestroyDevice(); g_D3DSettingsDlg.OnD3D11DestroyDevice(); CDXUTDirectionWidget::StaticOnD3D11DestroyDevice(); DXUTGetGlobalResourceCache().OnDestroyDevice(); SAFE_DELETE( g_pTxtHelper ); g_Mesh11.Destroy(); SAFE_RELEASE( g_pEffect ); SAFE_RELEASE( g_pVertexLayout11 ); SAFE_RELEASE( g_pVertexBuffer ); SAFE_RELEASE( g_pIndexBuffer ); SAFE_RELEASE( g_pEnvironmentMapSRV ); }
require 'sinatra' get '/validate_form' do erb :validate_form end post '/validate_form' do @name = params[:name] @email = params[:email] @phone = params[:phone] if @name == "" || @email == "" || @phone == "" @message = "All fields are required!" elsif !valid_email?(@email) @message = "Email must be valid!" elsif !valid_phone?(@phone) @message = "Phone number must be valid!" else @message = "Form is valid!" end erb :validate_form end def valid_email?(email) !!(email =~ /.+@.+\..+/) end def valid_phone?(phone) !!(phone =~ /\d{3}-\d{3}-\d{4}/) end
const axios = require('axios'); const cheerio = require('cheerio'); const classmongo = require('./classmongo'); let dados = {}; async function scrap(url) { await console.time('#TempoScraping'); await classmongo.start() const { data } = await axios.get(url); const $ = cheerio.load(data); for (i = 2; i < 1003; i++) { let distribuidora = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(1)`).text().trim(); let codigo = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(2)`).text().trim(); let titular = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(3)`).text().trim(); let classe = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(4)`).text().trim(); let subgrupo = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(5)`).text().trim(); let modalidade = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(6)`).text().trim(); let credito = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(7)`).text().trim(); let municipio = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(8)`).text().trim(); let uf = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(9)`).text().trim(); let cep = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(10)`).text().trim(); let data = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(11)`).text().trim(); let fonte = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(12)`).text().trim(); let potencia = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(13)`).text().trim(); let modulo = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(14)`).text().trim(); let inversores = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(15)`).text().trim(); let arranjo = $(`body > table:nth-child(4) > tbody > tr:nth-child(1) > td > table:nth-child(4) > tbody > tr:nth-child(${i}) > td:nth-child(16)`).text().trim(); dados = { distribuidora, codigo, titular, classe, subgrupo, modalidade, credito, municipio, uf, cep, data, fonte, potencia, modulo, inversores, arranjo } await classmongo.add(dados); //console.log(dados); } await classmongo.close(); await console.timeEnd('#TempoScraping'); } module.exports = scrap;
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 盒子档口模型 * * @author auto create * @since 1.0, 2018-12-20 11:37:52 */ public class PosStallModel extends AlipayObject { private static final long serialVersionUID = 3413251639443675944L; /** * 菜品下档口的排序号 */ @ApiField("sort") private Long sort; /** * 档口ID */ @ApiField("stall_id") private String stallId; /** * 档口名字 */ @ApiField("stall_name") private String stallName; public Long getSort() { return this.sort; } public void setSort(Long sort) { this.sort = sort; } public String getStallId() { return this.stallId; } public void setStallId(String stallId) { this.stallId = stallId; } public String getStallName() { return this.stallName; } public void setStallName(String stallName) { this.stallName = stallName; } }
#!/bin/sh which py > /dev/null 2>&1 if [[ $? == 0 ]]; then echo "Running in Windows" PYTHON='python' py -3 -m venv testenv3 source testenv3/Scripts/activate else echo "Running in Linux" PYTHON=python3 python3 -m venv testenv3 source testenv3/bin/activate fi ${PYTHON} -m pip install -r requirements-dev.txt ${PYTHON} -m pip install --upgrade --no-cache-dir git+https://github.com/foosel/OctoPrint.git@devel ${PYTHON} setup.py develop cp testconfig testenv3/ -rfv ${PYTHON} configtest3.py ${PYTHON} -m webbrowser -t http://127.0.0.1:5000 FAKE_SNAPSHOT=unittests/test_pattern.png octoprint serve -b testenv3/testconfig
// (c) <NAME> 'use strict'; describe('Requiem', function() { it('should have some tests soon', function() { }); });
<gh_stars>10-100 package cc.sfclub.transform.internal; import cc.sfclub.transform.Bot; import cc.sfclub.transform.ChatGroup; import cc.sfclub.transform.Contact; import java.util.Collections; import java.util.Optional; public class ConsoleBot extends Bot { private final VirtContact virtualContact = new VirtContact(0L); private final VirtGroup virtualGroup = new VirtGroup(0L, Collections.singleton(virtualContact)); public ConsoleBot() { this.addGroup(virtualGroup, true); } @Override public Optional<ChatGroup> getGroup(long id) { return super.getGroup(id); } @Override public String getName() { return "CONSOLE"; } @Override public Optional<Contact> asContact(String UserID) { return Optional.empty(); } }
const CompressionWebpackPlugin = require('compression-webpack-plugin'); const MarkdownIt = require('markdown-it'); const md = new MarkdownIt(); module.exports = { configureWebpack: { module: { rules: [ { test: /\.md$/, loader: 'ware-loader', enforce: 'pre', options: { raw: true, middleware: function(source) { return `<template><div>${md.render(source)}</div></template>`; }, }, }, { test: /\.md$/, use: 'vue-loader', }, ], }, plugins: (() => { const result = []; if (['production', 'staging'].indexOf(process.env.VUE_APP_MODE) >= 0) { result.push( new CompressionWebpackPlugin({ filename: '[path]', algorithm: 'gzip', test: /\.js$/, threshold: 0, }), ); } return result; })(), }, devServer: { proxy: 'http://localhost:8888', port: 8888, }, };
<gh_stars>0 /* Validator v3.0.3 (c) <NAME> https://github.com/yairEO/validator */ ;(function(root, factory) { if( typeof define === 'function' && define.amd ) define([], factory); else if( typeof exports === 'object' ) module.exports = factory(); else root.FormValidator = factory(); }(this, function(){ function FormValidator(texts, settings){ this.data = {}; // holds the form fields' data this.texts = this.extend({}, this.texts, texts || {}); this.settings = this.extend({}, this.defaults, settings || {}) } FormValidator.prototype = { // Validation error texts texts : { invalid : '유효한 형식의 값이 아닙니다.', // inupt is not as expected short : ':min 자릿수 이상여야 합니다.', // input is too short long : ':max 자릿수 이하여야 합니다.', // input is too long checked : ':attribute 필드는 필수입니다.', // must be checked empty : ':attribute 필드는 필수입니다.', // please put something here select : ':attribute 필드는 필수입니다.', // Please select an option number_min : ':min 이상의 숫자여야 합니다.', // too low number_max : ':max 이하의 숫자여야 합니다.', // too high url : '유효한 URL 형식이 아닙니다.', // invalid URL number : '반드시 숫자여야 합니다.', // not a number email : '유효한 메일주소 형식이 아닙니다.', // email address is invalid email_repeat : '메일주소가 일치하지 않습니다.', // emails do not match date : '유효한 날짜 형식이 아닙니다.', // invalid date time : '유효한 시간 형식이 아닙니다.', // invalid time password_repeat : '비밀번호가 일치하지 않습니다.', // passwords do not match no_match : '일치하지 않습니다.', // no match complete : '유효한 형식의 값이 아닙니다.' // input is not complete }, // default settings defaults : { regex : { url : /^(https?:\/\/)?([\w\d\-_]+\.+[A-Za-z]{2,})+\/?/, //phone : /^\+?([0-9]|[-|' '])+$/i, phone : /^(01[016789]{1}|02|0[3-9]{1}[0-9]{1})-?[0-9]{3,4}-?[0-9]{4}$/i, // 일반전화 + 휴대폰 tel : /^(02|0[3-9]{1}[0-9]{1})-?[0-9]{3,4}-?[0-9]{4}$/i, // 일반전화 mobile : /^(01[016789]{1})-?[0-9]{3,4}-?[0-9]{4}$/i, // 휴대폰 numeric : /^[0-9]+$/i, alpha : /^[a-zA-Z]+$/i, alphanumeric : /^[a-zA-Z0-9]+$/i, /*email : { illegalChars : /[\(\)\<\>\,\;\:\\\/\"\[\]]/, filter : /^.+@.+\..{2,6}$/ // exmaple email "<EMAIL>" }*/ email : /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ }, alerts : true, classes : { item : 'field', alert : 'alert', bad : 'bad' } }, // Tests (per type) // each test return "true" when passes and a string of error text otherwise tests : { sameAsPlaceholder : function( field, data ){ if( field.getAttribute('placeholder') ) { //return data.value != field.getAttribute('placeholder') || this.texts.empty; return data.value != field.getAttribute('placeholder') || this.texts.empty.replace(':attribute', field.title); } else { return true; } }, //hasValue : function( value ){ hasValue : function(field, data){ //return value ? true : this.texts.empty; return data.value ? true : this.texts.empty.replace(':attribute', field.title); }, // 'linked' is a special test case for inputs which their values should be equal to each other (ex. confirm email or retype password) linked : function(a, b, type){ if( b != a && a && b ){ // choose a specific message or a general one return this.texts[type + '_repeat'] || this.texts.no_match; } return true; }, email : function(field, data){ //if ( !this.settings.regex.email.filter.test( data.value ) || data.value.match( this.settings.regex.email.illegalChars ) ){ if ( !this.settings.regex.email.test( data.value ) ){ return this.texts.email; } return true; }, // a "skip" will skip some of the tests (needed for keydown validation) text : function(field, data){ var that = this; // make sure there are at least X number of words, each at least 2 chars long. // for example '<NAME>' should be at least 2 words and will pass validation if( data.validateWords ){ var words = data.value.split(' '); // iterate on all the words var wordsLength = function(len){ for( var w = words.length; w--; ) { if( words[w].length < len ) { //return that.texts.short; return that.texts.short.replace(':min', len); } } return true; }; if( words.length < data.validateWords || !wordsLength(2) ) { return this.texts.complete; } //return true; } if( data.lengthRange && data.value.length < data.lengthRange[0] ) { //return this.texts.short; return this.texts.short.replace(':min', data.lengthRange[0]); } // check if there is max length & field length is greater than the allowed if( data.lengthRange && data.lengthRange[1] && data.value.length > data.lengthRange[1] ) { //return this.texts.long; return this.texts.long.replace(':max', data.lengthRange[1]); } // check if the field's value should obey any length limits, and if so, make sure the length of the value is as specified if( data.lengthLimit && data.lengthLimit.length ){ while( data.lengthLimit.length ){ if( data.lengthLimit.pop() == data.value.length ) { //return true; } } return this.texts.complete; } if( data.pattern ){ var testResult, regexs = data.pattern.split(','); for(var i = 0; i < regexs.length; i++) { testResult = this.testByRegex(data.value, regexs[i]); if(testResult !== true) { return testResult; } } } return true; }, number : function( field, data ){ var a = data.value; // if not not a number if( isNaN(parseFloat(a)) && !isFinite(a) ){ return this.texts.number; } // not enough numbers else if( data.lengthRange && a.length < data.lengthRange[0] ){ //return this.texts.short; return this.texts.short.replace(':min', data.lengthRange[0]); } // check if there is max length & field length is greater than the allowed else if( data.lengthRange && data.lengthRange[1] && a.length > data.lengthRange[1] ){ //return this.texts.long; return this.texts.long.replace(':max', data.lengthRange[1]); } else if( data.minmax[0] && (a|0) < data.minmax[0] ){ //return this.texts.number_min; return this.texts.number_min.replace(':min', data.minmax[0]); } else if( data.minmax[1] && (a|0) > data.minmax[1] ){ //return this.texts.number_max; return this.texts.number_max.replace(':max', data.minmax[1]); } return true; }, // Date is validated in European format (day,month,year) date : function( field, data ){ var day, A = data.value.split(/[-./]/g), i; // if seperater not exists if( A.length != 3 ) { if ( String(A).length == 8 ) { A = [ String(A).substr(0, 4), String(A).substr(4, 2), String(A).substr(6, 2) ]; } else if (String(A).length == 6) { A = [ String(A).substr(0, 2), String(A).substr(2, 2), String(A).substr(4, 2) ]; } else { return this.texts.date; } } // if there is native HTML5 support: if( field.valueAsNumber ) return true; for( i = A.length; i--; ){ if( isNaN(parseFloat( data.value )) && !isFinite(data.value) ) return this.texts.date; } try{ //day = new Date(A[2], A[1]-1, A[0]); //if( day.getMonth()+1 == A[1] && day.getDate() == A[0]) // korean format (year, month, day) day = new Date(A[0], A[1]-1, A[2]); if( day.getMonth()+1 == A[1] && day.getDate() == A[2]) return true; return this.texts.date; } catch(er){ return this.texts.date; } }, time : function( field, data ){ //var pattern = /^([0-1][0-9]|2[0-3]):[0-5][0-9]$/; // hh:mm or hh:mm:ss var pattern = /^([0-1][0-9]|2[0-3]):?[0-5][0-9](:?[0-5][0-9])?$/; if( pattern.test(data.value) ) return true; else return this.texts.time; }, url : function( field, data ){ // minimalistic URL validation if( !this.settings.regex.url.test(data.value) ) return this.texts.url; return true; }, hidden : function( field, data ){ if( data.lengthRange && data.value.length < data.lengthRange[0] ) { //return this.texts.short; return this.texts.short.replace(':min', data.lengthRange[0]); } if( data.pattern ){ if( data.pattern == 'alphanumeric' && !this.settings.regex.alphanumeric.test(data.value) ) return this.texts.invalid; } return true; }, select : function( field, data ){ //return data.value ? true : this.texts.select; return data.value ? true : this.texts.select.replace(':attribute', field.title); }, checkbox : function( field, data ){ if( field.checked ) return true; //return this.texts.checked; return this.texts.checked.replace(':attribute', field.title); }, radio : function( field, data, form ){ if( form.querySelectorAll('[name=' + field.name + ']:checked').length > 0 ) return true; //return this.texts.checked; return this.texts.checked.replace(':attribute', field.title); } }, /** * Marks an field as invalid * @param {DOM Object} field * @param {String} text * @return {jQuery Object} - The message element for the field */ mark : function( field, text ){ if( !text || !field ) return false; var that = this; // check if not already marked as 'bad' and add the 'alert' object. // if already is marked as 'bad', then make sure the text is set again because i might change depending on validation var item = this.closest(field, '.' + this.settings.classes.item), alert = item.querySelector('.'+this.settings.classes.alert), warning; if( this.settings.alerts ){ if( alert ) alert.innerHTML = text; else{ warning = '<div class="'+ this.settings.classes.alert +'">' + text + '</div>'; item.insertAdjacentHTML('beforeend', warning); } } item.classList.remove(this.settings.classes.bad); // a delay so the "alert" could be transitioned via CSS setTimeout(function(){ item.classList.add( that.settings.classes.bad ); }); return warning; }, /* un-marks invalid fields */ unmark : function( field ){ if( !field ){ console.warn('no "field" argument, null or DOM object not found'); return false; } var fieldWrap = this.closest(field, '.' + this.settings.classes.item); if( fieldWrap ){ var warning = fieldWrap.querySelector('.'+ this.settings.classes.alert); fieldWrap.classList.remove(this.settings.classes.bad); } if( warning ) warning.parentNode.removeChild(warning); }, /** * Normalize types if needed & return the results of the test (per field) * @param {String} type [form field type] * @param {*} value * @return {Boolean} - validation test result */ testByType : function( field, data, form ){ data = this.extend({}, data); // clone the data var type = data.type; if( type == 'tel' ) data.pattern = data.pattern || 'phone'; //if( !type || type == 'password' || type == 'tel' || type == 'search' || type == 'file' ) if( !type || type == 'password' || type == 'tel' || type == 'search' || type == 'file' || type == 'hidden' ) type = 'text'; return this.tests[type] ? this.tests[type].call(this, field, data, form) : true; }, testByRegex : function( value, pattern ) { var regex, jsRegex; // instead of switch case if(this.settings.regex[pattern] === undefined) { regex = pattern; } else { regex = this.settings.regex[pattern]; } try{ jsRegex = new RegExp(regex).test(value); if( !value || ( value && !jsRegex ) ){ return this.texts.invalid; } } catch(err){ console.warn(err, field, 'regex is invalid'); return this.texts.invalid; } return true; }, prepareFieldData : function(field){ var nodeName = field.nodeName.toLowerCase(), id = Math.random().toString(36).substr(2,9); field["_validatorId"] = id; this.data[id] = {}; this.data[id].value = field.value.replace(/^\s+|\s+$/g, ""); // cache the value of the field and trim it this.data[id].valid = true; // initialize validity of field this.data[id].type = field.getAttribute('type'); // every field starts as 'valid=true' until proven otherwise this.data[id].pattern = field.getAttribute('pattern'); // Special treatment if( nodeName === "select" ) this.data[id].type = "select"; else if( nodeName === "textarea" ) this.data[id].type = "text"; /* Gather Custom data attributes for specific validation: */ this.data[id].validateWords = field.getAttribute('data-validate-words') || 0; this.data[id].lengthRange = field.getAttribute('data-validate-length-range') ? (field.getAttribute('data-validate-length-range')+'').split(',') : [1]; this.data[id].lengthLimit = field.getAttribute('data-validate-length') ? (field.getAttribute('data-validate-length')+'').split(',') : false; this.data[id].minmax = field.getAttribute('data-validate-minmax') ? (field.getAttribute('data-validate-minmax')+'').split(',') : false; // for type 'number', defines the minimum and/or maximum for the value as a number. this.data[id].validateLinked = field.getAttribute('data-validate-linked'); return this.data[id]; }, /* linkTo or required_if field selector */ fieldSelector : function(form, fieldName) { var field; if( fieldName.indexOf('#') == 0 ) field = document.body.querySelectorAll(fieldName); else if( form.length ) field = form.querySelectorAll('[name=' + fieldName + ']'); else field = document.body.querySelectorAll('[name=' + fieldName + ']'); return field; }, /* required_if field whether to check or pass */ isCheckRequiredIf : function(field) { var toField, toValue, toFieldData, required = field.getAttribute('required'), form = this.closest(field, 'form'); this.unmark(field); if(required && required.indexOf('_if') != -1) { toFieldData = required.split(':')[1].split(','); toField = this.fieldSelector(form, toFieldData[0]); toValue = toFieldData[1]; for(var i =0; i < toField.length; i++) { switch (toField[i].type) { case 'radio' : case 'checkbox' : if (toField[i].checked === true && toField[i].value == toValue) { return true; } break; default : if (toField[i].value == toValue) { return true; } break; } } } return false; }, closest : function(el, selector){ var matchesFn; // find vendor prefix ['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) { if (typeof document.body[fn] == 'function') { matchesFn = fn; return true; } return false; }) var parent; // traverse parents while (el) { parent = el.parentElement; if (parent && parent[matchesFn](selector)) { return parent; } el = parent; } return null; }, // MDN polyfill for Object.assign extend : function(target, varArgs){ if( !target ) throw new TypeError('Cannot convert undefined or null to object'); var to = Object(target), nextKey, nextSource, index; for( index = 1; index < arguments.length; index++ ){ nextSource = arguments[index]; if( nextSource != null ) // Skip over if undefined or null for( nextKey in nextSource ) // Avoid bugs when hasOwnProperty is shadowed if( Object.prototype.hasOwnProperty.call(nextSource, nextKey) ) to[nextKey] = nextSource[nextKey]; } return to; }, /** * Only allow certain form elements which are actual inputs to be validated * @param {HTMLCollection} form fields Array [description] * @return {Array} [description] */ filterFormElements : function( fields ){ var i, fieldsToCheck = []; for( i = fields.length; i--; ) { var isAllowedElement = fields[i].nodeName.match(/input|textarea|select/gi), isRequiredAttirb = fields[i].hasAttribute('required') && fields[i].getAttribute('required').indexOf('_if') == -1, isRequiredIfAttirb = fields[i].hasAttribute('required') && fields[i].getAttribute('required').indexOf('_if') != -1 && this.isCheckRequiredIf(fields[i]), isDisabled = fields[i].hasAttribute('disabled'), isOptional = fields[i].className.indexOf('optional') != -1; if( isAllowedElement && (isRequiredAttirb || isRequiredIfAttirb || isOptional) && !isDisabled ) { fieldsToCheck.push(fields[i]); } } return fieldsToCheck; }, /* Checks a single form field by it's type and specific (custom) attributes * {DOM Object} - the field to be checked * {Boolean} silent - don't mark a field and only return if it passed the validation or not */ checkField : function( field, silent ){ // skip testing fields whom their type is not HIDDEN but they are HIDDEN via CSS. // add must validate class if( field.type !='hidden' && !field.clientWidth && field.className.indexOf('must-validate') < 0 ) return { valid:true, error:"" } field = this.filterFormElements( [field] )[0]; // if field did not pass filtering or is simply not passed if( !field ) return { valid:true, error:"" } //this.unmark( field ); var linkedTo, testResult, optional = field.className.indexOf('optional') != -1, data = this.prepareFieldData( field ), form = this.closest(field, 'form'); // if the field is part of a form, then cache it // check if field has any value /* Validate the field's value is different than the placeholder attribute (and attribute exists) * this is needed when fixing the placeholders for older browsers which does not support them. * in this case, make sure the "placeholder" jQuery plugin was even used before proceeding */ // first, check if the field even has any value testResult = this.tests.hasValue.call(this, field, data); // if the field has value, check if that value is same as placeholder if( testResult === true ) testResult = this.tests.sameAsPlaceholder.call(this, field, data); data.valid = optional || testResult === true; if( optional && !data.value ){ return { valid:true, error:"" }; } if( testResult !== true ) data.valid = false; // validate by type of field. use 'attr()' is proffered to get the actual value and not what the browsers sees for unsupported types. if( data.valid ){ //testResult = this.testByType(field, data); testResult = this.testByType(field, data, form); data.valid = testResult === true ? true : false; } // if this field is linked to another field (their values should be the same) if( data.valid && data.validateLinked ){ linkedTo = this.fieldSelector(form, data['validateLinked']); testResult = this.tests.linked.call(this, field.value, linkedTo[0].value, data.type); data.valid = testResult === true ? true : false; } if( !silent ) { this[data.valid ? "unmark" : "mark"](field, testResult); // mark / unmark the field } return { valid : data.valid, error : data.valid === true ? "" : testResult }; }, checkAll : function( form ){ if( !form ){ console.warn('element not found'); return false; } var that = this, result = { valid : true, // overall form validation flag fields : [] // array of objects (per form field) }, fieldsToCheck= this.filterFormElements( form.elements ); // get all the input/textareas/select fields which are required or optional (meaning, they need validation only if they were filled) fieldsToCheck.forEach(function(elm, i){ var fieldData = that.checkField(elm); // use an AND operation, so if any of the fields returns 'false' then the submitted result will be also FALSE result.valid = !!(result.valid * fieldData.valid); result.fields.push({ field : elm, error : fieldData.error, valid : !!fieldData.valid }) }); return result; }, checkFirst : function( form, mark ){ if( !form ){ console.warn('element not found'); return false; } if ( !mark ) { this.settings.alerts = false; } var that = this, result = { valid : true // overall form validation flag }, fieldsToCheck= this.filterFormElements( form.elements ); // get all the input/textareas/select fields which are required or optional (meaning, they need validation only if they were filled) fieldsToCheck.reverse().forEach(function(elm, i){ var fieldData = that.checkField(elm); if ( !fieldData.valid ) { if ( !mark ) { alert(fieldData.error); //elm.select(); elm.focus(); } result.valid = false; // break fieldsToCheck.length = 0; } }); return result; }, checkRegex : function( value, pattern ) { var testResult, regexs = pattern.split(','), result = { valid : true // overall form validation flag }; for(var i = 0; i < regexs.length; i++) { testResult = this.testByRegex(value, regexs[i]); if(testResult !== true) { result.valid = false; } } if( result.valid === false) { alert(this.texts.invalid); } return result; } } return FormValidator; }));
<filename>logback-demo/src/main/java/com/darian/logbackdemo/controller/BaseController.java package com.darian.logbackdemo.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public abstract class BaseController { protected final Logger logger = LoggerFactory.getLogger(BaseController.class); }
<gh_stars>1-10 <?hh namespace Waffle\Tests\Container\Asset; class Bar { protected $something; public function setSomething($something) { $this->something = $something; } }
public class AdsAllocation { private static AdsAllocation instance = null; private static double mainLinePriceThreshold = 4.5; private AdsAllocation() { // Private constructor to prevent instantiation } public static AdsAllocation getInstance() { if (instance == null) { instance = new AdsAllocation(); } return instance; } public static void setMainLinePriceThreshold(double threshold) { mainLinePriceThreshold = threshold; } public boolean allocateAd(double adPrice) { return adPrice >= mainLinePriceThreshold; } }
<reponame>nabeelkhan/Oracle-DBA-Life REM FILE NAME: db_tgrnt.sql REM LOCATION: Security Administration\Reports REM FUNCTION: Report on database table or procedure grants given to a user REM TESTED ON: 7.3.3.5, 8.0.4.1, 8.1.5, 8.1.7, 9.0.1 REM PLATFORM: non-specific REM REQUIRES: dba_tab_privs, dba_objects REM REM This is a part of the Knowledge Xpert for Oracle Administration library. REM Copyright (C) 2001 Quest Software REM All rights reserved. REM REM******************** Knowledge Xpert for Oracle Administration ******************** COLUMN table_name format a16 heading 'Table or|Procedure' COLUMN grantee format a16 heading 'Role or|User' COLUMN privilege format a10 heading 'Granted|Privilege' COLUMN object_type heading 'Type of|Object' ACCEPT user prompt 'Enter user name: ' SET lines 80 feedback off verify off echo off @title80 'Table and Procedure Grants by User/Role' BREAK on object_type on grantee on table_name SPOOL rep_out\db_tgrnt SELECT grantee, table_name, PRIVILEGE, object_type FROM dba_tab_privs a, dba_objects b WHERE grantee LIKE UPPER ('%&user%') AND a.owner = b.owner AND a.table_name = b.object_name ORDER BY 4, 1, 2 / SPOOL off SET feedback on verify on CLEAR columns CLEAR breaks TTITLE off
#! /bin/bash IMAGE="lpbelliot/surfer_static" VERSION="latest" SCRIPT_PATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" docker build -t ${IMAGE}:${VERSION} $SCRIPT_PATH/../ docker push ${IMAGE}:${VERSION} kubectl rollout restart deployment \ lp-static-deployment \ cba-static-deployment \ -n surfer-static
#!/bin/bash NBARGS=$# if [ "$NBARGS" != "1" ]; then echo "usage: $0 <test_number>" exit 1 fi TEST_NUMBER=$1 touch /tmp/test_voxind ./run.sh $TEST_NUMBER & echo "type: pushd ../../build/rfs/usr/bin export LD_LIBRARY_PATH=../lib/x86_64-linux-gnu sudo gdb -p \$(pidof voxind) rm /tmp/test_voxind "
import React, { useState } from 'react'; const Counter = ({n}) => { const [count, setCount] = useState(0); const increment = () => { if (count < n) { setCount(count + 1); } }; return ( <div> <h3>Count: {count}</h3> <button onClick={increment}>Increment</button> </div> ); }; export default Counter;
//generate a set of random points let points = []; let numPoints = 10; for (let i=0; i<numPoints; i++) { points.push({ x: Math.random()*canvas.width, y: Math.random()*canvas.height }); } //draw the points on canvas let context = canvas.getContext('2d'); for (let i=0; i<points.length; i++) { context.fillRect(points[i].x, points[i].y, 5, 5); }
<reponame>PedroArthurB99/orange-talents-08-template-transacao package br.com.orange.transacoes.transacao; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.UUID; public interface TransacaoRepository extends JpaRepository<Transacao, UUID> { Boolean existsByNumero(String numero); List<Transacao> findTop10ByCartaoNumeroOrderByEfetivadaEmAsc(String numero); }
starttime=`date +%s` video_list_txt='../AIC20_track1/Dataset_A/list_video_id.txt' video_id_list=() while read -r line || [[ -n "$line" ]]; do stringarray=($line) video=${stringarray[1]} video_name=${video%%.*} video_id_list+=(${video_name}) done < ${video_list_txt} tmp_fifofile="/tmp/$$.fifo" mkfifo $tmp_fifofile exec 6<>$tmp_fifofile thread_num=31 for ((i=0;i<${thread_num};i++)); do echo done >&6 for i in "${video_id_list[@]}"; do read -u6 { echo ${i} #python count.py ${i} python counting.py ${i} echo >&6 } & done wait endtime=`date +%s` echo "TIME : `expr $endtime - $starttime` s" exec 6>&- exit
package ua.kata; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutableTriple; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; class NestedJoinsTest { private NestedJoins<Integer, String> nestedJoins; @BeforeEach void setUp() { nestedJoins = new NestedJoins<>(); } @Test void resultStreamIsEmpty_whenJoinLeftTwoEmptyStreams() throws Exception { nestedJoins.joinLeft(Flux.empty(), Flux.empty()) .as(StepVerifier::create) .verifyComplete(); } @Test void resultStreamHasNullsOnRight_whenJoinLeftNonemptyAndEmptyStreams() throws Exception { nestedJoins.joinLeft( Flux.create( emitter -> emitter .next(new ImmutablePair<>(1, "l1")) .next(new ImmutablePair<>(2, "l2")) .next(new ImmutablePair<>(3, "l3")) .complete() ), Flux.empty() ).as(StepVerifier::create) .expectNext(new ImmutableTriple<>(1, "l1", null)) .expectNext(new ImmutableTriple<>(2, "l2", null)) .expectNext(new ImmutableTriple<>(3, "l3", null)) .verifyComplete(); } @Test void resultStreamHasValuesOnRight_forCorrespondingKeys_whenJoinLeftTwoNonemptyStreams() throws Exception { nestedJoins.joinLeft( Flux.create( emitter -> emitter .next(new ImmutablePair<>(1, "l1")) .next(new ImmutablePair<>(2, "l2")) .next(new ImmutablePair<>(3, "l3")) .complete() ), Flux.create( emitter -> emitter .next(new ImmutablePair<>(1, "r1")) .next(new ImmutablePair<>(3, "r3")) .complete() ) ).as(StepVerifier::create) .expectNext(new ImmutableTriple<>(1, "l1", "r1")) .expectNext(new ImmutableTriple<>(2, "l2", null)) .expectNext(new ImmutableTriple<>(3, "l3", "r3")) .verifyComplete(); } @Test void resultStreamIsEmpty_whenJoinRightTwoEmptyStreams() throws Exception { nestedJoins.joinRight(Flux.empty(), Flux.empty()) .as(StepVerifier::create) .verifyComplete(); } @Test void resultStreamHasNullsOnLeft_whenJoinRightTwoEmptyAndNonemptyStreams() throws Exception { nestedJoins.joinRight( Flux.empty(), Flux.create( emitter -> emitter .next(new ImmutablePair<>(1, "r1")) .next(new ImmutablePair<>(2, "r2")) .next(new ImmutablePair<>(3, "r3")) .complete() ) ).as(StepVerifier::create) .expectNext(new ImmutableTriple<>(1, null, "r1")) .expectNext(new ImmutableTriple<>(2, null, "r2")) .expectNext(new ImmutableTriple<>(3, null, "r3")) .verifyComplete(); } @Test void resultStreamHasValuesOnLeft_forCorrespondingKeys_whenJoinRightTwoNonemptyStreams() throws Exception { nestedJoins.joinRight( Flux.create( emitter -> emitter .next(new ImmutablePair<>(1, "l1")) .next(new ImmutablePair<>(3, "l3")) .complete() ), Flux.create( emitter -> emitter .next(new ImmutablePair<>(1, "r1")) .next(new ImmutablePair<>(2, "r2")) .next(new ImmutablePair<>(3, "r3")) .complete() ) ).as(StepVerifier::create) .expectNext(new ImmutableTriple<>(1, "l1", "r1")) .expectNext(new ImmutableTriple<>(2, null, "r2")) .expectNext(new ImmutableTriple<>(3, "l3", "r3")) .verifyComplete(); } }
sudo docker rm -f sim2real_client sudo docker run -id --gpus all --name sim2real_client --network host \ --cpus=5.6 -m 8192M \ --privileged -v /dev:/dev -e DISPLAY=$DISPLAY -e QT_X11_NO_MITSHM=1 \ -v /dev/bus/usb:/dev/bus/usb \ -v /dev/video0:/dev/video0 \ -v /dev/video1:/dev/video1 \ -v /dev/video2:/dev/video2 \ -v /dev/video3:/dev/video3 \ -v /dev/video4:/dev/video4 \ -v /dev/video5:/dev/video5 \ -v /tmp/.X11-unix:/tmp/.X11-unix \ -v $HOME/Desktop/shared:/shared \ rmus2022/client:v1.0.0 sudo xhost +
import React from "react" const SoftSkills = ({ style }) => { return ( <div style={style}> <h3>SOFT SKILLS</h3> <ul> <li>Public Speaking</li> <li>Independent</li> <li>Self Motivated</li> <li>Self Taught</li> <li>Technical Writing</li> <li>Expository Writing</li> <li>Accountability</li> </ul> </div> ) } export default SoftSkills
#!/usr/bin/env bash set -euo pipefail VERSION=$(cat azure-application-insights-archives/version) cp azure-application-insights-archives/applicationinsights-agent-*.jar repository/azure-application-insights-$VERSION.jar cp azure-application-insights-archives/version repository/version
<gh_stars>0 const secret = process.env.JWT_SECRET
# Required variables # - client_user # - client_pwd # - security_enabled # - monitoring_enabled # - BIND_TO_ALL # - ES_HOST # - CURL_AUTH function setup_grafana_dashboard() { GRAFANA_BASIC_AUTH="" if [ "$security_enabled" == "true" ]; then GRAFANA_BASIC_AUTH=" --user $client_user:$client_pwd " fi while true; do echo "Waiting for grafana to become available..." if curl $GRAFANA_BASIC_AUTH --output /dev/null --fail http://localhost:3000; then break; fi sleep 5 done cat <<EOF >>/tmp/grafana-datasource.json { "name": "Elasticsearch Monitor", "type": "elasticsearch", "typeLogoUrl": "public/app/plugins/datasource/elasticsearch/img/elasticsearch.svg", "access": "proxy", "url": "$ES_HOST", "password": "", "user": "", "database": "[.monitoring-es-*-]YYYY.MM.DD", "isDefault": true, "jsonData": { "esVersion": 70, "interval": "Daily", "logLevelField": "", "logMessageField": "", "maxConcurrentShardRequests": 5, "timeField": "timestamp" }, "readOnly": false, EOF if [ "$security_enabled" == "true" ]; then cat <<EOF >>/tmp/grafana-datasource.json "basicAuth": true, "basicAuthUser": "$client_user", "secureJsonData": { "basicAuthPassword": "$client_pwd" } } EOF else echo '"basicAuth": false }' >> /tmp/grafana-datasource.json; fi curl $GRAFANA_BASIC_AUTH -XPOST -H 'Content-Type: application/json' localhost:3000/api/datasources -d @/tmp/grafana-datasource.json rm /tmp/grafana-datasource.json if [ -f /opt/grafana-dashboard.json ]; then echo '{ "meta": {"isStarred": true}, "dashboard":' > /tmp/grafana-dashboard.json cat /opt/grafana-dashboard.json | jq -r 'del(.uid) | del(.id)' >> /tmp/grafana-dashboard.json echo '}' >> /tmp/grafana-dashboard.json curl $GRAFANA_BASIC_AUTH -XPOST -H 'Content-Type: application/json' localhost:3000/api/dashboards/db -d @/tmp/grafana-dashboard.json fi } # Setup x-pack security also on Kibana configs where applicable if [ -f "/etc/kibana/kibana.yml" ]; then if [ "$BIND_TO_ALL" == "true" ]; then echo "server.host: 0.0.0.0" | sudo tee -a /etc/kibana/kibana.yml else echo "server.host: $(hostname -i)" | sudo tee -a /etc/kibana/kibana.yml fi echo "xpack.security.enabled: $security_enabled" | sudo tee -a /etc/kibana/kibana.yml echo "xpack.monitoring.enabled: $monitoring_enabled" | sudo tee -a /etc/kibana/kibana.yml if [ "$security_enabled" == "true" ]; then echo "elasticsearch.username: \"kibana\"" | sudo tee -a /etc/kibana/kibana.yml echo "elasticsearch.password: \"$client_pwd\"" | sudo tee -a /etc/kibana/kibana.yml fi systemctl daemon-reload systemctl enable kibana.service sudo service kibana restart fi if [ -f "/etc/grafana/grafana.ini" ]; then sudo rm /etc/grafana/grafana.ini if [ "$security_enabled" == "true" ]; then cat <<EOF >>/etc/grafana/grafana.ini [security] admin_user = $client_user admin_password = $client_pwd EOF else cat <<EOF >>/etc/grafana/grafana.ini [auth.anonymous] enabled = true org_name = Main Org. org_role = Admin EOF fi sudo /bin/systemctl daemon-reload sudo /bin/systemctl enable grafana-server.service sudo service grafana-server start setup_grafana_dashboard; fi if [ -d "/usr/share/cerebro/" ]; then CEREBRO_CONFIG_PATH="$(echo /usr/share/cerebro/cerebro*/conf/application.conf)" if [ "$security_enabled" == "true" ]; then sudo sed -i "s/.{?BASIC_AUTH_USER}/$client_user/ig" $CEREBRO_CONFIG_PATH sudo sed -i "s/.{?BASIC_AUTH_PWD}/$client_pwd/ig" $CEREBRO_CONFIG_PATH sudo sed -i 's/.{?AUTH_TYPE}/"basic"/ig' $CEREBRO_CONFIG_PATH fi sudo systemctl restart cerebro fi
<gh_stars>1-10 $(function () { //Form Wizard 2 var currentStep_2 = 1; $('.wizard-demo li a').click(function() { alert('You must enter your information') //return false; }); $('#formValidate2').parsley( { listeners: { onFormSubmit: function ( isFormValid, event ) { if(isFormValid) { alert('Your message has been sent'); return false; } } }}); $('#formWizard2').parsley( { listeners: { onFieldValidate: function ( elem ) { // if field is not visible, do not apply Parsley validation! if ( !$( elem ).is( ':visible' ) ) { return true; } return false; }, onFormSubmit: function ( isFormValid, event ) { if(isFormValid) { currentStep_2++; if(currentStep_2 == 2) { $('#account_no').bind('input propertychange', function() { var data = $('#account_no').val(); var number = data.substring(1,); if (data.charAt(0) === "U"){ if (isNaN(number)) { var timer; $('#account_no').val(data); clearTimeout(timer); timer = setTimeout(function(){ $('#account_no').val(data.slice(0,-1)) },200); } } else { var timer; $('#account_no').val(data); clearTimeout(timer); timer = setTimeout(function(){ $('#account_no').val("U") },200); } }); $('#wizardDemo2 li:eq(1) a').tab('show'); $('#prevStep2').attr('disabled',false); $('#prevStep2').removeClass('disabled'); } else if(currentStep_2 == 3) { $('#wizardDemo2 li:eq(2) a').tab('show'); } else if(currentStep_2 == 4) { function confirmDetails() { var unit = $('#units').val(); var totalUnit = $('#total_units').val(); var wallet = $('#wallet').val(); var paymentMethod = $('#payment_method').val(); var accountNo = $('#account_no').val(); var accountName = $('#account_name').val(); $('#unit_field').html(unit); $('#total_unit_field').html(totalUnit); $('#wallet_id_field').html(wallet); $('#perfect_money_account_no').html(accountNo); $('#perfect_money_account_name').html(accountName); if(paymentMethod == "1"){ paymentMethod = "Internet Bank Transfer"; }else if (paymentMethod == "2"){ paymentMethod = "Bank Deposit" }else if (paymentMethod == "3"){ paymentMethod = "Short Code" } $('#payment_method_field').html(paymentMethod) } confirmDetails(); $('#wizardDemo2 li:eq(3) a').tab('show'); $('#nextStep2').attr('disabled',true); $('#nextStep2').addClass('disabled'); } else { return true; } return false; } } }}); $('#prevStep2').click(function() { currentStep_2--; if(currentStep_2 == 1) { $('#wizardDemo2 li:eq(0) a').tab('show'); $('#prevStep2').attr('disabled',true); $('#prevStep2').addClass('disabled'); } else if(currentStep_2 == 2) { $('#wizardDemo2 li:eq(1) a').tab('show'); } else if(currentStep_2 == 3) { $('#wizardDemo2 li:eq(2) a').tab('show'); $('#nextStep2').attr('disabled',false); $('#nextStep2').removeClass('disabled'); } return false; }); });
def getMaxExpArray(max_precision): maxExpArray = [0] * (max_precision + 1) maxExpArray[0] = 0x386bfdba29 for i in range(1, max_precision + 1): maxExpArray[i] = 0x386bfdba29 + (0x38d1b71758 * i) return maxExpArray
''' File : rtdg.py Function : create a dictionary of faker functions Authors : Gouthaman,Aditya,kalaiyarasu ''' # import Faker from faker import Faker # initializing a pseudo-random number generator Faker.seed(20) fake = Faker() # dictionaries containing faker functions address = {'address': fake.address, 'city': fake.city, 'country': fake.country, 'postcode': fake.postcode} creditcard = {'card_no': fake.credit_card_number, 'expire_date': fake.credit_card_expire, 'security code': fake.credit_card_security_code} automotive = {'license_plate': fake.license_plate} bank = {'country': fake.bank_country, 'swift11': fake.swift11, 'iban': fake.iban} date_time = {'am_pm': fake.am_pm, 'date': fake.date, 'month': fake.month} file = {'file_extension': fake.file_extension, 'file_name': fake.file_name, 'file_path': fake.file_path} geo = {'coordinate': fake.coordinate, 'latitude': fake.latitude, 'location_on_land': fake.location_on_land, 'longitude': fake.longitude} color = {'color_name': fake.color_name, 'hex_color': fake.hex_color, 'rgb_css_color': fake.rgb_css_color} internet = {'ascii_email': fake.ascii_email, 'ascii_free_email': fake.ascii_free_email, 'ascii_safe_email': fake.ascii_safe_email, 'company_email': fake.company_email, 'dga': fake.dga, 'domain_name': fake.domain_name} isbn = {'isbn10': fake.isbn10, 'isbn13': fake.isbn13} job = {'job': fake.job} lorem = {'paragraph': fake.paragraph, 'paragraphs': fake.paragraphs, 'sentence': fake.sentence, 'sentences': fake.sentences, 'text': fake.text, 'texts': fake.texts, 'word': fake.word, 'words': fake.words} misc = {'binary': fake.binary, 'boolean': fake.boolean, 'csv': fake.csv, 'dsv': fake.dsv, 'fixed_width': fake.fixed_width, 'json': fake.json, 'md5': fake.md5, 'null_boolean': fake.null_boolean, 'password': <PASSWORD>} person = {'first_name': fake.first_name, 'first_name_female': fake.first_name_female, 'first_name_male': fake.first_name_male, 'language_name': fake.language_name, 'last_name': fake.last_name, 'name': fake.name} phone_number = {'phone_number': fake.phone_number, 'msisdn': fake.msisdn} profile = {'simple_profile': fake.simple_profile} python1 = {'pybool': fake.pybool, 'pydecimal': fake.pydecimal, 'pydict': fake.pydict, 'pyint': fake.pyint, 'pyiterable': fake.pyiterable} ssn = {'ssn': fake.ssn} user_agent = {'chrome': fake.chrome, 'android_platform_token': fake.android_platform_token, 'firefox': fake.firefox, 'linux_processor': fake.linux_processor} # dictionary containing all the groups all_func = {'address': address, 'creditcard': creditcard, 'automotive': automotive, 'bank': bank, 'date_time': date_time, 'file': file, 'geo': geo, 'color': color, 'internet': internet, 'isbn': isbn, 'job': job, 'lorem': lorem, 'misc': misc, 'phone_number': phone_number, 'person': person, 'python': python1, 'ssn': ssn, 'profile': profile, 'user_agent': user_agent}
def solution(xk, equation): x, k = map(int, xk.split()) x_value = x ** k result = eval(equation.replace('x', str(x_value))) return result
function countWordOccurrences(inputString, targetWord) { // Convert the input string and target word to lowercase for case-insensitive comparison const lowerCaseInput = inputString.toLowerCase(); const lowerCaseTarget = targetWord.toLowerCase(); // Use a regular expression to find all whole word matches of the target word const regex = new RegExp(`\\b${lowerCaseTarget}\\b`, 'g'); const matches = lowerCaseInput.match(regex); // If matches are found, return the total count; otherwise, return 0 return matches ? matches.length : 0; } export default countWordOccurrences;
import java.util.ArrayList; import java.util.List; public abstract class TransList<U, T> { private List<T> list; public TransList(List<T> list) { this.list = list; } public abstract U trans(T v); public List<U> transform() { List<U> transformedList = new ArrayList<>(); for (T element : list) { transformedList.add(trans(element)); } return transformedList; } }
<filename>src/modules/link/link.mapper.ts import {Link} from "./link.entity"; function mapActiveValue(isActive: number): string { switch (isActive) { case 1: return "ACTIVE" case -1: return "DEPRECATED" case -2: return "LOCKED" case -3: return "DELETED" } } module.exports = { basic: function (_link: Link) { const newLink = (({ id, short, original, nrOfCalls, isActive, iat, }) => ({ id, short, original, nrOfCalls: +nrOfCalls ? +nrOfCalls : 0, status: mapActiveValue(isActive), iat, })) (_link); return newLink; }, creation: function (_link: Link) { const newLink = (({ id, short, }) => ({ id, short, })) (_link); return newLink; }, };
<filename>extern/glow-extras/geometry/glow-extras/geometry/CoordFrame.cc #include "CoordFrame.hh" // empty
# frozen_string_literal: true require 'rails_helper' RSpec.describe OffersHelper, type: :helper do describe '#offer_logo_url' do context 'when offer has sponsor' do it "returns sponsor's logo URL in thumb version" do offer = FactoryBot.build(:offer, :with_sponsor) url = helper.offer_logo_url(offer) expect(url).to include("/sponsor/logo/#{offer.sponsor.id}") end end context 'when offer has no sponsor' do it 'returns default URL for logo' do offer = FactoryBot.build(:offer) url = helper.offer_logo_url(offer) expect(url).to eq(LogoUploader.new.default_url) end end end end
package de.judgeman.H2SpringFx.Tests.ServiceTests; import de.judgeman.H2SpringFx.HelperClasses.ViewRootAndControllerPair; import de.judgeman.H2SpringFx.Services.ViewService; import de.judgeman.H2SpringFx.Tests.HelperClasses.UITestFxApp; import de.judgeman.H2SpringFx.Tests.HelperClasses.UITestingService; import de.judgeman.H2SpringFx.ViewControllers.DialogControllers.InformationDialogController; import de.judgeman.H2SpringFx.ViewControllers.MainViewController; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; import org.junit.experimental.categories.Category; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.loadui.testfx.GuiTest; import org.loadui.testfx.categories.TestFX; import org.loadui.testfx.utils.FXTestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.TestPropertySource; import java.net.URL; import java.util.concurrent.atomic.AtomicBoolean; @SpringBootTest @TestPropertySource(locations="classpath:test.properties") @Category(TestFX.class) public class ViewServiceTests extends GuiTest { public static final String pathToTestXML = "/TestFXML.fxml"; @BeforeAll public static void setupTestGUI() { // avoid AWT headless exception System.setProperty("java.awt.headless", "false"); if (!UITestFxApp.isAppRunning) { FXTestUtils.launchApp(UITestFxApp.class); } } @Autowired private ConfigurableApplicationContext springContext; @Autowired private ViewService viewService; @Test public void loadTestFXMLFileTest() { URL url = viewService.GetUrlForView("/TestFXML.fxml"); Assertions.assertNotNull(url); } @Test public void loadMissingFXMLFile() { ViewRootAndControllerPair pair = viewService.getRootAndViewControllerFromFXML("/MissingFXML.fxml"); Assertions.assertNull(pair); } @Test public void setStyleToStageTest() throws Exception { FXTestUtils.invokeAndWait(() -> { Stage stage = new Stage(); Scene scene = null; scene = new Scene(viewService.getRootElementFromFXML(pathToTestXML)); stage.setScene(scene); Assertions.assertEquals(0, stage.getScene().getStylesheets().size()); viewService.setDefaultStyleCss(stage); Assertions.assertEquals(1, stage.getScene().getStylesheets().size()); URL resourceUrl = getClass().getResource(ViewService.FILE_PATH_DEFAULT_STYLE_CSS); Assertions.assertEquals(resourceUrl.toString(), stage.getScene().getStylesheets().get(0)); }, 10 ); } @Test public void registerPrimaryStageTest() throws Exception { FXTestUtils.invokeAndWait(() -> { Stage stage = new Stage(); viewService.registerPrimaryStage(stage); Assertions.assertEquals(stage, viewService.getPrimaryStage()); }, 10 ); } @Test public void restoreLastScenePositionAndSizeTest() throws Exception { FXTestUtils.invokeAndWait(() -> { // TODO: save last position Stage stage = new Stage(); viewService.restoreScenePositionAndSize(stage); // TODO: assert saved last position on the stage object }, 10 ); } @Test public void showInformationDialogTest() throws Exception { AtomicBoolean callBackCalled = new AtomicBoolean(false); FXTestUtils.invokeAndWait(() -> { MainViewController mainViewController = UITestingService.getNewMainController(viewService); Pane glassPane = mainViewController.getGlassPane(); Pane contentPane = mainViewController.getContentPane(); Assertions.assertEquals(0, glassPane.getChildren().size()); Assertions.assertEquals(1, contentPane.getChildren().size()); viewService.registerMainViewController(mainViewController); viewService.showInformationDialog("Test", "Test information"); Assertions.assertEquals(1, glassPane.getChildren().size()); viewService.dismissDialog(e -> { Assertions.assertEquals(0, glassPane.getChildren().size()); callBackCalled.set(true); }); UITestingService.waitForAnimationFinished(5, callBackCalled); }, 10 ); Assertions.assertTrue(callBackCalled.get()); } @Test public void showInformationDialogAndDismissWithOkButtonTest() throws Exception { AtomicBoolean callBackCalled = new AtomicBoolean(false); FXTestUtils.invokeAndWait(() -> { ViewRootAndControllerPair pair = null; MainViewController mainViewController = UITestingService.getNewMainController(viewService); Pane glassPane = mainViewController.getGlassPane(); viewService.registerMainViewController(mainViewController); ViewRootAndControllerPair dialogPair = null; dialogPair = viewService.showInformationDialog("Test", "Test information"); Assertions.assertEquals(1, glassPane.getChildren().size()); Assertions.assertTrue(dialogPair.getViewController() instanceof InformationDialogController); ((InformationDialogController) dialogPair.getViewController()).setCallBack(event -> { Assertions.assertEquals(0, glassPane.getChildren().size()); callBackCalled.set(true); }); ((InformationDialogController) dialogPair.getViewController()).okButtonClicked(); UITestingService.waitForAnimationFinished(5, callBackCalled); }, 10 ); Assertions.assertTrue(callBackCalled.get()); } @Test public void tryDismissDialogWithoutElementsOnGlassPane() { AtomicBoolean callBackCalled = new AtomicBoolean(false); MainViewController mainViewController = UITestingService.getNewMainController(viewService); Pane glassPane = mainViewController.getGlassPane(); Assertions.assertEquals(0, glassPane.getChildren().size()); viewService.registerMainViewController(mainViewController); viewService.dismissDialog(e -> { Assertions.assertEquals(0, glassPane.getChildren().size()); callBackCalled.set(true); }); UITestingService.waitForAnimationFinished(5, callBackCalled); Assertions.assertTrue(callBackCalled.get()); } @Test public void tryDismissDialogWithoutCallback() { MainViewController mainViewController = new MainViewController(); Pane glassPane = new Pane(); Pane overLayerPane = new Pane(); mainViewController.setGlassPane(glassPane); mainViewController.setDialogOverLayer(overLayerPane); viewService.registerMainViewController(mainViewController); viewService.showInformationDialog("Test", "Test information"); Assertions.assertEquals(1, glassPane.getChildren().size()); viewService.dismissDialog(null); UITestingService.waitForAnimationFinished(1); Assertions.assertEquals(0, glassPane.getChildren().size()); } @Override protected Parent getRootNode() { return null; } }
#!/bin/sh XSOCK=/tmp/.X11-unix XAUTH=/tmp/.docker.xauth touch $XAUTH xauth nlist $DISPLAY | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge - docker run --privileged -it \ --volume=$XSOCK:$XSOCK:rw \ --volume=$XAUTH:$XAUTH:rw \ --volume=/dev:/dev:rw \ --volume=`pwd`/share:/home/jetpack/share:rw \ --shm-size=1gb \ --env="XAUTHORITY=${XAUTH}" \ --env="DISPLAY=${DISPLAY}" \ --env=TERM=xterm-256color \ --env=QT_X11_NO_MITSHM=1 \ --net=host \ -u "jetpack" \ jetpack:3.2 \ bash
<filename>src/app/modules/game/services/hide-content.service.ts import {Injectable} from '@angular/core'; import {MatSidenav} from '@angular/material/sidenav'; @Injectable({ providedIn: 'root', }) export class HideContentService { private sidenavArray = []; public setSidenav(sidenav: MatSidenav, id: string): void { this.sidenavArray.push({sidenav, id}); } public toggle(id: string): void { const currentSidenav = this.sidenavArray.find((elem) => elem.id === id); currentSidenav.sidenav.toggle(); } public removeSidenav(id: string) { this.sidenavArray = this.sidenavArray.filter(elem => elem.id !== id); } }
curl -X GET 'http://localhost:3000/'
<gh_stars>0 // // <%- packageName %> // // Copyright (C) <%- copyrightYear %> <%- copyrightHolder %> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public // License along with this program. If not, see // <https://www.gnu.org/licenses/>. //
// Copyright 2019 Grabtaxi Holdings PTE LTE (GRAB), All rights reserved. // Use of this source code is governed by an MIT-style license that can be found in the LICENSE file package async import ( "context" "errors" "fmt" "testing" "github.com/stretchr/testify/assert" ) func TestForkJoin(t *testing.T) { first := NewTask(func(context.Context) (interface{}, error) { return 1, nil }) second := NewTask(func(context.Context) (interface{}, error) { return nil, errors.New("some error") }) third := NewTask(func(context.Context) (interface{}, error) { return 3, nil }) ForkJoin(context.Background(), []Task{first, second, third}) outcome1, error1 := first.Outcome() assert.Equal(t, 1, outcome1) assert.Nil(t, error1) outcome2, error2 := second.Outcome() assert.Nil(t, outcome2) assert.NotNil(t, error2) outcome3, error3 := third.Outcome() assert.Equal(t, 3, outcome3) assert.Nil(t, error3) } func ExampleForkJoin() { first := NewTask(func(context.Context) (interface{}, error) { return 1, nil }) second := NewTask(func(context.Context) (interface{}, error) { return nil, errors.New("some error") }) ForkJoin(context.Background(), []Task{first, second}) fmt.Println(first.Outcome()) fmt.Println(second.Outcome()) // Output: // 1 <nil> // <nil> some error }
<gh_stars>0 class SitesController < ApplicationController ## Sites Controller directs to the root page which does not require security. The only concern is that logged in users should not be able to logon again # before_action :is_authenticated? # before_filter :is_authenticated?, :except => :index def index end end
<reponame>caranzargar/platzi-store<gh_stars>0 import { NestFactory } from '@nestjs/core'; import { ValidationPipe } from '@nestjs/common'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.useGlobalPipes( new ValidationPipe({ whitelist: true, // Eliminar los parámetros recibidos que no estén definidos en los DTO forbidNonWhitelisted: true // Informar a la API que se está enviando un atributo no válido }) ); //Usar el Validation pipe de forma global await app.listen(3000); } bootstrap();
class class_a { private: int width, high; public: class_a(int _w, int _h) : width(_w), high(_h) {} // Constructor to initialize width and high ~class_a() {} // Destructor to release any allocated resources void print_info(void) { // Member function to print width and high std::cout << "Width: " << width << ", High: " << high << std::endl; } }; class class_b { private: // Add necessary data members for class_b public: // Add necessary member functions for class_b based on the problem requirements };
<filename>src/core/index.js<gh_stars>0 /** * @namespace PIXI */ export * from './const'; export * from './math'; import * as utils from './utils'; import * as ticker from './ticker'; import settings from './settings'; import CanvasRenderer from './renderers/canvas/CanvasRenderer'; import WebGLRenderer from './renderers/webgl/WebGLRenderer'; export { settings, utils, ticker, CanvasRenderer, WebGLRenderer }; export { default as glCore } from 'pixi-gl-core'; export { default as Bounds } from './display/Bounds'; export { default as DisplayObject } from './display/DisplayObject'; export { default as Container } from './display/Container'; export { default as Transform } from './display/Transform'; export { default as TransformStatic } from './display/TransformStatic'; export { default as TransformBase } from './display/TransformBase'; export { default as Sprite } from './sprites/Sprite'; export { default as CanvasSpriteRenderer } from './sprites/canvas/CanvasSpriteRenderer'; export { default as CanvasTinter } from './sprites/canvas/CanvasTinter'; export { default as SpriteRenderer } from './sprites/webgl/SpriteRenderer'; export { default as Text } from './text/Text'; export { default as TextStyle } from './text/TextStyle'; export { default as Graphics } from './graphics/Graphics'; export { default as GraphicsData } from './graphics/GraphicsData'; export { default as GraphicsRenderer } from './graphics/webgl/GraphicsRenderer'; export { default as CanvasGraphicsRenderer } from './graphics/canvas/CanvasGraphicsRenderer'; export { default as Texture } from './textures/Texture'; export { default as BaseTexture } from './textures/BaseTexture'; export { default as RenderTexture } from './textures/RenderTexture'; export { default as BaseRenderTexture } from './textures/BaseRenderTexture'; export { default as VideoBaseTexture } from './textures/VideoBaseTexture'; export { default as TextureUvs } from './textures/TextureUvs'; export { default as CanvasRenderTarget } from './renderers/canvas/utils/CanvasRenderTarget'; export { default as Shader } from './Shader'; export { default as WebGLManager } from './renderers/webgl/managers/WebGLManager'; export { default as ObjectRenderer } from './renderers/webgl/utils/ObjectRenderer'; export { default as RenderTarget } from './renderers/webgl/utils/RenderTarget'; export { default as Quad } from './renderers/webgl/utils/Quad'; export { default as SpriteMaskFilter } from './renderers/webgl/filters/spriteMask/SpriteMaskFilter'; export { default as Filter } from './renderers/webgl/filters/Filter'; /** * This helper function will automatically detect which renderer you should be using. * WebGL is the preferred renderer as it is a lot faster. If webGL is not supported by * the browser then this function will return a canvas renderer * * @memberof PIXI * @function autoDetectRenderer * @param {number} [width=800] - the width of the renderers view * @param {number} [height=600] - the height of the renderers view * @param {object} [options] - The optional renderer parameters * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional * @param {boolean} [options.transparent=false] - If the render view is transparent, default false * @param {boolean} [options.antialias=false] - sets antialias (only applicable in chrome at the moment) * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you * need to call toDataUrl on the webgl context * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 * @param {boolean} [noWebGL=false] - prevents selection of WebGL renderer, even if such is present * @return {PIXI.WebGLRenderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer */ export function autoDetectRenderer(width = 800, height = 600, options, noWebGL) { if (!noWebGL && utils.isWebGLSupported()) { return new WebGLRenderer(width, height, options); } return new CanvasRenderer(width, height, options); }
#!/bin/bash -e cdi=$1 cdi="${cdi##*/}" echo $cdi source ./hack/build/config.sh source ./cluster/gocli.sh CDI_NAMESPACE=${CDI_NAMESPACE:-cdi} # Set controller verbosity to 3 for functional tests. export VERBOSITY=3 registry_port=$($gocli ports registry | tr -d '\r') registry=localhost:$registry_port DOCKER_REPO=${registry} make docker push DOCKER_REPO="registry:5000" PULL_POLICY=$(getTestPullPolicy) make manifests # Make sure that all nodes use the newest images container="" container_alias="" images="${@:-${DOCKER_IMAGES}}" for arg in $images; do name=$(basename $arg) container="${container} registry:5000/${name}:latest" done for i in $(seq 1 ${KUBEVIRT_NUM_NODES}); do echo "node$(printf "%02d" ${i})" "echo \"${container}\" | xargs \-\-max-args=1 sudo docker pull" ./cluster/cli.sh ssh "node$(printf "%02d" ${i})" "echo \"${container}\" | xargs \-\-max-args=1 sudo docker pull" # Temporary until image is updated with provisioner that sets this field # This field is required by buildah tool ./cluster/cli.sh ssh "node$(printf "%02d" ${i})" "sudo sysctl -w user.max_user_namespaces=1024" done # Install CDI ./cluster/kubectl.sh apply -f ./manifests/generated/cdi-operator.yaml ./cluster/kubectl.sh apply -f ./manifests/generated/cdi-operator-cr.yaml ./cluster/kubectl.sh wait cdis.cdi.kubevirt.io/cdi --for=condition=running --timeout=120s # Start functional test HTTP server. ./cluster/kubectl.sh apply -f ./manifests/generated/file-host.yaml ./cluster/kubectl.sh apply -f ./manifests/generated/registry-host.yaml
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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. import math import numpy as np from abc import ABCMeta, abstractmethod from datetime import datetime from itertools import groupby from typing import Sequence, Tuple, Optional from qf_lib.backtesting.order.order import Order from qf_lib.common.enums.frequency import Frequency from qf_lib.common.enums.price_field import PriceField from qf_lib.common.enums.security_type import SecurityType from qf_lib.common.tickers.tickers import Ticker from qf_lib.common.utils.dateutils.relative_delta import RelativeDelta from qf_lib.common.utils.logging.qf_parent_logger import qf_logger from qf_lib.data_providers.data_provider import DataProvider class Slippage(metaclass=ABCMeta): """ Base class for slippage models. It can limit the Order's volume. This model needs to know the daily volume of the traded asset, thus it uses the data provider in order to be able to access the volume value for the day. Parameters ---------- data_provider: DataProvider DataProvider component max_volume_share_limit: float, None number from range [0,1] which denotes how big (volume-wise) the Order can be i.e. if it's 0.5 and a daily volume for a given asset is 1,000,000 USD, then max volume of the Order can be 500,000 USD. If not provided, no volume checks are performed. """ def __init__(self, data_provider: DataProvider, max_volume_share_limit: Optional[float] = None): self.max_volume_share_limit = max_volume_share_limit self._data_provider = data_provider self._logger = qf_logger.getChild(self.__class__.__name__) def process_orders(self, date: datetime, orders: Sequence[Order], no_slippage_fill_prices: Sequence[float]) -> \ Tuple[Sequence[float], Sequence[float]]: """ Calculates fill prices and quantities for Orders. For Orders that can't be executed (missing security price, etc.) float("nan") will be returned. Parameters ---------- date: datetime time when the slippage is applied orders: Sequence[Order] sequence of Orders for which the fill price should be calculated no_slippage_fill_prices: Sequence[float] fill prices without a slippage applied. Each fill price corresponds to the Order from `orders` list Returns ------- Tuple[Sequence[float], Sequence[float]] sequence of fill prices (order corresponds to the order of orders provided as an argument of the method), sequence of fill order quantities """ self._check_for_duplicates(date, orders) # Compute the fill volumes for orders if self.max_volume_share_limit is not None: fill_volumes = self._get_fill_volumes(orders, date) else: fill_volumes = np.array([order.quantity for order in orders]) fill_prices = self._get_fill_prices(date, orders, no_slippage_fill_prices, fill_volumes) return fill_prices, fill_volumes @abstractmethod def _get_fill_prices(self, date: datetime, orders: Sequence[Order], no_slippage_fill_prices: Sequence[float], fill_volumes: Sequence[int]) -> Sequence[float]: raise NotImplementedError() def _volumes_traded_today(self, date: datetime, tickers: Sequence[Ticker]) -> Sequence[int]: """ For each ticker return the volume traded today. In case of lacking volume data - 0 is returned. """ start_date = date + RelativeDelta(hour=0, minute=0, second=0, microsecond=0) end_date = start_date + RelativeDelta(days=1) # Look into the future in order to see the total volume traded today volume_df = self._data_provider.get_price(tickers, PriceField.Volume, start_date, end_date, Frequency.DAILY) volume_df = volume_df.fillna(0.0) try: volumes = volume_df.loc[start_date, tickers].values except KeyError: volumes = np.repeat(0, len(tickers)) # Replace negative values with 0 volumes[volumes < 0] = 0 return volumes def _get_fill_volumes(self, orders: Sequence[Order], date: datetime) -> Sequence[float]: """ Compute the fill volumes, where the fill volume for each asset should fulfill the following: abs(fill_volume) <= self.max_volume_share_limit * volume_traded_today """ order_volumes = np.array([order.quantity for order in orders]) tickers = [order.ticker for order in orders] market_volumes = self._volumes_traded_today(date, tickers) max_abs_order_volumes = [volume * self.max_volume_share_limit for volume in market_volumes] abs_order_volumes = np.absolute(order_volumes) abs_fill_volumes = np.minimum(abs_order_volumes, max_abs_order_volumes) fill_volumes = np.copysign(abs_fill_volumes, order_volumes) fill_volumes = np.array([volume if order.ticker.security_type == SecurityType.CRYPTO else float(math.floor(volume)) for volume, order in zip(fill_volumes, orders)]) return fill_volumes def _check_for_duplicates(self, date: datetime, orders: Sequence[Order]): sorted_orders = sorted(orders, key=lambda order: order.ticker) for ticker, orders_group in groupby(sorted_orders, lambda order: order.ticker): orders_list = list(orders_group) if len(orders_list) > 1: self._logger.warning("{} More than one order for ticker {}:".format(date, ticker)) for order in orders_list: self._logger.warning(order)
def div_by_7_not_5(start, end): result = [] for num in range(start, end + 1): if (num % 7 == 0) and (num % 5 != 0): result.append(num) return result
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+512+512-SS/model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+512+512-SS/512+512+512-SS-1 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_sentences_first_third_full --eval_function last_element_eval
import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; import { Document } from 'mongoose'; import { User } from '../../users/schemas/user.schema'; import * as mongoose from 'mongoose'; import { Lift } from './lift.schema'; import { LiftRequest } from './liftRequest.schema'; export type LiftBookingDocument = LiftBooking & Document; @Schema() export class LiftBooking { @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'LiftRequest'}) lift_request_id: LiftRequest; @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true }) user_id: User; @Prop({ type: mongoose.Schema.Types.ObjectId, ref: 'User' ,required: true }) driver_id: User; @Prop({type: Object, required: true }) to: { lat:string, long:string, address:string }; @Prop({type: Object, required: true }) from:{ lat:string, long:string, address:string }; @Prop({ required: true }) passenger: number; @Prop({ required: true }) price: number; @Prop({ required: true ,default: false}) is_virtual: boolean; @Prop({default: ''}) distance: string; @Prop({ type: String, required: true }) date: string; @Prop({ type: String, required: true, default: false }) is_cancle: boolean; @Prop({ type: String, enum: ['user','driver'], }) cancle_by: string; @Prop({ type: String, enum: ['active','completed','inactive'], default: 'inactive' }) status: string; @Prop() created_at: string; @Prop() updated_at: string; } export const LiftBookingSchema = SchemaFactory.createForClass(LiftBooking);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ic_iso_twotone = void 0; var ic_iso_twotone = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M0 0h24v24H0V0z", "fill": "none" }, "children": [] }, { "name": "path", "attribs": { "d": "M19 19V5L5 19h14zm-2-3.5V17h-5v-1.5h5z", "opacity": ".3" }, "children": [] }, { "name": "path", "attribs": { "d": "M12 15.5h5V17h-5zM19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5.5 7.5h2v-2H9v2h2V9H9v2H7.5V9h-2V7.5zM19 19H5L19 5v14z" }, "children": [] }] }; exports.ic_iso_twotone = ic_iso_twotone;
<reponame>rickkas7/DeviceNameHelperRK var searchData= [ ['checkname_2',['checkName',['../class_device_name_helper.html#ab3066ecb65a743809fa6764b6a264f94',1,'DeviceNameHelper']]], ['checkperiod_3',['checkPeriod',['../class_device_name_helper.html#aadd144cff1fb56515f9a009d7bd37c30',1,'DeviceNameHelper']]], ['commonsetup_4',['commonSetup',['../class_device_name_helper.html#af3b3562db7c4e6c053f24ddec44c08c2',1,'DeviceNameHelper']]] ];
import urllib.request import gzip import shutil import os # Define the URL for downloading the GeoLiteCountry database download_url = 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz' # Specify the local directory to save the downloaded and decompressed file local_directory = 'data/' # Ensure the local directory exists or create it if it doesn't os.makedirs(local_directory, exist_ok=True) # Download the database from the specified URL and save it to the local directory downloaded_file_path, _ = urllib.request.urlretrieve(download_url, local_directory + 'GeoIP.dat.gz') # Decompress the downloaded file to obtain the GeoLiteCountry database in its original format with gzip.open(downloaded_file_path, 'rb') as compressed_file: with open(local_directory + 'GeoIP.dat', 'wb') as decompressed_file: shutil.copyfileobj(compressed_file, decompressed_file) print('GeoLiteCountry database downloaded and extracted successfully.')
#!/bin/bash set -e # output some thing to stdout echo "Hello world!" input=f.b if [ ! -e $input ]; then echo "ERROR: input file $input does not exist" 1>&2 exit 1 fi # check that we got the input file cat $input # in the DAX, this job is specified to have an f.c output file echo "Hello world!" >f.c
const countCharacterOccurrences = (string) => { let strArr = string.split(''); let charMap = {}; for (let char of strArr) { charMap[char] = charMap[char] + 1 || 1; } return charMap; }
<gh_stars>0 package cn.wwl.radio.console.impl.gui; public interface TrayMessageCallback { int SINGLE_CLICK = 0; int DOUBLE_CLICK = 1; void clickMessage(int clickType); }
#!/bin/bash # # SPDX-License-Identifier: Apache-2.0 # set -o pipefail set -ev #### # Note: the tape integration suite is being deprecated in favour of cucumber. Please do not add files to this function #### runTape() { export HFC_LOGGING='{"debug":"test/temp/debug.log"}' # Run HSM tests by default E2E_SCRIPT_SUFFIX=-hsm # If the script has been called with noHSM parameter # run test/integration/network-e2e/e2e.js instead of test/integration/network-e2e/e2e-hsm.js if [ $1 ] && [ $1 == 'noHSM' ] then unset E2E_SCRIPT_SUFFIX fi # Tests have to executed in the following order # First run the ca-tests that run good/bad path member registration/enrollment scenarios # The remaining tests re-use the same key value store with the saved user certificates, in order to interact with the network npx tape test/integration/fabric-ca-affiliation-service-tests.js \ test/integration/fabric-ca-identity-service-tests.js \ test/integration/fabric-ca-certificate-service-tests.js \ test/integration/fabric-ca-services-tests.js \ test/integration/e2e.js \ test/integration/network-e2e/e2e${E2E_SCRIPT_SUFFIX}.js \ test/integration/signTransactionOffline.js \ test/integration/query.js \ test/integration/client.js \ test/integration/orderer-channel-tests.js \ test/integration/couchdb-fabricca-tests.js \ test/integration/fileKeyValueStore-fabricca-tests.js \ test/integration/install.js \ test/integration/channel-event-hub.js \ test/integration/upgrade.js \ test/integration/get-config.js \ test/integration/create-configtx-channel.js \ test/integration/e2e/join-channel-copy.js \ test/integration/instantiate.js \ test/integration/e2e/invoke-transaction-copy.js \ test/integration/e2e/query-copy.js \ test/integration/invoke.js \ test/integration/network-config.js \ test/integration/only-admin.js \ test/integration/discovery.js \ test/integration/grpc.js \ | npx tap-colorize } runTape $*
import React, { useState, useEffect } from 'react'; import Marketplace from './abis/Marketplace.json'; import Navbar from './components/Navbar'; import Main from './components/Main'; import './App.css'; import Web3 from 'web3'; function App() { const [account, setAccount] = useState(null); const [marketplace, setMarketplace] = useState(null); const [loading, setLoading] = useState(true); const [products, setProducts] = useState([]); const [productCount, setProductCount] = useState(null); const loadWeb3 = async () => { if (window.ethereum) { window.web3 = new Web3(window.ethereum); await window.ethereum.enable(); } else if (window.web3) { window.web3 = new Web3(window.web3.currentProvider); } else { window.alert('Non-Ethereum browser detected. You should consider trying MetaMask!'); } }; const loadBlockchainData = async () => { const web3 = window.web3; const accounts = await web3.eth.getAccounts(); setAccount(accounts[0]); const networkID = await web3.eth.net.getId(); const networkData = Marketplace.networks[networkID]; if (networkData) { const _marketplace = new web3.eth.Contract(Marketplace.abi, networkData.address); setMarketplace(_marketplace); const _productCount = await _marketplace.methods.productCount().call(); setProductCount(productCount); const _products = []; for (let i = 1; i <= _productCount; i++) { const product = await _marketplace.methods.products(i).call(); _products.push(product); } setProducts(_products); setLoading(false); } else { window.alert('Marketplace contract not deployed to detected network.'); } }; const createProduct = (name, price) => { setLoading(true); marketplace.methods.createProduct(name, price).send({ from: account }) .once('receipt', (receipt) => { setLoading(false); }) }; const purchaseProduct = (id, price) => { setLoading(true); marketplace.methods.purchaseProduct(id).send({ from: account, value: price }) .once('receipt', (receipt) => { loading(false); }) }; useEffect(() => { loadWeb3(); loadBlockchainData(); }, []); return ( <div className="App"> <Navbar account={account} /> <main role='main' className='col-lg-12 d-flex'> {loading ? ( <div className='d-flex justify-content-center'> <div className="spinner-grow" role="status"> <span className="sr-only">Loading...</span> </div> </div> ) : ( <Main products={products} createProduct={createProduct} purchaseProduct={purchaseProduct} /> )} </main> </div> ); } export default App;
SELECT SUM(order_amount) FROM orders WHERE YEAR(order_date) = 2020;
<filename>src/main/java/com/lob/example/controller/MainController.java package com.lob.example.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.lob.example.model.ExampleModel; import com.lob.example.repository.ExampleRepository; @Controller @RequestMapping(path="/demo") public class MainController { @Autowired private ExampleRepository userRepository; @PostMapping(path="/add") // Map ONLY POST Requests public @ResponseBody String addNewUser (@RequestParam String name , @RequestParam String email) { ExampleModel n = new ExampleModel(); n.setName(name); n.setEmail(email); userRepository.save(n); return "Saved"; } }
#!/bin/sh set -e set -u set -o pipefail function on_error { echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" } trap 'on_error $LINENO' ERR if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy # frameworks to, so exit 0 (signalling the script phase was successful). exit 0 fi echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" # Used as a return value for each invocation of `strip_invalid_archs` function. STRIP_BINARY_RETVAL=0 # This protects against multiple targets copying the same framework dependency at the same time. The solution # was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") # Copies and strips a vendored framework install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # Use filter instead of exclude so missing patterns don't throw errors. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" elif [ -L "${binary}" ]; then echo "Destination binary is symlinked..." dirname="$(dirname "${binary}")" binary="${dirname}/$(readlink "${binary}")" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Copies and strips a vendored dSYM install_dsym() { local source="$1" if [ -r "$source" ]; then # Copy the dSYM into a the targets temp dir. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" local basename basename="$(basename -s .framework.dSYM "$source")" binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then strip_invalid_archs "$binary" fi if [[ $STRIP_BINARY_RETVAL == 1 ]]; then # Move the stripped file into its final destination. echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" else # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" fi fi } # Copies the bcsymbolmap files of a vendored framework install_bcsymbolmap() { local bcsymbolmap_path="$1" local destination="${BUILT_PRODUCTS_DIR}" echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identity echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current target binary binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" # Intersect them with the architectures we are building for intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" # If there are no archs supported by this binary then warn the user if [[ -z "$intersected_archs" ]]; then echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." STRIP_BINARY_RETVAL=0 return fi stripped="" for arch in $binary_archs; do if ! [[ "${ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi STRIP_BINARY_RETVAL=1 } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/YDCategorySDK/YDCategorySDK.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "${BUILT_PRODUCTS_DIR}/YDCategorySDK/YDCategorySDK.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
#include <stdio.h> //for read_cycle #include "riscv_counters.h" // for PRIu64 #include <inttypes.h> #include "data_gemv.h" #include "clarinet.h" int main (void) { #ifdef POSIT #ifdef PWIDTH_8 unsigned char acc [VSZ]; #endif #ifdef PWIDTH_16 unsigned short acc [VSZ]; #endif #ifdef PWIDTH_24 unsigned int acc [VSZ]; #endif #ifdef PWIDTH_32 unsigned int acc [VSZ]; #endif #endif uint32_t start = 0; uint32_t end = 0; uint32_t elapsed = 0; // Now lets do some cycle analysis #ifdef FLOAT float acc [VSZ]; #ifdef WARM_CACHES fn_float_gemv (acc, VSZ, m_a, v_b); #endif start=read_cycle(); fn_float_gemv (acc, VSZ, m_a, v_b); #endif #ifdef DOUBLE double acc [VSZ]; #ifdef WARM_CACHES fn_double_gemv (acc, VSZ, m_a, v_b); #endif start=read_cycle(); fn_double_gemv (acc, VSZ, m_a, v_b); #endif #ifdef FLOAT_POSIT float acc [VSZ]; #ifdef WARM_CACHES fn_posit_gemv (acc, VSZ, m_a, v_b); #endif start=read_cycle(); fn_posit_gemv (acc, VSZ, m_a, v_b); #endif #ifdef POSIT #ifdef WARM_CACHES #ifdef PWIDTH_24 fn_posit_p_gemv (acc, VSZ, m_aH, m_a, v_bH, v_b); #else fn_posit_p_gemv (acc, VSZ, m_a, v_b); #endif #endif start=read_cycle(); #ifdef PWIDTH_24 fn_posit_p_gemv (acc, VSZ, m_aH, m_a, v_bH, v_b); #else fn_posit_p_gemv (acc, VSZ, m_a, v_b); #endif #endif end=read_cycle(); elapsed = end - start; #ifdef WARM_CACHES printf ("GEMV Cycle Report (warm caches). Size: %d. Cycles: %d\n", VSZ, elapsed); #else printf ("GEMV Cycle Report. Size: %d. Cycles: %d\n", VSZ, elapsed); #endif return (0); }
<reponame>alsuren/robokite<filename>KiteModel/tether.py import numpy as np x0 = 0 y0 = 0 z0 = 0 x1 = 100 y1 = 100 z1 = 100 dx = x1-x0 dy = y1-y0 dz = z1-z0 l = np.sqrt(dx**2 + dy**2+ dz**2) l0 = 150 epsilon = l/l0 E = 10 # Young modulus T=E*epsilon print T Fz = T*np.sin(atan2(z, np.sqrt(x**2+y**2)) Fy = T*np.sin(atan2(y, np.sqrt(x**2+z**2)) Fx = T*np.sin(atan2(x, np.sqrt(z**2+y**2))
# enable color support of ls and also add handy aliases if [ -x /usr/bin/dircolors ]; then test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" alias ls='ls --color=auto' alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' fi # Some more ls aliases alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' # Starts a local HTTP server using Python in working dir alias httpserver='python -m http.server' # Usage: cat file.json | asjson alias json_pp='python -mjson.tool' alias b='xmodmap /home/tom/.Xmodmap' alias k='kubectl' alias kv4='kubectl config use-context k8s-v4.descomplica.io' alias kv5='kubectl config use-context k8s-v5.us.descomplica.io' alias knodes='kubectl get nodes --sort-by='.metadata.creationTimestamp' | grep -v monit | grep node' alias kubectx='kubectl config use-context' alias pbcopy='xclip -selection clipboard' alias pbpaste='xclip -selection clipboard -o' alias tf="aws-vault --debug exec terraform --duration=1h -- terraform" ecrlogin(){ aws2 ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 307424997672.dkr.ecr.us-east-1.amazonaws.com } myip(){ #curl -s https://ipinfo.io/json | jq .ip | sed -e 's/\"//g' | pbcopy curl -s https://httpbin.org/ip | jq .origin | sed -e 's/\"//g' | pbcopy } sshls(){ for key in ~/.ssh/id_*; do ssh-keygen -l -f "${key}"; done | uniq } getsecret(){ echo -n $1 | base64 -d | sed -e 's/\n//g' | pbcopy } setsecret(){ echo -n $1 | base64 | sed -e 's/\n//g' | pbcopy } kmsdecrypt(){ aws --region $1 kms decrypt \ --ciphertext-blob fileb://<(echo -n $2 | base64 -d) \ --output text \ --query Plaintext | base64 -d } kmsencrypt(){ aws --region $1 kms encrypt \ --key-id $2 \ --plaintext fileb://<(echo -n $3) \ --output text \ --query CiphertextBlob } flushevicted() { kubectl -n $1 get pods | grep Evicted | awk '{print $1}' | xargs kubectl -n $1 delete pod } tameouvindo() { sudo lsof -iTCP -sTCP:LISTEN }
'use strict'; var should = require('should'); var helper = require("../../../helper"); var DocumentInventoryManager = require("../../../../src/managers/inventory/document-inventory-manager"); var documentInventoryManager = null; var documentInventoryDataUtil = require("../../../data-util/inventory/document-inventory-data-util"); var validate = require("mm-models").validator.inventory.documentInventory; before('#00. connect db', function (done) { helper.getDb() .then(db => { documentInventoryManager = new DocumentInventoryManager(db, { username: 'unit-test' }); done(); }) .catch(e => { done(e); }) }); it("#01. should success when create new data using status OUT", function (done) { documentInventoryDataUtil.getNewData() .then((data) => { data.type = "OUT"; return documentInventoryManager.create(data)}) .then((id) => { id.should.be.Object(); done(); }) .catch((e) => { done(e); }); }); it("#02. should success when create new data using status ADJ", function (done) { documentInventoryDataUtil.getNewData() .then((data) => { data.type = "ADJ"; return documentInventoryManager.create(data)}) .then((id) => { id.should.be.Object(); done(); }) .catch((e) => { done(e); }); }); it("#03. should success when read data", function (done) { documentInventoryManager.read({ "keyword": "test" }) .then((data) => { done(); }) .catch((e) => { done(e); }); });
<reponame>pniekamp/datum-studio<filename>src/plugins/image/imgviewer.h // // Image Viewer // // // Copyright (C) 2016 <NAME> // #pragma once #include "documentapi.h" #include "imgview.h" #include "imgproperties.h" #include "qcslider.h" #include "qcdoubleslider.h" #include <QMainWindow> #include <QToolBar> //-------------------------- ImageViewer ------------------------------------ //--------------------------------------------------------------------------- class ImageViewer : public QMainWindow { Q_OBJECT public: ImageViewer(QWidget *parent = nullptr); virtual ~ImageViewer(); public slots: QToolBar *toolbar() const; void view(Studio::Document *document); void edit(Studio::Document *document); private: QToolBar *m_toolbar; QcDoubleSlider *m_scaleslider; QcSlider *m_layerslider; QcDoubleSlider *m_exposureslider; ImageView *m_view; ImageProperties *m_properties; };
#!/bin/bash set -e deploy() { rm -rf build PKG_SVC_VER=9.0.1; PKG_SVC_REV=1; PKG_ABC_BIN_VER=1.0.0+1493729587; PKG_ABC_BIN_REV=1; PKG_ABC_LIB_VER=1.0.0+1493729098; PKG_ABC_LIB_REV=1; SVC_DEP=() SVC_DEP+=( "--pkg-depends=zmb2-abc-bin (= $PKG_ABC_BIN_VER-$PKG_ABC_BIN_REV)" ); SVC_DEP+=( "--pkg-depends=zmb2-abc-lib (= $PKG_ABC_LIB_VER-$PKG_ABC_LIB_REV)" ); # zmb2-abc-lib # zmb2-abc-bin mkdir -p build/stage/zmb2-abc-bin/opt/rr/bin cat > build/stage/zmb2-abc-bin/opt/rr/bin/abc.sh <<EOM set -e source /opt/rr/lib/my-abc-lib.sh echo "my-abc-bin-ver: my-abc-bin-2" echo "my-abc-lib-ver: \$MY_ABC_LIB_VER" EOM chmod +x build/stage/zmb2-abc-bin/opt/rr/bin/abc.sh ../../zm-pkg-tool/pkg-build.pl --out-type=binary --pkg-installs='/opt/rr/' --pkg-name=zmb2-abc-bin --pkg-summary='its zmb-abc-bin' \ --pkg-version=$PKG_ABC_BIN_VER --pkg-release=$PKG_ABC_BIN_REV \ --pkg-depends='zmb2-abc-lib' mv build/dist/*/* /tmp/local-repo/zmb-store/D2/ # zmb2-abc-svc mkdir -p build/stage/zmb2-abc-svc/opt/rr/bin cat > build/stage/zmb2-abc-svc/opt/rr/bin/abc-svc.sh <<EOM echo "my-abc-svc-ver: my-abc-svc-2" EOM chmod +x build/stage/zmb2-abc-svc/opt/rr/bin/abc-svc.sh ../../zm-pkg-tool/pkg-build.pl --out-type=binary --pkg-installs='/opt/rr/' --pkg-name=zmb2-abc-svc --pkg-summary='its zmb-abc-svc' \ --pkg-version=$PKG_SVC_VER --pkg-release=$PKG_SVC_REV \ "${SVC_DEP[@]}" \ --pkg-conflicts='zmb1-abc-svc' \ --pkg-conflicts='zmb1-abc-bin' \ --pkg-conflicts='zmb1-abc-lib' \ --pkg-conflicts='zmb1-cmn-lib' mv build/dist/*/* /tmp/local-repo/zmb-store/D2/ echo deployed } deploy "$@"
export default class BaseModule { constructor(el) { this.el = el; this.el.handler = this.el.handler || {}; console.log(el); } }
import PropTypes from 'prop-types'; import classNames from 'classnames'; import React, { Component, Fragment } from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faEllipsisH } from '@fortawesome/free-solid-svg-icons'; class UserOptions extends Component { constructor(props) { super(props); this.state = { toggled: false, }; } toggleOptions() { this.setState(prevState => ({ toggled: !prevState.toggled, })); } endChat() { this.setState({ toggled: false, }); this.props.endChat(); } render() { const userOptionsListClasses = classNames( 'sc-user-options__list', {'sc-user-options__list--visible': this.state.toggled}, ); return ( <Fragment> <div className="sc-user-options__toggle" onClick={this.toggleOptions.bind(this)} > <FontAwesomeIcon icon={faEllipsisH} /> </div> <div className={userOptionsListClasses}> <ul> <li onClick={this.endChat.bind(this)}>End Chat</li> </ul> </div> </Fragment> ); } } UserOptions.propTypes = { endChat: PropTypes.func.isRequired, }; export default UserOptions;
#!/usr/bin/env bash if ! (command -v az >/dev/null); then echo "Unmet system dependency: az" >&2; exit 1; fi if ! (command -v python >/dev/null); then echo "Unmet system dependency: python" >&2; exit 1; fi usage() { echo "Usage: $0 -i <subscriptionId> -l <resourceGroupLocation> -o <outputFile>" >&2; exit 1; } declare subscriptionId="" declare resourceGroupLocation="" declare outputFile="" readonly scriptDirectory="$(dirname "$0")" readonly templateFilePath="$scriptDirectory/template.json" readonly parametersTemplatePath="$scriptDirectory/parameters.json" readonly outputParserScriptPath="$scriptDirectory/parse-output.py" readonly parametersFilePath="$(mktemp)" readonly deployOutputFilePath="$(mktemp)" cleanup() { rm -f "$parametersFilePath" "$deployOutputFilePath"; } trap cleanup EXIT # initialize parameters specified from command line while getopts ":i:l:o:" arg; do case "$arg" in i) subscriptionId="$OPTARG" ;; l) resourceGroupLocation="$OPTARG" ;; o) outputFile="$OPTARG" ;; esac done shift $((OPTIND-1)) if [ ! -f "$templateFilePath" ]; then echo "$templateFilePath not found" >&2; exit 1; fi if [ ! -f "$parametersTemplatePath" ]; then echo "$parametersTemplatePath not found" >&2; exit 1; fi if [ -z "$subscriptionId" ]; then echo "Subscription ID not provided" >&2; usage; fi if [ -z "$resourceGroupLocation" ]; then echo "Resource group location not provided" >&2; usage; fi if [ -z "$outputFile" ]; then echo "Output file location not provided" >&2; usage; fi readonly userName="$(echo "${USER}" | tr -dC 'a-zA-Z')" readonly personalIdentifier="$userName${RANDOM:0:2}" readonly resourceGroupName="fortisdev$personalIdentifier$resourceGroupLocation" readonly deploymentName="fortisdeployment$personalIdentifier$resourceGroupLocation" # login to azure using your credentials az account show || az login az account set --subscription "$subscriptionId" # create resource group if it doesn't exist az group create --name "$resourceGroupName" --location "$resourceGroupLocation" || true # start deployment sed "s@\"value\": \"fortis@\"value\": \"${personalIdentifier}fortis@g" "$parametersTemplatePath" > "$parametersFilePath" az group deployment create --name "$deploymentName" --resource-group "$resourceGroupName" --template-file "$templateFilePath" --parameters "$parametersFilePath" | tee "$deployOutputFilePath" # set up postgres readonly postgresName="pgsql$personalIdentifier" readonly postgresUser="$userName" readonly postgresPassword="$(< /dev/urandom tr -dc '_A-Z-a-z-0-9' | head -c32)" az postgres server create \ --name="$postgresName" \ --admin-user="$postgresUser" \ --admin-password="$postgresPassword" \ --resource-group="$resourceGroupName" \ --location="$resourceGroupLocation" \ --compute-units="400" \ --performance-tier="Standard" az postgres server firewall-rule create \ --server-name="$postgresName" \ --resource-group="$resourceGroupName" \ --start-ip-address="0.0.0.0" \ --end-ip-address="255.255.255.255" \ --name="AllowAll" # save environment variables echo "FORTIS_RESOURCE_GROUP_NAME=$resourceGroupName" | tee "$outputFile" echo "FORTIS_RESOURCE_GROUP_LOCATION=$resourceGroupLocation" | tee --append "$outputFile" echo "FEATURES_DB_USER=$postgresUser@$postgresName" | tee --append "$outputFile" echo "FEATURES_DB_HOST=$postgresName.postgres.database.azure.com" | tee --append "$outputFile" echo "FEATURES_DB_PASSWORD=$postgresPassword" | tee --append "$outputFile" python "$outputParserScriptPath" "$deployOutputFilePath" | tee --append "$outputFile"
import base64 text = "Hello World!" encoded_text = base64.b64encode(text.encode()).decode() print(encoded_text) Output: SGVsbG8gV29ybGQh
package com.app.wechat; import com.app.wechat.code.WxConstant; import com.app.wechat.core.DefaultWxClient; import com.app.wechat.core.WxClient; import com.app.wechat.domain.mass.WxMassPreviewModel; import com.app.wechat.domain.mass.WxMassSendModel; import com.app.wechat.domain.msg.WxTextMsgModel; import com.app.wechat.domain.msg.WxVideoMsgModel; import com.app.wechat.internal.code.Constant; import com.app.wechat.internal.code.WxMsgType; import com.app.wechat.internal.util.WxMassUtil; import com.app.wechat.internal.util.WxMsgUtil; import com.app.wechat.request.WxMassGetRequest; import com.app.wechat.request.WxMassPreviewRequest; import com.app.wechat.request.WxMassSendRequest; import com.app.wechat.request.WxMediaUploadVideoRequest; import com.app.wechat.response.WxMassSendResponse; import org.junit.Test; /** * @author Administrator * @version 1.0 */ public class TestMassSend { WxClient client = new DefaultWxClient(WxConstant.APP_ID, WxConstant.APP_SECRET); String OpenId = "oX_DYt3AiupzsygSGIcqzw-l6NNo"; @Test public void TestMaterial() throws Exception { // WxMaterialAddRequest request = new WxMaterialAddRequest("E:\\WorkSpace\\Resouce\\timg.jpg", WxMediaType.THUMB); // WxMaterialAddRequest request = new WxMaterialAddRequest("E:\\WorkSpace\\Resouce\\test.mp4", WxMediaType.VIDEO, "欢迎标题", "欢迎描述"); // WxMediaUploadRequest request = new WxMediaUploadRequest("E:\\WorkSpace\\Resouce\\timg.jpg", WxMediaType.IMAGE); // WxMediaUploadRequest request = new WxMediaUploadRequest("E:\\WorkSpace\\Resouce\\test.mp4", WxMediaType.VIDEO); WxVideoMsgModel model = WxMsgUtil.getWxVideoMsgModel("mSkwZfH4uzfW_2BB-Tf4r68qATwJhPzaK2n_c65MkrwWNq8b1-StcmHieIyEf-LR", "标题", "描述"); WxMediaUploadVideoRequest request = new WxMediaUploadVideoRequest(model); client.execute(request); } @Test public void TestMassSend() throws Exception { // 1 上传图文消息内的图片获取URL // WxMediaUploadImgRequest request = new WxMediaUploadImgRequest("E:\\WorkSpace\\Resouce\\head.jpg"); // 2 上传图文消息素材 // WxMediaUploadRequest request0 = new WxMediaUploadRequest("E:\\WorkSpace\\Resouce\\timg.jpg", WxMediaType.IMAGE); // WxMediaUploadResponse response0 = client.execute(request0); // // WxNewsMsgModel newsMsgModel = WxMsgUtil.getWxNewsMsgModel(response0.getMediaId(), "标题", "内容"); // WxMediaUploadNewsRequest request1 = new WxMediaUploadNewsRequest(newsMsgModel); // WxMediaUploadNewsResponse response1 = client.execute(request1); // 素材准备 WxMsgType msgType = WxMsgType.TEXT; // WxMpNewsMsgModel mpNewsMsgModel = WxMsgUtil.getWxMpNewsMsgModel(response1.getMediaId()); WxTextMsgModel textMsgModel = WxMsgUtil.getWxTextMsgModel("欢迎"); // 5 预览接口 // WxMassPreviewModel previewModel = WxMassUtil.getWxMassPreviewModelById(OpenId, msgType, textMsgModel); WxMassPreviewModel previewModel = WxMassUtil.getWxMassPreviewModelByName("wjtree", msgType, textMsgModel); WxMassPreviewRequest request5 = new WxMassPreviewRequest(previewModel); client.execute(request5); // 3 进行群发 // 根据标签进行群发 // WxMassSendModel massSendAllModel = WxMassUtil.getWxMassSendModel(Constant.YES, String.valueOf(System.currentTimeMillis()), msgType, textMsgModel); // WxMassSendAllRequest request2 = new WxMassSendAllRequest(massSendAllModel); // WxMassSendAllResponse response2 = client.execute(request2); // 根据OpenID列表群发 String[] openIds = {"oSaeBtwPOpWYDKdePC_K-Lu6KswY", "oSaeBt4ay221ZzXk2hzig1psi9ZA"}; WxMassSendModel massSendModel = WxMassUtil.getWxMassSendModel(openIds, Constant.YES, String.valueOf(System.currentTimeMillis()), msgType, textMsgModel); WxMassSendRequest request3 = new WxMassSendRequest(massSendModel); WxMassSendResponse response3 = client.execute(request3); // 6 查询群发消息发送状态 WxMassGetRequest request6 = new WxMassGetRequest(response3.getMsgId()); client.execute(request6); // 4 删除群发 // WxMassDelRequest request4 = new WxMassDelRequest(response2.getMsgId()); // WxMassDelResponse response4 = client.execute(request4); // 7 控制群发速度 // WxMassSpeedSetRequest request7 = new WxMassSpeedSetRequest(WxMassSpeed.S0); // WxMassSpeedGetRequest request8 = new WxMassSpeedGetRequest(); // client.execute(request8); } public void test() throws Exception { // WxNewsMsgModel model = WxMsgUtil.getWxNewsMsgModel("36KPUMl5PSGRUoZ5ffTtlu996dWg4Pdokd-qUbUPXz8", "标题", "内容"); // WxMaterialAddNewsRequest request = new WxMaterialAddNewsRequest(model); } }
def generate_column_query(db_type, table_name): if db_type == "POSTGRES": return f"""Select * from information_schema.columns where table_name = '{table_name}' order by ordinal_position""" elif db_type == "SQLITE": return f"""Select * from pragma_table_info('{table_name}') order by cid""" else: return "Unsupported database type"
<gh_stars>0 export type Nullable<T> = T | null; export type Voidable<T> = T | null | undefined; export interface IpcResponse<T> { data?: T; error?: any; } export interface ICommon { id?: number | string; // Primary key. Optional (autoincremented) updatedAt: number; } export interface IConfig extends ICommon { ignoreError: boolean; //Continue on download errors, for example to skip unavailable videos in a playlist 继续处理下载错误,例如 例如,跳过某一视频列表中不可用的视频 播放列表 abortOnError: boolean; // Abort downloading of further videos (in the playlist or the command line) if an error occurs 终止下载更多的视频(在 播放列表或命令行),如果出现 发生错误 dumpUserAgent: boolean; // Display the current browser identification 显示当前的浏览器标识 ignoreConfig: boolean; // Do not read configuration files. When given in the global configuration file /etc/youtube-dl.conf: Do not read the user configuration in ~/.config/youtube-dl/config (%APPDATA%/youtube-dl/config.txt on Windows) 不要读取配置文件。当在全局配置文件/etc/youtube-dl.conf中给出。不要读取~/.config/youtube-dl/config中的用户配置(Windows下为%APPDATA%/youtube-dl/config.txt)。 proxy: string; // socketTimeout: number; // Time to wait before giving up, in seconds 放弃前的等待时间,以秒为单位 dist: string; // } export interface ITask extends ICommon { id: string; title: string; progress: number; webpage_url: string; thumbnail: string; duration: number; filesize: number; extractor: string; speed: string; eta: string; pending: boolean; config: IConfig; }