Posts

Showing posts from August, 2012

extracting a set amount of lines from a Text file - Python -

let imagine have text file following inside of it: (each line starts number , contains information next need) 1 325315 2 234265 3 345345 4 234234 5 373432 6 436721 7 325262 8 235268 how go extracting lines after number 3 , before number 6 example? while keeping other data held on same line. i have large text file ~1000 lines, need extract lines starting 300 through 800. either extract or remove lines not need, either way ok. thanks help do this. l = [line line in (open('xyz.txt','r')).readlines() if int(line.split()[0]) > 3 , int(line.split()[0]) < 6 ] output:(output lines between 3 , 6) c:\users\dinesh_pundkar\desktop>python c.py ['4 234234\n', '5 373432\n'] c:\users\dinesh_pundkar\desktop>

ios - Binary upload fails with "Missing 64-bit support" -

i'm building cordova app cordova build --device --release uploading itunes connect pilot upload -i platforms/ios/build/device/askpal.ipa --verbose the publishing process using fastlane pilot fails with: error itms-90086: "missing 64-bit support. ios apps submitted app store must include 64-bit support , built ios 8 sdk or later. recommend using default "standard architectures" build setting "architectures" in xcode, build single binary both 32-bit , 64-bit support." the way i'm "fixing" deleting ios platform cordova, , reinstalling coordova platform add ios . please tell me there way specify build architectures in cordova configs. it not working build active architecture

gradle - How to force build system to ignore resource files in Android Studio? -

i working android studio 2.2. if have resources (xml files, example) have errors in them, when try build these errors bring entire build screeching halt, even if not referencing them activity. don't want delete files directories because eventually fix them, not priority @ moment. how in world can "turn them off" now, or @ least tell build system ignore them? tried doing "keep.xml" tools:discard trick adding paths, doesn't when compiling debug target. way can project build either deleting files out of resources or moving them. seems overkill. lintoptions { abortonerror false } adding in app gradle file force complete build errors in it. or, can comment files.

Override AuthorizeAttribute in ASP.Net Core and respond Json status -

i'm moving asp.net framework asp.net core. in asp.net framework web api 2 project, can customize authorizeattribute : public class apiauthorizeattribute : authorizationfilterattribute { #region methods /// <summary> /// override authorization event custom authorization. /// </summary> /// <param name="httpactioncontext"></param> public override void onauthorization(httpactioncontext httpactioncontext) { // retrieve email , password. var accountemail = httpactioncontext.request.headers.where( x => !string.isnullorempty(x.key) && x.key.equals("email")) .select(x => x.value.firstordefault()) .firstordefault(); // retrieve account password. var accountpassword = httpactioncontext.request.headers.where( x =>

java - HIVE COUNT * OUT OF MEMORY -

hive> select count(*) ipaddress country='china'; warning: hive-on-mr deprecated in hive 2 , may not available in future versions. consider using different execution engine (i.e. tez, spark) or using hive 1.x releases. query id = pruthviraj_20160922163728_79a0f8d6-5ea6-4cb5-8dd2-d3bb63f8baaf total jobs = 1 launching job 1 out of 1 number of reduce tasks determined @ compile time: 1 in order change average load reducer (in bytes): set hive.exec.reducers.bytes.per.reducer=<number> in order limit maximum number of reducers: set hive.exec.reducers.max=<number> in order set constant number of reducers: set mapreduce.job.reduces=<number> starting job = job_1474512819880_0032, tracking url = http://pruthvis-macbook-pro.local:8088/proxy/application_1474512819880_0032/ kill command = /users/pruthviraj/lab/software/hadoop-2.7.0/bin/hadoop job -kill job_1474512819880_0032 hadoop job information stage-1: number of mappers: 1; number of reducers

Spotify loudness normalization -

spotify has loudness normalization option (called "play songs @ same volume"). please - know algorithm used calculate loudness of track? @ related broadcast loudness algorithm itu-r bs.1770? and how spotify handle clips if ends scaling clip loudness normalize it? thanks

Error during fetching git repository on Jenkins (not each time) -

