Posts

Showing posts from September, 2014

algorithm - how i can find the time complexity of the above code -

for(i=0; i<n; i++) // time complexity n+1 { k=1; // time complexity n while(k<=n) // time complexity n*(n+1) { for(j=0; j<k; j++) // time complexity ?? printf("the sum of %d , %d is: %d\n",j,k,j+k); time complexity ?? k++; } what time complexity of above code? stuck in second (for) , don't know how find time complexity because j less k , not less n. i having problems related time complexity, guys got article on it? step count , loops. from question : because j less k , not less n. this plain wrong, , guess that's assumption got stuck. know values k can take. in code, ranges 1 n (included). thus, if j less k, less n. from comments : i know the input n in second depends on k not in n . if variable depends on anything, it's on input. j depends on k depends on n , means j depends on n . however, not enough deduce complexity. in end, need know how many times printf called. the outer loop ex

spring - java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'product' available as request attribute -

this question has answer here: what causes “java.lang.illegalstateexception: neither bindingresult nor plain target object bean name 'command' available request attribute”? 1 answer whenever click on edit button, getting error java.lang.illegalstateexception: neither bindingresult nor plain target object bean name 'product' available request attribute , not able understand what's wrong here my product controller follows @requestmapping(value="/product/edit/{id}", method=requestmethod.get) public string editproducts(@pathvariable("id") string productid,model model){ system.out.println("productid"); product = productdao.get(productid); model.addattribute("product", product); model.addattribute("productlist",productdao.list()); return "product"; } my product.jsp

django - Adding a dict if the query set is empty -

i need check if django query has values if not need append dict query set validation purpose. so, don't want create entry in database. obviously, since can't append queryset(attribute error) there other way add this? listing = listing.objects.values() if len(listing) < 1: listing.append({ 'address': 'some string', 'range': 'some other string' }) if want manually create list when queryset empty, that's rather easy listing = listing.objects.values() if len(listing) < 1: listing = [{ 'address': 'some string', 'range': 'some other string' }] if want append regardless of whether queryset empty or not: listing = list(listing.objects.values()) listing.append({ 'address': 'some string', 'range': 'some other string' })

Analyse SQL Server histogram table -

is there way access histograms values in sql server sql command? easy see histogram of attribute using dbcc show_statistics, however, possible access histogram table in sql select command or in t-sql procedure/function? i remember trick video of kimberley tripp,so quick search yielded below create table histogram ( [range_hi_key] sql_variant , [range_rows] sql_variant , [eq_rows] sql_variant , [distinct_range_rows] sql_variant , [avg_range_rows] sql_variant ) insert histogram exec ('dbcc show_statistics(''dbo.orders'',''_wa_sys_00000001_29572725'') histogram') now can access table ..you can same stat_header , density_vector references: https://social.msdn.microsoft.com/forums/sqlserver/en-us/00a3fc6f-bc42-46da-9574-088522976fbb/dbcc-showstatistics-how-to-send-result-to-table?forum=sqltools

passing JSON data from one controller to another controller angularJS -

