Posts

Showing posts from May, 2014

c# - Mocking generic repository factory method -

i've made refactoring if our repository factory make more generic , right method creating repositories looks that: public trepository createrepository<trepository>(params object[] parameters) trepository : class { if (_serviceprovider == null) throw new argumentnullexception(nameof(_serviceprovider)); return activatorutilities.createinstance<trepository>(_serviceprovider, parameters); } in production code using , works charm: _concreterepo = repofactory.createrepository<concreterepo>(); but when trying refactor unit tests having difficulties setting factory, how doesn't work. public class tests { // since using moq can't mock abstract types having problems type conversion in set up. protected readonly mock<iconcreterepository> _concreterepositorymock = new mock<iconcreterepository>(); protected readonly mock<irepositoryfactory> _factorymock = new mock<irepositoryfactory>(); [s

java - JSch Exec output for error -

i need run shell script @ remote machine. using jsch connect remote machine , executing shell script using channelexec . need know how can know, if there error while execution of command. following code channelexec channel = (channelexec) session.openchannel("exec"); bufferedreader in = new bufferedreader(new inputstreamreader(channel.getinputstream())); string command = scriptname; if(parameter != null && !parameter.isempty()){ command += " " + parameter; } logger.debug("command executed: " + command); channel.setcommand(command); channel.connect(); //capture output string msg; stringbuffer output = new stringbuffer(); while ((msg = in.readline()) != null) { //output = output + msg; output.append(msg); } logger.debug("output message = " + output.tostring()); logger.debug("error status --" + channel.getexitstatus()); channel.disconnect(); session.disconnect(); start official

SQL - Include rows that don't return Sum results being cut from Query -

newish sql - pulling items inventory point vendor information , levels @ last database update. test inventory i'm using building query, contains 35 inventory items. i additionally added sum of usage on time frame function query, cuts of 18 items weren't used in timeframe i've given. (the usage pulls negative need abs additionally) sample text is: select item_no, inv_point, par_level, abs(sum(quantity_used) usage from.... do need split query 2 , can add usage column right of existing query , display null if no results? i've looked on here similar issues , tried coalesce can't seem work. thanks wiki

jquery - javascript sort and remap array -

i'm using following code (courtesy of jquery javascript sort array highest count ) sort list of strings highest lowest count: var items = {}, sortableitems = [], i, len, element, listofstrings; listofstrings = json.parse(the_chems); (i = 0, len = listofstrings.length; < len; += 1) { if (items.hasownproperty(listofstrings[i])) { items[listofstrings[i]] += 1; } else { items[listofstrings[i]] = 1; } } (element in items) { if (items.hasownproperty(element)) { sortableitems.push([element, items[element]]); } } sortableitems.sort(function (first, second) { return second[1] - first[1]; }); instead of type of array input ["red", "red", "red", "blue", "blue"] which returns [ [ "red", 3 ], [ "blue", 2 ] ] i use array [["red","apple"], ["red","chilli

Excel - sum to target for multiple targets -

i trying set spreadsheet highlights or somehow marks numbers in list add total. have looked @ solver add-in seems 1 total @ time. want find values in c add totals in , in d add totals in h. values in these rows pulled bank statement , 10250 tabs when paste new data 2 tabs automatically updates in e-transfer tab. numbers in columns c, d, h , change every time use spreadsheet figure out numbers add totals each time. ideas? spreadsheet sample wiki

javascript - Ember js 2, Using scss @import in my app.scss production doesn’t remove comments in final css -

in app.scss file i'm using @import "./node_modules/bootstrap/scss/bootstrap"; because i'm using (and changing) bootstrap variable app.scss. i found ember build -prod doesn't remove comments within bootstrap imports in final app.css. so in production css have this: /*! * bootstrap v4.0.0-beta (https://getbootstrap.com) * copyright 2011-2017 bootstrap authors * copyright 2011-2017 twitter, inc. * licensed under mit (https://github.com/twbs/bootstrap/blob/master/license) */address,dl,ol,p,ul{margin-bottom:1rem}body,caption{text-align:left}........ why? how can remove superfluous comments? /*! "special" comment due ! character @ end not stripped build. contains mandatory license information, means illegal strip if use bootstrap assets. wiki

ios - ARKit Unable to run the session, configuration is not supported on this device -

using arworldtrackingsessionconfiguration , error on iphone 6 plus unable run session, configuration not supported on device what can be? you can check arkit support programatically @ runtime using 'issupported` property of arconfiguration. arconfiguration.issupported if (arconfiguration.issupported) { // arkit supported. can work arkit } else { // arkit not supported. cannot work arkit } following ios devices (with ios 11 installed) supporting arkit: iphone x iphone 8 , 8 plus iphone 6s , 6s plus iphone 7 , 7 plus iphone se ipad pro (9.7, 10.5 or 12.9) ipad (2017) here reference links related arkit support & ios device configurations: arkit runs on apple a9 , a10 & a11 bionic chip processors. iphone models - (chip) ipad models - (chip) wiki

dns - Mailgun emails are blocked by a particular domain -

when use mailgun's smtp config, mails 1 particular domain blocked. if use gmail's smtp config instead, mails go through. reason mailgun's mails blocked? domain admin claims there no sign of email in logs when mailgun sends email. wiki

Is it possible to have SPA authentication without redirecting to an outside login page -

i developing spa application connects bunch of webapi's. these api require user logged in, started digging openid conect , oauth2 examples, using identityserver. they require, spa reasons, implicit grant should used retrieving access_tokens. token refreshes handled connecting authentication server using hidden iframe. what understand approach o renewing access_token that, sessions maintained @ authentication service. hidden iframe goes authentication server, sessions still active, new access_token provided. all looks me, except (for ux reasosn) fact user needs redirected authentication server page providing credentials. isn't possible have spa application send credentials authentication server, getting access_token, , refresh using hidden iframe silently renewing (we, dont want user keep informing credentials every 15 minutes or every hour..). if not acceptable security reasons, please explain why? this oidc-client-js library does. have @ automaticsilentr

python 2.7 - faster way to check list on membership multiple values -

i want test if multiple values have membership on list, script slow. tried far: list1 = [10,20,35,45,67,88,99] x in list1: if 9<x<11: x in list1: if 34<x<39: x in list1: if 87<x<90: print "yeah" the general idea finish iteration once conditions satisfied. there might cleverer ways solve it, simplest can think of keeping track of conditions' results, , breaking true . example: list = [10, 20, 35, 45, 67, 88, 99, 0] // there keep track of each test cond1 = false cond2 = false cond3 = false // each of conds become true , keep value. x in list: cond1 = cond1 or (9 < x < 11) cond2 = cond2 or (34 < x < 39) cond3 = cond3 or (87 < x < 90) if cond1 , cond2 , cond3: // once of them become true, know want , can break loop print "yeah" break wiki

Update date in MySQL to contain leading zeros -

let's have column col1 in table tab1 has following mixed format dates: 2015-03-03 2015-02-03 2017-3-6 2015-03-04 2017-11-6 what mysql query update column more consistent, dates contain leading zeros you should storing these date field begin anyway here's query update `tab1` set `col1` = date(`col1`); wiki

javascript - How to toggle class inside a loop of items in vue.js -

i'm new vue.js , have list of items: <div class="jokes" v-for="joke in jokes"> <strong>{{joke.body}}</strong> <small>{{joke.upvotes}}</small> <button v-on:click="upvote"><i class="fa fa-arrow-up grey"></i></button> <div> i want toggle grey green when user clicks upvote button, user knows jokes upvoted. in methods have: data () { return { jokes:[], //filled dynamically calling backend server id: '' } }, methods: { upvote: function(joke) { joke.upvotes ++; //how toggle grey green here? } } how can achieve this? have tried different tricks tutorials change class of items, not 1 up-voted. you need pass joke method, first of all. v-on:click="upvote(joke)" then need add v-class it. either v-bind:class, or :class. <div class="jokes" v-for="joke in jokes&quo

python - Error installing virtualenvwrapper -

Image
i'm getting error shown below trying install virtualenvwrapper. doing wrong? i'm using mac osx. i'm installing using pip sudo. same error if use pip without sudo last login: tue aug 22 09:45:59 on ttys001 john:~ tcl$ sudo pip install virtualenvwrapper password: directory '/users/tcl/library/caches/pip/http' or parent directory not owned current user , cache has been disabled. please check permissions , owner of directory. if executing pip sudo, may want sudo's -h flag. directory '/users/tcl/library/caches/pip' or parent directory not owned current user , caching wheels has been disabled. check permissions , owner of directory. if executing pip sudo, may want sudo's -h flag. collecting virtualenvwrapper downloading virtualenvwrapper-4.7.2.tar.gz (90kb) 100% |████████████████████████████████| 92kb 1.2mb/s requirement satisfied: virtualenv in /library/python/2.7/site-packages (from virtualenvwrapper) requirement satisfied: virtualenv-cl

regex - Regular Expressions two strings -

i not understand regular expressions. hope can me. i have in file date of files aug 15:07 file1.txt jul 15:04 file2.txt aug 15:05 file3.txt aug 15:05 file4.txt aug 2016 file5.txt jul 15:09 file6.txt i want files start 'aug' , have time (:) /^aug :/ but doing shows me files without exception this filenames starting 'aug :' not want. try /^aug [0-9]{1,2}:/ instead. looks filenames which: start 'aug ' then 1 or 2 digits then colon also, bash command you're running ? (you can test regex @ regex101.com, it's website or ;-) ) wiki