i've got jenkins job run unit tests. every 10 minutes checks if there new changes in git repository. if find changes, runs tests. this error occurs every 2-3 builds. other builds ok. logs error: > git rev-parse --is-inside-work-tree # timeout=10 fetching changes remote git repository > git config remote.origin.url gitlab@gitlab:group/project.git # timeout=10 pruning obsolete local branches fetching upstream changes gitlab@gitlab:group/project.git > git --version # timeout=10 > git fetch --tags --progress gitlab@gitlab:group/project.git +refs/heads/*:refs/remotes/origin/* --prune error: error fetching remote repo 'origin' hudson.plugins.git.gitexception: failed fetch gitlab@gitlab:group/project.git @ hudson.plugins.git.gitscm.fetchfrom(gitscm.java:797) @ hudson.plugins.git.gitscm.retrievechanges(gitscm.java:1051) @ hudson.plugins.git.gitscm.checkout(gitscm.java:1082) @ hudson.scm.scm.checkout(scm.java:485) @ hudson.model.abstract

android - Could not resolve com.commonsware.cwac:camera:0.6.+ -

i have added tedpicker in applications https://github.com/parksanggwon/tedpicker but weeks when try sync gradle internet error shows up error:a problem occurred configuring project ':app'. > not resolve dependencies configuration ':app:_debugapkcopy'. > not resolve com.commonsware.cwac:camera:0.6.+. required by: yourapp:app:unspecified > com.github.parksanggwon:tedpicker:v1.0.10 > not resolve com.commonsware.cwac:camera:0.6.+. > failed list versions com.commonsware.cwac:camera. > unable load maven meta-data https://repo.commonsware.com.s3.amazonaws.com/com/commonsware/cwac/camera/maven-metadata.xml. > not https://repo.commonsware.com.s3.amazonaws.com/com/commonsware/cwac/camera/maven-metadata.xml'. > host name 'repo.commonsware.com.s3.amazonaws.com' not match certificate subject provided peer (cn=*.s3.amazonaws.com, o=amazon.com inc., l=seattle, st=washington, c=us) but works fine if switch offline mode in gradle also app&

php - Android sharedpreference logout don't clear values -

when i'm testing login on mobile app editor.clear(); not working guess because whenever logout , click login without values on username , password still logs in previous 1 can guys me fix problem? here codes. loginfragment public class loginfragment extends fragment implements compoundbutton.oncheckedchangelistener { final string tag = this.getclass().getname(); button btnlogin; edittext etusername, etpassword; textview tvregister; checkbox cbremember; sharedpreferences pref; sharedpreferences.editor editor; boolean checkflag; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view v = inflater.inflate(r.layout.fragment_login, container, false); etusername = (edittext) v.findviewbyid(r.id.etfirstname); etpassword = (edittext) v.findviewbyid(r.id.etpassword); btnlogin = (button) v.findviewbyid(r.id.btnlogin); tvregister = (textview) v.findviewbyid(r.id.tvregister);

pandas - Aggregate dataframe indices in python -

i want aggregate indices of dataframe groupby function. word count 0 3 1 5 2 3 3 2 4 1 what want pd.series consists of list(descending order) of indices, word [2, 0] [3] [4, 1] i've tried built-in functions groupby, however, couldn't find way aggregate indices. provide hint or solution problem? i think can first change order of index [::-1] , groupby , apply index list . last sort_index : print (df[::-1].groupby('word', sort=false).apply(lambda x: x.index.tolist()).sort_index()) word [2, 0] [3] [4, 1] dtype: object another similar solution: print (df.sort_index(ascending=false) .groupby('word', sort=false) .apply(lambda x: x.index.tolist()) .sort_index()) word [2, 0] [3] [4, 1] dtype: object

Objective-C (aClassName *) -

i'm kind of self-programmer-made-man, i'm missing basic knowledge time time. that's why i'm unable define topic of question, because don't know how name , how works (but know answer seem trivial many of you). when know what's you're looking it's lot easier find answers. in objective-c, can see lines of code : aclassname *myobject = (aclassname *)[nsentitydescription insertnewobjectforentityforname:@"aclassname" inmanagedobjectcontext:app.managedobjectcontext]; what's bother me (aclass *) part. what's ? i know/feel it's related basic knowledge can't name can't find it. my guess (and that's how use now) that's used calling class methods (+) i'm not sure of , may more deep understand. thanks explanation. it's cast, in case down cast (even because casts implicit). a cast operation developer while writing code hint compiler type narrower 1 compiler thinking about. think following s