i want pass data 1 controller controller, getting data in $scope.imagegallerys variable , able set data setjson(); controller 1 function imagegallerycontroller($scope,$http,myservice){ var urlbase = "http://localhost:8084/apc/api/"; $http.get(urlbase + '/gallerylist'). success(function(data) { $scope.imagegallerys = data; myservice.setjson($scope.imagegallerys); }); } i want data anther controller getjson() not returning value or object. controller 2 function categorycontroller($scope,myservice){ $scope.myreturn = myservice.getjson(); } factory function myservice(){ var imagegallerys = null;//the object hold our data return{ getjson:function(){ return imagegallerys; }, setjson:function(value){ imagegallerys = value; } } angular.module('abc') .controller('categorycontroller', categorycontroller) .controller('imagegallerycontroller',

Inconsistency in Write-Output "$obj" and directly printing $obj in Powershell -

this dummy.json file { "key1":"value1", "key2":"value2" } i'm reading contents of file variable , outputting them c:> $obj = get-content .\dummy.json c:> $obj { "key1":"value1", "key2":"value2" } c:> write-host "$obj" { "key1":"value1", "key2":"value2" } i know get-content doesn't preserve line breaks , joins " ". powershell keep text formatting when reading in file but why there inconsistency in above 2 outputs ? guess write-host doing job correctly. or wrong ? it's not get-content joins lines (its output array of strings), putting variable in double quotes ( "$obj" ). can avoid joining lines yourself: write-host ($obj -join "`n") write-host ($obj | out-string) write-host $($ofs="`n"; "$obj") another option read file dire

c# - How to call .dll file by URL -

i don't know silly question or not can call .dll file hosted in iis url parameters. for eg. https://<ipaddress>/createuser.dll? (user variable client application name, email, address) if yes how that. i google lot no desired result.

jquery - HIghcharts Legend Symbol Getting out of graph Canvas -

Image
i using highcharts scatter chart , want display 1 specific data point legend more wider other data points have implmented problem when point comes on x-axis or y-axis line gets out of graph canvas . things have tried offset marginleft screenshot but not fix issue. is there alternate solution this. if want of points land within plot border, , long know minimal data values, set min on xaxis and/or yaxis. see example, http://jsfiddle.net/7wd8vwxh/ xaxis: { title: { enabled: true, text: 'x axis title' }, min: 150 // equal value lower lowest x value }, yaxis: { title: { text: 'y axis title' }, min: 0 // equal value lower lowest y value },

c# - ASPX File only Shows Code -

i've been trying upload site hostinger domain few days now, reason .aspx file shows raw code , doesn't show of gui present when run through browser. how advise? <%@ page title="" language="c#" masterpagefile="~/mater pages/primary.master" autoeventwireup="true" codefile="default.aspx.cs" inherits="_default" %> <asp:content id="content1" contentplaceholderid="head" runat="server"> <style type="text/css"> .auto-style1 { width: 873px; height: 455px; } </style> </asp:content> <asp:content id="content2" contentplaceholderid="cpmaincontent" runat="server"> <h2 style="text-align: center"> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; hello , welcome personal website. hope enjoy visit.</h2> <h3 style="text-alig

google maps - Use of unresolved identifier 'GMSPlacesClient' after updating from GoogleMaps SDK for IOS to GooglePlaces SDK for IOS -

Image
i using googlemaps sdk places in app (using essentialy autocomplete feature) & saw possible use googleplaces sdk. (the googlemaps sdk has big size -130mb in .ipa file) migration link here i followed instructions getting lot of 'use of unresolved identifier' gmsplaceclients ,cllocationdegrees or gmsautocompleteresultsviewcontroller althought suppose in googleplaces sdk. any ideas missing ? thanks help. edit: after pod install in terminal : the class have changed. use : googleapi.placeautocomplete(...)

php - Yii2: Subdomain in subdirs redirects to subdir -

i wan't have 2 complete yii2 frameworks running: 1 on main website , 1 in subdomain (for testing). example on www.example.com & staging.example.com. everything seems working fine staging keeps redirecting me subfolder (to staging.example.com/staging) , don't want that! want url staging.example.com the folder setup is: /var/framework-live/ -> yii2 framework /var/framework-staging/ -> yii2 staging framework /var/www/ -> web folder /var/www/staging/ -> staging web folder i have in htdocs/.htaccess: options +followsymlinks -multiviews rewriteengine on rewritebase / # staging rewritecond %{http_host} ^staging.example.com$ [nc] rewriterule ^((?!staging).*)$ /staging/$1 [nc,l] rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule . index.php and in htdocs/staging/.htaccess: options +followsymlinks rewriteengine on # if directory or file exists, use directly rewritecond %{request_filename} !-f rewritecond %{req

import a rule to a Drupal 7 with Drush -

how can import rule drupal 7 site drush. i export rule existing drupal 7 site , want import site, don't want ui. i want use drush or kind of script. you can using drush , feature/custom deploy module. please see link details: https://www.drupal.org/project/hook_update_deploy_tools#import-rule

ios - 'NSFastEnumerator.Element' (aka 'Any') has no subscript members -

i going through appcoda blog , came across function have indices of visible rows. learning , implementing swift 3 / xcode 8 . no subscript members error following function. func getindicesofvisiblerows() { visiblerowspersection.removeall() currentsectioncells in celldescriptors { var visiblerows = [int]() row in 0...((currentsectioncells as! [[string: anyobject]]).count - 1) { if currentsectioncells[row]["isvisible"] as! bool == true { //get compile time error here visiblerows.append(row) } } visiblerowspersection.append(visiblerows) } } how object of currentsectioncells array object key " isvisible " here? you need specify type of array celldescriptors [[[string:any]]] way. for currentsectioncells in celldescriptors.objectenumerator().allobjects as! [[[string:any]]]{ var visiblerows = [int]() row in 0..<currentsectioncells.count { if

r - Change name of point labels in -

Image
i know how add point labels when using ggplot2 using geom_text() p <- ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars))) p + geom_text() but if want change "fiat x1-9" "worst car ever" without changing entries in original dataframe? there way rename point in plot within geom_text()? thanks much. you can override aesthetic or use in initial expression: nms <- rownames(mtcars) p + geom_text(aes(label = replace(nms, nms == "fiat x1-9", "worst car ever"))) edit if not want create new object can use this. point of advice, don't become attached one-liners. fun, creating object best readability, debugging, , accuracy. p + geom_text(aes(label = replace(rownames(mtcars), rownames(mtcars) == "fiat x1-9", "worst car ever")))

Get Output from sqlplus prompt in bash script -

i have issue in writing bash script. i trying output sqlplus prompt bash variable. tried many ways suggested in many forums. t=$(./bin/sqlplus 'oracleuser/password@(description=(address=(protocol=tcp)(host=192.168.1.2)(port=1521))(connect_data=(sid=connectstring)))' << end select (1 - (sum(getmisses)/(sum(gets) + sum(getmisses)))) * 100 v\$rowcache; exit; end ) echo $t this trying exactly. in above, generating string 'oracleuser/password@(description=(address=(protocol=tcp)(host=192.168.1.2)(port=1521))(connect_data=(sid=connectstring)))' dynamically. part works well, issue comes when passing command select (1 - (sum(getmisses)/(sum(gets) + sum(getmisses)))) * 100 v\$rowcache; in sqlplus prompt. here happens like, $ symbol getting escaped, * symbol causes issues (like in sqlprompt lists files in directory runs!) when running command whole. i have coded :- connect="'oracleuser/password@(description=(address=(protocol=tcp)(host=192.

java - How does one decide to create a checked excpetion or an unchecked exception -

this question has answer here: java: checked vs unchecked exception explanation 18 answers i want know how 1 know create , throw checked exception or unchecked exception. for example have service takes data , validates before using it. during validation field did not meet rules , want throw exception validationexception(). how know of decide should checked or unchecked. in case calling external web service code example google stock api. let's assume have timeout of 3 seconds. if time exprires want throw exception backendexception(). how know if should checked exception or unchecked exception. thanks in advance. there might different opinions i'd difference how caller should handle exception: if want make sure caller handles exception either doing (logging, trying recover etc.) or rethrowing use checked exception. example said validationexcep

Azure WebApp Deployment Slot: Pre-Swap Job -

hy we have 2 app services: restservice (azure app service web app -> asp.net) webapplication (azure app service web app -> angular.js spa) the restservice has web.config , webapplication appconfig.json configuration-file. on each app service have staging-slot, tests (auto , manual). reason, need have sticky-slot settings web.config , appconfig.json file. sticky-slot settings portal, think not possible (these settings apply appsettings-configurations in web.config think). what best way that? i think of that: - in release-configuration deploy web-apps staging slots , modifying (adjust settings staging-environment) on web.config , appjson.config in task (power-shell or similar)...then can auto-tests, if succeed undo changes in config-files , swap production. is, if want manual tests , swapping in portal? have undo of changes myself... is there maybe pre-swap job, trigger before swapping? thanks help, peter as know, easy if store settings in web.conf

PrestaShop installing theme error -

when try install new theme both ftp , computer im getting following error: warning: error while sending query packet. pid=89741 in /home/fansport/public_html/fansportsklep.pl/classes/db/dbpdo.php on line 91 catchable fatal error: argument 2 passed objectmodelcore::hydratecollection() must of type array, boolean given, called in /home/fansport/public_html/fansportsklep.pl/classes/prestashopcollection.php on line 358 , defined in /home/fansport/public_html/fansportsklep.pl/classes/objectmodel.php on line 1495 i dont have idea wrong. check "max_allowed_packet" in mysql , increase value. solve problem.

Python CSV Error -

hello keep getting error while making small program sort large csv files out, below code , error, doing wrong? if selection: stuff in stuffs: try: textfile = open("output.txt",'w') mycsv = csv.reader(open(stuff)) d_reader = csv.dictreader(mycsv) headers = d_reader.fieldnames <-- error happens here if selection in headers: placeinlist = headers.index(selection) #placeinlist = selection.index(selection) selection in tqdm(mycsv, desc='extracting column values...', leave = true): textfile.write(str(selection[int(placeinlist)])+'\n') print 'done!' textfile.close() sys.exit() except ioerror: print 'no csv file present in directory' sys.exit() el

ios - Swift 3 - ">>>-" produces NSLayoutConstraint, not the expected contextual result type "Void" -

since swift 3 i'm getting error: ">>>-" produces nslayoutconstraint, not expected contextual result type "void" (aka "()") in project. fileprivate func configuratecell(_ cell: basepagecollectioncell, backimage: uiimage?) { cell.translatesautoresizingmaskintoconstraints = false view.addsubview(cell) // add constraints [(nslayoutattribute.width, cell.bounds.size.width), (nslayoutattribute.height, cell.bounds.size.height)].foreach { info in cell >>>- { $0.attribute = info.0 $0.constant = info.1 } } [nslayoutattribute.centerx, .centery].foreach { attribute in (view, cell) >>>- { $0.attribute = attribute } } cell.layoutifneeded() }

mysql - fill groups with values based on group values (update with group bys) - SQL - postgre -

Image
i have situation in produce output, , based on gorup of belonging, gets , index (common group). production goes on , insert new values belong same group. want assign these new records same "marker" group had. i'd sql alone. detailed in picture below, groups composed tuple (continent, zone, state) i, in fact, group by. (table name: ' geo ') how can put number 5 aside manchester , 6 aside lyon? if ok first inserting data, , running second query update blank group numbers, there 1 option: update yourtable t1 set group = t2.group ( select continent, zone, state max(group) group yourtable group continent, zone, state ) t2 t1.continent = t2.continent , t1.zone = t2.zone , t1.state = t2.state the inner query in from clause finds maximum group value each continent, zone, state combination. there should 2 types of values each group combination, namely number and/or null . null value indicate recor

mysql - Laravel update based on other value -

how can translate used within laravel query builder ? mysql update mytable set val = val +1 id = 1 in laravel $res = db::table('mytable') ->update(['val' => ?]); thanks try: db::table('mytable')->where('id',1)->increment('val'); the increment method accept second parameter amount sum, if need val = val + 2 can use ->increment('val', 2) . see reference: https://laravel.com/api/5.3/illuminate/database/eloquent/builder.html#method_increment

c - Porting Zed Shaw's debug macros to MSVC -

i've found zed shaw's debug macros on website when c book "learn c hard way" free read. designed linux initially, , works pretty well, been using while. now, i've started write c code windows , i'm using visual studio. want use these debug macros in project i'm working on. the problem follows: let's want use check macro make sure function returned without error. display = al_create_display(640, 480); check(display, "failed create display"); the definition macros used following: #define clean_errno() (errno == 0 ? "none" : strerror(errno)) #define log_err(m, ...) fprintf(stderr, "[error] (%s:%d: errno: %s) " m "\n", __file__, __line__, clean_errno(), ##__va_args__) #define check(a, m, ...) if(!(a)) { log_err(m, ##__va_args__); errno=0; goto error; } however, problem encountered visual studio marks strerror() deprecated , aborts compilation. plan on using threads in project, don't want go "

javascript - Output value from Json Array -

i'm getting output: [{"ref":"contact.html","score":0.7071067811865475}] $.getjson( "index.json", function(content) { idx = lunr.index.load(content); var results = idx.search(variabletosearch); var final = json.stringify(results); console.log(final); }); how can print value of ref? when console.log(final[0].ref); undefined. edit: json.stringify returns string, not object. in case 'final' string contains same data in object 'results' to access data object, can use result[0].ref, or if want use 'final' (although don't need to), can this: final = json.parse(final) console.log(final[0].ref) if it's 1 object within array, other answers enough, since arrays used store multiple objects, can follows: var arr = [ {"ref": "object1", "score": "1"}, {"ref": "object2", "score": "

c# - How to get device lock type? -

so, i`m trying check application if device has type of protection when user tries unlock it. means. need know if device unlocked without graphical (numeric) key mobile devices. desktop devices in need know if current user has password. possible in general both cases (mobile , pc)? on pc seems there no method detect if password set user account, there method check if pin set using keycredentialmanager.issupportedasync | issupportedasync method , can check official keycredentialmanager sample , passportavailablecheck() method in signin.xaml.cs file. for pc, pin higher level security, can set if password set , there have other security policies. on mobile there no password, if pin set, can detected. this topic belongs security part of uwp apps, here documents example create microsoft passport login app , fingerprint biometrics . may not able solve problem, can see can , not able in uwp app these documents.

android - Name of project on ActionBar of every Activity -

i facing issue since upgrading android studio 2.2... whenever create new activity in project, name of project getting displayed on actionbar of new activity rather name of new activity created. have learned intent , transition 1 activity fine action bar has name of project rather name of current activity. should do? declare label in manifest: <activity android:name=".your_activity" android:label="name_your_activity_label"/> <activity android:name=".your_activity" android:label="name_your_activity_label" /> example demonstration, edit in future. :p

php - Search query not working -

i have coded mysql query multiple fields, , result should match fields. below code, select e.es_id, e.es_sex, e.service_type, e.working_name, d.es_age, d.es_city, d.es_regional_city escorts e inner join escorts_details d on e.es_id = d.es_id es_sex '%" . $es_sex . "%' , category '%" . $category ."%' , es_city '%" . $es_city ."%' , es_regional_city '%" . $es_regional_city ."%'"; and when m executing code after filling fields.. select e.es_id, e.es_sex, e.service_type, e.working_name, d.es_age, d.es_city, d.es_regional_city escorts e inner join escorts_details d on e.es_id = d.es_id es_sex '%male%' , category '%waitresses%' , es_city '%7%' , es_regional_city '%%' its still showing female details, if see excuted query, have filled "male" (es_sex '%male%'). i don't know m doing wrong. please me. thanks. it's becaus

virtualenv - Installed python incorrectly -

i realised have been using python on mac in incorrect manner. installed modules in folder /usr/local/lib/python2.7/site-packages . i have heard unsafe install modules globally , virtualenv should used instead. have uninstalled python using brew uninstall python , modules still in site-packages folder. how reset environment , safely install python modules not globally installed , therefore not have use sudo while installing modules?

python: best way convey missing value count -

Image
i have data frame 9 features , features have missing values. following count of missing values in each feature: df.isnull().sum() which gives me: a 0 b 0 c 15844523 d 717 e 18084 f 118679 g 0 h 978505 0 i want display information in nice way. can create table in report there other way display in plot? i think can use numpy.log series.plot.bar : import matplotlib.pyplot plt np.log(s).plot.bar() plt.show() another solution categorize data bins cut , use series.plot.bar : import matplotlib.pyplot plt #convert series 1 column df column name 'name' df = s.rename('name').to_frame() bins = [-1,1, 10, 100, 1000,10000,100000,1000000,10000000, 100000000,np.inf] labels=[0,1,2,3,4,5,6,7,8,9] df['label'] = pd.cut(df['name'], bins=bins, labels=labels) print (df.label) 0 b 0 c 8 d 3 e 5 f 6 g 0 h 6 0 name: label, dtype: category categories (

java - Infinispan preload data from database table -

how preload data infinispan local cache? have pre-existing application table has key value pairs. want infinispan cache data in table , when read/write data cache, want underlying table in sync. possible infinispan? infinispan stores entries in sql db in marshalled form (as there no generic mapping between pojos , sql), , needs keep metadata along. that's why jdbc stores can't access existing db structure. there's jpa store uses hibernate orm access db , "marshall" entries according jpa specification. may option you.

Fitting a curve to a drawing in Gimp -

Image
i'd make logo contains mathematically defined shapes (to wit, log-normal , normal distribution; see below). can generate image of these shapes using python's matplotlib, import gimp. in gimp, i'm aware of tool drawing bezier curves hand, 'select color' option used select curves. however, i'd lines constant thickness. there way 'fit' 2 constant-thickness lines picture in gimp? if have them paths (in other words, bezier curves) "stroke" them ( edit>stroke path if done manually, pdb.gimp_edit_stroke_vectors(layer,path) in python).

python - Pandas DataFrame slicing based on logical conditions? -

Image
i have dataframe called data: subjects professor studentid 8 chemistry jane 999 1 chemistry jane 3455 0 chemistry joseph 1234 2 history jane 3455 6 history smith 323 7 history smith 999 3 mathematics doe 56767 10 mathematics einstein 3455 5 physics einstein 2834 9 physics smith 323 4 physics smith 999 i want run query "professors @ least 2 classes 2 or more of same students". desired output smith: physics, history, 323, 999 i familiar sql , have done easily, still beginner in python. how achieve output in python? line of thought convert dataframe sql database , have sql interface through python run queries. there way accomplish that? students_and_subjects = df.groupby( ['professor', 'subjects'] ).studen

linux - How can I get pyinstaller to working on Ubuntu? -

i using ubuntu 16 , installed python 3.5, installed pip3 , pip3 installed pyinstaller. not able run pyinstaller. whenever type in pyinstaller in the terminal, got below error? have add path? if so, how do that? thanks pyinstaller: command not found first need find pip installed pyinstaller: sudo find / -name pyinstaller then can either run using full path or add .bashrc file. add .bashrc, create following line or add path existing "export path=" line in .bashrc (found in home directory): export path="/path/to/pyinstaller:$path" save file , logout/login have take effect. to make path available users, add /etc/environment file (must sudo edited).

How to merge the elements in a list sequentially in python -

i have list [ 'a' , 'b' , 'c' , 'd'] . how list joins 2 letters sequentially i.e ouptut should [ 'ab', 'bc' , 'cd'] in python instead of manually looping , joining use zip within list comprehension: in [13]: ["".join(seq) seq in zip(lst, lst[1:])] out[13]: ['ab', 'bc', 'cd'] or since want concatenate 2 character can use add operator, using itertools.starmap in order apply add function on character pairs: in [14]: itertools import starmap in [15]: list(starmap(add, zip(lst, lst[1:]))) out[15]: ['ab', 'bc', 'cd']

pytz - Pandas convert datetime with a separate time zone column -

i have dataframe column time zone , column datetime. convert these utc first join other data, , i'll have calculations convert utc viewers local time zone eventually. datetime time_zone 2016-09-19 01:29:13 america/bogota 2016-09-19 02:16:04 america/new_york 2016-09-19 01:57:54 africa/cairo def create_utc(df, column, time_format='%y-%m-%d %h:%m:%s'): timezone = df['tz'] df[column + '_utc'] = df[column].dt.tz_localize(timezone).dt.tz_convert('utc').dt.strftime(time_format) df[column + '_utc'].replace('nat', np.nan, inplace=true) df[column + '_utc'] = pd.to_datetime(df[column + '_utc']) return df that flawed attempt. error truth ambiguous makes sense because 'timezone' variable referring column. how refer value in same row? edit: here results answers below on 1 day of data (394,000 rows , 22 unique time zones). edit2: added groupby example in case wants see result

playframework 2.0 - How to process Twilio 'Programmable video' JWT access token correctly? (Android) -

Image
i trying embed twilio's programmable video android app. i've created endpoint on java server, uses "com.twilio.sdk" % "twilio-java-sdk" % "6.3.0" library obtaining access tokens following code: private static final string account_sid = "acxxxxx"; private static final string api_key_sid = "skxxxxx"; private static final string api_key_secret = "aa8xxxxx"; private static final string twilio_configuration_sid = "vsxxxxx"; public result token(string identity) { return ok(json.tojson(new responsemessage(createtoken(identity)))); } public static string createtoken(string identity) { conversationsgrant grant = new conversationsgrant(); grant.configurationprofilesid = twilio_configuration_sid; accesstoken token = new accesstoken.builder( account_sid, api_key_sid, api_key_secret ).identity(identity).grant(grant).ttl(86400).build(); return token.to

db2 - How to match starting date to the closest ending date in order to get the time difference -

select out.emp_id, out.dt_tm "datetimeout", in.dt_tm "datetimein", cast(timestampdiff( 4, char(timestamp(in.dt_tm) - timestamp(out.dt_tm))) decimal(30,1))/60 "duration out" ( select e1.emp_id, e1.dt_tm hr.timeout e1 month(e1.dt_tm)=09 , year(e1.dt_tm)=2016 , e1.cd='out' ) out left join ( select e2.emp_id, e2.dt_tm hr.timeout e2 month(e2.dt_tm)=09 , year(e2.dt_tm)=2016 , e2.cd='in' ) in on out.emp_id=in.emp_id trying closest datetimein match datetimeout . repeats same datetimeout , datetimein multiple times. i think normal because table dont have constraint unique on emp_id, dt_tm , cd. if want unique result try : period ( select e1.emp_id, e1.dt_tm hr.timeout e1 month(e1.dt_tm)=09 , year(e1.dt_tm)=2016 ) select distinct out.emp_id, in.dt_tm datetimein, out.dt

oracle adf - How does this selectItems field get saved into the database -

i reading blog: http://andrejusb.blogspot.ca/2015/06/select-one-choice-with-select-items-tag.html he creates custom selectitems has list of values in bean. other fields bound view corresponds table in database. when user clicks save these fields saved, not understand how new custom selectitems saved. isn't binding table in database. how work? how can save custom list of values database? he demonstrating how create bean-based selectitems. when user selects, need capture index of selection in backing code: <af:selectonechoice label="select search" id="socsrch" autosubmit="true" valuechangelistener="#pageflowscope.wci.handleselectsearch}" contentstyle="width:250px"> <f:selectitems id="si1" value="#{pageflowscope.wci.searchnames}"/> </af:selectonechoice> public void handleselectsearch(valuechangeevent valuechangeevent) {

c# - UWP - Dependency property - UIPropertyMetada confusion -

i`m moving project wpf uwp , don't understand how can create dependency property in uwp coercevaluecallback, in wpf public static readonly dependencyproperty minimumfrequencyproperty = dependencyproperty.register("minimumfrequency", typeof(int), typeof(spectrumanalyzer), new uipropertymetadata(20, onminimumfrequencychanged, oncoerceminimumfrequency)); but understood there no coercecallback in uwp. or i`m not right? coercevaluecallback not supported in uwp. propertymetadata in uwp lives in windows.ui.xaml namespace , has following constructors: propertymetadata(object) propertymetadata(object, propertychangedcallback) propertymetadata in wpf lives in system.windows namespace, has 5 constructors. 1 of them coercevaluecallback: propertymetadata(object, propertychangedcallback, coercevaluecallback)

Creating SSL Certs For google app engine Using ZeroSSL And Let's Encrypt -

i'm trying install ssl certificates created using zerossl.com page let's encrypt, google cloud platform. followed free ssl certificate wizard so. zerossl page generates 4 files in process: domain-crt.txt domain-key.txt account-key.txt domain-csr.txt the google cloud platform asks 2 files: pem encoded x.509 public key certificate unencrypted pem encoded rsa private key i've made combinations, , followed suggestion find in web, had no success. i asked zerossl people, , alexander answers me solution. ssl certificate wizard generates longer more secure 4096 bits key default, google accepts 2048 bits key. should generate new csr separately first using csr generator @ https://zerossl.com/free-ssl/#csr , making sure select 2048 bits. download produced key , csr (please note domain key, not le key) , use same le key used , new csr ssl certificate wizard. @ last wizard step, might need split domain-crt.txt file in two. first part between -

php - How to return html without break recursive loop -

how concat html , tell php send html in end of recursive loop ? i have recursive loop build tree table (parent-child) nodes. functions work want return full html not print it, use return, breaks foreach loop. function show_full_tree($ne_id) { $store_all_id = array(); $id_result = $this->comment_model->tree_all($ne_id); foreach ($id_result $comment_id) { array_push($store_all_id, $comment_id['parent_id']); } //echo $this->db->last_query();exit; $this->in_parent(0,$ne_id, $store_all_id); } function in_parent($in_parent,$ne_id,$store_all_id) { if (in_array($in_parent,$store_all_id)) { $result = $this->comment_model->tree_by_parent($ne_id,$in_parent); echo $in_parent == 0 ? "<ul class='tree'>" : "<ul>"; foreach ($result $re) { echo " <li class='comment_box'>

sql server - Update field in a table with trigger after insert and update -

i have trigger in database. create trigger trigg_varer_ledit_iu on items insert, update begin update items set lastedit = getdate() itemnr in (select itemnr inserted) end; it works good. every time update , insert new data items "lastedit" field updated. but: have spesific fields in table should not trigger update lastedit field. how can achieve that? now works every fields updated. need keep of them out of circus. you can use if construct check. example on updates inserted.column = deleted.column related question - compare deleted , inserted table in sql server 2008

python - Improving frequency time normalization/hilbert transfer runtimes -

Image
so bit of nitty gritty question... i have time-series signal has non-uniform response spectrum need whiten. whitening using frequency time normalization method, incrementally filter signal between 2 frequency endpoints, using constant narrow frequency band (~1/4 lowest frequency end-member). find envelope characterizes each 1 of these narrow bands, , normalize frequency component. rebuild signal using these normalized signals... done in python (sorry, has python solution)... here raw data: and here spectrum: and here spectrum of whitened data: the problem is, have maybe ~500,000 signals this, , takes while (~a minute each)... entirety of time being spend doing actual (multiple) hilbert transforms i have running on small cluster already. don't want parallelize loop hilbert in. i'm looking alternative envelope routines/functions (non hilbert), or alternative ways calculate entire narrowband response function without doing loop. the other option make frequency

java - mystery on timstamp getTime diff -

here code: system.out.println(" serverstarttime:" + serverstarttime + " serverrunningtime:" + serverrunningtime); timestamp stime = converttimeformat(serverstarttime, "mmm d, yyyy h:mm:ss z"); timestamp etime = converttimeformat(serverrunningtime, "mmm d, yyyy h:mm:ss z"); long diff = (etime.gettime() - stime.gettime()); system.out.println("etime.gettime():" + etime.gettime() + " stime.gettime():" + stime.gettime() + " time diff:" + diff); the converttime looks like: private timestamp converttimeformat(string msgdate, string srcdateformat) { simpledateformat sdf = new simpledateformat(srcdateformat); simpledateformat output = new simpledateformat("yyyy-mm-dd hh:mm:ss"); try { date d = sdf.parse(msgdate); string formattedtime = output.format(d); return timestamp.valueof(formattedtime); } catch (parseexception e) { e.printstacktrace(); } retu

subprocess - Unable to loop the files to perform diff in python -

i new python. writing python script find diff between 2 html file1: beta.vidup.me-log-2016-09-21-17:43:28.html , file2: beta.vidup.me-log-2016-09-21-17:47:48.html. to give idea file organization: have 2 directories 2016-09-21 , 2016-09-22. file1: beta.vidup.me-log-2016-09-21-17:43:28.html present in dir1 , file2: beta.vidup.me-log-2016-09-21-17:47:48.html present in dir2. below snippet: dir1 = raw_input("enter date of archive folder compare in format yyyy-mm-dd---->\n") dir2 = raw_input("enter date of folder compare in format yyyy-mm-dd----->\n") = datetime.now() folder_output = '/home/diff_output/{}'.format(now.strftime('%y-%m-%d')) mkdir(folder_output) fname1 = '/home/output/%s/beta.vidup.me-log-2016-09-21-17:43:28.html'%dir1 fname2 = '/home/output/%s/beta.vidup.me-log-2016-09-21-17:47:48.html'%dir2 # open file reading in text mode (default mode) f1 = open(fname1) f2 = open(fname2) cmd = "diff "+fname1

log4j2 KeyValuePair for .properties file -

how create keyvaluepair in log4j2 in propterties file? i know in log4j version 1 it's done like: log4j.appender.x.additionalfields={'key': 'value'} and xml way in log4j2 is: <keyvaluepair key="key" value="value"/> so way properties file this: `appender.x.keyvaluepair ={'key': 'value'}` ? this working example of how define key value pair example graylog2 (gelf) appender: appender.graylog.type=gelf appender.graylog.name=graylog appender.graylog.server=yourhostname appender.graylog.includestacktrace=true appender.graylog.additionalfields.type=keyvaluepair appender.graylog.additionalfields.key=yarncontainer appender.graylog.additionalfields.value=containerxyz

Php Session Array - Updated Session Array not showing up in the listbox -

Image
what looking listbox refreshed $_session data. first inital load, loads fine. when select option want removed , click on submit. $_session modifys perfectly. --- index.php --- <select name="listbox" size="5" height="500px;"> <?php $array_length = count($_session['listmodify'][0]); if(isset($_session['listmodify'][0])){ ($i = 0; $i < $array_length ; $i++) { echo '<option value="' . $_session['listmodify'][0][$i]['sku'] .','. $_session['listmodify'][0][$i]['qty'] . '">' . $_session['listmodify'][0][$i]['sku'] . ' - ' . $_session['listmodify'][0][$i]['qty'] . '</option>'; } } ?> </select> --- delete.php --- $listsku = $_post['listbox']; $key = array_search(trim($listsku), array_column($_session['listmodify'][0],"sku")); unset($_session['listmo

android - Store contacts' name and phones into an ArrayList -

i cannot make solution work... result app crash. made listview, added items , got selected ones, miss making elements of list contacts' names instead of random ones. once selected, ask number , putextra them in activity. edit: suggested, here's code i'm trying working: cursor phones = getcontentresolver().query(contactscontract.commondatakinds.phone.content_uri, null,null,null, null); while (phones.movetonext()) { string name=phones.getstring(phones.getcolumnindex(contactscontract.commondatakinds.phone.display_name)); string phonenumber = phones.getstring(phones.getcolumnindex(contactscontract.commondatakinds.phone.number)); } phones.close(); i'll insert loop every contact, adding every time strings name , phonenumber arraylist. however, when press button should run code (and button working fine), long list of errors android monitor (here's first lines): e/androidruntime: fatal except

python - self.request.GET[] with href HTML -

i need have self.request.get[] have correct code when user clicks, based on click in html. below main.py: import webapp2 data import fighter data import data pages import page pages import contentpage class mainhandler(webapp2.requesthandler): def get(self): f = fighter() d = data() p = page() c = contentpage() if self.request.get[1]: self.response.write(c.results(d.fighter_data[0].name, d.fighter_data[0].rank, d.fighter_data[0].age, d.fighter_data[0].hometown, d.fighter_data[0].fights_out_of, d.fighter_data[0].height, d.fighter_data[0].weight, d.fighter_data[0].reach, d.fighter_data[0].wins, d.fighter_data[0].loses, d.fighter_data[0].bio)) else: self.response.write(p.page) app = webapp2.wsgiapplication([ ('/', mainhandler) ], debug=true) where if self.request.get[1]: needs work if ?fighter=1 clicked pages.py below: class page(object): def __init__(self): self.page = '

python - If statement checking if a variable is equal to a specific word is getting invalid syntax -

so, i'm trying make easter egg in calculator program, if type friend johns name in, prints nerd, keep getting invalid syntax on line if statement starts. here's code looks like: x = input(' ') if x = john: print nerd else: print x please keep in mind i'm using python 2.7, not 3. when googled it, got answers worked in 3. x = raw_input('enter name ') if x == 'john': print 'nerd' else: print x you doing assignment, need == check equality

parsing - Convert a simple command into an AST in python -

i function in python converts string command ast (abstract syntax tree). the syntax command follows: commandname(3, "hello", 5.0, x::int) a command can accept number of comma separated values can either integers strings floats types suppose function called convert_to_ast , then convert_to_ast('commandname(3, "hello", 5.0, x::int)') should yield following ast: { 'type': 'command', 'name': 'commandname', 'args': [{ 'type': 'int', 'value': 3 }, { 'type': 'str', 'value': 'hello' }, { 'type': 'float', 'value': 5.0 }, { 'type': 'var', 'kind': 'int', 'name': 'x }] seems evaluate string , pick off types there: >>> items = ast.literal_eval('(404.5, "hello", 5)') >>> [{'type': t

linux - How To Extract Text Between HTML Tags With Or Condition Multiple Times -

i have been researching how extract title tags html. i've pretty figured out regex , html don't mix , grep can used. however, code found here , looks this: awk -vrs="</title>" '/<title>/{gsub(/.*<title>|\n+/,"");print;exit}' now, works find text between title tags once. know how can make run on every line. cat file; while read line; ...; done . however, know not efficient there's better way. secondly, in file need keep lines start string '--'. believe requires adding 'or' statement in awk match title tags , line starting '--' the input file this: text text text <title>random text of title 1</title> random html stuff --time-- xyz more random text <title>random text of title 2</title> hmtl text --time-- text <title>random text of title 3</title> more text tags --time-- text here <title>random text of title 4</title> random text html --time-- t

Scala - Remove first row of Spark DataFrame -

i know dataframes supposed immutable , , know it's not great idea try change them. however, file i'm receiving has useless header of 4 columns (the whole file has 50+ columns). so, i"m trying rid of top row because throws off. i've tried number of different solutions (mostly found on here) using .filter() , map replacements, haven't gotten work. here's example of how data looks: h | 300 | 23098234 | n d | 399 | 54598755 | y | 09983 | 09823 | 02983 | ... | 0987098 d | 654 | 65465465 | y | 09983 | 09823 | 02983 | ... | 0987098 d | 198 | 02982093 | y | 09983 | 09823 | 02983 | ... | 0987098 any ideas? the cleanest way i've seen far along lines of filtering out first row csv_rows = sc.textfile('path_to_csv') skipable_first_row = csv_rows.first() useful_csv_rows = csv_rows.filter(row => row != skipable_first_row)

json - mimicking the behavior of a web-api with static folders -

the problem. have access static web site. built web-api mvc , node sent data based on id passed instance. http://10.10.10.10:5000/api/blueprint/191 (where 191 id) this return json string [ json ] after looking in database table. table 1000 records. could mimic same behavior returning files static website? files "blueprint/191.json" instance. files kept statically on web server. thoughts? > <?php /* * change license header, choose license headers in project properties. * change template file, choose tools | templates * , open template in editor. */ header("access-control-allow-origin: *"); header('content-type: application/json'); /* @var $_get type */ $typeid = $_get['typeid']; $data = file_get_contents($typeid.".json"); echo $data;

kafka consumer AbstractCoordinator: Discovered coordinator Java client -

i have 3 brokers running broker id s 0 1 , 2. consumer (java client) picks broker 0 group coordinator , starts consume messages correctly. when broker 0 group coordinator down, consumer not , stalls on poll() method. process resumes when broker 0 , running. how handle scenario of group co-ordinator change in java client? i error when group coordinator dies: 16/09/22 17:42:45 info internals.abstractcoordinator: discovered coordinator datascience1.sv2.trulia.com:9092 (id: 2147483647 rack: null) group group2. 16/09/22 17:42:45 info internals.abstractcoordinator: (re-)joining group group2 16/09/22 17:42:45 info internals.abstractcoordinator: marking coordinator datascience1.sv2.trulia.com:9092 (id: 2147483647 rack: null) dead group group2

Django pagination error, int has no len -

@csrf_exempt def board_searched(request): searchstr = request.get['searchstr'] pageforview = request.get['pageforview'] contact_list = board.objects.filter(title__contains=searchstr).count() paginator = paginator(contact_list, 10) # show 25 contacts per page contacts = paginator.page(1) return render(request, 'board/board_searched.html', {'contacts': contacts}) this views.py code, processing search in board. , give link http://127.0.0.1:8000/board/search/result/?searchstr=asd&pageforview=1 in case, occurred object of type 'int' has no len() and, occurred @ contacts = paginator.page(1) what problem..? you need remove count() here: contact_list = board.objects.filter(title__contains=searchstr).count() it should be: contact_list = board.objects.filter(title__contains=searchstr) you have provide queryset, , amount want returned. before, not passing queryset, number, invalid.

objective c - How to convert an array of NSString to an array of c-strings? -

i have nsarray<nsstring*>* object, , need invoke c api takes in array of strings char** . what's best way this? important note c-strings must not have const modifier, following isn't enough since utf8string returns const char* : nsarray<nsstring*>* names = ...; int len = args.count; char* cnames[len]; for( int = 0; < len; i++ ) { cnames[i] = names[i].utf8string; }; you want dynamic memory cannot rely on backing memory utf8string being released. nsarray *strings = @[ @"string 1", @"other string", @"random string"]; char **cstrings = null; nsinteger numcstrings = strings.count; if (numcstrings) { cstrings = (char **)calloc(numcstrings, sizeof(char*)) ; if (cstrings) { // safer allocate memory each string (nsinteger i=0;i<numcstrings;i++) { nsstring *nsstring = strings[i]; char *cstring = (char *)malloc([nsstring lengthofbytesusingencoding:nsutf8stringencod

python - Download a gzipped file, md5 checksum it, and then save extracted data if matches -

i'm attempting download 2 files using python, 1 gzipped file, , other, checksum. i verify gzipped file's contents match md5 checksum, , save contents target directory. i found out how download files here , , learned how calculate checksum here . load urls json config file, , learned how parse json file values here . i put following script, i'm stuck attempting store verified contents of gzipped file. import json import gzip import urllib import hashlib # function creating md5 checksum of file def md5gzip(fname): hash_md5 = hashlib.md5() gzip.open(fname, 'rb') f: # make iterable of file , divide 4096 byte chunks # iteration ends when hit empty byte string (b"") chunk in iter(lambda: f.read(4096), b""): # update md5 hash chunk hash_md5.update(chunk) return hash_md5.hexdigest() # open configuration file in current directory open('./config.json') configfile: data

r - replacing next value with "1" -

i have matrix contains 1565 rows , 132 columns. observations either "0" or "1". want keep observations same 1 change, i.e whenever there "1", next value in same row should become "1". please see below sample: >df 0 0 1 0 0 na 0 1 1 0 0 1 0 0 na what want : 0 0 1 1 0 na 0 1 1 1 0 1 1 0 na i shall thankful help. saba one option using which arr.ind=true row/column index, add 1 column index, subset values , change 1. i1 <- which(df==1, arr.ind=true) i1[,2] <- i1[,2]+1 df[i1] <- 1 df # [,1] [,2] [,3] [,4] [,5] #[1,] 0 0 1 1 0 #[2,] na 0 1 1 1 #[3,] 0 1 1 0 na if there na elements adjacent 1 , want keep na, can modify above code with df[i1] <- replace(df[i1], !is.na(df[i1]), 1) data df <- structure(c(0l, na, 0l, 0l, 0l, 1l, 1l, 1l, 0l, 0l, 1l, 0l, 0l, 0l, na), .dim = c(3l, 5l),