Check values in a form (Javascript) -

i've 5 variables in form, simplicity named them a, b, c, d , e. in order submit form (a or (b or c)) , (d or e) must have value (i hope it's clear :p). i've tried with if ((a == "" || (b == "" || c == "")) && (d == "" || e == "")) { alert ("error!"); } else { form.submit(); } but doesn't work in every case. example, if a, b , c have value, form submitted if neither d or e have values. thank help! if have strings, reverse condition , check logical , and 1 or. var = '', b = '', c = '', d = '', e = ''; if (a && b && c || d && e) { console.log('form.submit();'); } else { console.log('error!'); } why works: given (a == "" || (b == "" || c == "")) && (d == "" || e == "") simplified a == ""

javascript - How to add i tag after input tag -

my source code is: <div id="id1" class=class1> <label><input type="checkbox" name="something">uh, label</label> </div> i add tag after input tag. source code looks like: <div id="id1" class=class1> <label><input type="checkbox" name="something"> <i class="genius"></i> uh, label</label> </div> is possible javascript? wiki

plot - Any idea to implement parallel coordinate in matlab? -

Image
i trying implement plot any ideas or advice how implement parallel coordinates plot in matlab? please see parallelcoords . adding new y-axis done manually via line(...). way make parallel coordinates plot use function form safe toolbox wiki