C# regular expression match pattern with indentation -

i have text file, , want match 3 lines occur 10 times within text file. problem match 3 lines indentation, , third line can words line example: something follow found something this have tried far: string pattern = @"\s\s\s\sthen([\s\s]*)found(\n|\r|\r\n)(\s\s\s\s\s\s)(.*)"; match = regex.match(input, pattern, regexoptions.multiline); the result gives me 500 matches, not im looking for. i'm making wild guesses required format, can try this: var text = @" something follow found something "; var pattern = @"[ ]{4}then[\w\s]+(\r|\n|\r\n)[ ]{6}[\w\s]+found(\r|\n|\r\n)[ ]{6}[\w\s]+(\r|\n|\r\n)"; var match = regex.match(text, pattern, regexoptions.multiline)

leaflet.markercluster - Leaflet markercluster rails not displaying marker -

Image
i not graphic markercluster, number. suspect css missing, not sure i'm doing wrong. no errors in console, , everythings works ok without markercluster. gemfile source 'https://rubygems.org' # bundle edge rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.2.5.1' # use postgresql database active record gem 'pg', '~> 0.15' # use scss stylesheets gem 'sass-rails', '~> 5.0' # use uglifier compressor javascript assets gem 'uglifier', '>= 1.3.0' # use coffeescript .coffee assets , views gem 'coffee-rails', '~> 4.1.0' # see https://github.com/rails/execjs#readme more supported runtimes # gem 'therubyracer', platforms: :ruby # use jquery javascript library gem 'jquery-rails' # turbolinks makes following links in web application faster. read more: https://github.com/rails/turbolinks gem 'turbolinks' # build json apis ease. read

Cassandra snapshot using nodetool -

i trying take snapshot of cassandra keyspace using nodetool. when executing nodetool snapshot , getting following error. nodetool: failed connect '127.0.0.1:7199' - connectexception: 'connection refused'. after specifying host same error comes. nodetool -h 10.92.12.1 -p 7199 -u user -pw passpass snapshot is cassandra running? error shows when node not active. if execute tail <path cassandra logs>/system.log may explanation of happening

php - Joins - get row from one table then get all rows that match in another table? but first table matching row should not be repeated -

i have 2 tables. gallery , joins. gallery id | title 1 | dog gallery 2 | cat gallery joins id | gallery_id | picture_id 1 | 1 | 100 2 | 1 | 101 3 | 2 | 56 4 | 1 | 102 i want id, gallery title gallery - id equal specific id of rows joins gallery id equals specific gallery id. so above if id 1. want dog gallery gallery , picture_ids 100,101 , 102 joins. now problem gallery title should comes 1 time. result title=dog gallery picture_id=100,title=dog gallery picture_id=101,title=dog gallery picture_id=102 need result title=dog gallery picture_id=100,picture_id=101 , picture_id=102 you can use group_concat have ids string select g.*, group_concat(distinct p.picture_id order p.picture_id desc separator ',') gallery g left join pictures p on p.gallery_id = g.id group g.id;

html - line-height doesn't vertically center inline-block -

i tried vertically center inline-block this: div { width: 50px; height: 50px; background: red; line-height: 50px; } span { display: inline-block; width: 20px; height: 20px; background: white; } <div> <span></span> </div> but span not vertically centered. why? because line-height sets position of baseline of text (the bottom end of span ). since span 20px high must add half of line-height : div { width: 50px; height: 50px; background: red; line-height: 60px; } span { display: inline-block; width: 20px; height: 20px; background: white; } <div> <span></span> </div>

Does redis bind to CPU cores automatically? -

