Posts

Showing posts from March, 2014

python - How to use "sqlContext" in different notebooks when using one of them as a module (Pyspark) -

i have notebook a.pynb has function read statement of parquet file. i using a.pynb in notebook b.pynb , in new notebook, calling function of a.pynb read parquet file , create sqltable. fails error: global name sqlcontext not defined, when defined in both notebooks. the exact code : a.pynb ( utils) sc = sparkcontext.getorcreate() sqlcontext = sqlcontext(sc) def parquet_read(file_name): df = sqlcontext.read.parquet(file_name+"*.parquet") return df in b.pynb have used function import nbimporter import commonutils reload(commonutils) sc = sparkcontext.getorcreate() sqlcontext = sqlcontext(sc) df2 = commonutils.parquet_read("abc") it fails error: global name sqlcontext not defined, when defined in both notebooks. i hesitantly use approach you're following (i.e. importing notebooks modules). think far better served moving utility code .py file , not trying use

Appending values to all keys of python dictionary -

i have following dictionary: dic={'a': {'aa': [], 'ab': [], 'ac': []}, 'b': {'ba': [], 'bb': [], 'bc': []}} i want append 3 values either keys in 'a' or 'b'. following example works: dic['a']['aa'].append(value_a) dic['a']['ab'].append(value_b) dic['a']['ac'].append(value_c) any way can in 1 single line. i'm searching following: dic['a'][*] = [value_a, value_b, value_c] where * wildcard indexing keys in dic['a']. as complexity of dictionary in actual program grows current working example becomes unreadable. motivation readability. to use true one-liner (i.e., not writing for loop in 1 line) possible use map , exploit mutability of dicts: dic={'a': {'aa': [], 'ab': [], 'ac': []}, 'b': {'ba': [], 'bb': [], 'bc': []}} vals = [1,2,3] key = 'a'

aws lambda - AWS SES- Using Feedback-ID(from the header) to get Notification Obj -

is there way(apis?) bounce/complaint notification object(atleast bounce/feedback type) using feedback-id receive 1 of header of 'email feedback forwarding' email address. ex. feedback-id: 1.us-east-a.bbhhibbl0bujpgboscbsio9yjtpanvca6dkz3gkk0uxg=:amazonses thanks, j.

Android: How to check which Fragment/Activity called the method -

my case follows, have common toolbar between activities and fragments, have method attached toolbar (like button) can called all, however, want method behave differently according activity/fragment called it.so should code inside method? here code public boolean onsupportnavigateup(){ intent mainactivity=new intent(this,main_activity.class); mainactivity.addflags(intent.flag_activity_clear_top); startactivity(mainactivity); this.finish(); return true; } use putextra , getextra intent , set different values different activity in put identify exact calling activity/fragment.

javascript - How to provide chai expect with custom error message for mocha unit test? -

i have mocha test using chai's expect: it("should parse sails out of cache file", async () => { const sailextractor = new extractor(); const result = await sailextractor.extract("test.xml"); try { expect(result.length).to.be.greaterthan(0); const withmandatoryflight = result.filter((cruises) => { return cruises.hasmandatoryflight === true; }); expect(withmandatoryflight.length).to.be.greaterthan(0); const cruiseonly = result.filter((cruises) => { return cruises.hasmandatoryflight === false; }); expect(cruiseonly.length).to.be.greaterthan(0); return promise.resolve(); } catch (e) { return promise.reject(e); } } now if 1 to.be.greaterthan(0) expectation fails, error output on mocha not dev-friendly: assertionerror: expected 0 above 0 @ assertion.assertabove (node_modules/chai/lib/chai/core/assertions.js:571:12) @ a

sql - how to select specific rows with values with \ without group by -

cust_id | acc_type -------------------- 1 | l1 -------------------- 1 | m1 -------------------- 1 | o1 -------------------- 2 | r1 -------------------- 3 | s1 -------------------- result needed is cust_id | acc_type -------------------- 1 | l1 -------------------- 1 | m1 -------------------- i.e single cust_id need these 2 values. when use group 3 mapped 1. please me resolve in db2\sql based on comment, seem want: select t.* t (t.acc_type = 'l1' , exists (select 1 t t2 t2.cust_id = t.cust_id , t2.acc_type = 'm1') ) or (t.acc_type = 'm1' , exists (select 1 t t2 t2.cust_id = t.cust_id , t2.acc_type = 'l1') ) ; for query, want index on t(cust_id, acc_type) .

android - Retrofit: Parse JSON with different array elements -