python - Change row values based on a range of indices in pandas? -

i have dataset this: index _id first last date 0 11 john doe 2016-01-01 1 12 jane doe 2016-01-06 2 13 jack hammer 2016-01-06 3 14 peter dex 2016-01-10 i want change date 2016-01-06 2016-01-10 based on range of index(1-2 in case). how can that? thanks! is there involved logic or methodology behind this? if not, can access slice using df.loc : in [354]: df.loc[df.index.isin([1, 2]), 'date'] = '2016-01-10' in [355]: df out[355]: index _id first last date 0 0 11 john doe 2016-01-01 1 1 12 jane doe 2016-01-10 2 2 13 jack hammer 2016-01-10 3 3 14 peter dex 2016-01-10 you can substitute [1, 2] range object: df.loc[df.index.isin(range(1, 3)), 'date'] = '2016-01-10' wiki

How to download multiple file in angular 2 -

this code download file in angular 2. want download pdf, txt, docx, excel file code. used file saver can download diffrent files on click of button. public downloadcsvfile() { this.downloadpdf().subscribe( (res) => { //console.log(res); saveas(res,'frontend.xlsx') } ); } public downloadpdf(): { let urls='assets/files/frontend.xlsx' let headers = new headers(); //headers.append('authorization', 'jwt ' + localstorage.getitem('id_token')); return this.http.get(urls, { headers: headers,responsetype: responsecontenttype.blob }).map( (res) => { return new blob([res.blob()], { type: 'application/vnd.ms-excel' }) }) } this html code how download diffrent file. file name displayed in table want corrosponding file downloaded. <tr *ngfor ="let mydrive of providermydrive"> &l

java - HttpMessageNotReadableException: Could not read document: Stream closed; -

i working spring boot , filtering requests using filters. filter being used have check user verification reading data request body (for have used httpservletrequestwrapper implementation). requestwrapper getting data expected , services working fine in filter. but, when on success, filter passes request main controller, getting stream closed exception follows: o.s.w.s.m.s.defaulthandlerexceptionresolver - failed read http message: org.springframework.http.converter.httpmessagenotreadableexception: not read document: stream closed; nested exception java.io.ioexception: stream closed here filter class: @webfilter(urlpatterns = {"/getdocs" }) public class authenticationfilter implements filter{ private static logger logger = logger.getlogger(authenticationfilter.class); @autowired private userverificationservice userverificationservice; @override public void destroy() { // todo auto-generated method stub } @override publ

ios - Ensuring that FetchedResultsController matches its linked TableView after MOC save -

tldr - frc appears out of sync table view linked to. how can sync? my view controller (vc) has table view called holestable managed fetched results controller (frc) called fetchedresultscontroller . when user presses save button on vc, calls ibaction called saveholes . saves data in frc's managed object context tests data rules have been followed. errors caught , message sent on vc displays error user after unwind (not shown here). i'm discovering frc doesn't have same contents on-screen holestable because function lookforsiproblems doesn't pick errors when called. however, able validate underlying database has received , stored data that's on screen. subsequent calls vc show saved data , subsequent presses of save button will find error problems. so, appears frc results out of sync shown in holestable @ time validation. here's salient code: fileprivate lazy var fetchedresultscontroller: nsfetchedresultscontroller<hole> = { //

excel - VBA - Comparison anomalies using variant -

i have found couple of other questions dealing variants none of them seem address issue. i have simple loops doing comparisons. purpose color excel cell red if there isn't match. results 99% accurate, have noticed couple of seemingly random errors. example, cell containing number 104875 not colored red, indicates there should matching cell in comparison column. there isn't. seems should wrong or correct. of other threads variants have mentioned comparisons have of same type or weird errors. in case, of same type (both integers), isn't problem. i brand new vba , still trying understand how works. this relevant part of code: private sub commandbutton1_click() dim long, j long dim flag boolean dim array1() variant, array2() variant dim column1 double dim column2 double column1 = convertcolumn(textbox1.text) column2 = convertcolumn(textbox2.text) set wb1 = workbooks("advocate july 2017 data.xlsm").sheets(1) set wb2 = workbooks("bi report 8-18-17.xl

maven - java.lang.NoClassDefFoundError: javax/el/ELManager -

i'm working on webapp in spring using spring tool suite. if build , deploy application there using ide onto provided pivotal tc server, works fine. however, if manual "mvn clean package" build , attempt deploy standalone tomcat server (using newest tomcat 7), throws following exception: 2017-08-23 15:24:13 warn annotationconfigwebapplicationcontext:551 - exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.beancreationexception: error creating bean name 'requestmappinghandleradapter' defined in org.springframework.web.servlet.config.annotation.delegatingwebmvcconfiguration: bean instantiation via factory method failed; nested exception org.springframework.beans.beaninstantiationexception: failed instantiate [org.springframework.web.servlet.mvc.method.annotation.requestmappinghandleradapter]: factory method 'requestmappinghandleradapter' threw exception; nested exception org.springframewo

html - Multiple layers of absolute positioning -

i creating comment stream layout, has bar in background has position:absolute. comment items placed on top of bar. works fine, people able mention other users in comment. dropdown menu open when typing @ placed behind consecutive comment. dropdown menu using position: absolute whereas comment has position:relative. seems these multiple layers don't work together. <div class="timeline"> <div class="comment"> <input placeholder="mention @username"> <div class="mention-dropdown"> <div class="mention">username</div> <div class="mention">username</div> <div class="mention">username</div> <div class="mention">username</div> <div class="mention">username</div> </div> </div> <div class="comment"> comment text </div> <div

ag grid - Typescript augmentation -

i've been trying unsuccessfully augment type in aggrid few new properties. import * aggrid 'ag-grid/main'; declare module "ag-grid/main" { export interface coldef { format: string; unittype: string; } } everything have tried results in original coldef being overwritten , build error of: export declaration conflicts exported declaration of 'coldef' so figured out how this. problem cannot augment re-exported module. have directly import it. import coldef 'ag-grid/dist/lib/entities/coldef'; // patch coldef interface allows add new properties it. declare module "ag-grid/dist/lib/entities/coldef" { interface coldef { format?: string; unittype?: string; } } this apply library re-exports it's modules. in case of aggrid there main.d.ts exports modules other definition files export modules directly. more info here. https://github.com/microsoft/typescript/issues/8427 wiki

java - What is the equivalent of layout_constraintRight_toLeftOf programmatically in android? -

i add constraints textview within constraintlayout programmatically. know had use constraintset , have no idea how add xml attribute: layout_constraintright_toleftof (and equivalencies) on textview in java in android. any appreciated!! you can set this, constraintset constraintset = new constraintset(); constraintset.clone(layout); // root layout // if want align parent layout left constraintset.connect(textview.getid(), constraintset.left, layout.getid(), constraintset.left); // if want align left of 1 more textview - second text view constraintset.connect(textview.getid(), constraintset.right, textview1.getid(), constraintset.left); /*______________________________ | text1 text2 | | |*/ constraintset.applyto(layout); wiki

ios - If you rotate the iPhone's video with ffmpeg, the rotation information sticks. Can I hide this? -

the following implementation command rotate movie 90 degrees. ffmpeg -i video.mp4 -vf transpose=1 -metadata:s:v:0 rotate=0 videoo.mp4 -vf transpose=1 the iphone's video contains rotation information , actually ffprobe -show_streams -print_format json videoo.mp4 2>/dev/null to output motion picture information or rotation information described below. "tags": { "rotate": "90", "creation_time": "2017-08-24t01:49:38.000000z", "language": "und", "handler_name": "core media data handler", "encoder": "'avc1'" }, "side_data_list": [ { "side_data_type": "display matrix", "displaymatrix": "\n00000000: 0 65536 0\n00000001: -6

dependency injection - Unable to resolve service for type 'Core.Data.CoreContext' while attempting to activate 'Core.Data.Repositories.UnitOfWork' -

i have part of webapi application want move separate project class library. common base structure every app has idea make easy shareable. application type is: asp.net core web application / .net framework - asp.net core 2.0 / web api what have done in direction created project named core , moved shared elements there, including base entities (e.g. user, settings, etc), corecontext, unitofwork, generic repository, baserepositories,... in main project of app there others entities, appcontext inherits corecontext, more repositories, , controllers, ... i able build app when starting following error: invalidoperationexception: unable resolve service type 'core.data.corecontext' while attempting activate 'core.data.repositories.unitofwork'. microsoft.extensions.dependencyinjection.servicelookup.callsitefactory.createargumentcallsites(type servicetype, type implementationtype, iset callsitechain, parameterinfo[] parameters, bool throwifcallsitenotfound

java - HIbernate - Many to Many - Nested c:foreach -

i'm trying run nested c:loop in following. before page loads, list itemsextrascat objects itemsextrascatservice.getextrascatbyiditems(item) . no problem here, right number of results. however, nested loop not displaying properly. not sure if hibernate issue or jstl. jsp <c:foreach var="itemsextrascat" items="${itemsextrascat}"> <th><c:out value="${itemsextrascat.extrascat.name}"></c:out> </th><br> <table> <c:foreach var="extras" items="${itemsextrascat.extrascat.extras}"> <tr><c:out value="${extras.name}"></c:out></tr> </c:foreach> </table> </c:foreach> which returns fruit overy easy syrups on medium breakfast additions sunny side so category titles correct, extras 1) incorrect item , extrascat , 2) not listing extras under category. pretty sure how hibernate calling o

Google Script and Anonymous user in Google Sheet -

i've public google sheet (everyone can access , edit it). in it, use script, function, download csv urlfetchapp.fetch(url); . when anonymous user access (without google login), user can view, , edit sheet, but, user cannot run script. user must logged google account script working. the stranger thing sheet script working anonymous users early. problem didn't occur before couple weeks ago. do know if google change security or error doing? i guess intended behavior long anonymous user access sheet via shareable link. stated in support page , might see name don’t recognize or "anonymous animals" viewing document, spreadsheet, or presentation. this can happen when document shared publicly or has link. limit how people can view file if want stop sharing file can edit, can learn how to: turn off link sharing file. prevent others sharing files own. hope helps. wiki

node.js - Request Graphql api running on different port from Next.js app in development mode localhost -

i'am switching existing app create-react-app next.js, seems work correctly except api end point running on node app on port 4000, can't access next.js app. followed examples in repo can't make work, in production use nginx reverse proxy no problem , i'am in dev mode . setting apollo redux followed example : with-apollo-and-redux , proxy used example with-custom-reverse-proxy i know , making wrong, can't figure out @ moment in initapollo.js ... function create() { return new apolloclient({ ssrmode: !process.browser, networkinterface: createnetworkinterface({ uri: "/api" }) }); } ... in server.js ... const devproxy = { "/api/": { target: "http://localhost:4000/api/", changeorigin: true } }; app .prepare() .then(() => { const server = express(); if (dev && devproxy) { const proxym

How not to compile files under test (junit) in Eclipse using Ant build -

i using ant compile eclipse project. reads src folder description .classpath file (atleast assume so) because, in ant build script compiles files src (hence decided should pick .classpath). following entries in .classpath file make junit test compile through ant. how avoid junit test files , compiles src java files when compiled through ant build process. <?xml version="1.0" encoding="utf-8"?> <classpath> <classpathentry kind="src" output="target/classes" path="src/main/java"> <attributes> <attribute name="optional" value="true"/> <attribute name="maven.pomderived" value="true"/> </attributes> </classpathentry> <classpathentry kind="src" output="target/test-classes" path="src/test/java"> <attributes> <attribute name="optiona

amazon web services - Complete steup of Monit client and server -

i need setup monit in 40 aws servers. i tried 1 test server below link http://xmodulo.com/server-monitoring-system-monit.html but how can rest server? should need server client setup 1 main server dashboard , rest clients? wiki

Calculate time between 2 events in Javascript -

i'm doing beginners course in javascript , working on basic project reaction timer. idea random shapes (squares or circles only) appear in random positions @ random intervals , user has click on them. here's have far: document.addeventlistener("domcontentloaded", function() { var shape = document.getelementbyid("shape"); function generaterandomshape() { console.log("test"); var shapetype = ["50%", ""]; var shapecolor = ["red", "green", "yellow", "purple", "orange", "brown", "gray", "black", "blue"]; shape.classlist.remove("disappear"); shape.style.backgroundcolor = shapecolor[math.floor(math.random() * shapecolor.length)]; shape.style.height = math.random() * 300 + "px"; shape.style.width = shape.style.height; shape.style.borderradius = shapetype[math.floor(ma

python - How to create abaqus model using script according to joints directly -

Image
i'm working on transformer can transform sap2000 model abaqus model, , can finish work modeling, add boundary, add load , on. there beam elements , shell elements in model. 1.at first, read .s2k file, , use mypart.element(...) function create beam element or shell element.(mypart = mdb.models['model-1'].part(name='structure')). model consists of elements only. this modeling result, can see have elements in model 2.and in way, can calculate normal structures, question is: if structure has prestress, want add minus temperature specified frame simulate prestressing. step 1 said, model has elements, , predefinedfiled in load module can't add temperature on elements...... 3.so idea create faces , lines according joints belong(i.e. not create elements directly), can't find functions in abaqus scripting reference guide ...... so can help? thanks, all!! wiki

Eclipse e4 RCP - Integration from Xtext Plugin -

i'm new rcp development , stumbling around 1 problem. created e4 example application application.e4xmi. want use external editor. got sources github repo ( https://github.com/franca/franca ). repo contains xtext generated editors want integrate new e4 application. i'm not sure if should use feature, dsl parts or ui parts plugins , what's best way of integrating editors. recognized there seem compatibility issues e3 , e4 parts can't find proper solution work around. i imported serveral plugins repo workspace , tried link them e4 application. tried import plugin jar didn't work better. won't work feature. i'm sorry question within 2 days of looking around internet couldn't find solution how setup project right. although found indicators compatibility problems shared element id org.eclipse.ui.editorss didn't understand neither did work shown in these tutorials. help. wiki

c# - MySQL causing fatal error after executing query with parameters -

i creating method execute query 1 or more parameters. code: public static ienumerable<t> executequerywithparameters<t>(string query, string connectionstring, string[] parametersarray, string[] valuesarray) { using (mysqlconnection connection= new mysqlconnection(connectionstring)) { using (var cmd = new mysqlcommand(query, connection)) { (int = 0; < parametersarray.length; i++) { cmd.parameters.addwithvalue(parametersarray[i], valuesarray[i]); } connection.open(); return connection.query<t>(query); } } } tempsave table structure: +------------------------------+ |id|localization|items|quantity| +------------------------------+ how works: when called, method receive 4 parameters: a query (example: select * tempsave localization = @localization ) a connection string (example: server=localhost; database=wintestbeta;user=root; password

java - I need to check the status of the activemq broker before the messages sent -

actually usecase need handle broker not available situation. need know status of broker before send messsages? tried below sendtimeout property, still not success. <bean primary="true" id="jmsconnectionfactory" class="org.apache.activemq.activemqconnectionfactory"> <property name="brokerurl" value="failover:(tcp://localhost:61616)" /> <property name="useasyncsend" value="true" /> <property name="watchtopicadvisories" value="false" /> <property name="sendtimeout" value="2000" /> </bean> connection conn = null; try { conn = connectionfactory.createconnection(); jmstemplate.send(...); } catch (exception e) { ... } { if (conn != null) { conn.close(); } } or can send within try/catch. also, it's better wrap activemqconnectionfactory in cachingconnectionfactory avoid opening

jpa - Jetty+Jersey: are container-managed entity transactions possible? -

i'm using hibernate/jpa 5.2.10 jetty 9.4. is possible set jetty in way such that: a) servlet requests (including jersey) wrapped in entity transactions, and b) required entitymanager accessible within jersey resource classes ? i don't want use spring/di/ioc , stuff , keep things simple , fast possible. there other ways achieve jersey restful development rapid "rtt"? maybe implement static method create entity manager , associate current request, , set request listener cleanup, , use method explicitly inside jersey resource methods? em factory , store inside webapp context, , use listener cleanup. though, i'd prefer trodden path, existing java ee seem bent on killing unit testing extent. wiki

ios - cannot invoke initializer for Unmanaged<AnyObject>? with no arguments in swift -

what want convert rsa sec key base64 encoded string swift. initialized variable below, var publickeybits = unmanaged<anyobject>?() then gives cannot invoke initializer unmanaged? no arguments in swift i want covert publickey below var publickeybits = unmanaged<anyobject>?() secitemcopymatching(queryattrs, &publickeybits) let opaquebits = publickeybits?.toopaque() let publickeydata = unmanaged<nsdata>.fromopaque(opaquebits).takeunretainedvalue() let publickeybase64 = publickeydata.base64encodeddata(nsdatabase64encodingoptions.encoding64characterlinelength) error. idea of this. you need check initialization of unmanaged class, there might initialization parameters. var publickeybits = unmanaged<anyobject>("mykey") wiki

c# - Cannot connect to AD server through userprincipalname -

i'm trying connect ad server attributemapusername="userprincipalname" , error the server not operational same code attributemapusername="samaccountname" works fine. sample web.config <connectionstrings> <add name="myadproviderconnection" connectionstring="ldap://xxxx.xxxx.xxxx.com:636/ou=testou,dc=xxx,dc=xxxx,dc=xxxx" /> </connectionstrings> <membership defaultprovider="myadprovider" userisonlinetimewindow="15"> <providers> <add name="myadprovider" type="system.web.security.activedirectorymembershipprovider, system.web, version=2.0.3600.0, culture=neutral, publickeytoken=b03f5f7f11d50a3a" connectionstringname="myadproviderconnection" connectionusername="administrator@xxxx.xxxx.com" connectionpassword="xxxxxx" connectionprotectio

java - Random number generator generates duplicates -

framework: java public static list<integer> buttonidlist = new arraylist(); public void mymainmethod() { for(integer = 0; < 11; i++) { int randombuttonid = getuniqueidnumber(); } } private static integer getuniqueidnumber() { random ran = new random(); int randombuttonid = ran.nextint(20) + 1; if(buttonidlist.contains(randombuttonid)) { getuniqueidnumber(); } else { buttonidlist.add(randombuttonid); } return randombuttonid; } when code encounters duplicate, calls (recursively) , in second try if number unique return statement returns mymainmethod or getuniqueidnumber? where should return statement placed? you should return result of recursive call: private static integer getuniqueidnumber() { random ran = new random(); int randombuttonid = ran.nextint(20) + 1; if(buttonidlist.contains(randombuttonid)) { return getuniqueidnumber(); } else {

apache - Default Launching Page For App -

i using apache2 , tomcat host application on ubuntu server. have used mod_jk connect apache , tomcat. have configured virtual host on apache serving port 80 , 443. want whenever user tries access domain-name-of-my-server.com should serve login page of application hosted on tomcat. whenever request made apache serves document root's index page expected. now question what's standard way redirect user tomcat application through apache default page. redirecting through javascript index page login page of tomcat app. wiki

erlang - How to Convert a list of tuples into a Json string -

i have erlang list of tuples follows: [ {{"a"},[2],[{3,"b"},{4,"c"}],[5,"d"],[1,1],{e},["f"]} , {{"g"},[3],[{6,"h"},{7,"i"}],[{8,"j"}],[1,1,1],{k},["l"]} ] i wanted list of tuples in form: <<" [ {{"a"},[2],[{3,"b"},{4,"c"}],[5,"d"],[1,1],{e},["f"]} , {{"g"},[3],[{6,"h"},{7,"i"}],[{8,"j"}],[1,1,1],{k},["l"]}] ">> so tried using json parsing libraries in erlang (both jiffy , jsx ) here did: a=[ {{"a"},[2],[{3,"b"},{4,"c"}],[5,"d"],[1,1],{e},["f"]} , {{"g"},[3],[{6,"h"},{7,"i"}],[{8,"j"}],[1,1,1],{k},["l"]} ], b=erlang:iolist_to_binary(io_lib:write(a)), jsx:encode(b). and following output(here have changed list binary since jsx

Dynamically transform simple array to multidimensional array in PHP -

i have array contry list this $array = array('country1' => countryone, 'country2' => country two); how can dynamically transform array in multiple array like: array(2) { [0] => array(2) { ["code"] => "country1",["name"] => "countryone"} [1] => array(2) { ["code"] => "country2",["name"] => "countrytwo"} }} simply loop through , create new array each key/value pair. <?php $array = array("country1" => "countryone", "country2" => "countrytwo"); $newarray = array(); foreach($array $key => $value) { array_push($newarray, array("code" => $key, "name" => $value)); } var_dump($newarray); ?> wiki

How do I send POST requests with HTTP header containing newlines in postman? -

Image
when http header contains newlines lf or crlf, postman doesn't send request. gives error: how send post requests containing newlines in postman? thank you. from w3 docs , line breaks, in multi-line text field values, represented cr lf pairs, i.e. `%0d%0a' also, try using x-www-form-urlencoded format send request. hope helps. wiki

c# - Locking properties vs Locking the entire object. Which is better for performance? -

i writing triggerbot , i'm creating class called settings contain private variables (all controls in form) , public properties (bools , ints) public class settings { private bunifucustomtextbox xoffsettb; private bunifucustomtextbox yoffsettb; private bunifucustomtextbox scanintervaltb; private bunifucustomtextbox rclickintervaltb; private bunifucustomtextbox snipewatitimetb; private bunifucustomtextbox arrowwaittimetb; private bunifucheckbox closerangerclickcb; private bunifucheckbox longrangerclickcb; private bunifucheckbox closerangelclickcb; private bunifucheckbox longrangelclickcb; private bunifuswitch kinessamodecb; private bunifuswitch shalinmodecb; private bunifuiosswitch drawcb; private bunifuiosswitch disableonshiftcb; public int xoffset { get; set; } public int yoffset { get; set; } public int scaninterval { get; set; } public int rclickinterval { get; set; } public int snipewaittime { get