Posts

Showing posts from February, 2010

Python: Dynamically call function within abstract class -

i have class instance needs call analyse method. constructor receives request object kind of message { "message":{ "attributes":{ "message_id":"2aj78h98-2112-4637-76h1-09ec727933bb", "topic":"mytopic", "version":1 }, "data":"{"id": 123541234}" } } my_model = mymodel(request) my_model.analyse(data) the structure of class mymodel is: import importlib class mymodel(object): def __init__(self, req): """ request, extract topic , dynamically create instance """ try: self.req = req classname = self.req.topic # in example: mytopic classpath = 'foo.bar' module = importlib.import_module(classpath) self.some_object = getattr(module, classname) except exception e:

reverse engineering - Binwalk - Compressed data is corrupt / Compressed data is corrupt -

root@kali:~/router# binwalk new-firmware.bin decimal hexadecimal description -------------------------------------------------------------------------------- 84 0x54 uimage header, header size: 64 bytes, header crc: 0xe52a7f50, created: 2012-02-10 07:27:12, image size: 819799 bytes, data address: 0x80002000, entry point: 0x801ac9f0, data crc: 0x6a10d412, os: linux, cpu: mips, image type: os kernel image, compression type: lzma, image name: "linux kernel image" 148 0x94 lzma compressed data, properties: 0x5d, dictionary size: 8388608 bytes, uncompressed size: 2386252 bytes 917588 0xe0054 squashfs filesystem, little endian, version 4.0, compression:lzma, size: 2588426 bytes, 375 inodes, blocksize: 16384 bytes, created: 2016-02-05 02:05:56 root@kali:~/router# dd if=new-firmware.bin of=uboot.lzma skip=148 bs=1 3735488+0 records in 3735488+0 records out 3735488 bytes (3.7 mb, 3.6 mib) copied, 4.16712 s, 896

amazon web services - Kinesis timing out when invoked via Lambda but code hasn't changed -

so encountering weird situation kinesis timing out on me when invoke putrecord lambda function. weird part worked me earlier morning, doesn't work me now. code has not changed , it's same zip file before. has encountered situation before?

python - Create List from List of Key-Values -

given json structure below, want grab data item, pull 1 of values link out randomly. using random - familiar grabbing random value list. i'm stuck how make list list. see code below json. item0: 0 caption: "caption 0" link: "www.item0.com" type: "type0" 1 caption: "caption 1" link: "www.item1.com" type: "type1" python: chosen_item = "item0" firebase = firebase.firebaseapplication('https://app.firebaseio.com') result = firebase.get(chosen_item, none) if result: in result: result_link = (i['link']) print result_link the if-statement loops through , returns link 's in item unicode type. how make list this? ( result_link ) chosen_item = "item0" firebase = firebase.firebaseapplication('https://app.firebaseio.com') result = firebase.get(chosen_item, none) if result: links = [] in result: links.appe

sql server 2008 - SQL Merge matching rows in SQL table -

here table schema table1 { column1 nvarchar(max), column2 nvarchar(max) } here sample data column1 column2 tom blue tom gary green gary yellow sam sam red i update column2 if column1 value duplcated , either 1 of rows in column2 empty , empty cell replaced non empty cell. for example desired output above sample data column1 column2 tom blue tom blue gary green gary yellow sam red sam red the below update maximum value, ignoring nulls or empty strings. if there 1 distinct possibility of course 1 chosen. ;with t ( select *, max(nullif(column2,'')) on (partition column1) c2 yourtable ) update t set column2 = c2 column2 null or column2 = '';

c# - How to bind Gridview update with Object Datasource parameters -

i have gridview shopping cart columns id | productname | productprice | productquantity | totalprice quantity editable column in gridview. need pass id , quantity datasource , how can that? beginner , have been working on hour , appreciated .aspx file <asp:objectdatasource id="objectdatasource1" runat="server" selectmethod="getlistfromcart" typename="getfromcart" deletemethod="deletelistfromcart" updatemethod="updatelistfromcart" > <deleteparameters> <asp:parameter name="id" type="int32" /> </deleteparameters> <updateparameters> <asp:parameter name="id" type="int32" /> <asp:parameter name="quantity" type="int32" /> </updateparameters> </asp:objectdatasource> <asp:gridview id="gridview1" runat="serve

mingw32 - How do I use CMake to build a package using MinGW? -

