Posts

Showing posts from August, 2011

r - Calculating change of values between same day in different years -

i need calculate called mat (movie anual total), means % change in sales value between same day in 2 different year: id sales day month year 500 31 12 2015 100 1 1 2016 200 2 1 2016 ... 200 1 1 2017 does have idea how deal it? i want this: id sales day month yeas **mat** with way data set up, you're quite close. want group data month , day, order each group year, , take successive differences (assuming want mat sequential years) library(lubridate) library(dplyr) x <- data.frame(date = seq(as.date("2014-01-01"), as.date("2017-12-31"), = 1)) %>% mutate(day = day(date), month = month(date), year = year(date), sales = rnorm(nrow(.), mean = 100, sd = 5)) x %>% group_by(month, day) %>% arrange(month, day, year) %>% mutate(mat = c(na, diff(sales))) %>% ungroup() if wanting abl

jquery - How to make changes in the element on mouse hover whenever element has focus? -

this code: .metismenu li a:hover{ background:#112542;} .metismenu li a:focus{ background:inherit;} when have clicked on a it's background-color being inherited , hovering mouse again on it's background-color not being #112542 until not clicking anywhere outside a remove focus it. there solution can change it's background-color without clicking outside , hovering mouse again? you can try :focus:hover state, in example : see fiddle .metismenu li a:focus:hover{ background:yellow;} .metismenu li a:hover{ background:#112542;} .metismenu li a:focus{ background:inherit;} .metismenu li a:focus:hover{ background:yellow;} <div class="metismenu"> <ul> <li><a href="#!">link test</a></li> </ul> </div>

error LSF: undefined symbol: _ZN3ajn15_RemoteEndpoint17 [alljoyn] -

i have trouble lsf alljoyn 15.04, build lsf in ubuntu 16.04 success cannot run app. i'm receiving notification whenever run ./lighting_controller_client_sample in service_framework-15.04/core/service_framework/build/linux/standard_core_library/lighting_controller_client/samples : ./lighting_controller_client_sample: symbol lookup error: ./lighting_controller_client_sample: undefined symbol: _zn3ajn15_remoteendpoint17pushmessagerouterern3qcc10managedobjins_8_messageeeerm how can fix it? sounds can't find cpp libs (the .a , .so files). in case need define ld_library_path. for example, if building alljoyn scons, define following environment variable before running sample. export ld_library_path=/core/alljoyn/build/linux/x86_64/release/dist/cpp/lib or export ld_library_path=/core/alljoyn/build/linux/x86_64/debug/dist/cpp/lib that @ least allow find alljoyn cpp lib files.

Management Information Model In Network Security -

my professor have not taught management information model in network security , gave assignment. not find precise , detailed information on topic. can me explain "what management information model in network security". exams near have clear concepts. thank in advance! :)

html - Apple File system Permission to read from Photo Library -

i have uiwebview inside ios application , loads responsive website webview, developed in asp.net . website has button choose video device photo library , button upload video. in till ios version 10.2 uploading files server. apple introduce new version ios 10.3 new file system apfs before hfs+ file system. in ios 10.3 doesnot allow application read video file , 0kb size uploaded server. because app doesnot have read permission file. how can allow file system permission read file app.is there can added info.plist do stuck kind of issue. thanks the problem related bug in uiwebview makes file input have multiple attribute set automatically. the solution ios 10.3 use wkwebview instead, not add multiple attribute automatically. it's old ios apps use uiwebview guess reason why there not many bug reports on web related problem.

x86/x64 instructions generated by .net jitter -

when running .net program know how @ msil. how view x86/x64 assembly instructions generated .net jitter on linux/mac platforms? if you're willing build coreclr yourself, can follow this guide make coreclr show disassembly.

php - Laravel Cors (Middleware NOT working) -