i using tmdb api fetch search results of movies, tvs, , people. , in results array, json objects of different type. movie, object format different tv object format. in retrofit, cant this list<pojoclass> results; so question how can deal these situations, json array contains different entries in retrofit. here's json format getting tmdb api. { "results": [ { "vote_average": 7.4, "vote_count": 2301, "id": 315635, "video": false, "media_type": "movie", "title": "spider-man: homecoming", "popularity": 86.295351, "poster_path": "/c24sv2wethpsmda7jemn0m2p3rt.jpg", "original_language": "en", "original_title": "spider-man: homecoming", "genre_ids": [ 28, 12, 878 ], "backdrop_path": "/vc8bcgjdvp0ubmnlzhnhslrbbwq.jpg

ios - My layout constraints are being overridden -

Image
i'm trying display table view overlaid on top of view show list of auto-complete options, i'm having trouble getting table view sized correctly. i have simple uitableview defined in xib file. load it, embed in existing on-screen view, , programmatically set layout constraints leading, trailing, top, , height anchors in view controller method (code in c#): public void embedin(uiview outerview) { outerview.addsubview(view); var constraints = new[] { view.leadinganchor.constraintequalto(outerview.leadinganchor, 8), view.trailinganchor.constraintequalto(outerview.trailinganchor, 8), view.topanchor.constraintequalto(outerview.topanchor, 15), view.heightanchor.constraintequalto(outerview.heightanchor, 0.4f, 0), }; nslayoutconstraint.activateconstraints(constraints); } the result table view small - has same dimensions had in xib (except, weirdly, row dividers continue past bottom down bottom should be). when examine vi

python - How can I run my fan if temp/humid > 26c, 60%? -

raspberry pi, a2302 sensor, 5v fan qn how can request fan connected gpio 18 activates , stays active, until temperature sensor @ pin 5 reads either temperature of less 26 celcius, or humidity of less 60%? #!/usr/bin/python import time import adafruit_dht import rpi.gpio gpio sensor = adafruit_dht.am2302 pin = 5 humidity, temperature = adafruit_dht.read_retry(sensor, pin) if humidity not none , temperature not none: print('temp={0:0.1f}*c humidity={1:0.1f}%'.format(temperature, humidity)) else: print('failed reading. try again!') gpio.setmode(gpio.bcm) gpio.setup(18,gpio.out) gpio.output(18, 1) time.sleep(5) gpio.output(18, 0) gpio.cleanup() i can't provide actual code, seems want know logic use? do following once every minute (or often): if temp< 26 turn off fan elseif hum < 60 turn off fan else keep fan on

java - ListSelectionModel and listener -

i've jtable listselectionmodel , listselectionlistener. the selection model set in jtables constructor: lsm.getselectionmodel() and listselectionlistener set via public method: public void setlistselectionlistener(listselectionlistener l){ lsm.addlistselectionlistener(l); } called controller class: view.settableselectionlistener(new listselectionlistener(){ @override public void valuechanged(listselectionevent e){ if (!e.getvalueisadjusting()) { int viewrow = e.getfirstindex(); system.out.println(viewrow + " selected"); } } }); because listener created in class can't use jtable's getselectedrow(); method, using listselectionevent object's getfirstindex(); doesn't current selection. so i'm using int viewrow = ((listselectionmodel)e.getsource()).getleadselectionindex()); does seem correct way current selection? s

swift - Why are where clauses only valid on functions with generic parameters? -

it seems absurd method signature not compile in swift 4: class bar<valuetype> { func version() throws -> string valuetype == [string: any] { ... } } (error: clause cannot attached non-generic declaration) compiles fine: class bar<valuetype> { func version<t>(_ foo: t? = nil) throws -> string valuetype == [string: any] { ... } } anyone have insight why case? because valuetype has nothing method (in first example). wrong put such method in type ( class / struct / enum ), since it's not true member of type. it's conditionally member of type, depending on truth value of where clause. to achieve this, want put method in extension of type, where clause want. e.g. extension yourtype valuetype == [string: any] { func version() throws -> string { ... } }

c# - Unable to replace bools with ints -

i have sql strings such following, several trues , falses : insert systemrules (col1, col2, col3, col4, col5) values (false,false,true,false,false) i want replace false 0 , true 1. when try this: sql = sql.replace(",true,", ",1,").replace(",true)", ",1)").replace(",false,", ",0,").replace(",false)", ",0)"); ...it removes some of falses...not of them. example, end this: insert systemrules (col1, col2, col3, col4, col5) values (0,false,1,0,false) what expected this: insert systemrules (col1, col2, col3, col4, col5) values (0,0,1,0,0) so try regex instead (showing 1 piece below): sql = regex.replace(sql, ",true)", ",1)"); that particular line blows error: parsing ",true)" - many )'s. what efficient way replace trues , falses in sql statement 1s , 0s? have found string.replace() in c# replace globally, i'm baffled why it's missing some. th