i have server 32 logical cores(16 physical cores , hyper-thread enabled) , have 8 redis instances on it. seems 16 cores, id 0 7 , 16 23, used , other 16 cores idled. shows cpu affinity mask redis process ffffffff(from taskset -p pid). so wonder cpu affinity has been set automatically in redis? thanks leo no, redis doesn't set cpu affinity . think misunderstand output of taskset command. the affinity mask got, i.e. ffffffff , means process might running on of processors. , that's default behavior. can test starting process doesn't set cpu affinity, e.g. vim xxx.conf , , use taskset check mask. should return ffffffff . in order make process running on specific cpu, can run following command: taskset -pc 0 process_id , i.e. running on 0th processor.

makefile implicit rule override error -

when building try.img, following makefile works, because uses implicit rule %.o: %.c. if uncomment last 3 lines, not work more. idea why? thank in advance may provide. try.img: try.elf $(objcopy) $< -o binary $@ %.elf: %.o %.ld %.symbols $(ld) $(ldflags) -t $(@:.elf=.ld) $(@:.elf=.o) -o $@ #%.o: %.c # echo "abc" # $(cc) $(cflags) -c $< -o %@

javascript - Using BB promise to create server with free port -

when run create server & listen in unit test times i'm getting following error: eaddrinuse, now want handle using module portscanner find free port i this var http = require('http'); var promise = require('bluebird'); var portscanner = require('portscanner'); var server = http.createserver(function (req, res) { if (req.url == '/fail') { res.end("failed"); } else { res.writehead(200, {"content-type": "text/plain"}); } }); promise.promisifyall(server); server.listenasync(portscanner.findaportnotinuse) module.exports = server; this working not sure if it's stable code my question if it's ok use this? , not dirty workaround , if yes how can handle better? not sure why using promise in case, can use : portscanner.findaportnotinuse(3000, 5000, '127.0.0.1', (error, port) =>{ server.listen(port); });

python - How do I make text(one letter) fill out a tkinter button? -

i have tic tac toe game i'm trying put finishing touches on. each tile in game button letter 'x' or 'o'. can't seem letters fill out frame. when change font size, buttons bloat out. if try set tile height/weight after setting font size doesn't seem have effect. is there way make 'x' expand out fill button it's in? class tictactoeboard(frame): def __init__(self, parent=none, game=none): frame.__init__(self, parent) # controlling gui through external game class. self.game = game self.symbol = game.sym() mainframe = ttk.frame(root, padding=(12, 12, 12, 12)) mainframe.grid(column=0, row=0, sticky=(n, w, e, s)) # how change tile player plays on. self.strvars = [stringvar() x in range(9)] # setup button tiles self.buttons = [] i, s in enumerate(self.strvars): func = (lambda i=i: self.btn_press(i)) b = button(mainframe, textva

javascript - Changing a value of a html tag -

i using inside page <span> tag <span class="class_name">1500</span> and have javascript code change "1500" 15% my question how read number inside span , print new number want example code. try this <span id="thisspan" class="whateverclass">1500</span> <div id="thevalueis"></div> <script> document.getelementbyid("thevalueis").innerhtml=document.getelementbyid("thisspan").innerhtml; </script> i hope got question right. :)

javascript - Angular 2 (click) sometimes does not fire -

in angular 2 / bootstrap / adminlte have following template: <button type="button" class="btn btn-default"><i class="fa fa-cutlery" (click)='munch(1);'></i></button> which calling method: async munch(amount: number) { console.log("start") await this.food.redeem(amount); console.log("stop") } the button embedded in navigation bar. press it, there seems 2/3 random chance fires. however, in 1/3 of cases nothing happens, don't see start on console. is there might interfere how angular 2 fires these click events? page relatively vanilla, , pretty sure not messing low-level dom / event handling / javascript myself. could be, i-tag smaller button? why not put (click) inside button instead of tag?

c# - How to use DropdownList selected Value to filter data -

