Posts

Showing posts from March, 2010

vb.net - Check if file exist before counting the length of the string in text file -

i having hard time figuring why code of mine gives me unhandled exception error in fact if statement.. if (not system.io.file.exists("c:\file.txt") , system.io.file.readalltext("c:\file.txt").length <> "20") messagebox.show("code executed!") else messagebox.show("failed execute!") end if can please tell me have missed? it better break down code shown below makes detecting , debugging whole lot easier. better write few lines happen here not happen @ all. dim filename string = "c:\file.txt" dim filetext string = "" if io.file.exists(filename) filetext = io.file.readalltext(filename) if filetext.length <> 20 messagebox.show("code executed!") else ' recover end if else messagebox.show("failed execute!") end if

javascript - Angular: Run some JQuery against a selection of views -

i wrote code this, way did felt so inelegant had ask if had basic advice me. want run jquery modify attributes of buttons in sub-set of views (they're in same directory). wrote jquery i cannot figure out put code . right i'm shoving .js file in views' directory , using include statement toward end of each view file. not mvc...... situation several buttons appear in interface no visible label. info them in popover attribute. fine (or maybe it's bad ui or whatever) long you're not blind , using screen-reader, won't pick popover text. want copy contents of popover text aria-label adding labels "manually" right button in question created within angular framework. jade button looks this: button.customize-option(class='pet_egg_{{::egg}}', ng-class='{selectableinventory: selectedpotion && !(user.items.pets[egg+"-"+selectedpotion.key]>0) && (content.dropeggs[egg] || !selectedpotion.premium)}', ...

Removing an Object from an Array of Objects in Java -

i working on school project learning use arrays of objects. have come across 2 separate issues along way address. using netbeans ide code mention below. firstly, after have added values array, attempt use list button should display values in jtextarea. there no noticeable errors pop-up although, values "null" instead of user inputted values should say. since there 5 values program displays "null null null null null". not sure why , input appreciated. secondly, attempting allow user remove information based on 1 of 5 values have been stored. in case of program user must enter "employee id" remove of said employee's data program list. having trouble doing able see in code below. so sum things up: how can correct random "null" error imputed data displayed? how can remove values of given index based on user input idnumber? things keep in mind: - need use array of objects - new coding please excuse possible ignorance - appears missing ...

python - Import statement flow -

my app layout my_app __init__.py my_app __init__.py startup __init__.py create_app.py create_users.py common_settings.py core __init__.py models.py views.py errors __init__.py errors.py inner __init__.py from flask import flask flask_script import manager flask_sqlalchemy import sqlalchemy app = flask(__name__) # wsgi compliant web application object db = sqlalchemy(app) # setup flask-sqlalchemy manager = manager(app) # setup flask-script my_app.startup.create_app import create_app create_app() create_app.py def create_app(extra_config_settings={}): # load blueprints manager commands, models , views my_app import core return app core/__init__.py # . import views views.py from my_app import app, db flask imp...

android - Back Key code not working -

hey have following code within application, when use button close music activity or main menu not seem work music still plays when button has been pressed exit app. work film activity/film clips explain may problem? i not errors: @override public boolean onkeydown(int keycode, keyevent event) { if ((keycode == keyevent.keycode_back)) { this.finish(); } return super.onkeydown(keycode, event); } you can use in activity @override public void onbackpressed() { this.finish(); }

xcode - Updating objects on parse - [Error] object not found -

i trying update object on parse, error message: [error]: object not found update (code: 101) let query = pfquery(classname: "answers") query.findobjectsinbackgroundwithblock { (objects, error) -> void in if let objects = objects { object in objects { object["upvoters"] = ["one","two"] object.saveinbackground() } } } what causing this, , how fix it? the cause of issue acl settings of object trying edit. trying edit object wasn't created me, , acl did not have public write access true. see parse acl

MVC in php, model for categories? -

i building first little app php , trying mvc. my website requires quite large arrays of cities , categories. my question simple 1 arrays data website php arrays, should arrays placed own models? from understood models used business logic , accessing data, cities , categories data justify them having model? and if answer no why , should do? thanks model responsible retrieving, editing, deleting , manage data. data comes static sources such databases, xml files , such. you should create model classes interface data. that's model supposed do. can hold data in private members way want, arrays, other classes etc. you wondering why idea? well, data should stored in classes because can set visibility class members. data items private can decide actions allowed, leading general better design , security. also models don't contain logic in them. it's controller deals logic. it's in mv (model / view) architecture models implements logic. you can take...

Parsing XML data in C# and show into ListBox -

i trying parse xml file in c# using visual studio , show data in listbox, don't know how parse when i'm dealing nested xml file. this code xml file: <?xml version="1.0" encoding="utf-8" ?> <!doctype root [ <!element root (persons*)> <!element persons (name)> <!element ismale (#pcdata)> <!element age (#pcdata)> <!element name (#pcdata)> <!element likedperson (name)> ]> <root> <persons name ="bob"> <ismale>true</ismale> <age>30</age> <likedperson name ="iulia"> <ismale>false</ismale> <age>32</age> </likedperson> </persons> </root> the code i've written in c# return me name, gender , age every person, don't know how write show me person_liked: private void loadpersons() { xmldocument doc = new xmldocument(); doc.load("baza_...

Is it possible to add a javascript variable into a JQuery .css()? -

i have javascript function loop in it function blackout() { 'use strict'; (i = 100; > 0; = - 1) { $("body").css(); } } i want add css code using jquery function .css() -webkit-filter: brightness(i); filter: brightness(i); such screen blackout. what write inside .css() allow me have variable 'i' inside well? this should make trick: function blackout() { 'use strict'; $body = $("body"); (i = 100; > 0; = - 1) { $body.css('-webkit-filter', 'brightness('+ +')'); $body.css('filter', 'brightness('+ +')'); } }

python - flask unable to run db migrate - NameError: name 'conn_uniques' is not defined -

every time update models have delete , reinitialize database. ./manage.py db init , initial ./manage.py db migrate work every subsequent ./manage.py db migrate fails following error: info [alembic.migration] context impl sqliteimpl. info [alembic.migration] assume non-transactional ddl. traceback (most recent call last): file "manage.py", line 110, in <module> manager.run() file "/home/sergi/.virtualenvs/flaskvenv/lib/python3.4/site-packages /flask_script/__init__.py", line 405, in run result = self.handle(sys.argv[0], sys.argv[1:]) file "/home/sergi/.virtualenvs/flaskvenv/lib/python3.4/site-packages /flask_script/__init__.py", line 384, in handle return handle(app, *positional_args, **kwargs) file "/home/sergi/.virtualenvs/flaskvenv/lib/python3.4/site-packages /flask_script/commands.py", line 145, in handle return self.run(*args, **kwargs) file "/home/sergi/.virtualenvs/flaskvenv/lib/python3.4/site-packages ...

java - Hibernate/JPA - NullPointerException when accessing SingularAttribute parameter -

i'm trying use jpa2 type-safe criteria queries hibernate 5.0.7.final. ... criteria.where( builder.equal( root.get(singularattribute.attr), value )); //where parameters //criteria.where( builder.equal( root.get(person_.name), "can" )); ... the root.get throw nullpointerexception . metamodel class person_ person generated org.hibernate.jpamodelgen.jpametamodelentityprocessor . a similar problem asked in jpa/hibernate static metamodel attributes not populated -- nullpointerexception time both classes in same package. stack trace: java.lang.nullpointerexception @ org.hibernate.jpa.criteria.path.abstractpathimpl.get(abstractpathimpl.java:123) my code: interface use make sure have getid(); . package it.unibz.db.hibernate.model; public interface modelinterface<pk extends serializable> extends serializable { pk getid(); } model class package it.unibz.db.hibernate.model; @entity @table(name ="person") public class person implements ...

scheme - fetch n-elements from a list Racket -

how can fetch n-elements list, know first, rest etc, if want first 3 elements in list, i.e (get-first 3 (list 1 2 3 4 5 6)) -> (list 1 2 3) (get-first 5 (list 54 33 2 12 11 2 1 22 3 44)) -> (list 54 33 2 12 11) this not homework, code me complete bigger picture of assignment, stuck , need few hints. not allowed use lambda or build-list , no recursion, somehow need b able map, filter, foldr etc... as mentioned @alexisking, can use take procedure that's built-in in racket: (take '(1 2 3 4 5 6) 3) => '(1 2 3) (take '(54 33 2 12 11 2 1 22 3 44) 5) => '(54 33 2 12 11) if reason that's not allowed can still roll own version using higher-order procedures , no explicit recursion, do notice not using lambda impossible, allowed procedures mention ( map , filter , foldr ) all receive a lambda as parameter , , anyway all procedures in scheme lambda s under hood. here's contrived solution, passing accumulator remembers in inde...