i tries enabling cors in laravel 5.4 unfortunately doesn't want work. have included code , error it's giving me below. can finding out why isn't working? have passed required headers. i have renamed domain domain.uk example purposes , don't wan't expose domain of site yet under development. routes (made 1 route ::any testing purposes while developing, on production post): route::group(['domain' => 'api.domain.uk', 'namespace' => 'api'], function() { route::group(['middleware' => ['cors'], 'prefix' => 'call'], function() { route::get('/rooms/{id}/get-locked-status', 'apicontroller@getroomlockstatus'); route::any('/rooms/{id}/update-locked-status', 'apicontroller@updateroomlockstatus'); }); }); error: xmlhttprequest cannot load http://api.domain.uk/ajax/rooms/1/update-locked-status. no 'access-control-allow-origin' h

wpf - Why isn't my user control with a combobox binding correctly? -

i've got simple usercontrol i'm trying create contains list of states. trying expose selected state via "selectedstate" property. however, i'm having trouble trying binding fire once it's hooked in usercontrol / form. the xaml user control looks this: <usercontrol x:class="sample.desktop.usercontrols.statedropdown" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:sample.desktop.usercontrols" mc:ignorable="d" width="170" height="28" d:designheight="28" d:designwidth="170"> <combobox x:name="cbostate" itemssource=&qu

iis - Is there a difference between "Etc/UTC" and "UTC" in logstash? -

im parsing w3c iis logs , i'm using found in this article starter. but part of logstash config im unsure of: ## set event timesteamp log # date { match => [ "log_timestamp", "yyyy-mm-dd hh:mm:ss" ] timezone => "etc/utc" } log_timestamp comes from: match => ["message", "%{timestamp_iso8601:log_timestamp}..... my question why using "etc/utc" , not "utc"? example find online of logstash config using "etc/utc". is necessary because of iis? happen if did utc? should identical (etc/utc "long" name) want confirm. the supported timezones date filter listed here: http://joda-time.sourceforge.net/timezones.html etc/utc 1 of allowed timezones universal time coordinated. utc allowed value. they're synonyms.

android - Is it possible to show a view with frosted glass effect, and a videoView playing below this view? -

just ios notification bar,when drag down notification bar,backgroud fog in meantime; not blur image ,it's blur every thing below view in meantime,in real time. an explanation given here. http://nicolaspomepuy.fr/blur-effect-for-android-design/ check out these libraries, https://github.com/kikoso/android-stackblur https://github.com/pomepuyn/blureffectforandroiddesign

python - Fitting data to a Generalized extreme value distribution -

Image
i've been trying use scipy.stats.genextreme fit data generalized extreme value distribution. i've tried of methods find, don't know why won't fit data. i've tried both these methods: import numpy np matplotlib import pyplot plt scipy.stats import genextreme gev datan = [0.0, 0.0, 0.122194513716, 0.224438902743, 0.239401496259, 0.152119700748, 0.127182044888, 0.069825436409, 0.0299251870324, 0.0199501246883, 0.00997506234414, 0.00498753117207, 0.0] t = np.linspace(1,13,13) fit = gev.fit(datan,loc=3) pdf = gev.pdf(t, *fit) plt.plot(t, pdf) plt.plot(t, datan, "o") print(fit) as as popt, pcov = curve_fit(gev.pdf,t, datan) plt.plot(t,gev.pdf(*popt),'r-') the second method resulted in " valueerror: unable determine number of fit parameters." thanks can give me! according scipy.stats documentation at: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.genextreme.html the fit()

html - jQuery file reader not working -

jquery code: var reader = new filereader(); reader.readasdataurl($("#img1").val()); reader.onload = function() { console.log(reader.result); }; html code: <input type="file" name="img4" id="img1"> i don't know why not working can please me how resolve error? filereader readasdataurl() function requires html5 blob or file object, not jquery object. see filereader.readasdataurl() on mdn . in example can achieve uploading file way: var file = document.getelementbyid('img1').files[0]; var reader = new filereader(); reader.addeventlistener('load', function() { var res = reader.result; console.log(res); }); reader.readasdataurl(file);

gnu sed - sed : Add newline after specific number of spaces and not characters -