i have dropdown,a textbox , button,dropddown contains columnnames (name,cpr),to see filtered data user selects value dropdown,enters string , clicks button. doing wrote following code,but unable dropdown selected value,except problem code working perfectly.plz tell me im doing mistake. following controller public actionresult index(string searchtype,formcollection frm) { list<selectlistitem> obj = new list<selectlistitem>(); obj.add(new selectlistitem { text = "agent name", value = "name", selected = true }); obj.add(new selectlistitem {text = "cpr number", value = "cpr"}); viewbag.cmb = obj; var agents = s in db.agents select s; if (searchtype != null) { viewbag.searchstring = searchtype; string cmbcolumnselection = frm["cmb"]; switch (cmbcolumnselection)

plsql - Oracle PL/SQL - How can I insert multiple rows using dynamic SQL -

i want go through tables , copy ids , tablename table. since have use variable table name, tried immediate execute. dynamic sql insert statement allows single rows. the following sql statement it, if immediate execute allow insert muplitple rows. declare sqlstat varchar2(500); begin tname in ( select table_name all_tab_cols column_name='id' ) loop sqlstat := 'insert storetab (id,table_name) select id, '' :1 '' :2'; execute immediate sqlstat using tname.table_name,tname.table_name; end loop; end; how can loop through tables , collect records? an insert ... select can insert multiple rows, regardless if executed through "plain" sql, through pl/sql or through dynamic sql. but can't use placeholders identifiers (names) in dynamic sql. need concatenate query. , don't need use single quotes if passing values through using clause: declare sqlstat varchar2(500); begin tname in (select ta

VBA Multiple Word Tables to Excel - No Tables in Document -

i exported of tables large word document few months ago, computer went , lost vba had used...note ++ decided disappear , take files it. so, have looked several different options out there pull tables word file excel. every 1 try says there no tables in word file. have tried multiple files, same thing. the other change in environment upgraded windows 10. i have racked brain , cannot figure out why not seeing tables? i can copy tables different word file: sub copytables() dim source document dim target document dim tbl table dim tr range set source = activedocument set target = documents.add each tbl in source.tables set tr = target.range tr.collapse wdcollapseend tr.formattedtext = tbl.range.formattedtext tr.collapse wdcollapseend tr.text = vbcrlf next end sub and can find table number in word file: sub findtablenumber() dim j integer dim itablenum integer dim otbl table selection.bookmarks.add ("tempbm") j = 1 activedocument.tables.

“Unresolved Identifier” error SparkSetupMainController()” custom Particle Photon Swift iOS app (Standard Particle documentation procedure) -

hello there, i’m trying connect particle photon custom swift ios app. i’m writing code in swift , use official particle ios development documentation guidance. ( https://docs.particle.io/guide/how-to-build-a-product/mobile-app/ ) all sdk’s within xcode project , ready used. sdk installation process via cocoapods didn’t show errors or ploblems. i had create uibutton (startdevicesetup) , added code (i think) asks functions within particle’s sdk. code given particle in documentation: @ibaction func startdevicesetup(sender: anyobject) { var setupcontroller = sparksetupmaincontroller() self.presentviewcontroller(setupcontroller, animated: true, completion: nil) } after creating , connecting uibutton , entering following code. xcode gives me unresolved identifier error when i’m trying make build: unresolved identifier error the internet tells me “unresolved identifier” seems common error have target memberships or classes aren’t public. unfortunately c

batch file - deleting content between lines containing certain words - in a text document -

i have huge text file , want delete portions of between 2 words. e.g: lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis @ vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. claritas est etiam processus dynamicus, qui sequitur mutat

c - sdl2 drawing from separate threads on Linux vs Windows -

i have simple drawing going on sdl2 working under windows i've ported on linux, isn't drawing different threads i've spawned. i'm controlling access renderer using mutex's. the functions process , output logging expected, thing doesn't appear working renderer never updates display under linux. if comment out the threading, , run function main expected result. code hasn't changed between linux , windows versions. the code compiles without warnings under -wall , -pedantic. since i've started compiling linux i've added -pthread flag in case required (hasn't made difference). if aware of gotchas or might have inkling why isn't working doing me enormous favour. static int thread_processing(void* data) { srand(time(null)); //randomize threaddata *td = data; bucket *bucket; int b_id = -1; color threadcolor; //unique color each respective thread color_rand

xml - Transforming an argument's contents with xslt -

i have xml document structure like: <report> <row> <field raw="&lt;table&gt; &lt;tr&gt; &lt;td&gt; r1c1 &lt;/td&gt; &lt;td&gt; r1c2 &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;" /> </row> </report> i can not directly change xml document far can tell, , can update raw attribute value. transform value way transform xml contents itself, rather showing contents: "<table><tr><td>r1c1</td><td>r1c2</td></tr></table>" i can instead match transform tags within contents generate corresponding fo tags pdf output, akin being able set template match like: <xsl:template match="//report/row/field/attribute::raw/table/"> <fo:table> <xsl:for-each select="../tr"> <fo:table-row> <xsl:for-each select="../td">

utf 8 - MySQL's UTF-8 character support -

i getting exception java.sql.sqlexception: incorrect string value: '\xc2\x99 adm...' column when trying insert value in mysql table. found \xc2\x99 maps u+0099 (or \u0099) 2-byte character. documentation, character 3 bytes or less supported mysql's utf-8. read utfmb4, since character 2 bytes , still giving error, issue might else. please suggest. looks using default collation latin1_swedish_ci whereas should using utf8_general_ci since meant store utf-8 data in column. check mysql documentation on character sets , collations in mysql you can use alter command change collation character set alter table your_table convert character set utf8 collate utf8_general_ci;

javascript - How to show an own text block when mouseover on a picture -

i learning html , want when move mouse picture, elephant not shown more. instead there box (without border) same size, inside box there text blue background. how should change code? https://fiddle.jshell.net/66j07kyg/ try : $(document).ready(function() { $("td").mouseenter(function(){ $("img").css({display:"none"}); $(".txt").show(); $(this).css({verticalalign:"top",backgroundcolor:"blue"}) }).mouseleave(function(){ $("img").css({display:"block"}); $(".txt").hide(); $(this).css({backgroundcolor:""}) }) }) img { width: 200px; height: 200px; } td { width: 200px; height: 200px; } .txt { display: none; color: #fff; } <table align='center'> <tr> <td> <img src=

java - How can i run a Test multiple times using testNG using XML file? -

i've 3 @test methods say, methoda, methodb , methodc. 3 methods used fill form 1 one takes input csv file. xml file looks below... <?xml version="1.0" encoding="utf-8" ?> <!doctype suite system "http://testng.org/testng-1.0.dtd" > <suite name="fill forms"> <test name="fill multiple times"> <classes> <class name="com.class"/> <methods> <include name='methoda'/> <include name='methodb'/> <include name='methodc'/> </methods> </class> </classes> </test> </suite> i want run test 'fill multiple times' multiple times. kindly suggest me idea... if each method interacting same elements , passing different inputs, try parameterizing tests 1 of approaches a

Adding Helper Rails Methods to a Directory -

i've created pdfs directory in app/ invoices , purchase orders (i'm using prawn). naturally, want numberhelper available. whats best way this? you include actionview::helpers::numberhelper in classes use generate pdfs

html - How to use the content element in Polymer? -

from documentation says <content> element supports select attribute filters nodes via simple selector. so should light dom elements targeted @ content element contain css class label/tag/value allows browser map corresponding content element has css tag/label/value set in select attribute? contained light dom elements no such labels mapped <content> element no select attribute? example enumerates possibilities helpful. so have little description dom distribution : to support composition of element's light dom local dom, polymer supports <content> element. <content> element provides insertion point @ element's light dom combined local dom. <content> element supports select attribute filters nodes via simple selector. in shadow dom, browser maintains separate light dom , shadow dom trees, , creates merged view (the composed tree) rendering purposes. in shady dom, polymer maintains own light dom , shady dom

java - How to simulate objectpointers -

i hava facade object dll cant modify using jna. dll keeps internal states , should same instance. facade object keeps state aswell. if understand correctly, if change non-primitive of object, change not traverse caller since internal pointer non-primitive might have changed. is there better way passing around wrapperobject keep changes? eg.: public class facade { private final dll dll; public facade(int foo, int bar) { //init facade this.dll = new dll(); } int foo(int bar) {} // more methods } public class wrapper { public final facade facade; public wrapper(facade facade) { this.facade = facade; } } public static class app { public static int main(string[] args) { facade fac = new facade(0,0); wrapper pointersim = new wrapper(fac); methoda(pointersim); methodb(pointersim); } } with goal of pointersim reflecting changes after methoda , b member classes , byt

c# - Create relationships with Entity Framework Core -

Image
i want build database entity framework core. use command prompt , migrations create database. can see on diagram, have many-to-many relationship. how create relationship classes below? code: public class shoppingdbcontext : identitydbcontext<user> { public shoppingdbcontext(dbcontextoptions options) : base(options) { } protected override void onconfiguring(dbcontextoptionsbuilder optionsbuilder) { base.onconfiguring(optionsbuilder); } public dbset<order> orders { get; set; } public dbset<product> products { get; set; } public dbset<partcategory> partcategory { get; set; } public dbset<part> parts { get; set; } } public class product { public int productid { get; set; } public string productname { get; set; } public double price { get; set; } public list<partcategory> partcategory { get; set; } } public class partcategory { public int partcategoryid { get; set; }

javascript - Event binding on dynamically created elements? -

i have bit of code looping through select boxes on page , binding .hover event them bit of twiddling width on mouse on/off . this happens on page ready , works fine. the problem have select boxes add via ajax or dom after initial loop won't have event bound. i have found plugin ( jquery live query plugin ), before add 5k pages plugin, want see if knows way this, either jquery directly or option. as of jquery 1.7 should use jquery.fn.on : $(staticancestors).on(eventname, dynamicchild, function() {}); prior this , recommended approach use live() : $(selector).live( eventname, function(){} ); however, live() deprecated in 1.7 in favour of on() , , removed in 1.9. live() signature: $(selector).live( eventname, function(){} ); ... can replaced following on() signature: $(document).on( eventname, selector, function(){} ); for example, if page dynamically creating elements class name dosomething bind event parent exists, document . $(document

Python, list of strings, rows into columns -

so, problem is, want transpose list rows columns example: ["aaa", "bbb", "ccc"] => ["abc", "abc", "abc"] can't find efficient way it. you can simple use of zip , unpacking: strs = ["aaa", "bbb", "ccc"] print zip(*strs) output tuples, though: [('a', 'b', 'c'), ('a', 'b', 'c'), ('a', 'b', 'c')] for strings can use: strs = ["aaa", "bbb", "ccc"] print map(''.join, zip(*strs)) # python 3 use: list(map(''.join, zip(*strs))) # @cesar output list of strings: ['abc', 'abc', 'abc'] ''.join used map tuples strings.

Python PIL saved black image -

Image
i'm trying screenshot of phone element in site. save screenshot of entire page, element coordinates , crop screenshot in phone element place. after cropping got black image. don't understand why, , how can fixe it. my code: # coding: utf-8 selenium import webdriver selenium.webdriver.common.keys import keys selenium.webdriver.chrome.options import options selenium.webdriver.common.action_chains import actionchains selenium.webdriver.common.proxy import * import time pil import image driver = webdriver.chrome(executable_path='chromedriver') driver.get('https://www.avito.ru/moskva/audio_i_video/televizor_samsung_i_tumba_iz_stekla_k_nemu_838296913') button = driver.find_element_by_xpath('//*[@id="i_contact"]/div[3]/div/span[1]/span') button.click() time.sleep(4) element = driver.find_element_by_xpath('//*[@id="i_contact"]/div[3]/div/span[1]') location = element.location size = element.size driver.save_screenshot('scr

javascript - d3.js v4 force diagram update -

trying update force diagram nodes , links exist in current diagram. example, have simple diagram 2 nodes , b , link between them "a" --> "b". i wondering correct way of handling if node, same, added. in fiddle i've put , in personal development end duplicates, thought handled in .data(nodes, function(d) { return d.id; }) and links appropriate data function (for example .data(links, function(d) { return d.target; }) ) ideally, i'm looking "nothing happen" when same node/ link added. hopefully, makes sense, please see fiddle example here

javascript - Enabling CORs on Safari -

i have made simple angularjs website. backend google sheet, not ideal it's free. have deployed following script webapp json google sheet: (this not code btw) function doget(request) { var output = contentservice.createtextoutput(); var data = {}; var id = request.parameters.id; var sheet = request.parameters.sheet; var cell = request.parameters.cell; var ss = spreadsheetapp.openbyid(id); if (sheet) { if (cell) { data = ss.getsheetbyname(sheet).getrange(cell).getvalue(); } else { data[sheet] = readdata_(ss, sheet); } } else { // grab sheets except name // starts underscore ss.getsheets().foreach(function(osheet, iindex) { var sname = osheet.getname(); if (! sname.match(/^_/)) { data[sname] = readdata_(ss, sname); } }) } var result = cell ? data : json.stringify(data); var callback = request.parameters.callback; if (callback == undefined)

python - module not found error in migration files after renaming model files in django -

i renamed model files users.py users.py . makemigrations , migration worked fine when tried run command manage.py runserver , throwing error. no module named 'accounts.models.users' in migration file. # -*- coding: utf-8 -*- # generated django 1.9.7 on 2016-09-12 16:37 __future__ import unicode_literals import accounts.models.users django.db import migrations class migration(migrations.migration): dependencies = [ ('accounts', '0004_usermodel_is_active'), ] operations = [ migrations.altermodelmanagers( name='usermodel', managers=[ ('objects', accounts.models.users.myusermanager()), ], ), ] how resolve error? should not change model file names?

python - How do i set django setting to a file which is outside the django tree? -

i have python file tasks.py import os os.environ.setdefault('django_settings_module', 'djangowebproject.settings') django.contrib.auth.models import user logreg.models import activationcode import datetime def remove_users(): print 'hello worldddddddddddddddddddddddddddddddddd' inactive_users = [] activation_codes = activationcode.objects.all() activation_code in activation_codes: if datetime.datetime.date(activation_code.key_expires) < datetime.datetime.date(datetime.datetime.now()): inactive_users.append(activation_code.user_id) inactive_user in inactive_users: user.objects.filter(id=inactive_user).delete() but in root folder , when try execute it, gives me following error file "c:\users\deybala1\appdata\local\continuum\anaconda2\lib\site-packages\dj ango\apps\registry.py", line 124, in check_apps_ready raise appregistrynotr

jquery - socket.io connecting but not firing events on ios10 -

i'm using jquery/socket.io/nodejs. until ios 10 (ipad - not tested on iphone), used work , connection server. abstracted larger project, duplicate issue. nodejs server gets connection in example, seen in it's log file. i don't have connection browser console, since it's ipad. using safari, though chrome not work also. tried putting "try/catch" around (not shown here) , "catch" never fires. socket.io uses websockets, not ipv6 compatible, apple may have issue that, have not found definitive answers referencing that. have read somewhere apple may cripple javascript uses "eval", again not find more definitive. <html> <head> <title>ios10 socket.io test</title> <meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' /> <meta http-equiv="content-security-policy" content="default-src 'self' data: gap: ws:

sql - Select SubQuery for Comma Separated Values from Single row -

from select query getting following values in single row , not in different rows: id statuses --- ------------- 1 released,in progress,completed now want write query should orders in statuses: select * orders status in (select statusesfrom statustable) adopt 1 of these splitters. can write own see lot has gone researching these: http://www.sqlservercentral.com/articles/tally+table/72993/ this splits value table single column. can join on after run function on like: select o.* orders o inner join splittable s on o.keycolumn = s.column

sql server - SQL extracting information from columns names -

i have sql server table column names such int115 , int430 , on corresponding data. want multiply data in int115 column 115, data in int430 column 430 , on. not sure how proceed. edit: need parse column names , rid of left 3 characters come multiplier number. edit2: working grandfathered table can't make changes how database looks like. edit after question updated this not require hard coding @ all: cursor through temp table parsed through column names multiplication values, select table , give multiplied values. using 'sampletable' table name. assumes each of columns begin int , have number after. select column_name, cast(substring(column_name, 4, 10)as int) multiplier_number #values information_schema.columns table_name = 'sampletable' declare @ssql nvarchar(max) declare @columnname nvarchar(50) declare thing cursor ( select column_name #values ) open thing fetch next thing @columnname whil