r - Convert a string with concatenated indices and values to a vector of values -

i have data frame this: v2 v3 1.000 2:3,3:2,5:2, 2.012 1:5,2:4,6:3, the second column v3, consists of 'index-value' pairs, each pair separated , . within each 'index-value' pair, number preceeding : vector index. number after : corresponding value. e.g. in first row, vector indices 2, 3, , 5, , corresponding values 3, 2, , 2. indices not represented in string should have value 0 in resulting vector. i wish convert 'index-value' vector vector of values. thus, 2 strings above expected result is: v2 v3 1.000 c(0,3,2,0,2,0) 2.012 c(5,4,0,0,0,3) we make use of data.table package use tstrsplit function. removes intermediate step. try this: require(data.table) df$v3<-lapply( lapply(strsplit(as.character(df$v3),",",fixed=true),tstrsplit,":"), function(x) {res<-numeric(6);res[as.numeric(x[[1]])]<-as.numeric(x[[2]]);res}) # v2 v3 #1 1.000 0,3,2,0,2,0 #2 2.012 ...

Difference between dot operator and fully qualified named call in Clojure -

i'm learning clojure. still have no understanding language , philosophy. but want more familiar language. hence have started read clojure core api documentation , found interesting stuffs in clojure.core/get source code. (defn "returns value mapped key, not-found or nil if key not present." {:inline (fn [m k & nf] `(. clojure.lang.rt (get ~m ~k ~@nf))) :inline-arities #{2 3} :added "1.0"} ([map key] (. clojure.lang.rt (get map key))) ([map key not-found] (. clojure.lang.rt (get map key not-found)))) to value given key code uses clojurelang.rt/get function. code calls dot operator - (. clojure.lang.rt (get map key)) . my question why author wrote (. clojure.lang.rt (get map key)) instead of (clojure.lang.rt/get map key) . is there technical difference? or benefit? the dot in clojure used host interop (with java class clojure.lang.rt in case). idiomatic form static method (classname/staticmethod args*) gets exp...