i want add newline txt file after 48 spaces. this text line 151 150 147 155 148 133 111 140 170 174 182 154 153 164 173 178 185 185 189 187 186 193 194 185 183 186 180 173 166 161 147 133 172 151 114 161 161 146 131 104 95 132 163 123 119 129 140 120 151 149 149 153 137 115 129 166 170 181 164 143 157 156 169 179 185 183 186 186 184 190 191 184 186 190 183 175 168 160 147 136 135 167 136 108 153 167 149 137 111 90 134 162 121 122 141 137 151 151 156 143 116 124 159 164 174 169 135 144 155 153 164 170 176 178 177 178 187 185 181 182 183 181 178 170 164 158 148 144 130 136 173 130 97 137 167 157 138 113 90 138 168 109 123 146 151 152 155 127 113 159 167 170 171 142 131 140 154 162 168 169 169 164 168 173 176 179 178 176 173 172 170 161 154 152 146 145 137 124 130 171 124 102 133 164 152 138 110 86 154 149 100 139 153 151 136 113 142 159 161 174 150 127 136 140 154 164 163 167 173 172 171 170 167 168 172 167 162 161 160 163 163 154 145 146 140 133 122 135 167 127 101 126 164 147 1

node.js - MongoDB - shutting down with code:100 -

i've been trying set mongodb on ubuntu 16.04.2 lts (gnu/linux 4.4.0-22-generic x86_64) vps , i've been running few problems. running user on server has root access not using root account itself. i started notice problem when executing db.createuser() on admin database add other users , getting error: not authorized execute command so proceeded uninstall , install again using tutorial provided on website: https://docs.mongodb.com/v3.2/tutorial/install-mongodb-on-ubuntu/ now when i'm on stage 2 verify mongodb has started successfully on run mongodb community edition section, @ output file /var/log/mongodb/mongod.log , following: 2017-04-14t14:23:09.309+0200 control [main] ***** server restarted ***** 2017-04-14t14:23:09.316+0200 control [initandlisten] mongodb starting : pid=9691 port=27017 dbpath=/var/lib/mongodb 64-bit host=vps338741 2017-04-14t14:23:09.316+0200 control [initandlisten] db version v3.4.3 2017-04-14t14:23:09.316+0200 control [initandlis

How to test in Clojure if any given value is not-empty collection? -