python - CIFAR-10 neural net doesn't accept batch -

i making neural network in python using tensorflow library classify cifar-10 dataset. issue cannot find way of converting batch train step accept feed. code, sections have verified work being replaced comments describing them: # import statements # declare global variables # declare filepaths def read_cifar10(filename_queue): # parse cifar10 file, return label uint8image (cifar10record) def generate_batch(image, label): # generate shuffled batch, given images , labels def get_imgs(test = false, fmin = 1, files = 1): # generate filename(s) , filename_queue # read input using read_cifar10 # cast uint8image , float32 # apply distortions # set shape of image , label # return batch, made using generate_batch # build placeholders input , output x = tf.placeholder(tf.float32, shape=[none, 784]) y_ = tf.placeholder(tf.float32, shape=[none, 10]) # create weight variable given shape # slight amount of variation def weight_variable

c - fscanf crashing while reading empty file -

i'm working on large project has function reads file of data. in test code however, file doesn't exist, , when it's created, creates empty text file. wrote following code compensate event: typedef struct system_boot_status_s{ char timestamp[18]; int power_down_type; int power_down_cause; int boot_number; int antenna_deployed; int images_captured; int beacon_count; }system_boot_status_t; //////////////////////////////// // read boot status info boot status struct ret = fscanf(f, "%s %d %d %d %d %d %d", bootstatus->timestamp, bootstatus->power_down_type, bootstatus->power_down_cause, bootstatus->boot_number, bootstatus->antenna_deployed, bootstatus->images_captured, bootstatus->beacon_count); if (ret != 7) // if 7 items weren't read { // make sure boot status members set 0 snprintf(bootstatus->timestamp, boot_info_len, "xx-xx-xx-xx-xx-xx"); bootstatus->power_down_type = 0

How to concatenate password with mysql:// protocol in Rebol? -

i have password contains "]" rebol doesn't accept mysql://user:password how concatenate string mysql:// ? you can use block form open port: my-database: open [ scheme: 'mysql host: "localhost" user: "user" pass: "pass" path: "/dbpath" ] you can examine output decode-url function see how rebol turns url port specification: probe decode-url foo://bar:baz@foobar.qux:999/quux

debian - OpenLayers installation using npm - packet not found -

i trying install openlayers within express project using npm create custom builds following error: npm err! 404 not found npm err! 404 npm err! 404 'mapbox/vector-tile' not in npm registry. npm err! 404 should bug author publish npm err! 404 specified dependency of 'openlayers' npm err! 404 npm err! 404 note can install npm err! 404 tarball, folder, or http url, or git url. npm err! system linux 3.16.0-4-amd64 npm err! command "/usr/bin/nodejs" "/usr/bin/npm" "install" "openlayers" npm err! node -v v0.10.29 npm err! npm -v 1.4.21 npm err! code e404 npm err! npm err! not ok code 0 i tried updating npm , installing vector-tile manually didn't help. what doing wrong? edit: same error when calling npm install ol instead of npm install openlayers . use more recent version of node , npm, preferably lts versions

Can elasticsearch return boolean flags if a certain query matches? -

i'm using elasticsearch find documents bool-query multiple 'should' clauses. clauses represent different "attributes" relative query. close enough example: index books , want return attributes "title_matches_perfectly", "title_matches_fuzzy_2", "title_matches_slop_2", "author_matches_perfectly", "author_matches_90%", "publisher..." idea. right 'encode' attributes using score king of 'bitmap' in "function_score" query. is there better way achieve that? "script_fields" don't seem allow that. having script in "script_score" modify result document didn't seem work either. (it resulted in 'unsupported_operation_exception'.) i know sounds weird use case. elasticsearch made retrieval of documents in list ordered relevancy score , not reasoning why hit hit. and yet need ... the solution think of writing custom plugin. are there ot

php - How to set Data source within Table Model file In Cake 3 ? -