i'm trying build software ecmwf called eccodes . it builds fine on gnu/linux. it builds fine on mac os x. it builds fine on windows/cygwin. unfortunately (ugh!!), must use windows , can't use cygwin. i have use mingw. the build instructions use cmake. no expert @ cmake. windows system on has: cygwin64 mingw64 a bare-bones visual studio 14 i've tried every incantation , override of cmake variables/options: -dcmake_c_compiler=... \ -dcmake_cxx_compiler=... \ -dcmake_fortran_compiler=... \ -dcmake_make_program=... \ -g ... to eccodes build using mingw, no luck. know ask, "why not contact ecmwf?" short answer is, response time long (months/years). faq page empty, , can't post questions on jira site (it's locked). would possible knows cmake , mingw download .tar.gz , build eccodes using mingw, , tell how did it? http://www.ecmwf.int/ https://software.ecmwf.int/wiki/display/ecc/eccodes+home https://software.ecmwf.int/wiki/

c# - Back button doesn't dispose App / MainActivity -

neither application class nor mainactivity getting disposed when click button on android phone. my problem: i cannot figure out if app closed or pausing. in both cases protected override void onsleep() {} is being called. but front after pressing back-button, mainactivity & forms application reinstantiated again , whole app appears restart. whereas tapping buttom middle button minimize , bringing front again doesnt restart app , still running , open... my question: the problem now, have application , activity in memory, doesnt use anymore. never getting disposed, far can see. further more don't want app restart when click button, how solve issue? act if have used minimize button in middle. possible? from can tell, design. when on root (main) page, , press home button, app goes background, main page still instantiated , in memory. in contrast, when hit button, app removes main page navigation stack, destroying it. therefore, app need re-initiali

c++ - Where do local variables get stored at compile time? -

maybe i'm missing obvious, isn't during runtime local variables placed on stack when function containing variables gets called. therefore when compiler step through our source code, place operations of function in .text segment, variables placed @ compile time can placed onto stack @ run-time? thanks local variables aren't placed anywhere @ compile time. the compiler generates code that, when executed @ run time, allocate space on stack (typically; other schemes possible). compiler records information each variable (name, type, size, offset relative stack pointer, etc.) , uses information generate code creates, accesses, , deallocates variable. a technical digression: c doesn't have "local" , "global" variables, or @ least language standard doesn't use terms. object has lifetime ( storage duration ), span of time during execution when exists. more or less independently othat, object's name has scope , region of program t

function - Scala Function1 Generic parameter and return type -

lets want store map[string, function1] parameter , return type of function1 can vary. how go storing function1[string, string] , function1[int, int] in same map. i've tried function1[anyref, anyref] function1[string, string] isn't function1[anyref, anyref] fails compile. if have 2 possible value types, can wrap values in either : val m = map[string, either[int => int, string => string]]() if want store more 2 different types, create own wrapper, or use coproduct shapeless .

mysql - SQL GROUP_CONCAT with LEFT JOIN to multiple relative rows -

i have been stuck on hours now, appreciated i have 2 tables 'products' , 'product_subcategorys' 'products' holds unique ids 'product_subcategorys' holds multiple ids relative 'products' table 'products' id brand 1 2 b 3 'product_subcategorys' id subcat 1 u 1 2 u 3 u this query have, group 'p.id' doesn't appear work select group_concat(p.brand) products p left join product_subcategorys s on p.id = s.id ( s.subcategory = "u" or s.subcategory = "i" ) groupbrand so problem is, want return list of brands 'product' table cant use distinct because need count multiples i want query return brand 'a' twice, query returning 3 times since there 2 matching ids in 'product_subcategorys' does want? select group_concat(p.brand order p.id) products p exists (select 1 product_subcategorys s

ios - CosmicMind/Material - Storyboard example for SideMenu and NavigationController -

i'm quite new in swift programming , view design possible storyboard. want make application using cosmicmind/material framework have side menu , selecting menu point open new view embedded in navigationcontroller. the storyboard examples include simple cases both sidenavigationcontroller , navigationcontroller . based on this, app example in programmatic folder , answers in stackoverflow create example 3 menu points , 3 views. can found under github repository tag stackoverflow . i think side menu , pushing views within navigationcontroller works well. question is, if best practice of how use material framework. problem not show menu icon , title in navigationitem main screen . can me wrong in code? or maybe have similar more complex example within storyboard examples sidemenu. thank much. i looked @ code , gather, placing navigationitem code in wrong place. how setup should be. sidenavigationcontroller.rootviewcontroller -> menuviewcontroller. me

java - how I deal with this ArrayIndexOutOfBoundException in this noun finding program -

this question has answer here: what causes java.lang.arrayindexoutofboundsexception , how prevent it? 14 answers i have came out problem couldn't find way solve exception. please help. program trying find out nouns,verbs , adjectives user given sentence(here tried find out nouns). if had made errors in program please point errors , can correct it. here code: enter code here import java.io.fileinputstream; import java.io.inputstream; import java.util.hashset; import java.util.set; import opennlp.tools.cmdline.parser.parsertool; import opennlp.tools.parser.parse; import opennlp.tools.parser.parser; import opennlp.tools.parser.parserfactory; import opennlp.tools.parser.parsermodel; import opennlp.tools.util.objectstream; public class parsertest { static set<string> nounphrases = new hashset<>(); static set<string> adjectivephrases = new hash

delphi - Indy, IdTCPSever sending data in utf=8 charset -

i have problem conversion strings utf-8. use standard indy method sending conversion inside: acontext.connection.iohandler.writeln(utf8encode('ĄĘÓ')); but client reads them '???' - 3f 3f 3f in hex (i checked using wireshark too). i use delphi xe , indy 10. big help. ~artik i found solution problem, think siplest using code below: acontext.connection.iohandler.defstringencoding := tidtextencoding.utf8;

scala - Json Parse obj without case class ref -

i don't know how explain want do, i'll make example : case class c1(id: string, name: string, description: string) case class c2(id: string, status: boolean) trait test[anyref] { implicit val writesc1 = json.writes[c1] implicit val writesc2 = json.writes[c2] def test(obj:anyref) = { println(json.tojson(obj)) } } object oc1 extends test[c1] {} object oc2 extends test[c2] {} val x = c1(1, "test", "desc test") c1.test(x) // here want c1 instance parsed json how this: trait test[t] { implicit val writest = json.writes[t] def test(obj: t) { println(json.tojson(obj)) } } object c1 extends test[c1] val x = c1(1, "test", "desc test") oc1.test(x) i unfortunately don't have play installed right can't test. update if upper doesn't work, will: trait test[t] { implicit val writest: writes[t] // ... } object oc1 extends test[c1] { implicit val writest = json.writes[c1] } but

php - Combine post values and remove empty -

i have 2 sets of arrays coming $_post . keys both numeric , count same, since come in pairs names , numbers: $_post[names] ( [0] => first [1] => second [2] => [3] => fourth ) $_post[numbers] ( [0] => 10 [1] => [2] => 3 [3] => 3 ) now need combine two, remove each entry either values missing. the result should like: $finalarray ( [first] => 10 [fourth] => 3 ) post data dynamically created there might different values missing based on user input. i tried doing like: if (array_key_exists('names', $_post)) { $names = array_filter($_post['names']); $numbers = array_filter($_post['numbers']); if($names , $numbers) { $final = array_combine($names, $numbers); } } but can't seem filter correctly, since giving me error: warning: array_combine(): both parameters should have equal number of elements how using array

java - UnsatisfiedLinkError in exported (Eclipse) executable jar file -

Image
the code works fine when executing eclipse. i'm using opencv 2.4.11 , javafx ui. when export executable jar eclipse , run cmd following exception: i followed many post here on , opencv forum( 1 , 2 , 3 , 4 ) but, none of answers seems me. i have added opencv jar library , native library linked /build/java/x64 suggested in answers. the exception occurs @ system.loadlibrary(core.native_library_name), checked native_library_name , opencv version same 1 imported in project. public class customframe extends application{ @override public void start(stage primarystage){ group root = new group(); canvas canvas = new canvas(1440, 840); imageview imageview = new imageview(); imageview.setfitheight(canvas.getheight()); imageview.setfitwidth(canvas.getwidth()); new framecontroller().startcamera(imageview); root.getchildren().addall(imageview, canvas); primarystage.setscene(new scene(root)); prima

python - Parse a git URL like 'ssh://git@gitlab.org.net:3333/org/repo.git'? -

how extract hostname git url ssh://git@gitlab.org.net:3333/org/repo.git u = urlparse(s) gives me parseresult(scheme='ssh', netloc='git@gitlab.org.net:3333', path='/org/repo.git', params='', query='', fragment='') which means netloc closest want , leaves disappointing amount of work me. should do u.netloc.split('@')[1].split(':')[0] or there library handles better? the returned parseresult has hostname attribute: >>> urlparse('ssh://git@gitlab.org.net:3333/org/repo.git').hostname 'gitlab.org.net'

mysql - Combining two tables in a complex way -

the situation: i have main table, lets call maintable . +---------+----------+----------+----------+ | id (pk)| title | text | type | +---------+----------+----------+----------+ | 1 | text|more stuff| | | 2 | | example | b | +---------+----------+----------+----------+ and have second table called translationstable , in id field representation of maintable row id (no foreign key, can refering different tables), objtype objecttype (same name table), fieldname name of field objectype , value has translation value fieldname value in objtype table. +---------+-----------+-----------+------------+----------+ | id | objtype | fieldname | value | language | +---------+-----------+-----------+------------+----------+ | 1 | maintable | title | algum texto| pt | | 1 | maintable | text | mais coisas| pt | +---------+-----------+-----------+------------+----------+ and because need search in t

NaN return value from function Javascript || Function Execution Order -

newbie in javascript here, , after hours digging trough other questions i'm not quite sure how explain honest, i'll give best, you'll able me. html: <div id='header'> <h1> pastel land </h1> </div> <div id='container'> <div id='readycontainer'> <h3> game start in </h3> <h1 id='readyseconds'> </h1> </div> <div id='shape'> </div> </div> <div id='features'> <button id='start'> start </button> <button id='stop'> stop </button> <p id='timebox'></p> <p id='timeaveragebox'></p> </div> <div id='testbox'> </div> full script: document.getelementbyid('start').onclick = function () { document.getelementbyid(&

c++ - Replace std::vector's buffer with a malloc'ed char array -

i have following class holding std::vector resizable "buffer" data. class packet { public: struct packetheader { size_t datasize = 0; size_t paddeddatasize = 0; } header_; const unsigned char* data() const { return &data_[0]; } unsigned char* data() { return &data_[0]; } /// changes size of data vector void resize(size_t sz) { header_.datasize = sz; // check if padding needed if (sz % aes_block_size != 0){ auto padding = aes_block_size - (sz % aes_block_size); data_.resize(sz + padding); (int = 1; <= padding; i++) { data_[(sz + padding) - i] = '\0'; } header_.paddeddatasize = sz + padding; } else{ data_.resize(sz); } } private: std::vector<unsigned char> data_; }; then i'm p

javascript - How to provide a parent's model to a dynamically loaded child component in angular 2? -

i have many directives built in angular 1.x application. directives used various internal applications @ company. i'd applications not have change code, instead abstract many of syntax changes within directives upgrade angular 2.x. example let's have following directive: <my-directive my-first-attribute="vm.someproperty" my-second-attribute="vm.somefunction()" ></my-directive> assume can't change syntax parent component's perspective attributes need transformed like: [myfirstattribute]="vm.someproperty" (click)="vm.somefunction()" there used compile function make many of these template changes before linking. i've got constructor function can pull in elementref , , dynamiccomponentloader however, how can provide vm dynamically loaded component? i've tried: this._loader.loadintolocation(subcmp, this._el, 'container') .then((compref:componentref) => { compref.instance.v

Can Lupa be used to run untrusted lua code in python? -

let's create luaruntime register_eval=false , attribute_filter prevents access except few python functions. safe assume lua code won't able os.system("rm -rf *") or that? from looking @ lupa doc : restricting lua access python objects lupa provides simple mechanism control access python objects. each attribute access can passed through filter function follows... it doesn't preventing or limiting access facilities provided lua itself. if no other modifications done luaruntime environment lua script can indeed os.execute("rm -rf *") . to control kind of environment lua script works in can use setfenv , getfenv sandbox script before running it. example: import lupa l = lupa.luaruntime() sandbox = l.eval("{}") setfenv = l.eval("setfenv") sandbox.print = l.globals().print sandbox.math = l.globals().math sandbox.string = l.globals().string sandbox.foobar = foobar # etc... setfenv(0, sandbox)

ms access - SQL Inner Join two Columns(being the minimum from the one column) -

i working on project here have 2 tables, 1 expiry dates named tracking , 1 inventory data named inventoryreport. need gather minimum expiry date tracking table quantity associated , update inventoryreport table. unique identifier in each table sku number. far have, know is incomplete , have tried min() on tracking.expirydate appreciate suggestions. update inventoryreport inner join tracking on [inventoryreport].[sku] = [tracking].[sku] set [inventoryreport].[expiry date] = [tracking].[expiry date], [inventoryreport].[quantity] = [tracking].[quantity]; if there exists nothing smaller something, minimum, or in sql: update inventoryreport inner join tracking t on t.[sku] = i.[sku] , not exists( select t2.[expiry date] tracking t2 t2.[sku] = t.[sku] , t2.[expiry date] < t.[expiry date] ) set i.[expiry date] = t.[expiry date], i.[quantity] = t.[quantity] ;

html - CSS: inline a <pre> tag -

here html: <p>the following text <pre>is inline preformat block</pre> , not parsed.</p> i want rendered single line, preformat block in middle of sentence. however, rendering 3 separate lines: the following text is inline preformat block , not parsed. and want on 1 single line. have tried setting style use display:inline , solves problem halfway: no newline introduced @ end of pre block, there still 1 @ start. as has been suggested elsewhere, tried using white-space:nowrap , accomplishes absolutely nothing @ all. no solutions based on javascript or jquery, please. want make sure solution works on browsers have scripting disabled. solution #1 using <pre> (not recommended): can use following code, <p> element little bit broken. if want avoid affect <p> elements, add class or id attribute <p> element. pre, p { display:inline; } <p>the following text <pre>is inline pref

javascript - false statement not executed by ternary operator -

in following code, ternary operator isn't assigning value if condition returns false! <script> function lgn() { document.getelementbyid('overlay').style.display = 'none' ? 'block':'none'; document.getelementbyid('lgn').style.display = 'none' ? 'block':'none'; } </script> i trying make overlay on webpage, following twig: <div class="nvg"> <ul> {% block links %} <li class="n.link"><span class="fa fa-times close" onclick="lgn()"></span></li> {% endblock %} </ul> </div> and {% block overlay %} {{ form_start(form, {'attr':{'id':'lgn'}}) }} <span class="fa fa-times close" onclick="lgn()">

hsts - How to add strict-transport-security header to a Grails Application -

i have groovy code running on grails server. how configure hsts ? looked through groovy specs there nothing found useful. this want achieve when @ http response server. must see header such below strict-transport-security: max-age=31536000 can please suggest pointers ? i suggest implement custom servlet filter, this: @priority(integer.min_value) public class hstsfilter extends onceperrequestfilter { public hstsfilter() { } @override protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception, ioexception { filterchain.dofilter(request, response); response.addheader("strict-transport-security", "max-age=31536000"); } } then need register in resources.groovy : beans = { hstsfilter(hstsfilter) } this code tested on grails 3.1.4

forms - excel 2010: based on a radio button selection save user from date to ain a different worksheet -

i have excel form works , saves data 1 worksheet. able put radio button , based on selection save diffent work sheet. example: if radio button 1 selected save sheet1 if radio button 2 selected save sheet2 if radio button 3 selected save sheet3 same form used save on different worksheet. the code im working with. private sub btn_append_click() dim irow long dim ws worksheet set ws = worksheets("assessment") 'find first empty row in database irow = ws.cells.find(what:="*", searchorder:=xlrows, _ searchdirection:=xlprevious, lookin:=xlvalues).row + 1 'check part number if trim(me.txt_roomnumber.value) = "" me.txt_roomnumber.setfocus msgbox "please enter room number" exit sub end if 'copy data database 'use protect , unprotect lines, ' password ' if worksheet protected ws ' .unprotect password:="password" .cells(irow, 1).value = me.txt_roomnumber.value .cells(irow, 2).value =

c++ - Adding a Native .dll file from SIMULINK to Visual Studios C# -

i have created .dll file using simulink's embedded coder. (system target file set : ert_shrlib.tlc) builds model_win64.dll. want reference visual studios. i first tried using "add reference" tool got following error: a reference 'file path\model_win64.dll' i searched around solution online , getting error cause .dll file being native .dll should use dllimportattribute class https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx so code have using system; using system.runtime.interopservices; namespace gui_interface { class main { [dllimport("modbot_model_win64.dll", charset = charset.unicode)] public static extern int[] mpc(double x, double y, double theta, double vx, double vy, double vtheta); public static backgroundworker test() { ints = mpc(0, 0, 0, 0, 0, 0); } } and runtime error:cannot marshal 'return value': invalid managed/unmanaged type combina

sorting - Moving files to different directories by file type in a batch file(Win) -

basically trying sort downloads folder batch file. need know how either make batch file overwrite duplicate files or create "(1)" @ end of file name. moving file .jpeg, jpg, etc... pictures folder , like. have this, @echo off mkdir %userprofile%\downloads\exes mkdir %userprofile%\downloads\jars mkdir %userprofile%\downloads\zips mkdir %userprofile%\downloads\crafts mkdir %userprofile%\documents mkdir %userprofile%\downloads\iso's mkdir %userprofile%\pictures mkdir %userprofile%\downloads\torrent mkdir %userprofile%\music mkdir %userprofile%\videos mkdir %userprofile%\contacts move %cd%\*.exe %userprofile%\downloads\exes move %cd%\*.jar %userprofile%\downloads\jars move %cd%\*.zip %userprofile%\downloads\zips move %cd%\*.rar %userprofile%\downloads\zips move %cd%\*.gz %userprofile%\downloads\zips move %cd%\*.7z %userprofile%\downloads\zips move %cd%\*.tar.gz %userprofile%\downloads\zips move %cd%\*.craft %userprofile%\downloads\crafts move %cd%\*.pdf %userprofile

Arithmetic casting to generic type in F# -

i try write function generic casting arithmetic types, example function receives argument of type uint64 , converts type being same type parameter. idea is: let convert<'t> (x:uint64) = 't x but code not compile, , stuck here after trying several approaches like: let convert<'t> (x:uint64) = match unchecked.defaultof<'t> | :? uint32 -> uint32 x .... so how write such generic arithmetic casting in f#? (i start learning question maybe stupid, please take easy). you can use static member constraints, here's "short" example: type explicit = static member inline ($) (_:byte , _:explicit) = byte static member inline ($) (_:sbyte, _:explicit) = sbyte static member inline ($) (_:int16, _:explicit) = int16 static member inline ($) (_:int32, _:explicit) = int // more overloads let inline convert value: 't = (unchecked.defaultof<'t> $ unchecke

python - Returning individual string representation of all objects in list of objects -

is possible return string representation (using __str__) of objects in list of objects different classes own __str__ function? say have class contains methods being performed on bar objects. call class foo. then: class foo: def __init__(self): self.bars = [] # contains bar objects def __str__(self): return "this foo object" class bar: def __init__(self, arg1): self.arg1 = arg1 def __str__(self): return "this bar object: " + arg1 def main(): foo = foo() print(str(foo)) i want print string representation of of objects in self.bars when call main(), since creating instance of bar object not give me access string representation of of objects in self.bars. to clarify, not asking same question in this post relating need of __repr__ . instead, want return each object's string representation individually, loop. is there anyway this, reasonably or unreasonably? you said how this, use lo

node.js - which functions done/next are bound to in mongoos pre/save/(serial/parallel) middleware -

trying understand mongoose middleware (pre/save/parallel) thru docs/blogs(tim casewell). based on http://mongoosejs.com/docs/middleware.html var schema = new schema(..); schema.pre('save', true, function (next, done) { // calling next kicks off next middleware in parallel next(); doasync(done); }); hooked method, in case save, not executed until done called each middleware. what done/next bound here? can please give complete example of how use it? for eg: use serial follows: mymodel.save(function(err) { if (err) console.error("error occured") else console.info("document stored"); }); schema.pre('save', function(next) { if (!self.validatesomething()) { next(new error()); } else { next(); } }); what next bound here? needs bound executed? fail understand function(s) next/done referring to? if elaborate control flow code above, great help. ------------- this elaborate understanding (not part of quest

c# - Event handling with WPF -

i started learning wpf , c#. i'm trying listen global events on wpf application. has run during entire time program running. on console application, run logic in main() function. however, main() generated during compile time in wpf application. where put event handlers in wpf application? not sure mean global events in context, : public partial class mainwindow : window { public mainwindow() { initializecomponent(); this.loaded += mainwindow_loaded; } private void mainwindow_loaded(object sender, routedeventargs e) { //do stuff here } } this mainwindow.xaml.cs class generated in every wpf template in visual studio.

bluetooth lowenergy - Error code 2 in beacon transmitter for Android Beacon library -

i want send ble advertisement using android beacon library. below code using it. package com.example.beacon_emitter; import java.util.arrays; import org.altbeacon.beacon.beacon; import org.altbeacon.beacon.beaconparser; import org.altbeacon.beacon.beacontransmitter; import android.support.v7.app.actionbaractivity; import android.app.activity; import android.bluetooth.le.advertisecallback; import android.bluetooth.le.advertisesettings; import android.os.bundle; import android.util.log; import android.view.menu; import android.view.menuitem; import android.widget.toast; public class mainactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); beacon beacon = new beacon.builder() .setid1("2f234454-cf6d-4a0f-adf2-f4911ba9ffa6") .setid2("1") .setid3("2") .setmanufacturer(0x011

How can I use a regex match as a hash index in Ruby? -

i'm new ruby , i've run issue can't solve. i'm trying use gsub() match pattern in string, use match index hash. far, haven't been able figure out. here's code: farm = { "pig_num" => 5, "horse_num" => 2, "cow_num" => 4} assessment = "there 'pig_num' pigs on farm" assessment.gsub(/'(.+?)'/, '\1') # => "there pig_num pigs on farm" assessment.gsub(/'(.+?)'/, farm) # => "there pigs on farm" assessment.gsub(/'(.+?)'/, farm['\1']) # => typeerror: no implicit conversion of nil string assessment.gsub(/'(.+?)'/) { |key| farm[key] } the first call gsub() shows matching string want. the second call attempt use gsub(pattern, hash) flavor found @ the ruby documentation site . the third call trying reference value using match index. the fourth fancy pants way thought might work using lambda/proc/block. what doing wrong?

postgresql - redshift - how to use listagg with information_schema.columns table -

i'm using redshift , create comma separated list of columns. i'm trying grab column names information schema using listagg : select listagg(column_name,',') within group (order ordinal_position) information_schema.columns table_schema = 'my_schema' , table_name = 'my table'; i'm getting following error: [amazon](500310) invalid operation: function (listagg(text,text)) must applied on @ least 1 user created tables; although not answer how apply listagg on information_schema, can recommend alternative method of using listagg on pg catalog tables instead. try this: select distinct listagg(attname, ',') within group (order a.attsortkeyord) "columns" pg_attribute a, pg_namespace ns, pg_class c, pg_type t, stv_tbl_perm p, pg_database db t.oid=a.atttypid , a.attrelid=p.id , ns.oid = c.relnamespace , db.oid = p.db_id , c.oid = a.attrelid , typname not in ('oid','xid','tid','cid&

javascript - How to track the following event in the system? -

there sites has user system video watching function, check following, notice logined user view , need include user name @ track event: a. if viewer finish watch entire video; , if number of videos viewed per visit / session? b. if viewer signed ie conversion rate? here guess: a) track finish watching video add track code @ video complete event ga('send', 'event', 'videos', 'complete', '<?= $video_title; ?>' ); but whole session not sure above code have track b) video viewer sign up add @ video detail page: if logined: ga('send', 'event', 'videos', 'play', '<?= $video_title; ?>' ,1); if not logined ga('send', 'event', 'videos', 'play', '<?= $video_title; ?>' ,0); the problem how add user name , , above track code can fulfill requirement? thanks lot helping. google analytics terms of use not allow track users

mysql - Where statement from concat/union script -

i have written below sql statement , results, when add name = statement doesn't recognise 'name' select concat( `surname` , ' ', `firstname` ) name prospects union select concat( `last_name` , ' ', `first_name` ) name customer order name; a couple of options. add clause each select. it's not possible reference result of expression in select list assigned alias, in clause of same query. specify predicate in clause, need repeat expression: select concat(p.surname,' ',p.firstname) name prospects p concat(p.surname,' ',p.firstname) = ? union select concat(c.last_name,' ',c.first_name) customer c concat(c.last_name,' ',c.first_name) = ? order 1 mysql extends sql standard, , allows having clause reference non-aggregate expressions not in group select concat(p.surname,' ',p.firstname) name prospects p having name = ? union select concat(c.last_name,' ',c.f

c - Retrieving local IP before a connection is made -

i trying determine local ip used on socket tcp connection towards given host on linux, using c. let me make example. connect socket , use getsockname() on file descriptor local ip (and local tcp port); can without opening connection? i read routing table , make decision based on - networking subsystem must have algorithm already, when connection open. in short, i'd know if there api access routing algorithms without having parse rules myself or opening actual connection. solution - if - linux that's ok. edit: on irc suggested create udp socket , use connect() on it. no network used @ point should able use getsockname() on it the solution know traceroute does. send packet ttl of 1 , see interface icmp return comes in on. recall there lots of incompatibilities between different hosts, there's several different types of messages might need send/receive data need.

cocoa - customise main menu bar NSMenuItems -

Image
how can customize main menu bar of os x app? so far, have tried adding submenu menu item, want item perform func xyz when pressed, , have created nsmenuitem class: class itemclass: nsmenuitem { func xyz(){ //function code } } then in attributes inspector menu item have assigned class itemclass. when run app menu item disabled despite fact enabled in attributes inspector. any help? you don't need subclass nsmenuitem so. nsmenuitem objects rely on responder chain. have set method in attributes inspector of first responder object this: . then need connect menuitem firstresponder , select method created. after that, follow answers instructions enable menu item.

Fail restore a SQL Server database .BAK from Enterprise to Express (Error 909) -

i need help. download sample sql server database internet (link: https://www.microsoft.com/en-us/download/details.aspx?id=18279 ). when tried restore database computer, process failed because sql server not in same version database came from. using sql server 2014 express edition, , data i've download enterprise edition, of features not available in current edition. what should restore database without installing enterprise edition? need sample of huge database (with millions of rows or more) educational purpose, , think proper one. or maybe of can give me similar database compatible express edition. thank you. you can restore long database doesn't have enterprise features , doesn't exceed max size of express edition.you have ensure both of same version .this can checked using select @@version if none of above helps,you can generate scripts , run them

database - How-to Maintain DB Java Connection -

i have .db file in github (same level src folder) can commit/push rest of files. how make sure connection java code sqlite database stays valid once loaded onto user's system? can stick with connection = drivermanager.getconnection("jdbc:sqlite:mydatabase.db"); or need rework path? sqlite creates new empty db if doesn't find 1 it's looking for, want make sure connects. (i imagine best solution involve maven or ant, haven't learned how use yet.) (edit bump.)

ruby on rails - Is it necessary to add index to latitude and longitude fields -

i using rails , geocoder gem postgres database. therefore have add latitude , longitude fields database. speaking isnt better add indexing fields faster querying? if end querying database records using latitude , longitude, you'll benefit adding index. indexes used not exact matching queries, comparison queries, such select * table_name latitude between 30 , 40 , longitude > 50 . depending on queries , number of records, postgres query planner choose optimal way find matching records (either sequential scan, or index scan).

spring - what is the idiomatic way to use ConfigurationProperties and EnableConfigurationProperties in tests? -

i trying setup unit tests elements used within spring(-boot) application, , struggled setup around configurationproperties , enableconfigurationproperties . way got work doesn't seem consistent examples have seen in have witnessed needing both configurationproperties , enableconfigurationproperties on configuration class, doesn't seem right, , hoping might provide guidance. here simplified example: javatestconfiguration.java package com.kerz; import org.springframework.boot.context.properties.configurationproperties; import org.springframework.boot.context.properties.enableconfigurationproperties; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import javax.validation.constraints.notnull; @configuration @configurationproperties @enableconfigurationproperties public class javatestconfiguration { public void setfoo(string foo) { this.foo = foo; } @notnull string foo; @bean string f

If URL Contains a Specific Port Redirect With JavaScript -

i need redirect url such http://forum.domain.com:4567 https://forum.domain.com . code run site wide, must redirect when visitor goes http://forum.domain.com:4567 i have tried this, loops: <script> if (window.location.href = "http://forum.domain.com:4567") { window.location = "https://forum.domain.com"; } </script> window.location location type, similar url type, meaning should have port property. you can like: if (window.location.port === "4567"){ window.location = "https://forum.domain.com"; } or in case want little more extensibility: if (window.location.port === "4567"){ window.location = window.location.href.replace(':' + window.location.port, ""); }

mysql - Java returning null pointer exception for SQL query that gets passed to JSP -

i working on school assignment required use sql statements in java code use like operator search. in order search have string user, , split string delimiter, , run query so: select * movies (movies.title '%userinput%'); i return query in form of arraylist. now, when testing out. tested no user input, , query became: select * movies (movies.title '%%'); . gave me correct results. however when put title in there, of sudden nullpointerexception on line: if(title.equals("")) { return "(movies.title '%%') "; section of code: public string getsearchstring(string title) { if(title.equals("")) { return "(movies.title '%%') "; } string ret = "("; arraylist<string> titlearray = util.splitsearch(title); for(int = 0; < titlearray.size() - 1; ++i) { string temp = titlearray.get(i); string stmt = "movies.title '%" + temp + "%' or "