i need predicate returns logically true if given value not-empty collection , logically false if it's else (number, string etc.). , more specifically, predicate won't throw illegalargumentexception if applied single number, or string. i came following function, i'm wondering if there more idiomatic approach? (defn not-empty-coll? [x] (and (coll? x) (seq x))) this satisfy following tests: (is (not (not-empty-coll? nil))) ;; -> false (is (not (not-empty-coll? 1))) ;; -> false (is (not (not-empty-coll? "foo"))) ;; -> false (is (not (not-empty-coll? []))) ;; -> nil (false) (is (not (not-empty-coll? '()))) ;; -> nil (false) (is (not (not-empty-coll? {}))) ;; -> nil (false) (is (not-empty-coll? [1])) ;; -> (1) (true) (is (not-empty-coll? '(1))) ;; -> (1) (true) (is (not-empty-coll? {:a 1})) ;; -> ([:a 1]) (true) edit: potential use case: let's ne

amazon web services - Where to put auto-deploy script for Forge on gitlab? -

i using forge , aws forge giving me deploy script put on gitlab, don't know put it, , dont want brake on digital ocean server, auto-deploy button worked out of box but on aws, , auto-deploy not working can tell me how can set up?

c# - How to make a List variable constant in ASP.NET -

in code, trying check rooms available @ time has been entered user. test whether room free, change roomname options , clash check. problem is, when change room name, updates on list of existingbookings. there way make sure existingbookings not change? var existingbookings = _context.bookings.tolist(); var booking = await _context.bookings.singleordefaultasync(m => m.bookingid == id); list<room> roomlist = new list<room>(); roomlist = (from product in _context.room select product).tolist(); list<room> availablerooms = new list<room>(); foreach (var item in roomlist) { booking.roomname = item.roomname; if (businesslogic.bookingchecker.doesbookingclash(booking, existingbookings) == null) { availablerooms.insert(0, new room { roomid = item.roomid, roomname = item.roomname }); } booking.roomname = "undef"; } thanks help! in order have create new instance of booking . can call constructor , co

Search blank numeric value from a column SQL Server -

i have numeric column having blank in db table. i'm trying : select top 10 chqno, account, surname, othrname, chqamt, bankno, pymtno, glacctno table1 chqamt = '' note: chqamt column type decimal and getting error: error converting data type varchar numeric. how resolve this? if chqamt numeric, should check if it's null (blank = '' string) select top 10 chqno, account, surname, othrname, chqamt, bankno, pymtno, glacctno table1 chqamt null; some simple tests: create table test1 (num int, string varchar(10)); insert test1 values (null, null); insert test1 values (1, ''); insert test1 values (0, 'zero'); select * test1 num null; output: num string 1 null null select * test1 string null; output: num string 1 null null -----next 1 (for datatype varchar have different

html - How to append a button when already appending a row in javascript -

i appending row in html table using java script. need append button 1 of table data of row. button should have on click event well. how so? cant results out previous answers please help. below code. $(document).ready(function () { $.ajax({ url: '/api/userapi/', type: 'get', contenttype: "application/json;charset=utf-8", datatype: "json", success: function (data) { alert('user added successfudly'); (var = 0; < data.length; i++) { $("#absa").append("<tr><td>" + data[i].user_name + "</td><td>" + data[i].address + "</td><td>" + data[i].email + "</td><td>" + data[i].mobileno + "</td><td><button onclick="update()"/></td></tr>");

Facebook Graph API for App Insights Not Returning Latest Results -

i'm trying query in facebook graph api , it's not returning latest results. it's giving me data dates 3 days (april 11th), , can't make return results include last 2 days (12th or 13th). when explicitly set since , until parameters last 2 days, returns no data. === query curl -i -x \ "https://graph.facebook.com/v2.8/266492440452954/app_insights/facebook_features_daily_active_users?access_token=<access token sanitized>" === access token info { "perms": [ "user_birthday", "user_about_me", "email", "read_insights", "read_audience_network_insights", "manage_pages", "public_profile" ], "user_id": "10101060008646191", "app_id": 145634995501895 } === response { "data": [ { "time": "2017-04-08t08:00:00+0000", "value&q

openacc - Launching a kernel within a kernel -

isn't nested parallelism , doesn't pgi 17. support this? please let me know if code correct? #include <openacc.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int n = 20; int* array = (int*) malloc(n * n * sizeof(int)); #pragma acc kernels loop for(int = 0; < n; i++ ) { #pragma acc kernels loop for(int j = 0; j< n; j++) { array[i*n + j] = 1; } } (int = 0; < n; ++i) { (int j = 0; j < n; ++j) { printf("%d ", array[i*n + j]); } puts(""); } printf("res: %d\n", res); return 0; } this how compiled it: pgcc -acc -ta=tesla -minfo=accel test.c -o test these errors: pgc-s-0155-nested #pragma acc kernels loop ignored (test.c: 14) pgc-s-0155-illegal context #pragma acc kernels loop (test.c: 14) pgc-s-0039-use of undeclared variable res (test.c: 27) pgc

ios - Custom View in xib not working -

Image
i have vpmotpview custom view in `.xib' this. class verifyotp: uiview { @iboutlet weak var otpview: vpmotpview! var emailid = "" var userid = "" @ibaction func resendotpaction(_ sender: uibutton) { print("asdds") } override func awakefromnib() { super.awakefromnib() otpview.otpfieldscount = 4 otpview.otpfielddefaultbordercolor = uicolor.blue otpview.otpfieldenteredbordercolor = uicolor.red otpview.otpfieldborderwidth = 2 otpview.delegate = self // create ui otpview.initalizeui() } } extension verifyotp: vpmotpviewdelegate { func hasenteredallotp(hasentered: bool) { print("has entered otp? \(hasentered)") } func enteredotp(otpstring: string) { print("otpstring: \(otpstring)") } } then in 'viewcontroller' var verifyotpview: verifyotp? self.verifyotpview = verifyotp.fromnib()

c++14 - Compilers implementing C++ Concept -

which of compilers have implemented concepts per c++17 iso standard? , please give me example of usage in code? (no pseudo examples please) as answered in post looks yours: wandbox supports g++ 7.0 svn , clang++ 4.0 svn versions, have (experimental) c++17 feature support. https://gcc.gnu.org/projects/cxx-status.html#cxx1z http://clang.llvm.org/cxx_status.html original: https://stackoverflow.com/a/40740344/6524598

grouping - How to make pairs from Range? -

i have got range mysqltablesrange . it's consist data like: aa_1 aa_3 aa_2 bb_2 bb_1 bb_3 i need create pairs like: aa_1 bb_1 aa_2 bb_2 aa_3 bb_3 std.algorithm have method group doing similar thing, not know how write in code. did: mysqltablesrange.each!(a => a.split("_")[1].array.group.writeln); but it's wrong, because group works array, not single element. any ideas? update: after testing - realised it's not 'group' want. chunkby. updated answer reflect that. https://dlang.org/phobos/std_algorithm_iteration.html#chunkby you have tell chunkby how chunk data... [1,2,3,4,5,6] .sort!((a,b) => a%2 > b%2) // separate odds n evens .chunkby!((a,b) => a%2 == b%2); // chunk them evens in 1 range, odds in another. that create 2 groups. 1 odd numbers, 1 evens. in case looks you'd group them on text comes after '_' in each element. "aa_1 aa_2 aa_3 bb_1 bb_2 bb_3 cc_1" .split(

vb.net fastest way to remove duplicates from listview? -

does have quicker , better way remove duplicates listview? doing this: sort items alphabetically, , checks item below , compares 1 above. this time consuming though.. when enter 20.000 records excel sheet, , remove duplicates takes few miliseconds, code below takes hours check 20.000 items in vb.net. know of faster method? dim max integer = listview2.items.count dim integer = 0 each item listviewitem in listview2.items if = max exit end if if > 0 if item.text = listview2.items(i - 1).text max -= 1 item.remove() -= 1 end if end if += 1 label4.text = "total domains: " & listview2.items.count next use hashset accept unique values. dim itemstext = listview2.items.cast(of listviewitem).select(function(item) item.text) dim uniquesvalues hashset(of string) = new hashset(of string)(itemstext) then set i

apache - Using .htaccess to redirect to an subdirectory -

i developing rest service , have versioned. have 1 subdomain named api points api folder. have following folder structure: api |__ v1 |___ public_html |____ .htaccess at moment can use " http://api.mydomain.com/v1/public_html " (which triggers .htaccess) use version of service. i have able call " http://api.mydomain.com/v1 " instead of previous url. have .htaccess in v1 folder this: api |__ v1 |___ .htaccess |___ public_html |____ .htaccess the question should .htaccess contain make redirect ? after redirecting trigger .htaccess public_html ? i tried use rewriterule ^(/)?$ public_html [l] doesn't work. edit: the api folder localized in host home folder (the subdomain points api folder only) : home |__api |__ v1 |___ public_html |____ .htaccess try use following source code: rewriteengine on rewriterule ^$ /v1 [l]

How to write R for loops w/ variable value replacement -

question: v vector multiple nas. write function replace these na values such missing value @ index should replaced mean of non-na values @ index p , q |p – i| + |q – i| minimized. so, if vector ("na", 1, 2, "na", "na", 3) result needs (1.5, 1, 2, 1.5, 1.5, 3) how can write nested loop produce output? you can use one: vect <- c( na, 1, 2, na, na, 3) flag <- is.na(vect)+0 wh <- which(is.na(vect)==1) flag[flag==1] <- wh #flag container of values, missing vector position contain value of 0 non missing value contain position k <- 0 #a rolling itertor changes mean per non missing values in vector vect_ <- vect # final vector have outcome. for(i in 1:(length(vect))){ k <- ifelse(flag[i] > 0 , k+1,k) k <- ifelse(k == length(wh), k-1,k) vect_[i] <- ifelse(flag[i] > 0, mean(vect[min(wh):diff(c(1,wh[1+k]))],na.rm=t),vect[i] ) } vect_ > vect_ [1] 1.5 1.0 2.0 1.5 1.5 3.0

javascript - how to make divs fly from one container to another container using greensock.js? -

Image
i trying create ui on click tiles [sub-divs] move 1 parent div parent div. have created pen explain question.the pen working fine need know how show them moving, animation. want them fly 1 one on click. used greensock.js before don't have idea how use in case, or can use here? $(".mybox").on('click', function() { $(this).css('background', 'red'); $(this).detach(); $(this).appendto("#two"); var p = $("#two"); var position = p.position(); tweenlite.to(this, 0.5, {x:position.left, y:position.right}); }); #one { width: 200px; height: 200px; float: left; background: rgba(255,40,100,0.5);; } #two { margin-left: 300px; width: 200px; height: 200px; background: rgba(0,240,10,0.5); } .mybox { float:left; width: 50px; height: 50px; backgroun

google cloud platform - How to set up a compute engine instance with GPU? -

i trying set instance gpu nvidia k80 have error: "you out of nvidia k80 quota". should do? first, please keep in mind free trial accounts not receive gpu quota default. then, can either request quota increase account on compute quota page or might able more gpu machines in other zones .

python - Matplotlib Basemap: avoid text overlapping -

Image
i using matplotlib basemap draw map , points labels: map = basemap(...) x, y = map(lons, lats) label, xpt, ypt in zip(labels, x, y): plt.text(xpt + 10, ypt + 10, label, size=2) i getting lots of overlapped labels in dense areas. there way prevent labels overlapping? the ways can think of adjust distance text printing starts ( have specified 10 ) zoom map while showing labeled points a crude example point 2 from mpl_toolkits.basemap import basemap import matplotlib.pyplot plt m = basemap(width=120000,height=90000,projection='aeqd', resolution=none,lat_0=30.,lon_0=80.) lats=[30.0,30.1,30.2,30.0,30.1,30.2] lons=[80.0,80.1,80.2,80.3,80.4,80.5] m.bluemarble() x, y = m(lons,lats) labels=['point1','point2','point3','point4','point5','point6'] m.scatter(x,y,10,marker='o',color='k') label, xpt, ypt in zip(labels, x, y): plt.text(xpt + 10, ypt + 10, label, size=20) plt

python - Undersampling vs class_weight in ScikitLearn Random Forests -

i applying scikitlearn's random forests on extremely unbalanced dataset (ratio of 1:10 000). can use class_weigth='balanced' parameter. have read equivalent undersampling. however, method seems apply weights samples , not change actual number of samples. because each tree of random forest built on randomly drawn subsample of training set, afraid minority class not representative enough (or not representated @ all) in each subsample. true? lead biased trees. thus, question is: class_weight="balanced" parameter allows build reasonably unbiased random forest models on extremely unbalanced datasets, or should find way undersample majority class @ each tree or when building training set? i think can split majority class in +-10000 samples , train same model using each sample plus same points of minority class.

text to speech - Deal with multiple shot on TTS service -

i trying optimize code on text speech service. in code, possible multiple shots start tts service @ same time. i hope service can catch texts these shots tts queue 1 one. please check code follows: public class voiceservice extends service implements texttospeech.oninitlistener, texttospeech.onutterancecompletedlistener { private final string tag = "voiceservice"; private texttospeech mtts; private string messagetitle; private string messagecontext; @override public void oncreate() { log.i(tag, "oncreate"); try{ log.i(tag, "new texttospeech(this, this);"); mtts = new texttospeech(this, this); mtts.setonutterancecompletedlistener(this); } catch(exception e){ log.i(tag, "exception e : " + e.tostring()); e.printstacktrace(); } } @override public int onstartcommand(intent intent, int flags, int startid){ log.i(tag, "s of onstartcommand @ voiceservice"); message

java - Codename One: How to stream live video to YouTube Live -

i'm developing app need stream video captured smartphone's video camera (on iphones , android phones) directly youtube live. i looked codename one's capture.capturevideo(actionlistener response) method must wait video stopped, file saved, , actionlistener called. obviously, can't work work because video has streamed output stream (to url given youtube live api) on continuous basis. there other way accomplish this? (what unofficial api, method override, input stream camera?) if not, codename 1 consider providing feature version upgrade market trend seems moving on live video streaming apps? if cannot done codename one's api, way write native code android , ios. i've read article integrating native api , using freshdesk api example, pointers on how integrate youtube api purpose of streaming live video? https://developers.google.com/youtube/v3/live/getting-started https://developers.google.com/youtube/v3/live/libraries https://developers.google.com/api-

node.js - One-liner $in nullification MongoDB -

the idea make request (in js) fetch documents field being contained in given array if array defined, or documents if array not defined. i wondered if there elegant mean give $in argument parameter nullifies behavior, can used one-liner. take idea have make kind of conditional request more elegant. here snippet using mongoose: let query = somemodel.find(); if (somearray) { query = query.where(somefield).in(somearray); } query.exec(); sure works, requires store query in variable, not cool. aggregation might help. let itemvalues = somearray || []; somemodel.aggregate([ { $match: { "somefield": { [itemvalues.length > 0 ? "$in" : "$nin"]: itemvalues} } } ]).exec()

angular - Typescript v2.2.2 union type makes error (TS2339) -

in angular 2 use ngrx , have actions , reducers. example of actions : import { action } '@ngrx/store'; export const actiontypes = { action_1: type('actions 1'), action_2: type('actions 2'), }; export class actionone implements action { public type = actiontypes.action_1; constructor(public payload: any) { } } export class actiontwo implements action { public type = actiontypes.action_2; } export type actions = actionone | actiontwo; so, actions has payload, others - no, , actions union type, can actionone or actiontwo . in me reducer have error: property 'payload' not exist on type 'actions' property 'payload' not exist on type 'actiontwo'. reducer this: export function reducer(state = initialstate, action: actions): istate { switch (action.type) { case actions.actiontypes.action_1: { return object.assign({}, state, { data: action.payload, }); } case ... } }

Python using combinations to sum values in a tuple in a list in a dictionary? -

i trying sum combination of values list of tuples in dictionary. example, dictionary contains: dict = {1: [(2, 2), (4, 3), (6, 1), (7, 1), (8, 3)], 2: [(4, 1), (5, 3), (1, 2)],...} and goes on multiple entries. i'm trying sum second value of tuples each entry in many combinations sum maximum of 4. entry 1, desired output be: {1: [(2, 6, 3), (2, 7, 3), (4, 6, 4), (4, 7, 4), (6, 7, 2), (8, 6, 4), (8, 7, 4)] where third value in tuple sum of combinations of second value of previous tuples, , first , second values of tuple associated first values of previous tuples. i have tried following code: for key, value in dict.items(): object1 = key mylist = value tup in mylist: object2 = tup[0] pair = tup[1] combo = itertools.combinations(tup[1],2) sum = {k:sum(j _,j in v) k,v in combo} if sum <= 4: print(sum) and error 'numpy.float64' object not iterable i think error stems "combo&qu

r - How do I add percentage and fractions to ggplot geom_text label? -

Image
i have dataset interested in looking @ score on test , percentage of people experiencing event: dat <- data.frame(score = 1:7, n.event = c(263,5177,3599,21399,16228,10345,1452), n.total = c(877,15725,13453,51226,32147,26393,7875), percentage = c(30,33,27,42,50,39,18)) i can plot percentages on graph this: ggplot(data=dat, aes(x=score, y=percentage)) + geom_line() + geom_text(aes(label = paste0(dat$percentage,"%"))) or can plot fractions this: ggplot(data=dat, aes(x=score, y=percentage)) + geom_line() + geom_text(aes(label = paste0("frac(",dat$n.event, ",", dat$n.total, ")")),parse = true) but want have both of them side side. doesn't work: ggplot(data=dat, aes(x=score, y=percentage)) + geom_line() + geom_text(aes(label = paste0(dat$percentage,"%","frac(",dat$n.event, ",", dat$n.total, ")")),parse = true) i error: er

Spring Boot adding thymeleaf-layout-dialect -

i using spring boot (v1.5.3.build-snapshot) new spring boot. using gradle note normal thymeleaf dialect works fine (th:...) spring-boot-starter-thymeleaf\1.5.3.build-snapshot i want add thymeleaf-layout-dialect added dependency compile('nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect') the documentation says add dialect doing following templateengine templateengine = new templateengine(); // or springtemplateengine spring config templateengine.adddialect(new layoutdialect()); so added configuration class @configuration public class myconfiguration { @bean public springtemplateengine templateengine(){ springtemplateengine templateengine = new springtemplateengine(); templateengine.adddialect(new layoutdialect()); return templateengine; } } but when try running app following error org.thymeleaf.exceptions.configurationexception: cannot initialize: no template resolvers have been set @ org.thymeleaf.configuration.initialize(configuratio

smartcard - I can't select MF on credit card -

i'm trying following apdu: 00 a4 00 00 02 3f 00 00 everything according iso 7816-4 (7.1.1), execution fails sw 0x6a86 (incorrect parameters p1-p2) why? i'm doing wrong? standard states follows: if p1 set '00', card knows whether file select mf, df or ef, either because of specific encoding of file identifier, or because of command processing context. ... if p2 set '00' , command data field absent or set '3f00', mf shall selected. i checked visa/mc cards , apdu fails on of them. your idea correct, difficult understand without background: smartcard either native cards (these have file system including mf, of course) or javacards / open plattform cards (which have none). select command both types share, select aid (application id), i. e. selecting application (p1 = 4, command data field contains aid). emv compliant cards can realized on both, apparently have latter.

asp.net - Custom and unique field for ApplicationUser -

i creating register form on application. have field must unique , have created custom validation ensure this. when submit form unique values page not change or submit anything. far viewmodel looks this public class registerviewmodel { [required] [customvalidation(accountcontroller, "checkifusernametaken", errormessage = "in use already")] [display(name = "username")] [maxlength(15, errormessage = "this field must less 15 characters in length"), minlength(2, errormessage = "this field must have value greater 2")] public string usernameidentity { get; set; } [required] [display(name = "first name")] [maxlength(15, errormessage = "this field must less 15 characters in length"), minlength(2, errormessage = "this field must have value greater 2")] public string firstname { get; set; } [required] [emailaddress] [display(name = "email")] pu

php - Unable to get vCalendar (vcs) to be time adjusted when opened in different time zone -

i creating .vcs file using icalcreator (v2.6) php library. when event opened in outlook (newest version, don't know other versions), meeting date/time not adjusted local time. thought might related this , setting x-microsoft-cdo-tzid value did not seem help. i'm hoping knows vcs file creation can point me in right direction. here vcs file creating: begin:vcalendar calscale:gregorian method:publish prodid:-//127.0.53.53//nonsgml icalcreator 2.6// version:2.0 begin:vtimezone tzid:us/pacific last-modified:20040110t032845z x-microsoft-cdo-tzid:13 begin:daylight dtstart:19900404t010000 tzoffsetfrom:-0800 tzoffsetto:-0700 rrule:freq=yearly;bymonth=4;byday=1su tzname:pdt end:daylight begin:standard dtstart:19901026t060000 tzoffsetfrom:-0700 tzoffsetto:-0800 rrule:freq=yearly;bymonth=10;byday=-1su tzname:pst end:standard end:vtimezone begin:vevent uid:20170413t205736cest-5403nbu2iu@127.0.53.53 dtstamp:20170413t185736z description:sdfg\n\nsome awesome description dtstart:20170419t

arrays - How to write a function that compute differences between two Map object in javascript -

i tried modify function collecting array/map difference here handle multi-dimensional array, code not working expected... code function arrdiff(xs, yx, d) { const apply = f => x => f(x); const flip = f => y => x => f(x)(y); const concat = y => xs => xs.concat(y); const createmap = xs => new map(xs); const filter = f => xs => xs.filter(apply(f)); //left difference const differencel = xs => yx => { const zs = createmap(yx); return filter(([k, x]) => zs.has(x) ? false : true)(xs); }; if (d == 'left') return differencel //right difference const difference2 = flip(differencel); if (d == 'join') return difference2; //union if (d == "union") { const map = new map([...xs, ...yx]); return map;//it 1 working } // symmetric difference const difference = yx => xs => concat(differencel(xs)(yx)(flip(differencel)(xs)(yx)); re