ios - adjustsFontSizeToFitWidth not working when change constraints? -

i have costview holds uilabel dollarsign , uilabel cost . this how dollarsign being constrained. this how cost being constrained. in addviewcontroller changed of constraints, including height of costview class addviewcontroller: uiviewcontroller { @iboutlet weak var costview: uiview! @iboutlet weak var statusbarheight: nslayoutconstraint! @iboutlet weak var navigationbar: uinavigationbar! @iboutlet weak var dollarsign: uilabel! @iboutlet weak var cost: uilabel! @iboutlet weak var keyboardheight: nslayoutconstraint! @iboutlet weak var costviewheight: nslayoutconstraint! override func viewdidload() { super.viewdidload() //set size of cost view & numbers keyboard let halfviewheight = (view.bounds.height - statusbarheight.constant - navigationbar.bounds.height)/2 costviewheight.constant = halfviewheight/cgfloat(4) keyboardheight.constant = halfviewheight - costviewheight.constant //adjust font size of dollar sign & cost cost.adjustsfon...

hadoop - Spark Execution of TB file in memory -

let assume have 1 tb data file. each node memory in ten node cluster 3gb. i want process file using spark. how 1 terabyte fits in memory? will throw out of memory exception? how work? as thilo mentioned, spark not need load in memory able process it. because spark partition data smaller blocks , operate on these separately. number of partitions, , size depends on several things: where file stored. commonly used options spark store file in bunch of blocks rather single big piece of data. if it's stored in hdfs instance, default these blocks 64mb , blocks distributed (and replicated) across nodes. files stored in s3 blocks of 32mb. defined hadoop filesystem used read files , applies files other filesystems spark uses hadoop reed them. any repartitioning do. can call repartition(n) or coalesce(n) on rdd or dataframe change number of partitions , size. coalesce preferred reducing number without shuffling data across nodes, whereas repartition allows specify ...

When using ASP.NET MVC and LINQ, should you be creating stored procedures in your SQL database? -

this don't understand. conventional wisdom stored procedures create them if know know query executed part of application , can describe in terms of paramaters (which 99.9999% of time .. other 0.0001% being if create application in queries unpredictible because user writing queries or something). if -- set triggers, cascade deletes, sprocs -- when create database, point of having model? purpose model serves in case tell database "go!" , database performs logic. makes m in mvc irrelevant. sorry if seems opinion-based quesiton, feel i'm not getting gist of asp.net mvc if on 1 hand i'm being told "make database handle logic possible" , other hand have these tools linq, entity, etc., creating c# way of querying database. are asp.net mvc , stored procedures antonyms? firstly, asp.net mvc , stored procedures not antonymous. not related. not mean cannot both in same application. i'd think of mvc design pattern presentation/ui. m in mvc ent...

swift - got error on xcode7... I can't use 'new()' on xcode7? -

the error said 'new()' unavailable swift::use object initializers instead. don't know how fix... func showimage(notif:nsnotification) { if let userinfo = notif.userinfo nsdictionary! { //the code below 1 got error let photos:nsmutablearray = nsmutablearray.new() let photo:idmphoto = idmphoto(image: userinfo["img"] as! uiimage!) photos.addobject(photo) let browser:idmphotobrowser = idmphotobrowser(photos: photos [anyobject]!) browser.delegate = self browser.displayactionbutton = false self.presentviewcontroller(browser, animated: true, completion: nil) } } simply change nsmutablearray.new() nsmutablearray() .

php - Wordpress custom permalinks using .htaccess -

Image
currently added custom structure posts premalinks /post/%post_id% through permalinks settings in admin. since need rewrite permalinks categories, tags , author pages follow: categories current /post/category/category_name /category_name tags current /post/tag/tag_name tag/tag_name author current /post/author/author_username /author/author_username i tried create custom rewriterule in .htaccess, didn`t work @ all: rewriterule ^/([^/]*)$ ./post/category/$1 [l] rewriterule ^/tag/([^/]*)$ ./post/tag/$1 [l] rewriterule ^/author/([^/]*)$ ./post/auhtor/$1 [l] any .htaccess rules coding achieve such permalinks appreciated. make sure have rewrite engine on in apache configuration login wordpress administrative rights , go settings -> permalinks shown attached 3 images. if permalink not updated, don't have write access root of website or rewrite module of apache not enabled. if permalink message appears, means created .htaccess in root of wordpress...

swing - Java JTable combobox validation -

Image
there 3 things trying here: first trying make combo box show "not feed" when u lanuch program, @ moment when launches shows nothing, when click on combo box shows option "feed" , "not feed". secondly trying validation combobox, when click jbutton next, validate if combobox "feed" if go next, else have pop saying "check again" lastly, make cells on first 4 col uneditable , last column editable. public class dosagetablehelper { private static jtable todotable; private static jscrollpane jpane; private static int counter=1; public static defaulttablemodel getelderlyfromquerydos(string timing,string position) throws sqlexception { sqlobject = new sqlobject(); resultset rs = null; if(timing.equalsignorecase("morning")){ preparedstatement stmt = so.getpreparedstatementwithkey("select morningdosage et_elderly name = ?"); stmt.setstring(1,position); stmt.executequery(); ...

c# - How to stop Translate when I need? -

Image
i have cupboard boxes. when on box , press mouse button, want open/close translate . want move box, till it's x coordinate 1.0 (and start point 1.345). moves longer point. i tried use fixedupdate, doesn't helped.. public layermask mask; private bool shouldclose; private bool changexcoordinate; private transform objecttomove; void update () { if (changexcoordinate) openclosebox(); else if(doplayerlookatcupboardbox() && input.getmousebuttondown(0)) changexcoordinate = true; } bool doplayerlookatcupboardbox() { raycasthit _hit; ray _ray = camera.main.screenpointtoray(new vector3(screen.width / 2, screen.height / 2, 0)); bool ishit = physics.raycast(_ray, out _hit, 1.5f, mask.value); if (ishit && !changexcoordinate) { objecttomove = _hit.transform; return true; } else return false; } void openclosebox() { if (shouldclose) { if(objecttomove.position.x ...

arrays - what is numpy.ndarray without column in python? -

i saw sample: from sklearn import cross_validation sklearn import metrics sklearn import svm sklearn import datasets iris = datasets.load_iris() clf = svm.svc(kernel='linear', c=1) predicted = cross_validation.cross_val_predict(clf, iris.data,iris.target, cv=10) metrics.accuracy_score(iris.target, predicted) so wrote: from sklearn import cross_validation sklearn import metrics sklearn import svm clf = svm.svc(kernel='linear', c=1) train_data_input=train_df.iloc[:,1:].values train_data_output=train_df[[0]].values predicted = cross_validation.cross_val_predict(clf, train_data_input,train_data_output, cv=10) metrics.accuracy_score(train_data_output, predicted) but got error: indexerror: many indices array. i think, problem relate type of "train_data_output". whilst see these types: type(train_data_output) out[32]: numpy.ndarray type(iris.target) out[33]: numpy.ndarray but in "spyder>variable explorer window" can see difference...

php - Indexes on foreign key in MySQL -

i have simple code. create table foo ( client_id int, order_id int, primary key (client_id, order_id), index (order_id), foreign key (client_id) references baz(id), foreign key (order_id) references bar(id) ); i know mysql automatic add index column primary key, if have complex primary key? (example in code). why must add index second column in primary key? think mysql automatic add index first column second, third ... must add constraint manually? answer in official documentation? you can refer link http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html if table has multi-column index eg: (col1, col2, col3) , can have search capabilities (col1) , (col1, col2) , , (col1, col2, col3) this index never used if search not form left prefix on index, in case col1 so need have col1 prefix , search col2,col3 wont use index you might need different index same, have index col2 separately

java - how do i use the information from a deep link url that opens an activity in android? -

i'm sending confirmation email don't know how confirm account when link clicked? when user click on link send, want extract query string token , compare token token in database. how do this? thanks guys! there different approaches! have @ follwing approach: generate unique random unique string used token generating random string find reference in question here store token in database , send link token attached link query string . when user click on link sent, extract the query string token compare token token in database. if token matches email validated!! e.g.suppose generated token 5dti72eo6sfu215dti72eo6sfu store in database , generate link mydomain.com?action=validateemail&user=theuser&token=5dti72eo6sfu215dti72eo6sfu don't forget remove token database , update email verified status!! hope helps.

vue.js - Vuejs: v-model array in multiple input -

i'm amazed vuejs brings table, i'm hitting wall @ following. have input text field v-model attached, , every time hits "add" button, input text added dom same v-model attached. thought i'd array of v-model values, gets value of first v-model input: <label class="col-sm-2" for="reference">referenties</label> <div class="col-sm-6"> <input v-model="find.references" class="form-control" type="text"> </div> <div class="col-sm-2"> <button @click="addreference" class="form-control"><span class="glyphicon glyphicon-plus"></span>add</button> the html append dom triggered addreference method: addreference : function (e) { e.preventdefault(); console.log(this.find.references); div = '<div class="col-sm-6 col-md-offset-2 reference...

range - Does Xapian support query string like "x: 1..2 OR x: 8..10"? I cannot figure it out -

following simple code, index function establishes indexers , search function searches using querystring directly: #include <xapian.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <string> using namespace std; int index() { try { xapian::writabledatabase db("./index.db", xapian::db_create_or_open); xapian::termgenerator indexer; xapian::stem stemmer("english"); indexer.set_stemmer(stemmer); (int = 1; < 12; i++) { xapian::document doc; indexer.set_document(doc); string title("title "); string desc("example data number of "); stringstream num; num << i; title.append(num.str()); desc.append(num.str()); indexer.index_text(title, 1, "s"); indexer.index_text(desc, 1, "xd"); indexer.inde...

php - How is this URL being mapped in Apache? -

i've taken on project old developer disappeared, , first self-assigned task able replicate entire stack on ec2 host. on original pre-existing host, can hit url http://www.example.com/users/login/ (i can drop trailing slash , hits login page fine). looking through source code in /var/www/[example.com]/ -- can find sections/users/login.php looks html page rendered from. i have same code in secondary ec2 host, i'm not bothering use virtual hosts, i'm putting in /var/www/html/ (rather /var/www/[example.com]/), i'm getting 404. where should mapping points http://www.example.com/users/login/ /sections/users/login.php? i not well-acquainted rewriterule stuff, 2 .htaccess files in repo, , in httpd.conf, see nothing 'sections' anywhere, i'm not sure look. the .htaccess in root directory is: php_value post_max_size 1024m php_value upload_max_filesize 1024m php_value memory_limit 1024m php_value max_input_time 1800 php_value max_execution_time...

c# - Linq to Entities : using ToLower() on NText fields -

i'm using sql server 2005, case sensitive database.. in search function, need create linq entities (l2e) query "where" clause compare several strings data in database these rules : the comparison "contains" mode, not strict compare : easy string's contains() method allowed in l2e the comparison must case insensitive : use tolower() on both elements perform insensitive comparison. all of performs ran following exception : "argument data type ntext invalid argument 1 of lower function" on 1 of fields. it seems field ntext field , can't perform tolower() on that. able perform case insensitive contains() on ntext field ? never use .tolower() perform case-insensitive comparison. here's why: it's possibly wrong (your client collation be, say, turkish, , db collation not). it's highly inefficient; sql emitted lower instead of = case-insensitive collation. instead, use stringcomparison.ordinalignorecase...

Can Google Analytics track third party cookies? -

i've searched information if ga can track if specific third party cookie set in visitors web browser. , if so, if tracking data can used segmentation of data in reports. ex: visitor x arrives website. third party cookie y has earlier been set in visitor x's web browser when he/she interacted web application. now, can ga track existence of cookie y , send tracking data analytics system use in reports? example segmentation of visitor behaviour. /axel a third party cookie cookie set on different domain. google analytics tracking code runs within context of own domain. scripts on own domain cannot read cookies other domains. no, default google analytic cannot track third party cookies. there workarounds, imo work if owner of other domains cooperate (e.g. once built poor mans banner postview tracking adserver calling script on domain resolve cookie , return user id in jsonp response, built on infrastructure in place).

asp.net - Distributed networks with microservices -

i'm reading lot microservices , there use cases. azure service fabric great framework develope such services. i found nice usage pattern service fabric: https://azure.microsoft.com/en-us/documentation/articles/service-fabric-reliable-actors-pattern-distributed-networks-and-graphs/ in example there 1 microservice type representing user reliable stateful actor. each user instance of service. so if have thousends of users, have thousends of actor instances. in facebook can update feed , feed of friends easy. example, state of user actor service stores social feed , social feed of friends entries of our social states. makes easy these informations fast low latency display , on. that working well, because user hasn't thousends of friends. know store public feed entries of social states users available? e.g. iterate on user actor instances , alle states. would't fast, because have find actor instances , on. there pattern or best practice that? maybe stateful service...

As I try compiling my c code it keeps notifying me that " line 13:error:identifier expected ".my programming involves storing string of arrays -

#include<stdio.h> struct names { char name1[49]; char name2[48]; char name3[49]; }; stud1,stud2,stud3; int main() { char names; printf("enter first name of first student\n"); scanf("%s",&struct names.name1.stud1); printf("enter second name of first student\n"); scanf("%s",&struct names.name2.stud1); printf("enter third name of first student\n"); scanf("%s",&struct names.name3.stud1); printf("enter first name of second student\n"); scanf("%s",&struct names.name1.stud2); printf("enter second name of second student\n"); scanf("%s",&struct names.name2.stud2); printf("enter third name of second student\n"); scanf("%s",&struct names.name3.stud2); printf("enter first name of third student\n"); scanf("%s",&struct names.name1.stud3); printf("enter second name of third student\n...

Linq Datatable separated comma -

there problem. long d = (_dtgetdocumentslist.asenumerable().where(c => c.rowerror == "selected").sum(order => order.field("debcre"))); digits in debcre separated , (group digit). how can remove , column before select ? thanks

php - Validate inputs with jQuery -

objective: validate input form. if okay, submit it, otherwise return error user. problem: i want validate inputs in form, don't know how cleanly. how can validate form safely without heavy validation libraries? try this: function validate() { if (validatefield(document.form.field1) && validatefield(document.form.field2) && validatefield(document.form.field3) && validatefield(document.form.field4) && validatefield(document.form.field5)) return true; else return false; } function validatefield(field) { //your condition of validation }

how to read a specific line which starts in "#" from file in python -

Image
how can read specific line starts in "#" file in python , set line key in dictionary (without "#") , set lines after line until next "#" value dictionary please me here file : please me :( from collections import defaultdict key = 'nokey' d = defaultdict(list) open('thefile.txt', 'r') f: line in f: if line.startswith('#'): key = line.replace('#', '') continue d[key].append(line) your dictionary have list of lines under each key. lines come before first line starting '#' stored under key 'nokey' .

php - Overriding custom login error messages in laravel 5.2 -

i've been struggling laravel 5.2 login function messages. i've override default sendfailedloginresponse function in authcontroller works failed attempts. but need override validate function response not figure out how that. not want override default login functionality in authcontrller , want stick same login function. the reason overriding validate function making angular app , want response in json format custom keys. currently default login function in illuminate\foundation\auth\authenticateusers.php public function login(request $request) { $this->validate($request, [ $this->loginusername() => 'required', 'password' => 'required', ]); // if class using throttleslogins trait, can automatically throttle // login attempts application. we'll key username , // ip address of client making these requests application. $throttles = $this->isusingthrottlesloginstrait(); if ($throttles ...

height - Issue with Android devices having soft status bar which hides bottom tabs -

Image
i having issue different android devices set layout soft status bar @ bottom covers bottom tabs. there way overcome issue tried set margin of tab layout works need way detect different android devices can set margin particular. any appreciated.

python - Add header to np.matrix -

Image
i trying export numpy matrix ascii format, want add header first. my code concept this: import ascii file np.ndarray, matrix take header of (first 6 rows). header contains both float values , characters take rows of not header (from rows 6 last row), giving array b apply functions on b save ascii in form: header(a) + b i tried following: try 1: import numpy np = np.genfromtxt('......input\chm_plot_1.txt', dtype=none, delimiter='\t') header = a[0:6] b = a[6:] mat_out = np.concatenate([a,b]) np.savetxt('........out.txt', mat_out, delimiter='\t') ,but gives error: typeerror: mismatch between array dtype ('|s3973') , format specifier ('%.18e') try 2: import numpy np = np.genfromtxt('......input\chm_plot_1.txt', dtype=none, delimiter='\t') header = a[0:6] headers = np.vstack(header) head_list = headers.tolist() head_str = ''.join(str(v) v in head_list) b = a[6:] np.savetxt('\out.tx...

Fast Copy Array in Array VB6.0 -

i have array want copy in two-dimensional (like jagged) code : dim cb(1000000) double dim buffer(50, 1000000) double = 1 1000000 cb(i) = cint(int((50 * rnd()) + 1)) next i can use copy cb buffer. code : for = 1 10 j = 1 1000000 buffer(i, j) = cb(j) next next but want know there faster method this? in vb.net or c# use list. there thing in vb6.0? thanks. maybe don't copy array @ all? function accessmyarray(arr, i, j) ' todo: add range check using lbound() / ubound() accessmyarray = arr(i * 1024 + j) end function

swift - Hierarchical Nav just to Main Controller in Apple WatchKit 2 -

i building app moves between set of controllers using: self.pushcontrollerwithname("scene a", context: nil) calling create ability @ top ideal e.g. main scene -> scene -> scene b -> scene c, how can pop whole stack main scene scene c in "pop beginning" type call? function can see goes backwards 1 step. self.popcontroller() there self.poptorootcontroller() discussion use method return interface initial configuration. might can reset navigation hierarchy initial state before pushing 1 or more different interface controllers onto navigation stack. always call method watchkit extension’s main thread. availability available in ios 8.2 , later. reference document

java - What happens if you remove the space between the + and ++ operators? -

edit 1 disclaimer: i know that +++ is not operator + , ++ operators without space. know there's no reason use this; question out of curiosity. so, i'm interested see if space between + , ++var required in java. here test code: int = 0; system.out.println(i); = +++i; system.out.println(i); this prints out: 0 1 which works expect, if there space between first , second + . then, tried string concatenation: string s1 = "s " + ++i; system.out.println(s1); // string s2 = "s " +++i; this prints out: s 2 but if third line uncommented, code not compile, error: problem3.java:13: unexpected type required: variable found : value string s2 = "s " +++i; ^ problem3.java:13: operator + cannot applied <any>,int string s2 = "s " +++i; ^ what's causing difference in behavior between string concatenation , integer addition? edit 2 as discussed in abhijit...