Posts

Showing posts from March, 2014

activerecord - Rails 4 includes multiple has_many and belongs_to index.html.erb -

how handle belong_to following include. instead of displaying product_colour_id id show associated colour ( update:solved part below ). product_colour_id in product table , matches corresponding product_colour id. its case of 2 or more has_many associations cant work out. can done? app/controller/home_controller.rb class homecontroller < applicationcontroller def index products = product.last(5) product_ids = products.map(&:id) @product_colour_ids = products.map(&:product_colour_id) @allproduct_colours = productcolour.all @product_colour_map = productcolour.find(@product_colour_ids) @product_images = product.includes(:product_images) .where(product_images: {product_id: product_ids, :default_image => true}) end end /app/views/home/index.html.erb <% @product_images.each |pd| %> <%= content_tag :div, :class => "col-md-3 col-sm-6 hero-feature" %> <% pd.produc...

python - How to assign one JSON key to all output dictionaries? -

i working pyodbc iterate through table return records json , send server validation. able iterate , return rows, however, server expecting json in format below. how iterate through results , append {"metadata": {}, "srdata": keys each iterated result/output? code below. desired output: { "metadata": {}, "srdata": { "srnumber": "1-3580671" } }, { "metadata": {}, "srdata": { "srnumber": "1-3580156" } } code: import pyodbc import json import requests connstr = 'driver={sql server};server=server;database=servicerequest; uid=sa;pwd=pwd' conn = pyodbc.connect(connstr) cursor = conn.cursor() cursor.execute("""select srnumber containerfc""") columns = [column[0] column in cursor.description] results = [] row in cursor.fetchall(): results.append(dict(zip(columns...

How do i construct a regex for the hostnames -

host names can long/fqdn: cs25-admin.nmtg.company.com cs25-admin.nms.company.com or short: cs25-xyz23 but should not match 11.22:33:44:55-66 i wrote this: /.*-.*(nmtg)*|.*(\.nms)/ but fails last 1 11.22:33:44:55-66 /^[^:]+$/ , although suspect misunderstood question.

sql - In PostgreSQL, get a minimum value if there is none -

sorry if title did not match actual question. i'm not sure how phrase this. in postgres, have users can @ station. stations numbered 1 5. have table users , has column station . if user @ station, station value number of station, if not, null. here's how find number of users @ each station: select station, count(users) users users station not null group station order station; this yields: station | users ---------+--------- 1 | 4 2 | 1 3 | 1 but that's not really true. there 0 users on station 4 , 5. how can address that? use query view calculate other things, need stations there. don't need table stations, far know: i'm not going use them anywhere else. so how account unused stations? need make table them , reference stations table users table or there simpler way? assuming have table stations , can handle left join : select s.station, count(u.station) users stations s left join users...

javascript - Skype Button: How to prevent vertical space -

i started learning html, css , js. trying add skype button web, creates blank lines above , below. how remove blank lines , make skype button appear inline text coded before skype button code? (sorry, new stackoverflow, not able post image of result. this sample code trying with. <link rel="stylesheet" type="text/css" href="960-grid-system-master/code/css/960_12_col.css" /> <div class="container_12 clearfix"> <div class="grid_12"> <span>contact xxxxxxx xxxxx</span> <script type="text/javascript" src="http://www.skypeassets.com/i/scom/js/skype-uri.js"></script> <div id="skypebutton_call_xxxxxxx_1"> <script type="text/javascript"> skype.ui({ "name": "call", "element": "skypebutton_call_xxxxxxx_1", "participants": ["xxxxxx...

sql - How to identify sessions in traffic logs by detecting periods of idleness or inactivity? -

i'm looking @ traffic logs (collected through haproxy) , trying identify user sessions (aka visits). i'm defining user unique ip + user agent checksum, or else available, user id logged-in users. i'm not sql wiz, , i'm wondering if there's way identify new session defined logged event after 30 minutes since last logged event same user. use t-sql, , we're running on sql server 2012. it may i'm overlooking obvious confounds session id methodology. i'd appreciate wisdom comes mind. the db schema looks this, filtered user defined ua: abcdefghij + ip: 11.11.11.1 : id || user agent || ip || accountid || routename || creationdate ----------------------------------------------------------------------------------- 9 || abcdefghij || 11.11.11.1 || null || home || 2015-05-29 00:00:25 ----------------------------------------------------------------------------------- 45 || abcdefghij || 11.11.11.1 || null || hom...

c# - Testing for Dictionary KeyNotFoundException -

i have scenario there dictionary might or might not have key value @ given time. presently testing see if value exists in following manner, know if best approach or if there better approach handling this. int myint; try { myint = {value dictionary}; } catch { myint = 0; } any input? thanks. take @ dictionary's trygetvalue method int myint; if (!_mydictionary.trygetvalue(key, out myint)) { myint = 0; } a couple of people have suggested using containskey. not idea if want value because mean 2 lookups - e.g. if (_mydictionary.containskey(key)) // 1 { myint = _mydictionary[key]; // 2 }

angularjs - ionic state controller doesn't execute after $state.go -

i'm experiencing issues ionic , it's state functionnality. basically, i'm retrieving data distant server, display in view/state. if user clicks on 1 of element display calls scope function changes $state via $state.go('other_view',{params}) call... until here no problems, thing when change state, controller assigned state doesn't execute, can't display simple console.log("hello"). here's simple illustration of i'm experiencing. var incarooms = angular.module('inca.rooms', ['ionic','ui.router', 'cb.x2js','ngsanitize']) // ---------------------------- // config app (routing) // ---------------------------- .config(function($stateprovider, $urlrouterprovider) { $stateprovider .state('rooms',{ url: '/rooms', templateurl: 'scripts/rooms/rooms.html', controller : controllers.roomscontroller, resolve : { ...

seo - Heading order in HTML5 -

this webpage example of site: <html> <title> artilce header </title> <body> <header> <h1> nme of website</h1></header> <section> <h2> name of section</h2> <article> <h3>article header</h3> </article> </section> </body> </html> i want know if order correct? or maybe have bad effect on seo? header in pages, section must have header because of header/… for example, i have change this: <html> <title> artilce header </title> <body> <header> <h2> nme of website</h2></header> <section> <h3> name of section</h3> <article> <h1>article header</h1> </article> </section> </body> </html> both variants valid html5. the html5 spec says headings , sections : ...

reporting services - How can External Assemblies deal with SSRS variables? -

i want create external assembly , reference inside ssrs reports, avoid repeating functions on every report create: public function username() try return report.user!userid catch return "system" end try end function however, "report.user!id" won't available inside external assembly. i'm trying implement item 7 from: http://www.ssw.com.au/ssw/standards/rules/rulestobettersqlreportingservices.aspx#userexperience

python - Pandas multiindex and pytables... separate indexes or one concatenated index? -

what structure of pandas multiindex on hdf5 when data frame saved hdf5 through pytables? each of parts separate index or there 1 concatenated index? it stored df.reset_index() , except index columns automatically data columns (meaning can select them). in [1]: df = dataframe({'a' : np.random.randn(9)},index=pd.multiindex.from_product([range(3),list('abc')],names=['first','second'])) in [2]: df out[2]: first second 0 -1.249058 b -0.674645 c -0.000458 1 0.455390 b -1.693221 c 1.245806 2 0.337478 b 0.672525 c 0.160914 in [3]: store = pd.hdfstore('test.h5',mode='w') in [4]: store.append('df',df) in [5]: store out[5]: <class 'pandas.io.pytables.hdfstore'> file path: test.h5 /df frame_table (typ->appendable_multi,nrows->9,ncols->3,indexers-...

reporting services - SSRS - Counting Correct Answers and Calculating Percentages via Comparison Fails -

this first time using ssrs, gentle! i'm working on report want compare number of correct answers number of user answers group. group repeats , looks set okay, part isn't worry. it's calculation of field seems worry. here's dataset: topicid topicname groupscore totalpossible questionid question correctanswer groupanswerscore useranswer 1 test topic 2 1 6 when did start? 1917 1 1896 1 test topic 1 3053 1200th governor? olestra chyppin 1 brent spoon 1 test topic 2 1 3053 1200th governor? olestra chyppin 1 olestra chyppin this query calculate percentage based on correct answers compared answers not work: =iif(fields!useranswer.value=fields!correctanswer.value,1,0)/count(fields!useranswer.value)) likewise, query ...

java - Creating a Hibernate reference in a client app -

i want add relation detached entity. want use entity reference created id. examples have found , understood need configured db connection create references. in example: reference = session.byid( employeeentity.class ).getreference( 1 ); i'm using in client program , accessing db indirectly through remote ejbs, don't have direct access db. possible create entity reference without db connection? short answer: no. long answer: in theory write own persistence strategy , plug hibernate talk remote ejbs, lot of work, doesn't have notable benefits except making expert of rather obscure corner of hibernate environment.

html - Disable credit card autofill on Mac Safari -

i'm developing simple point-of-sale web app, , part of there credit card field. field entering customer's credit card, , therefore number should neither a) saved browser, or b) or loaded local computer. the app used reps enter credit card info on behalf of customer ringing up. i can tell them not save card best disable feature. i've seen number of posts seems either outdated or different use cases. this html field - <input autocomplete="off" class="form-control" id="creditcard" placeholder="credit card number" type="text"> you can use autocomplete attribute , set value off .. this: <input type="text" id="creditcard" autocomplete="off" />

php - Mod_Rewrite - CSS and Images not found -

i know easy questions confused now. tried several options result same: css file not found if use mod_rewrite what solution should contain: domain.tld -> www.domain.tld www.domain.tld/category/page-title -> index.php?a=category&b=page-title www.domain.tld/category/page-title/ -> index.php?a=category&b=page-title www.domain.tld/category -> index.php?a=category www.domain.tld/category/ -> index.php?a=category .htaccess: options +followsymlinks rewriteengine on rewritecond %{http_host} ^domain.tld rewriterule (.*) http://www.domain.tld/$1 [r=301,l] rewriteengine on rewritecond %{request_filename} !-d rewritecond %{request_filename} !-f rewriterule ^(.*)/(.*)/?$ index.php?a=$1&b=$2 rewriterule ^(.*)/?$ index.php?a=$1 [l] index.php: <link href="/css/bootstrap.min.css" rel="stylesheet"> <link href="/css/internal.css" rel="stylesheet"> problem last rewrite rule running without rewrite...

domReady vs ready - Migrating to Polymer 1.0 -

in polymer0.5, had following code: template: <div class="scroll"> <div class="content"> <content></content> </div> </div> script: domready: function() { var width = $(this.shadowroot).find('.content')[0].scrollwidth; } this code worked, , received non-zero value width. now trying migrate polymer1.0, added id div: <div class="scroll"> <div id="content" class="content"> <content></content> </div> </div> and script now: ready: function() { var width = this.$.content.scrollwidth; } however, width 0 . is there difference between old domready function, , new ready function? have tried using attached function did not work either. when try access width later on (triggered button press), non-zero value looking for. the element used this: <my-scrollbar> lorem ipsum dolor sit a...

angularjs - Catching Angular promise success response twice -

it seems console output be: this first response second response because success function of inner method invoked first. correct assumption? order guaranteed? app.controller("ctrl", function($scope,$http) { var geturl = function () { var config = { method: 'get', url: 'some.txt' }; return $http(config) .success(function (response, status, headers, config) { console.log('this first response'); }) .error(function (data, status, headers, config) { }); }; var init = function () { var promise = geturl(); promise.then( function() { console.log('this second response'); }); }; init(); }); yes, because $http return promise , above promise chaining. although might better use $http.then(success,error).then(success,er...

list - QList in classes with QT Creator/c++ -

how can make qlist so,that list contain information more 1 class (the classes operated 2 map-containers)? these 4 classes: class lecture: class veranstaltung { private: qmap<qstring, lv >mylv; public: veranstaltung() {} void listlv(qtextstream& out) const; ... }; #endif // class professorships list_h class professurlist { private: qmap<qstring, professur> myprofessuren; public: professurlist() {} //kann man weglassen void addprof(qtextstream& in,qtextstream& out); void listprof(qtextstream& out) const; //warum const? ... }; #endif // proflist_h another class lectures,where private , public defined: #ifndef lv_h #define lv_h class lv { private: qstring mynummer; qstring mybezeichnung; qstring mytyp; public: lv(const qstring& nummer, const qstring& bezeichnung, const qstring& typ): mynummer(nu...

c# - Difficulty only mapping base class in Entity Framework -

i'm having difficulty figuring out how map base class in entity framework database, while preventing information classes inherit being mapped database. i created simple example highlight difficulty there base worker class, , child class called engineer . reason, assume don't care store details of engineer... want database contain information in worker class. so i've done following: class program { static void main(string[] args) { engineer e = new engineer(); e.name = "george"; e.focus = "software"; mydatabase db = new mydatabase(); e.save(db); } } public class mydatabase : dbcontext { public dbset<worker> workers { get; set; } public mydatabase() : base("mytempdb") { } } [notmapped] public class engineer : worker { public string focus { get; set; } } public class worker { [key] [databasegeneratedattribute(databasegeneratedoption.identity)] publ...

type constraints - How does the <:< operator work in Scala? -

in scala there's class <:< witnesses type constraint. predef.scala : sealed abstract class <:<[-from, +to] extends (from => to) serializable private[this] final val singleton_<:< = new <:<[any,any] { def apply(x: any): = x } implicit def $conforms[a]: <:< = singleton_<:<.asinstanceof[a <:< a] an example of how it's used in tomap method of traversableonce : def tomap[t, u](implicit ev: <:< (t, u)): immutable.map[t, u] = what don't understand how works . understand a <:< b syntactically equivalent type <:<[a, b] . don't how compiler can find implicit of type if , if a <: b . assume asinstanceof call in definition of $conforms making possible somehow, how? also, significant singleton instance of abstract class used, instead of using object ? suppose we've got following simple type hierarchy: trait foo trait bar extends foo we can ask proof bar extends foo : val ev =...

php - Laravel Eloquent - Is it inefficient -

i'm looking @ developing new site laravel. reading tutorial on http://vegibit.com/laravel-eloquent-orm-tutorial/ , regarding using eloquent join tables , retrieve data. in last example trying join still eloquent executing 2 queries instead of one. eloquent inefficient or poor example? seems have been done single left join query. can provide insight on this? there better way execute query? specific example is: route::get('/', function() { $paintings = painting::with('painter')->get(); foreach($paintings $painting){ echo $painting->painter->username; echo ' painted '; echo $painting->title; echo '<br>'; } }); results in following queries: string ‘select * paintings‘ (length=25) string ‘select * painters painters.id in (?, ?, ?)’ (length=59) leonardo da vinci painted mona lisa leonardo da vinci painted last supper vincent van gogh painted the starry night vincent van gogh painted ...

spring - Inject HTTPServletRequest into a request scoped bean -

i have rest api webservice injects singleton bean. bean needs know httpservletrequest. have created bean called requestserviceimpl has httpservlerrequest injected. public class requestserviceimpl implements requestservice { @autowired private httpservletrequest request; } web-context contains bean definition <bean id="requestservice" class="com.requestserviceimpl" scope="request"> <aop:scoped-proxy/> </bean> this requestservice injected singleton bean. see requestservice bean being injected correctly httpservletrequest object null. not sure going wrong httpservletrequest interface. cannot have instance of interface. may inject class implements httpservletrequest , httpservletrequestwrapper . have reference implementation if want. this answer further.. spring dependency injection interfaces

javascript - Clear Angular JS templateCache once (for each deployment) -

this issue angularjs disable partial caching on dev machine suggests using $templatecache.removeall() clear cache templates. if want fire once upon each deployment cycle in order visitor browsers refresh/update template? our problem browsers not updating template html files, we'd end new css mixed old html. not want function fire time, defeat point of cache templates begin (right?). per title question, what's recommended way clear $templatecache "once", example ideas i've crunched: does angular have internal method of detecting if template file has changed? , if "update" it. does angular have internal "version" or "date" compare , add conditional fire function removeall()? does $templatecache ever know refresh? angular creator's intentions in forcing templatecache on if html files bound change overtime , served multiple browsers. i not want use grunt add workflow overhead happens periodically, nor chop html file ...

templates - Execute the Code in a PHP Page And Echo the HTML Output -

i absolutely don't post question here in unless can't find way solve problem myself. did lot of googling , not able find solution 1 problem describe. here problem. creating templated php website. templated mean below: <?php include("header.php");?> <div id="content"> <div id="main"> <h2><?php echo($page_title);?></h2> <?php echo ($page_content); ?> </div> <?php include("sidebar.php");?> </div> <?php include("footer.php");?> as can see here page template echoes content of $page_content variable between header , footer sections build page. keep code clean , separated (in own way) have been placing html content in .txt files (let's page1_content.txt) , assigning txt content variable ($page_content) below: $page_content = file_get_contents("page1_content.txt"); my problem starts when place php cod...

multithreading - Workload balancing between akka actors -

i have 2 akka actors used crawling links, i.e. find links in page x, find links in pages linked x, etc... i want them progress more or less @ same pace, more not 1 of them becomes starved , 1 consumes resources. i've tried following approaches (simplified). single page crawling done following actor: class crawler extends actor { def receive = { case crawl(url, kind) => // download url // extract links sender ! parsed(url, links, kind) } } approach 1: class coordinator extends actor { val linksa = ... val linksb = ... def receive = { case parsed(url, links, kind) => val store = if (kind == kinda) linksa else linksb val newlinks = links -- store store ++= links newlinks.foreach { link => val crawler = context.actorof(props[crawler]) crawler ! crawl(link, kind) } } } approach 2: class coordinator extends actor { val linksa = ... val linksb = ... val rrprops = props[cra...

c# - Listbox isn't populating with Data -

i have set listbox called lboxsupplier, have created data adapter used populate supplier listbox. when run form listbox empty. want listbox populate supplier id , company click on populate listbox products. namespace pennyburn_greg { public partial class formprocess : form { sqldataadapter dasupplier; dataset dspennyburngreg = new dataset(); sqlconnection conn; sqlcommand cmdsupplierdetails; sqlcommandbuilder cmdbsupplier; datarow drsupplier; string connstr, sqlsupplier; public formprocess() { initializecomponent(); } private void formprocess_load(object sender, eventargs e) { connstr = @"data source= arlene-pc; initial catalog= pennyburngreg; integrated security=true"; //dataadapter supplier listbox sqlsupplier = @"select* supplier"; conn = new sqlconnection(connstr); cmdsupplierdetails = new sqlcommand(sqlsupplier, conn); dasupplier = new sqldataadapter(cmdsupplierd...

css - How to make thumbnail image 100% width inside a div (on WordPress), and not larger? -

(first off, let me not ask such basic-seeming question here if hadn't tried think of -- manipulating of involved variables. the image loads in functions: add_theme_support('post-thumbnails'); add_image_size('mobile-thumb', 800, 300); that size (800,300) problem. when display on mobile, stubbornly stays 800 wide. need 100% width of screen. i styled div.thumbnail-box { width:100%; height: 100%; background-color: #eee; margin-bottom:10px; margin-top:0px; margin-left:0px; } .the_post_thumbnail { max-width:100%; } .desktop-featured-image { width:100%; } i've tried inside , without div. i've adjusted heights , widths. my current html is: <div class="thumbnail-box"> <img width="800" height="300" src="http://website/wp-content/uploads/2015/05/obama-e1424474715102-800x300.jpg" class="attachment-banner-image wp-post-image" alt="obama-e1424474715...

inheritance - Rails "superclass mismatch for class (TypeError)". A well documented error, but I need some tailored advice -

ok. understand why i'm getting error. according stackoverflow question, "that error shows when redeclare class that’s been declared". question seems point out solutions, not quite. have additional questions. here's have... /models/item.rb class item < activerecord::base .. end class theme < item end class setting < item end this item model has existed quite time. added sing inheritance theme , setting. as as... /models/setting.rb class setting < activerecord::base .. end /models/theme.rb class theme < activerecord::base .. end so makes sense why i'm getting error. never got error in local workspace, when pushed heroku, did migrations, , tried run "heroku run rails c". run command, error , booted out. according answers, should quit console , come in. however, can't in begin with. launch "heroku run rails c", booted. additionally, if wipe db, , remigrate everything, going same error given ord...

Elasticsearch indexing -

i using elasticsearch in project. have 2 indexes 1 contains list of employ id’s , other contains employee_name, joining date , employee id. there way can use employee id 1 index , find employee information other index? index list of employee id: june 1st 2015, 12:02:15.209 message:8997745 june 1st 2015, 12:02:15.210 message:8997728 june 1st 2015, 12:02:15.211 message:8997719 index list of employee information: june 1st 2015, 12:02:15.205 message: bob,2015-05-31,8997745 june 1st 2015, 12:02:15.206 message: james,2015-05-31,8997728 june 1st 2015, 12:02:15.207 message: tom,2015-05-31,8997719 also, noticed each entry in index has unique id. there way can provide unique id index entries same index have same index id? thanks in advance!  depending on needs, can either in code (read employee_id index1 , ids filter lookup ( https://www.elastic.co/guide/en/elasticsearch/reference/1.7/query-dsl-ids-filter.html ). this might not practical large lists of employe...

web services - Cxf interceptors as spring beans having autowired fields, using plain annotation configuration -

my problem quite same asked in other question: "how use spring autowired in custom cxf interceptor?" . valid response there recommends configure endpoint through context xml: <jaxws:endpoint id="mywebservice" address="/mywebservice"> <jaxws:ininterceptors> <ref bean="myininterceptor" /> </jaxws:ininterceptors> </jaxws:endpoint> but want to without xml configurations, annotation. possible somehow add interceptor (which spring bean autowired members) @webservice endpoint through annotation @ininterceptors. or there way? unfortunatly nobody give hint how solve problem through annotations since year. want inform how solved problem. my work around programmatically within init() method of services bean: generatedbywsdl2javaservices services = new generatedbywsdl2javaservices(); igeneratedbywsdl2javaservices service = services.getbasichttpbindingigeneratedbywsdl2javaservices(); ...

MATLAB will not plot figure correctly -

why matlab plot figure straight horizontal line? y1 = (1+(x/2))/(1-(x/2)); what wrong code? the function supposed resemble e^x. thank you. code here below. x = linspace(0,3); y1 = (1+(x/2))/(1-(x/2)); %plot lines. figure plot(x,y1) as @nkjt pointed out: do know difference between / , ./ if want divide pointwise, have use ./ , otherwise result of vector (1+(x/2)) divided (1+(x/2)) what want is: x = linspace(0,3); y1 = (1+(x/2))./(1-(x/2)); figure, plot(x,y1)

Python (Post) submit a form -

i teaching myself submitting form on web but somehow post not working. the url https://courselist.wm.edu/courselist/ and code far is: from bs4 import beautifulsoup import requests import urllib import re url = 'http://courselist.wm.edu/courselist' requests.session() session: response = session.get(url) soup = beautifulsoup(response.content) data = { 'term_code' : '201530', 'term_subj' : 'afst', 'attr' : '0', 'levl' : '0', 'status' : '0' } r = session.post(url, data=data) #response = session.post(url, data=data) print r.content #soup = beautifulsoup(response.content) #for row in soup.select('table'): # print [td.text td in row.find_all('td')] you cannot submit form beautifulsoup . should use mechanize . see here example of how use form submitting.

r - Knitr and kable not finding data frame -

i attempting show simple table in knitr on word document. have following code: library(knitr) a<-c(1,2,3,4,5,6) b<-c(1,2,3,4,5,6) tab<-data.frame(a,b) in console runs correctly knitr::kable(tab) however when put markdown documents called 'medinventory' code not run , returns following error: ````{r echo=false,results='asis'} knitr::kable(tab) ```` processing file: medinventory.rmd |...................... | 33% ordinary text without r code |........................................... | 67% label: unnamed-chunk-1 (with options) list of 2 $ echo : logi false $ results: chr "asis" quitting lines 17-18 (medinventory.rmd) error in is.data.frame(x) : object 'tab' not found calls: <anonymous> ... eval -> eval -> <anonymous> -> colnames -> is.data.frame execution halted so data frame in globalenvr not recogni...

arrays - Javascript Variable Scope - Values Not Assigning -

i'm working on calendar application , i'm having trouble setting values globally declared variables , accessing values in function. here of code. if need more please comment , can paste all var eventhold = []; var eyears = []; var emonth = []; var eday = []; var events; var loaddata = function() { $.ajax({ type: "post", url: "getevents.php" }).done(function(data) { events = json.parse(data); //returning json object (i = 0; < events.length; i++) { eventhold[i] = events[i].edate; //returns 2015-06-15 each object eyears[i] = eventhold[i].substring(0, 4); //trims 2015 emonth[i] = eventhold[i].substring(5, 7); //trims 06 emonth[i] = parseint(emonth[i]); //change int emonth[i] --; //decrement 0 base eday[i] = eventhold[i].substring(8, 10); //trims 08 eday[i] = parseint(eday[i]); //change int } }); } function test() { firstday = new date(odate.cyear, odate.cmonth, 1); //return da...

angularjs - Reset Chosen Select to Original Disabled State -

i have 2 chosen select elements, 1 bound other. before first selection made, second element shown in default disabled state because assuming first model hasn't been activated. have "clear filters" button supposed reset these elements state... so far, i'm using reset chosen elements following... html: <div class="input-group"> <label>vehicle make</label> <select id="carmake" ng-model="carmake" chosen ng-options="carmake carmake.name carmake in carmakes track carmake.name"> <option value="">all</option> </select> </div> <div class="input-group carmodels"> <label>vehicle model</label> <select id="carmodel" ng-model="carmodel" chosen ng-options="carmodel carmodel.name carmodel in carmake.models track carmodel.name"> <option value="">all</o...

Microsoft Access formatting: Need format to display either Date or "0". 0 keeps displaying as 12:00:00AM, how to fix? -

i need make 1 field either displays date or value of 0. they're 2 separate formats, , can't access mix 2 up. logic functions keep displaying errors me. you can conditional formatting "custom" format: [=0] 0; [>0] mm/dd/yyyy; [=0] checks if value zero, if so, cell set 0. if greater 0, use mm/dd/yyyy or whatever date format like.

node.js - Deploying meteor app to intranet -

i needing deploying meteor app made onto our works intranet server. bundled app make node app , installed node,npm,and mongodb onto intranet server. when go through setting environment variables with export port=3000 export mongo_url=mongodb://localhost:27017/databasename export root_url=http://localhost:3000 npm install node bundle/main.js i blank web page. in apache set virtual host in /etc/httpd/conf/httpd.conf such as <virtualhost *:80> servername servername.dcn proxyrequests off proxypreservehost on <proxy *> order deny,allow allow </proxy> proxypass /timesheet http://localhost:3000/ < /virtualhost> any ideas why i'm getting plain blank page instead of app? advice.

swift - I cannot fix this bug Cannot invoke 'findObjectsInBackgroundWithBlock' with an argument list of type '(([AnyObject]!, NSError!) -> Void)' -

i tried follow many posts on stackoverflow , google, true. need resolve bug, thanks my code using parse api func loaddata(){ timeline.removeallobjects() var findtimelinedata:pfquery = pfquery(classname: "twitter") findtimelinedata.findobjectsinbackgroundwithblock({ (objects: [anyobject]!, error: nserror!) -> void in if error == nil{ object in objects{ let twitter:pfobject = object pfobject self.timeline.addobject(twitter) } let array:nsarray = self.timeline.reverseobjectenumerator().allobjects self.timeline = nsmutablearray(array: array) self.tableview.reloaddata() } }) } the compiler looking objects , error optional, may nil. try: findtimelinedata.findobjectsinbackgroundwithblock({(objects: [anyobject?], error: nserror?) -> void in ...

java - How to see name inside the link after renaming by jQuery? -

jsp loop: <c:foreach items="${feedlist}" var="feed"> <input type="hidden" readonly="readonly" id="feedid" value="<c:out value="${feed.id}" />" /> <tr> <td class="feed-name" id="<c:out value="${feed.id}" />"><c:out value="${feed.name}" /></td> <td><a href="feedcontroller?action=delete&id=<c:out value="${feed.id}"/>">delete</a> </td> <td><a href="feeditemcontroller?action=feeditemlistasc&id=<c:out value="${feed.id}"/>">view</a></td> <td><button onclick="openeditdialog('${feed.id}', '${feed.name}' )" name="modal">edit</button></td> </tr> </...

java - How can I manage to make a line of code run once? -

when form opens, runs song. when go option frame , come main frame, re-runs code. did while loop , works , thing should declare initial value? if declare on windowopened resets 0 doing loop again. my code in openedwindow event int sound = 0; while (sound < 1) { try { inputstream test = getclass().getclassloader().getresourceasstream("musics/menu.wav"); audiostream audio = new audiostream(test); audioplayer.player.start(audio); } catch (exception e){} sound = sound + 1; } } the inputstream , audiostream should instance variables of object. if residing in function openedwindow , garbage collector after function has finished running. instead, should instantiate them in class needs access them, possibly in constructor method. also, make sound variable instance variable of class too. way won't reset each time openedwindow called. or instead use boolean flag variable indicate if sound has...

php - How do I pass Google maps lat and lng values and save to MySQL database? -

Image
i writing google maps application user can click want save marker filling form in infowindow , clicking submit button saves data mysql database. a picture of mean here: i not know how retrieve lat , lng values event.latlng , use them part of addlocation form action. the javascript contains addlocation form action: function placemarker(location) { var latlng = event.latlng; // don't know how retrieve lat & lng latlng? var contentstring = '<form action="addlocation" method="post">' + '<div id="addmarkerinfowindow">' + '<b>name:</b>&nbsp;<input type="text" name="name"><br>' + '<b>facilities:</b>&nbsp;<input type="text" name="facilities"><br>' + '<b>opening hours:</b>&nbsp;<input type="text" name="opening"><br>' + ...

Random string generator PHP -

this question has answer here: php random string generator 42 answers i'm trying create random string numbers , letters , found function , thought good, don't know if correct way create true random string or if there easier way this? below have: function randomgen() { $chars = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; $length = strlen($chars); $random; ($i = 0; $i < 8; $i++) { $random = $chars[rand(0, $length - 1)]; } return $random; } you try using $random = substr(str_shuffle(md5(microtime())), 0, 8); , output same amount of random characters have in example. prefer method on doesn't require put in expected characters , more importantly, can done in 1 line of code!

meteor iron router prepends "undefined" to id -

hi i'm following discover meteor book, , i'm in chapter 5-3. have router.js , post_item.html precisely book, , every url, /posts/undefined<id> . can't figure out why undefined present in front of every id. below relevant code: router.configure({ layouttemplate: 'layout', loadingtemplate: 'loading', waiton: function() { return meteor.subscribe('posts'); } }); router.route('/', {name: 'postslist'}); router.route('/posts/:_id', { name: 'postpage', data: function() { return posts.findone(this.params._id); } }); <template name="postitem"> <div class="post"> <div class="post-content"> <h3><a href="{{url}}">{{title}}</a><span>{{domain}}</span></h3> </div> <a href="{{pathfor 'postpage'}}" class="discuss btn btn-default">discuss...

node.js - Mocking file system contents not working with gulp.src -

i'm trying use mock-fs mock file system contents test gulp tasks. unfortunately, gulp.src doesn't seem play mock-fs . specifically, enoent errors: message: enoent, lstat '/vagrant/study-node-heroku/instances/development/app.json' details: errno: -2 code: enoent path: /vagrant/study-node-heroku/instances/development/app.json domainemitter: [object object] domain: [object object] domainthrown: false stack: error: enoent, lstat '/vagrant/study-node-heroku/instances/development/app.json' @ error (native) other parts of code , test code access mock-fs -created files fine. what doing wrong? suspect problem related gulp's usage of vinyl. here function under test: var herokutarball = function(options, done) { var instance = options.instance || 'development'; var tarballname = options.tarballname || instance var tarballpath = path.join(config.temp, tarballname + '.tar.gz'); var files = path.jo...

visual studio 2010 - How To Extend A File Size In OpenFileDialog C# -

i making expand-file-size program in c#, having problem. works fine, don't have code expand size of file select openfiledialog . know how expand file's size in c#? need extend each file +16. familiar eof (end-of-file), don't know how use it. one possibility append file. @ file open function documentation - can open file appending.

sql - Why does this GROUP BY and NA combo produce a character type? -

why y end character class? seems should never happen sqldf sum? library(sqldf) # 3 similar data.frame objects x <- structure(list(size = c(1l, 2l), diff = c(1, na)) , .names = c("gb","diff"), row.names = 1:2, class = "data.frame") y <- structure(list(size = c(1l, 1l, 2l, 2l), diff = c(na, na, 1, na)) , .names = c("gb","diff"), row.names = 1:4, class = "data.frame") z <- structure(list(size = c(2l, 2l, 1l, 1l), diff = c(na, na, 1, na)) , .names = c("gb","diff"), row.names = 1:4, class = "data.frame") # when summed in sqldf: numeric, character, numeric sapply(sqldf("select sum(diff) x"),class) sapply(sqldf("select sum(diff) , gb y group gb"),class)[1] sapply(sqldf("select sum(diff) , gb z group gb"),class)[1] # despite both being numeric class( x$diff ) class( y$diff ) exclude na , (i.e.: null ) before aggregating: out1 <- sqldf(...

multithreading - Thread errors when running Java game -

i getting strange errors when running java game. i've been working on game weeks project computer science class , due on 6/4/2015, appreciate help. wrote game in class called game , ran static method called run. later, decided add gui menu in class called control. run game now, call main method in control class. menu has button action listener. when button clicked, run method in game class called. if click , run run method directly game works fine. if click button calls run method draws frame, not actual game. here code gui: public class control extends jframe implements actionlistener { // jpanel public jpanel pnlbutton = new jpanel(); // buttons public jbutton btnaddflight = new jbutton("multiplayer"); public jbutton single = new jbutton("singleplayer"); public control() throws ioexception,interruptedexception { super("bouncy ball"); //set button size btnaddflight.setbounds(150, 400, 220,...

angularjs - ionic $state.go redirect does not load ui correctly until click -

i using ionic firebase, , trying redirect upon login home page. $state.go redirect work, have hidden tab called 'profile', not show until user authenticated. tab remains hidden on $state.go redirect, , doesn't show until click on 'home' tab again. how load load ui on redirect? html: tabs html: <ion-tabs class="tabs-icon-top tabs-color-active-positive" ng-controller="loginctrl"> <!-- login tab --> <ion-tab title="login" icon-off="ion-locked" icon-on="ion-locked" href="#/tab/login"> <ion-nav-view name="tab-login"></ion-nav-view> </ion-tab> <!-- dashboard tab --> <ion-tab title="new post" icon-off="ion-compose" icon-on="ion-compose" href="#/tab/new"> <ion-nav-view name="tab-new"></ion-nav-view> </ion-tab> <!-- chats tab --> <ion-tab title=...

java - How to use serialized CRFClassifier with StanfordCoreNLP prop 'ner' -

i'm using stanfordcorenlp api interface programmatically basic nlp. need train model on own corpus, i'd use stanfordcorenlp interface it, because handles lot of dry mechanics behind scenes , don't need specialization there. i've trained crfclassifier i'd use ner, serialized file. based on documentation, i'd think following work, doesn't seem find model , instead barfs on not being able find standard models (i'm not sure why don't have model files, i'm not concerned since don't want use them anyway): // string constants final string serializedclassifierfilename = "/absolute/path/to/model.ser.gz"; properties props = new properties(); props.setproperty("annotators", "tokenize, ssplit, ner"); props.setproperty("ner.models", serializedclassifierfilename); stanfordcorenlp pipeline = new stanfordcorenlp(props); string filecontents = ioutils.slurpfilenoexceptions("te...

python 3.x - How to convert HTML to PDF with python3 -

how convert html pdf python3? write code webview pyqt5,and want convert html in webview pdf,what should do? i have tried use html2pdf,but seem support python2.x , have tried install wkhtmltox-0.12.2.2_msvc2013-win64.exe , pdfkit,and use example code. import pdfkit pdfkit.from_url('http://google.com', 'out.pdf') pdfkit.from_file('test.html', 'out.pdf') pdfkit.from_string('hello!', 'out.pdf') but failed.and error following. traceback (most recent call last): file "e:\python34\lib\site-packages\pdfkit\configuration.py", line 21, in __init__ open(self.wkhtmltopdf) f: filenotfounderror: [errno 2] no such file or directory: b'' during handling of above exception, exception occurred: traceback (most recent call last): file "<pyshell#2>", line 1, in <module> pdfkit.from_url('http://google.com', 'out.pdf') file "e:\python34\lib\site-packages\pdfkit\api.py", line ...