in cake 2 set $this->setdatasource('database_name'); , create property of same name in config\database.php in cakephp 3 have added additional datasource in app.php after default unable use $this->setdatasource( within initialize. unknown method "setdatasource". in cakephp 3.x, datasources "connections". can set connection on table so: use cake\orm\tableregistry; use cake\datasource\connectionmanager; $connection = connectionmanager::get('default'); $table = tableregistry::get('users'); $table->setconnection($connection); if want table use different connection, can use initialize hook set it. you can set connection specific query .

jestjs - Redux Saga: Testing plain javascript function inside my saga with redux-saga-test-plan and jest -

i trying figure out how can test saga contains regular ol' javascript function in it. here saga: export function* watchgetactivities() { yield takelatest(actiontypes.get_activities, getactivitiessaga); } function* getactivitiessaga() { try { const activities = yield call(api.getactivities); const timezone= yield call(gettimezone); const activitywithtimezone=attachtimezonetoactivities(activities.data,timezone.data); yield put(getactivitessuccess(activitywithtimezone)); } catch (e) { yield put(getactivitiesfailure()); yield put(showmodal(modaltypes.error, 'could not retrieve activities.')); } } the function third const calls (this loops through activities retrieved apis , combines them): export const attachtimezonetoactivities= (activities,timezones)=>{ activities.foreach(function (activity) { activity['timezone']=getactivitytimezone(timezones,activity.start_epoch_ms) }) r

java - Pinpointing defect in a method to find the maximum double slice sum of an array -

the task in question taken https://codility.com/programmers/lessons/9-maximum_slice_problem/max_double_slice_sum/ . i paraphrase task description here: let slice of array (possibly empty) contiguous part of array. is, a[i],..,a[j-1] (where 0 <= <= j < length(a)) slice of a. let sum of slice sum of elements contained within slice. the task find maximal combined sum of pair of slices separated precisely 1 element in first , last element of array not present in either slice nor used separator. is, max{a[i+1]+..+a[j-1]+a[j+1]+..+a[k-1] | 0 <= < j < k < length(a)}. my question not how solve task (i have found working solution online) rather why following solution fails work in cases. every test case have tried on succeeds, codility's large_random test produced wrong answer (my code produced: 2004640 correct answer: 2403731). unfortunately, not input caused error. what causes below code return incorrect answer in exceptional cases? public class m

angular - Angular2 Kendo-Datepicker Popup-overlay Throws Error -

Image
i using kendo-datepicker controls on form. working expected except when datepicker opens calendar popup on top of input control, in: if opens underneath fine, on top seems break rest of controls using @progress/kendo-angular-popup dependency nonresponsive (requires form refresh). i've updated @progress/telerik controls latest versions, can't figure out why happening... there no exceptions being thrown in console. is there way disable behavior opens underneath? user have scroll down see calendar instead of flipping remain in viewport. edit: updated angular version , getting error thrown in console when control open on top: error error: expressionchangedafterithasbeencheckederror: expression has changed after checked. previous value: 'true'. current value: 'false'. there open issue @ https://github.com/telerik/kendo-angular/issues/687 . current solution upgrade @progress/kendo-angular-dateinputs version 1.0.6 , worked on end. note: make

powershell - Need split to long (1,000,000+ line) CSV files based on column value and rename with value from other column -

i have folder csv files in following format: file-2017-08-14.csv ticker price date aapl 1 2017-08-14 aapl 2 2017-08-14 aapl 3 2017-08-14 aapl 4 2017-08-14 msft 5 2017-08-14 msft 6 2017-08-14 msft 7 2017-08-14 goog 8 2017-08-14 goog 9 2017-08-14 ... file-2017-08-13.csv ticker price date aapl 1 2017-08-13 aapl 2 2017-08-13 aapl 3 2017-08-13 aapl 4 2017-08-13 msft 5 2017-08-13 msft 6 2017-08-13 msft 7 2017-08-13 goog 8 2017-08-13 goog 9 2017-08-13 ... and on. need split 2x3= 6 subfiles, named accordingly: /out/aapl-2017-08-14.csv ticker price date aapl 1 2017-08-14 aapl 2 2017-08-14 aapl 3 2017-08-14 aapl 4 2017-08-14 /out/msft-2017-08-14.csv ticker price date msft 5 2017-08-14 msft 6 2017-08-14 msft 7 2017-08-14 /out/goog-2017-08-14.csv ticker price date goog 8 2017-08-14 goog 9 2017-08-14 /out/aapl-2017-08-

Replace code with a variable Python -

i have program in part of code has modified constantly: var = 'math.sin(x*y)*math.sin(x*y)' while (x <= vfinal) , (y <= vfinal): v1 = bm.verts.new((round(x,3),round(y,3),var)) x = x + precision v2 = bm.verts.new((round(x,3),round(y,3),var)) y = y + precision x = x - precision v3 = bm.verts.new((round(x,3),round(y,3),var)) x = x + precision v4 = bm.verts.new((round(x,3),round(y,3),var)) bm.faces.new((v1,v2,v4,v3)) y = y - precision if (round(x,1) == vfinal): y = y + precision x = vinicial since math.sin(x*y)*math.sin(x*y) appears 4 times (possibly more once expand program), want change program changing whats stored in var . so far tried making var string, gives error because bm.verts.new wont accept strings. tried removing ' ' in var, make number, won't give desired result further down because x , y change constantly. thing worked writing math.sin(x*y) math.sin(x y) 4 times, tedious , i

bash - copy file inside chroot fails -

trying copy file (created script) inside chroot environment. have 2 scripts: first , second . both have same issue (same text can found inside script): ./tmp/caja-qdigidoc.sh: line 4: edit/tmp/caja-qdigidoc.py: no such file or directory cp: cannot stat 'edit/tmp/caja-qdigidoc.py': no such file or directory file exist, path correct still cannot solve issue. tried or without script - did not help. doing wrong?

office365 - Office 365 content searches returning mailboxes outside of tenant -

i'm working https://protection.office.com/#/contentsearch consider search (c:c)(date=2017-08-14..2017-08-15)(kind=email)(body="foo") i'm presented search errors mailboxes outside of tenant. any ideas why? search errors throwing off automation i'm trying work on. thanks

javascript - Fill Duration when user inputs time -

i'm trying auto fill duration in live form when user inputs data. formula followed: time duration = out – in . not sure how data user inputs in live form(before hit submit) , display in duration location in form. below example of user imputing in , out data , result being duration should displayed before submit button clicked. ex: in:01:00:00 out:00:01:00 duration:00:99:00 var template; var numofsegments = 1; window.addeventlistener('load', function() { template = document.queryselector("#wrapper").innerhtml; document.queryselector("#more_fields").addeventlistener("click", function(e) { e.preventdefault(); // tell browser not send form document.getelementbyid('wrapper').insertadjacenthtml('beforeend', template); // add next segment numofsegments = document.queryselectorall("div.segment").length; document.queryselector("div.segment:last-of-type >

javascript - ng-serve constructor error -

Image
i working on angular js application. while trying run dev server, getting error ng serve constructor: without being able see code (most forgot small or misspelled something), recommend update node . there other questions unexpected token errors, , solution update node and/or angular-cli. see this , this .

python - How to efficiently include results of a MongoDB's cursor in another query? -

suppose have mongodb collection , i'm running 2 queries on it, , b. both returning lists of indexes documents in collection. records in intersection of a's , b's outcome, i.e. intersection of sets. a naive implementation on pymongo this: cursor_result_a = db.collection.find(a) result_a = [x x in cursor_result_a] cursor_result_b = db.collection.find({"$and":[{"_id":{"$in":result_a}}, b]}) however, approach makes me first pull outcome of first query database python , send in first query. inefficient. how can more efficiently?

c# - open xml; trying to add multiple sheets to a workbook -

i trying add multiple spreadsheets same workbook, code seems add last element sheet. please let me know going wrong. using (spreadsheetdocument spreadsheet = spreadsheetdocument.create( system.io.path.combine(appdomain.currentdomain.basedirectory, xlspath), spreadsheetdocumenttype.workbook)) { // create worksheet spreadsheet.addworkbookpart(); uint = 1; foreach (var section in errorsections) { spreadsheet.workbookpart.workbook = new workbook(); var sheetname = section.title.replace("xxxx - ", ""); sheetname = sheetname.replace(" - xxxxx", ""); worksheetpart worksheetpart = spreadsheet.workbookpart.addnewpart<worksheetpart>(); worksheetpart.worksheet = new worksheet(new sheetdata());

python - SparkException: Only one SparkContext may be running in this JVM (see SPARK-2243) -

i see several post contain same error error receiving, none leading me fix on code. have used exact same code many times no issue , having problems. here error receive: y4j.protocol.py4jjavaerror: error occurred while calling none.org.apache.spark.api.java.javasparkcontext. : org.apache.spark.sparkexception: 1 sparkcontext may running in jvm (see spark-2243). here how start context within python script: spark = ps.sql.sparksession.builder \ .master("local[*]") \ .appname("collab_rec") \ .config("spark.mongodb.input.uri", "mongodb://127.0.0.1/bgg.game_commen$ .getorcreate() sc = spark.sparkcontext sc.setcheckpointdir('checkpoint/') sqlcontext = sqlcontext(spark) please let me know if have suggestion. sparksession new entry point in spark 2.x. replacement sqlcontext, uses sqlcontext in internal code. everything making sqlcontext should possible sparksession. if want use sqlcontext, use sp

syntax with arrow function in TypeScript -

in code in typescript saw (() => { const abc = 'blabla'; ... })(); what syntax mean ? know arrow functions js - understand this: () => { const abc = 'blabla'; ... }); but interest of rest of parenthesis ? ps: original code is (() => { const title = 'new document' newdoc.initialize = () => { render( <app title={title} />, document.queryselector('#contnr') ); }; render( <progr />, document.queryselector('#contnr') ); })(); thank you in javascript these functions called iife (immediately-invoked function expression), it's definition of function , invoking immediately! for? many reasons... but, before go reasons, please note arrow functions not part of question, there's not this in example... also not question not relevant typescript. few on many reasons: you have scope (by reac

javascript - Blob URL not working on Android Browsers -

i've created simple web app using .net (with entity framework) , angularjs retrieve pdf files. i'm able have app work on desktop browsers , ios browsers. unfortunately i'm having issues getting work on android browser. inside controller function triggered ng-click on simple button requests , displays pdf. able use solution here pdf's working correctly on ios , edge browsers. appmodule.controller("cellcontroller", ['$scope','$http','$routeparams','$window','$sce', function ($scope, $http, $routeparams,$window,$sce) { .... $scope.getlayout = function () { var attachmentpromise = $http.get("/api/pdf" + $routeparams.id, { responsetype: 'blob' }).then(function (result) { var file = new blob([result.data], { type: 'application/pdf' }); if (window.navigator.mssaveoropenblob) { window.navigator.mssaveoropenblob(file, "layo

sql - Php/PDO does user exist? -

i know there posts it, got other solution others: $sql= 'select * pr_users nick = :nick '; $sqldot = $db->prepare($sql); $checkif = $sqldot->execute(array(':nick' => $nick)); if (count($checkif) == 1) { $_session['ng'] = "<p class=\"text-warning\">nickname exists!</p>"; header("location: ../register.php"); } else { $final++; $_session['nick'] = $nick; } $db defined here: $db = new pdo( "mysql:host=" .dbserver. ";dbname=" .dbname,dbuser,dbpass, array( pdo::mysql_attr_init_command => "set names utf8", pdo::mysql_attr_init_command => "set character set utf8" ) ); i count if $checkif has characters in, reason if "name" not exist -> $checkif still has characters in, tells me exist, wrong. execute func

node.js - findOneAndUpdate with push array elements gives error in mongoose -

my query shown below: const updatelikes = (item_id, userinfo) => { return new promise((resolve, reject) => { itemlike.findoneandupdate({ 'item_id': item_id }, { $inc: { no_of_likes: 1 } }, { "$push": { "users": userinfo } }, { 'new': true }, (err, info) => { if (err) { reject(err); } else { if (info) { resolve(); } else { reject('no item found'); } } }); }); }; itemlike.js const itemlike = new schema({ item_id: { type: mongoose.schema.objectid, ref: 'items', index: true }, no_of_likes: { type: number, default: 0 }, users: [{ type: mongoose.schema.objectid, ref: 'user' }] }, { versionkey: false }); module.exports = mongoose.model('item_like', itemlike); as execute query , error shown below: events.js:160 throw er; //

c# - Keep DbContext open for DataGridView -

i have datagridview , datagridview's datasource bindinglist got entity framework (v6) via context.person.local.tobindinglist(). after set datasource bindinglist, dispose context, because read keeping context open bad practice. so, if wanted add new row, click on "add" button comes bindingnavigator got created when dragged "people" object data source windows form. every time click "add" button, exception tells me context has been disposed. need keep context open time when using datagridview? oh and: datasource might change during runtime depending on selection of listbox item. also, when context has been disposed , edited 1 row datagridview, how find out (after multiple changes) row has changed? tried do: foreach(datagridviewrow row in peopledatagridview.rows) { people item = (people)row.databounditem; if (item != null) { db.people.attach(item); } } db.savechanges(); ...but savechanges() did not recognize changes. how

Erlang's typer deduced weird types for strings -

i'm exploring typer , , gave function nothing but: const_str() -> "qwe". that guy's type deduced as: -spec const_str() -> [101 | 113 | 119,...] , i.e. " eqw " (huh?!), followed '...' business. it looks constant strings confusing typer ; understand shouldn't using them this, there atoms purpose; trying wrap head around typer (and erlang's type options), thought surprising , interesting. explain what's happening here? thanks! strings in erlang lists of integers correspond ascii code of characters (i.e. "qwe" = [$q,$w,$e] = [113,119,101] ). the type language cannot express order of list's elements (and not aim so). the type got of "a nonempty list containing numbers 101, 113 , 119", close inference can get.

Why isn't ldaps (LDAP over SSL) auth supported in postgresql -

seems postgres chose support starttls ldap auth encryption. know why? our organization explicitly denying unsecured connections starttls won't work since requires initial connection unsecure. me seems postgres should not care protocol used ldapurl , should leave underlying library. thoughts? workarounds ldap auth server supports ldaps work? so line in pg_hba.conf not work? hostssl samerole 10.10.10.0/24 ldap ldapserver=ldap.mycompany.com ldapprefix="uid=" ldapsuffix=", ou=people, dc=mycompany, dc=com" ldaptls=1 not work?

javascript - Using global function in vuejs. linter (?) -

i have use javascript library (emailjs) send email vuejs application. problem library create global function , when try use function, eslint notify me funcion not defined. is posible wrap funtion javascript module use on components? sometimes globals cannot avoided (i'm looking @ you, gapi ). add eslint globals config. in .eslintrc.js module.exports = { // ... globals: { smtpclient: true // or whatever global variable named } } see http://eslint.org/docs/user-guide/configuring#specifying-globals

spring - MissingServletRequestParameterException -

i'm passing formdata object spring back-end: imagebanner(banner: file, bannerpath: string, id: number, callback: (response) => void){ var formdata = new formdata(); formdata.append('name', banner.name); console.log(formdata.get('name')); formdata.append('file', banner); console.log(formdata.get('file')); this.sendpost("/upload/" + bannerpath, formdata, response => { callback(response); }); } the console log shows: 1.jpg file {name: "1.jpg", lastmodified: 1496737372408, lastmodifieddate: tue jun 06 2017 10:22:52 gmt+0200 (w. europe daylight time), webkitrelativepath: "", size: 38983…} so looks formdata has values. in back-end have this: @requestmapping(value="/rest/upload/localeventbanner", method=requestmethod.post, headers = "content-type!=multipart/form-data") public @responsebody string uploadfilehandler(@requestparam("name"

javascript - Merging Arrays of Objects by Key/Values -

i have 2 separate arrays of objects need merge based if specific key value matches. might make more sense after analyzing data: array 1 let categories = [ { id: 5, slug: 'category-5', items: [] }, { id: 4, slug: 'category-4', items: [] }, { id: 3, slug: 'category-3', items: [] }, ] array 2 let items = [ { id: 5, data: [{ title: 'item title', description: 'item description' }] }, { id: 5, data: [{ title: 'item title 2', description: 'item description 2' }] }, { id: 4, data: [{ title: 'item title 4', description: 'item description 4' }] }, ] expected output let mergedoutput = [ { id: 5, slug: 'category-5', items: [ { title: 'item title', description: 'item description' }, { title: 'item title 2', description: 'item description 2' } ] }, { id: 4, slug: 'category-4', it

javascript - Weird stuttering when generating animated gifs using gifshot.js on ios -

Image
ok, little bit of background... i'm trying generate animated gifs animations done on html5 canvas using javascript. specifically, i'm adding data layers mapbox gl js map , looping through them. on each iteration, save canvas element , transform blob before calling url.createobjecturl(blob) , setting source new image. after loop finished generate gif using gifshot ( https://github.com/yahoo/gifshot ) , images created. this process works in browsers (mobile too!) except on iphone ios. on ios gif has weird stutters , transparency issues. have tried other gif creation libraies have same issue on ios. memory problem or something? i'm @ wit's end on this, appreciated! this code inside each loop: var cv = map.getcanvas() var oneimage = new image(); cv.toblob(function(blob) { url = url.createobjecturl(blob); oneimage.src = url images_arr.push(oneimage) i++; settimeout(function(){ gifloop(images_arr); },1000) }) and code call

Python - Finding Row Discrepancies Between Two Dataframes -

i have 2 dataframes same number of columns, d1 , d2. note: d1 , d2 may have different number of rows. note: d1 , d2 may not indexed same row in each data frame. what best way check whether or not 2 dataframes have same data? my current solution consists of appending 2 dataframes , dropping rows match. d_combined = d1.append(d2) d_discrepancy = d_combined.drop_duplicates(keep=false) print(d_discrepancy) i new python , pandas library. because using dataframes millions of rows , 8-10 columns, there faster , more efficient way check discrepancies? can shown initial dataframe resulting discrepancy row from? setup d1 = pd.dataframe(dict(a=[1, 2, 3, 4])) d2 = pd.dataframe(dict(a=[2, 3, 4, 5])) option 1 use pd.merge . i'll include parameter indicator=true show data came from. d1.merge(d2, how='outer', indicator=true) _merge 0 1 left_only 1 2 both 2 3 both 3 4 both 4 5 right_only if have same data, i'd exp

android - What type of operation I'm missing..? -

i read android studio documentation: https://developer.android.com/guide/practices/screens_support.html#declaringtabletlayouts well documentation pretty obvious, support different screens. use match_parent, wrap_content, create layout-sw folders.. hmm, eazy task.. yep, made 5 layout-sw300dp-700dp folders, every layout owns match-parent , wrap content characteristic.. somehow image isn't getting scaled , want scale image in 1 of linearlayouts.. i know theres lot of answer out there on forum, can see not confusing me, i'm sure i'm missing important end screen support.. should create different size images , place them in drawable folder? because whenever i'm reviewing layout file example sw600dp image isnt scaled there.. layouts aren't getting scaled.. should configure every layout-sw folders? mean place bigger image, resize layouts. i need fill linearlayout image. there's white spaces on left , right side of linearlayout the code belongs relativ

ios - AFHTTPResponseSerializer subclass not calling error handler when data doesn't validate -

i'm subclassing afhttpresponseserializer because need validation. i'm overriding these 2 methods: override func validate(_ response: httpurlresponse?, data: data?) throws { // checking logic throw nserror(....) } override func responseobject(for response: urlresponse?, data: data?, error: nserrorpointer) -> any? { { try validate(response as? httpurlresponse, data: data) } catch let e { return nserror(...) } } // later in code manager.post(url, parameters: params, ...) i put break points in these 2 functions , saw error thrown in validate function , nserror returned in responseobject , looks never triggers error handler post method. trigger success handler. why this?

Java 8 - Static Method Reference Rule -

i have following piece of code: public class chap20 { public static void main(string[] args) { string[] names = { "john", "jane" }; stream<string> namesstream = stream.of(names); path path = paths.get("."); stream<path> files; try { files = files.list(path); files.foreach(system.out::println); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } } now here´s file.foreach method signature: void java.util.stream.stream.foreach(consumer<? super path> action) i´m reading method accepts consumer of type @ least path type or superclass of path, i´m missreading it, since system.out not superclass of path. can please explain how correct read it? ? super path says: 'it has super class of path. system.out.println accepts object . object super class of path hence correct.

visual studio 2015 - Confuser.Console.exe obfuscation error -

Image
i have post build event have used automate obfuscation of class library. this works fine in visual studio 2010, after upgrading project visual studio 2015 has seemed stop working. this post build event: c:\anand\confuser\confuser.console.exe "$(projectdir)obfuscate\obfuscateemailmerge.xml" copy /y "$(targetdir)confused\$(projectname).dll" "$(targetdir)$(projectname).dll" rmdir /s /q "$(targetdir)confused" copy /y "$(targetdir)$(projectname).dll" "$(projectdir)\obj\debug\$(projectname).dll" copy /y "$(targetdir)$(projectname).dll" "$(projectdir)\obj\release\$(projectname).dll" "c:\signtool.lnk" sign /t http://timestamp.digicert.com /a "$(projectdir)obj\$(configurationname)\$(targetfilename)" the obfuscation successful in debug build, fails in release build. this output vs2015: please note not using confuserex, using older version called confuser. any clue?

rest - Had to use POST for GET job for security reasons, Is there any alternate approach to without compromising api naming conventions? -

we using post /xxx/usage/get instead of using get /xxx/usage security reasons, per api naming conventions verbs not allowed used in resource path. using post instead of avoid sending sensitive information on query param, best way identify uri has job?? option 1: use method, since security primary concern. avoided. option 2: while using post, use naming convention tell job without compromising naming convention. thinking of using post /xxx/usage/queries . we using post instead of avoid sending sensitive information on query param, best way identify uri has job?? you don't. in rest, uri opaque -- clients not supposed make assumptions based on spelling of identifiers. information encoded identifier done @ server's discretion , own exclusive use. when communicate resource responds post messages (whether documentation, hypermedia, or options), communicating specific messaging semantic cannot overridden changing spelling of identifier. as far rest con

mongodb - Searching with Precedence on Array Order -

my gut feeling answer no, possible perform search in mongodb comparing similarity of arrays order important? e.g. have 3 documents so {'_id':1, "my_list": ["a",2,6,8,34,90]}, {'_id':2, "my_list": ["a","f",2,6,19,8,90,55]}, {'_id':3, "my_list": [90,34,8,6,3,"a"]} 1 , 2 similar, 3 wildly different irrespective of fact contains of same values 1. ideally search similar {"my_list" : ["a",2,6,8,34,90] } , results document 1 , 2. it's regex search wild cards. know can in python enough, speed important , i'm dealing 1.3 million documents. any "comparison" or "selection" more or less subjective actual logic applied. general principle consider product of matched indices array test against , array present in document. example: var sample = ["a",2,6,8,34,90]; db.getcollection('source').aggregate([ { "$matc