Posts

Showing posts from April, 2011

How to use Google's OpenID connect provider with CORS? -

i've written javascript app use google's openid-connect provider authentication. i've registered app @ google's developer console. i'm using oidc-client-js library handle interactions google , passed app's client_id configuration, passed google authenticate app. my configuration: { client_id: 'secret', redirect_uri: `${window.location.protocol}//${window.location.hostname}:${window.location.port}/callback`, response_type: 'token id_token', scope: 'openid profile', authority: 'https://accounts.google.com/', silent_redirect_uri: `${window.location.protocol}//${window.location.hostname}:${window.location.port}/silent_renew.html`, automaticsilentrenew: true, filterprotocolclaims: true, loaduserinfo: true }; my dev server runs on https://localhost:8080 (with self-signed dev certificate). i've registered url & redirect uri @ google authorized host app, google knows dev server. when try access goo

mysql - Create multi column view from single column data -

i have following result sql query: eventid p_num pn_namecount1 pn_name abc-i-10942683 1089213 1 company 1 abc-i-10942683 1326624 8 company 2 i still learning capability in sql , need assistance, pivot's not working in scenario. i have tried several different ways in attempting this, not able create desired results: eventid p_num1 pnc1 pn_name pnc_num2 pnc2 pn_name abc-i-10942683 1089213 1 company 11326624 8 company 2 the eventid change based on different events companies, eventid based on particular date event occurred company. this sample of 500k+ rows of data working with. go temp table joined other various pieces of data needed. i have tried without success: select key, max(col1) col1, max(col2) col2, max(col3) col3 table group key select eventid , min(p_num) p_num1, min(pn_namecount1) pnc1, min(pn_name) pn_name1 , m

python - How to get data from youtube api automaticly when you add item on django -

i have model class in django such as class youtubevideo(models.model): title = models.charfield(max_length=200,blank=true,null=true) video_id = models.charfield(max_length=2000, unique=true) duration = models.charfield(blank=true,null=true,max_length=200) def __unicode__(self): return self.title i want duration (and other data) when add video_id on admin interface. how can trigger crawler after adding item. extend save method of model: def save(self, **kwargs): if self.video_id not none , self.duration none: self.duration = call_youtube_to_get_duration() return super(youtubevideo, self).save(**kwargs)

Why composer.phar needs to be updated after 60 days? -

i want understand that, why composer.phar file needs updated after 60 days? why composer.phar needs updated after 60 days? composer doesn't need updated after 60 days. update recommended after time! why 60 days? i can't speak core developers on decision, can give educated guess: composer used shorter frequency recommending updates during development , alpha stages. former message warning: development build of composer on 30 days old. recommended update... . users recommended pull updates in short frequency stay on latest, bleeding-edge version. short update frequency allows users report bugs , issues project. results in fast feedback , development cycle fast roll-outs of new versions address urgent issues. now, composer released stable time increased 60 days, because (i guess) fast feedback cycle no longer needed. reflects project no longer in pre-release/alpha development mode, has stabilized. stats might lie, might take @ issue tracker find m

Distributing Python script which depends on a package -

i wrote script makes use of selenium, installed selenium through pip. there way can distribute script others without having them install selenium through pip? i looking at: https://pypi.python.org/pypi/selenium#downloads would if included source distribution of selenium pypi in project folder? people have click on source distribution's install.py install selenium? you can use setuptools , use install_requires keyword. like this: from setuptools import setup setup( # options install_requires = ['selenium'], ) see tutorial here then when install package/module using pip, selenium installed.

Modify text in column cells and make it hyperlink, listView WPF C# -

for displaying in 1 of columns in listview, gridview 1 of property of class. looks more or less: <listview x:name="offers_listview" margin="38,185,35,81" > <listview.view> <gridview> <gridviewcolumn width="100" header="itemid" displaymemberbinding="{binding path=itemid}" /> itemid number. what make hyperlink based on number. example itemid equals 1234 make clickable link address www.website.com/showitem.php?itemid=1234. best solution if column still display 1234 clickable link address mentioned. of course whole list, each item have different itemid property. may give me hint how or sample of code can based ? edit: solution gave below have been adapted me. however on logic side navigateuri have been null, link opened in browser have been not correct. have adapt idea directly textblock paste code below: <gridviewcolumn width="100&q

php - Reading Serial Port in Perl -

i'm bit tired of reading serial port, using perl first of perl not primary development tool, i'm php background. please guide me in right way. intention read data weight machine web page, did lot of research on topic. the browser app cannot read serial port data directly choose user end machine can installed server (apache) , task php , web application can read result using ajax call localhost url idea working great on linux machines on windows pc stuck. i understand php can't read data serial port in windows linux choose perl stuff. did search got few codes , last 8 hours i'm fighting :( #!e:\xampp\perl\bin\perl.exe # above line perl execution path in xampp # below line tells browser, script send html content. # if miss line show "malformed header script" error. print "content-type: text/plain\n\n"; # use strict; use warnings; use win32; require 5.003; use win32::serialport qw( :stat 0.19 ); print "here"; $port

android - Error in overriding onCreateView() method -

i new android.i trying link fragment file named "top_section_fragment" java class getting error while overriding oncreateview() method.error says "can not resolve symbol r" please me fix it. package com.example.abdulrafay.myapplication; import android.os.bundle; import android.support.annotation.nullable; import android.support.v4.app.fragment; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; public class topsectionfragment extends fragment { @nullable @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view view=inflater.inflate(r.layout.top_section_fragment,container,false); return view; } } you're missing import: import com.example.abdulrafay.myapplication.r; if it's still not found, means wasn't generated. in case, do: build -> rebuild project.

datetime - Python find index of all dates between two dates -

i trying implement equivalent of numpy.where dates follows: from datetime import date, timedelta td, datetime d1 = datetime.strptime('1/1/1995', "%m/%d/%y") d2 = datetime.strptime('12/31/2015', "%m/%d/%y") alldays = [] while(d1<=d2): alldays.append(d1) d1 = d1 + td(days=1) validdate = alldays trainstdt = '1/1/1995' trainendt = '12/31/2013' teststdt = '1/1/2014' testendt = '12/31/2015' indtrain = (validdate >= datetime.strptime(trainstdt,'%m/%d/%y')) & (validdate <= datetime.strptime(trainendt,'%m/%d/%y')) indtest = (validdate >= datetime.strptime(teststdt,'%m/%d/%y')) & (validdate <= datetime.strptime(testendt,'%m/%d/%y')) traindates = validdate[indtrain] testdates = validdate[indtest] print traindat

Validate input fields after changing input values with jQuery or echoing values with PHP -

i'm using jquery validation plugin. have simple function copies 1 input's value input. function sameasshipping() { $('#billingfirstname').val($('#firstname').val()); } i validate newly copied input values using valid() method. i'm trying call valid() method if input's value isn't blank. $(document).ready(function(){ $(":input, select").each(function() { if(!$(this).val() === "") $(this).valid(); }); }); along manipulating input values jquery, if form submitted , there error, echo submitted values. these validate these fields on load, however, if there value in input. <input type="text" id="billingfirstname" name="billingfirstname" class="required" placeholder="first name" value="<?php if(isset($_session['firstname'])){echo $_session['firstname'];} ?>"> dynamically created dom objects can

performance - Is it a bad practice to use php transactions with every query? -

in php can start transactions when performing queries. when should use it? bad use feature every query? or should use query when adding/removing/updating large quantities of data? example of transaction: try { $db->begintransaction(); $db->exec("some query"); $stmt = $db->prepare("another query"); $stmt->execute(array($value)); $stmt = $db->prepare("another query again??"); $stmt->execute(array($value2, $value3)); $db->commit(); } catch(pdoexception $ex) { //something went wrong rollback! $db->rollback(); echo $ex->getmessage(); } my guess would heavily bring down performance if every query in code tl;dr can use transactions every query? or should use them when performing large manipulations database? you need use transactions if want make changes or none. example if transferring money 1 person should increase one's balance , decrease another's. it's

I keep getting an error message of i use an else function in PHP -

this question has answer here: php parse/syntax errors; , how solve them? 12 answers here php block using: $reg = @$_post['reg']; $fn = ""; $ln = ""; $un = ""; $em = ""; $em2 = ""; $pswd = ""; $pswd2 = ""; $d = ""; $u_check = ""; $fn = strip_tags(@$_post['fname']); $ln = strip_tags(@$_post['lname']); $un = strip_tags(@$_post['username']); $em = strip_tags(@$_post['email']); $em2 = strip_tags(@$_post['email2']); $pswd = strip_tags(@$_post['password']); $pswd2 = strip_tags(@$_post['password2']); $d = date("y-m-d"); //year - month - day if ($reg) {} if ($em==$em2){} $u_check = mysql_query("select username users username='$un'"); $check = mysql_num_rows ($u_check); if ($check == 0){} if

java - Overloaded Constructor calling other constructors based on input type -

say have 2 constructors taking type of input. (t1 , t2 in example) i want call either of them more general constructor taking object (or superclass of t1 , t2 matter) class test{ public test(t1 input){...} public test(t2 input){...} public test(object input){ if(input instanceof t1) this((t1) input); if(input instanceof t2) this((t2) input); } the third constructor give compile error since this constructor call isn't on first line. you can use kind of factory method follows: public class test { private test(t1 input) { // ... } private test(t2 input) { // ... } public static test createtest(object input) { if (input instanceof t1) return new test((t1) input); if (input instanceof t2) return new test((t2) input); return null; } }

haskell - Flexibility of the hierarchy of module sources allowed in cabal project -

i have project source tree: src/ src/a/ src/a/a.hs src/b/ src/b/c/ src/b/c/c.hs ... the 2 haskell files divide source code modules: -- file a/a.hs module ... and -- file b/c/c.hs module b.c ... the cabal file contains: other-modules: a, b.c, ... hs-source-dirs: src/, src/a/, src/b/, src/b/c/, ... but while module a can found, cabal complains b.c : cabal: can't find source b/c in ... i see no rational explanation why placing file defining module a under a/a.hs ok placing b.c under b/c/c.hs isn't. there workaround other placing c.hs directly under b (i maintain separation of sources)? the reason error module b.c should defined in file b/c.hs , not b/c/c.hs (that module b.c.c ). error have appeared if had 1 source dir 1 source file, not because of parts have put in. also, dir appears in hs-source-dirs directive should root of dir tree, doubtful need of parts put in, instance, src/b/c (which treat src/b/c root.... meaning can define t

android time calculator example code (help) -

i little bit confused date formatter/calander , formats related time. trying current time no date and, although have seen several code snippets still confuses me. problem following current time , send method calculations. for example public void oncreate(bundle savedinstancestate){.... ......... ........ **get current time** sendtomethod(currenttime) } public void sendtomethod(currenttime) { date pasttime long diff = currenttime - pasttime; if (diff > 1000) // here want check if diffrence more 10 seconds // } i searched , tried several codes got lost. found there alot of ways this, still have no clue how solve this. please, if can me appreciate lot. try this: private long diff, start = system.currenttimemillis(); public void sendtomethod() { diff = system.currenttimemillis() - start; if (diff > 10000) { // difference more 10 seconds // } start = system.currenttim

regex - python split a unicode string by 3-bytes utf8 character -

suppose have unicode string in python, s = u"abc你好def啊" now want split no-ascii characters, result result = ["abc", "你好", "def", "啊"] so, how implement that? with regex split between "has or has not" a-z chars. >>> import re >>> re.findall('([a-za-z0-9]+|[^a-za-z0-9]+)', u"abc你好def啊") ["abc", "你好", "def", "啊"] or, asciis >>> ascii = ''.join(chr(x) x in range(33, 127)) >>> re.findall('([{}]+|[^{}]+)'.format(ascii, ascii), u"abc你好def啊") ['abc', '你好', 'def', '啊'] or, simpler suggested @dolda2000 >>> re.findall('([ -~]+|[^ -~]+)', u"abc你好def啊") ['abc', '你好', 'def', '啊']

Reading Audio file in Java as in audioread of MATLAB -

audioread function of matlab returns y , fs. y "audio data in file, returned m-by-n matrix, m number of audio samples read , n number of audio channels in file." fs sample rate. for example, when audio .wav , has 16 bits per sample, data range of y -32768 , 32767. i want read .wav file in java , have same type of data in matlab. audioinputstream has information such sample rate, sample size in bits, frame size , frame rate how can samples? extra: can read .mp3 file , transform samples value range of .wav ?

excel - Custom number format for NULL -

i have excel sheet populate database. custom number format can use replace null values in excel hyphen '-' ? know can use following formula #,##0_);(#,##0);–_);_(@_) in order display zero. don't know how handle null value. the simple answer number format strings not have section null values. see ecma-376 section 18.8.31 explanation: up 4 sections of format codes can specified. format codes, separated semicolons, define formats positive numbers, negative numbers, 0 values, , text, in order. if 2 sections specified, first used positive numbers , zeros, , second used negative numbers. if 1 section specified, used numbers. one workaround check null values, emit text value, , set text format. example, using formula 0;0;0;"-" : value formatted #null! - null - 1 1 2 2 3 3 4 4 note works if expect result numerical. if expect string value, can opposite ( "-";"-";"-";@ )

jquery - Onepage scroller panels not 100% height -

i have 1 page scrolling plugin on site i'm testing out, have working panels not 100% height, have copied css demo still not working correctly i'm wondering if i'm doing basic wrong. can see issue here every parent element of .onepage-wrapper must have height:100% in order make full height. you can add following css page: .site, .site-inner, .site-content, .content-area, .site-main { height: 100%; }

java - Interleaving two threads such that one of the thread gets null when called putIfAbsent of concurrentHashMap -

can explain interleaving of 2 threads such 1 of thread gets null when 2 threads call putifabsent of concurrenthashmap in java? from javadoc of putifabsent : returns: previous value associated specified key, or null if there no mapping key. so first thread attempting put value in map have null returned it.

java - Service abstraction springMVC -

i'm trying create abstract service in springmvc application. data flows* perfect through layers, persistence (abstraction), not find way save/delete/update database, these classes: abstract class baseserviceimpl<t, id extends serializable> implements baseservice<t, id> { protected abstract baserepository<t, id> getrepository(); private baserepository<t, id> repository; public baseserviceimpl(baserepository<t, id> repository){ this.repository = repository; } public list<t> findall(){ return getrepository().findall(); } public t find(id id){ return getrepository().findone(id); } public t save(t persisted){ return this.repository.save(persisted); } public void delete(id id){ getrepository().delete(id); } public long count(){ return getrepository().count(); } public boolean exists(id id){ return getrepository().exists(id); } } //--- @service public class medicineserviceimpl extends baseserviceimpl<m

algorithm - Calculate comparative rank of things compared two at a time -

how calculate weights of 10 things express person's relative preference when input data follows: the list of 10 things presented in random pairs (ignoring order, vs b might shown, or b vs a, not both; , not item itself); a better b d better f h better b c better j etc. is there way rank or weight 10 items data this? , there way shorten sequence 10! / (2! (10 - 2)!) =45 questions. you're making dangerous psychological assumption here: assume "better than" relation transitive, from a > b b > c directly follows that a > c that is, without loss of generality, not case humans preferences. puts whole approach in questionable light. however, if can justify assumption, yeah, breaks down sorting problem. there's truckload of sorting algorithms out there, rely on existence of ordering relation ">". weight position in sorted list. every real-world programming language out there has library contains @ least 1 sorter algor

How to get Windows window names with ctypes in python -

i try windows window title names , pids through handles long objects. code works there wrong it. 4 window titles when should 10 or more. can , tell me how fix code? think problem how convert long objects (i don't understand them well, ctypes in general). from __future__ import print_function ctypes import * psapi = windll.psapi titles = [] # window title pid def gwtfp(): max_array = c_ulong * 4096 pprocessids = max_array() pbytesreturned = c_ulong() psapi.enumprocesses(byref(pprocessids), sizeof(pprocessids), byref(pbytesreturned)) # number of returned processes nreturned = pbytesreturned.value/sizeof(c_ulong()) pidprocessarray = [i in pprocessids][:nreturned] print(pidprocessarray) # enumwindows = windll.user32.enumwindows enumwindowsproc = winfunctype(c_bool, pointer(c_int), pointer(c_int)) getwindowtext = windll.user32.getwindowtextw getwindowtextlength = windll.user32.

c - Segment violation writing to variable in DLL (lcc-win32) -

i've built dll few functions , global variables. i've used buildlib create import library it. the .exp file is: csc_ffsw.dll _csc_ffsw_b _csc_ffsw_b data _csc_ffsw_dwork _csc_ffsw_dwork data _csc_ffsw_m _csc_ffsw_m data _csc_ffsw_u _csc_ffsw_u data _csc_ffsw_y _csc_ffsw_y data _csc_ffsw_initialize _csc_ffsw_initialize _csc_ffsw_step0 _csc_ffsw_step0 _csc_ffsw_step1 _csc_ffsw_step1 when import dll program, can read global variables (e.g. csc_ffsw_u), when try write them segment violation exception. instead of using import library, tried manually importing symbols dll using: dllhandle = loadlibrary("csc_ffsw.dll"); mytype* pcsc_ffsw_u = (mytype*)getprocaddress(dllhandle, "_csc_ffsw_u"); ... etc. with approach can write variables fine. however, method not nice because requires more manual, error prone work. should p

Python 2.7.2 - Cannot import name _random or random from sys -

im few months new python , pulling hair out on trying generate random integer. ive been scouring internet, tried many solutions provided on here nothing takes. python doesnt seem know has random module, though can see right there in lib. ive tried: copied relative .py doc , did import random without sys , same error. in interactive found "_random", import _random doesn't give me line 1 error, says random not defined though ive copied , pasted numerous random number code examples straight python , many site stated worked them. about throw in towel tried post pic apparently not "reputable" enough. exact error is: macintosh:week 03a ersander$ python secretdoor.py traceback (most recent call last): file "secretdoor.py", line 1, in <module> sys import _random importerror: cannot import name _random import random random isn't in sys . don't know why you're trying import there.

sql - Group By Result Into a List -

i trying list of rental properties manager manages schema: create table rental_property(property_number int primary key, managerid int, foreign key(managerid) references manage(managerid)); here procedure: create or replace procedure supervisor_properties list_of_properties varchar (300) := ' '; begin select 'manager' || ': ' || managerid || ' ' || property_number list_of_properties rental_property group managerid; end; the part having trouble procedure above group by group tuples have same managerid together. how print out results this: manager m1: rental_prop1, rental_prop2, rental_prop3 manager m2: rental_prop9, rental_prop6, rental_prop4 you can use list_agg() : select (managerid || ' ' || list_agg(property_number, ' ') within group (order property_number) ) list_of_properties rental_property group managerid; the issue into pu

java - Can't create a runnable jar file via Eclipse -

i made java project eclipse. project has public static void main(string[] args) method in it. when try export runnable jar, launch configuration not include project created can't create jar project. ideas why? try creating new launch configuration scratch: run -> run configurations... right click "java application" in list on left , select new on right enter descriptive name. in main tab browse project , search , select appropriate main class. close dialog. now try exporting runnable jar again using run configuration.

haskell - How to make fromList lazy in this dynamic programming example? -

module main import system.random import data.foldable import control.monad import qualified data.map m import qualified data.vector v import debug.trace import data.maybe import data.ord -- represents maximal integer. maxbound no because overflows. -- ideally should billion. maxi = 1000 candies :: v.vector int -> int --m.map (int, int) int candies ar = ff [l (v.length ar - 1) x | x <- [0..maxi]] go :: int -> int -> int go _ 0 = maxi go 0 j = j go j = case compare (ar v.! (i-1)) (ar v.! i) of lt -> ff [l (i-1) x + j | x <- [0..j-1]] gt -> ff [l (i-1) x + j | x <- [j+1..maxi]] eq -> ff [l (i-1) x + j | x <- [0..maxi]] l :: int -> int -> int l j = frommaybe maxi (m.lookup (i,j) cs) ff l = --minimum l case l of l:ls -> if l < maxi l else ff ls [] -> maxi -- need make lazy somehow. cs :: m.ma

ruby on rails - How to write rspec tests for controllers that assume authentication -

for controllers assume user authenticated, how should go writing tests? i don't need keep testing login feature, best inject user or whatever authentication assumes somehow? my application_controller includes module "current_user". module currentuser def self.included(base) base.send :helper_method, :current_user end def current_user ... # returns user model instance end end class applicationcontroller < actioncontroller::base include currentuser then have admin controller has before_action method makes sure current_user present. you can achieve writing concern, , include every spec controller, in concern support utility methods login system. so code like: spec/support/controller_authentication_helper.rb module controllerauthenticationhelper extend activesupport::concern module classmethods def login_user before # expect using devise here, if not, modify below line request.env['devise.mappin

http - Which REST operation (GET, PUT, or POST) for validating information? -

my users enter few information fields in ios app. information must validated on server, has restful api. after validation ui of ios app changes indicate result. neither get, put, or post seem appropriate, because i'm not getting resource, , neither resource created or updated. what best fitting rest operation implement validation? my users enter few information fields in ios app. information must validated on server, has restful api. after validation ui of ios app changes indicate result....i'm not getting resource, , neither resource created or updated. since aren't saving (not modifying resource), i'd think technically more rpc restful me. the following opinion, don't take gospel: if information being submitted , you're saying yes or no, and you're not saving it , i'd post fine.. if information being saved / updated , choosing proper http method lot more relevant. post = create / submit (in rpc context) put = up

php - What is the difference between the laravel homestead box and the homestead repo? -

from official docs, "laravel homestead official, pre-packaged vagrant box provides wonderful development environment without requiring install php, hhvm, web server, , other server software on local machine." i installed vagrant, , downloaded box, great. then, later on, in the docs , read have install "homestead" cloning repo https://github.com/laravel/homestead/ i find confusing, because thought homestead virtual box downloaded. difference between laravel homestead box , homestead repo? there no docs github repo. the homestead repo , github , stores global preferences used when running homestead. the homestead box virtual machine image runs operating system.

mockito - What is the point of a spied instance -

i debugging test using spy , found confusing. public class spytest { @test public void testspy1(){ thing thing = new thing(); thing thingspy = mockito.spy(thing); thingspy.modify("bar"); assertthat(thing.getfoo(), is("bar")); } @test public void testspy2(){ thing thing = new thing(); thing thingspy = mockito.spy(thing); thingspy.modify("bar"); assertthat(thingspy.getfoo(), is("bar")); } private static class thing { private string foo = ""; public void modify(string foo){ this.foo = foo; } public string getfoo() { return foo; } } } i expected spy defer passed instance. testspy1 fails , testspy2 succeeds, because tried read data actual object instead of spy. so, if spy not interact passed object, why accept 1 , why keep around in mock settings? a spy make

makefile - Make: recursive make ignores -s -

observe difference between make silent , make noisy . asked make silent on bar rule, silent on foo rule, too. what missing? noisy: @make foo silent: @make -s foo foo: @make -s bar bar: @echo bar running it: $ make silent bar $ make noisy make[1]: entering directory `/tmp/s' make[2]: entering directory `/tmp/s' bar make[2]: leaving directory `/tmp/s' make[1]: leaving directory `/tmp/s' i expected noisy foo -> bar call not print "entering directory" options passed parent make sub-make using makeflags environment variable, sub-make adds command-line flags received. if sub-make doesn't receive -s ( --silent ), -w ( --print-directory ), or --no-print-directory , automatically adds -w own makeflags. order of precedence enabling , disabling directory printing seems (from weakest strongest) -s , -w , --no-print-directory . so, when run make silent , first recursive call adds -s makeflags, , second call knows

asp.net - How do I get my web site to recognize a COM reference that may not exist on the server -

i creating excel spreadsheet web site. have added reference site through properties page points file c:\program files (x86)\microsoft office\office14\excel.exe on local drive. works fine running locally. however, when publish server site runs, error because can't see excel.exe file. file need in order site see it? thanks most it's because application running login on server opposed locally on box. investigate user application's app pool runs as, ensure user has read/execute access location on server excel.exe file is.

ParseTree in AnTLR4 C# -

i creating grammar using antlr4 targeting c# facing problem while developing visitor. can't find class parsetree referred in book. in book have: labeledexprlexer lexer = new labeledexprlexer(input); commontokenstream tokens = new commontokenstream(lexer); labeledexprparser parser = new labeledexprparser(tokens); parsetree tree = parser.prog(); // parse can't see equivalent c# code. can please help? interfaces in c# have prefix i . qualified name here antlr4.runtime.tree.iparsetree .

Scala compiler throws annotation argument needs to be a constant error on constant argument -

i'm using following annotation parameter shipped spark-sql: @sqluserdefinedtype(udt = actionudt.clazz) trait action extends actionlike { ...implementation } where actionudt.clazz defined constant val: object actionudt extends actionudt { final val clazz: class[_ <: actionudt] = this.getclass } but got following compiler error: error:(25, 37) annotation argument needs constant; found: actionudt.clazz @sqluserdefinedtype(udt = actionudt.clazz) ^ why produce such false alarm? bug? i'm using scala 2.10.5 a class not constant object defined here. constant .. .. constant in numeric or string literal.

ruby - Bootstrap time picker rails without gem -

i trying i have starts_at:datetime field , want fill form using bootstrap-datetimepicker here form: = simple_form_for @event |f| = f.input :title = f.input :starts_at = f.button :submit my main.js file: $(document).ready(function(){ $(".form_datetime").datetimepicker({format: 'yyyy-mm-dd'}); }); how can give starts_at datettimepicker input style? you'll have call .datetimepicker() method on input element want give datepicker. simple_form should generate element id "event_starts_at" , try: $("#event_starts_at").datetimepicker({format: 'yyyy-mm-dd'}); if doesn't work or if want give input element different id , can override passing option: = f.input :starts_at, id: "event_starts_at"

MongoDB. Find documents which contain value from array -

so have array values. how can find documents contain in specific field value array? for example: array : ["1", "2"] documents {field : "1"}, {field : "2"}, {field : "3"} i need find: {field : "1"}, {field : "2"} can please try this? db.inventory.find( { field: { $in: [ "1", "2"] } } )

c++ - WinAPI: Correctly copying a HBITMAP to the clipboard -

i have difficulties trying copy hbitmap clipboard. hbitmap created colorref array , able display correctly. here how created: colorref* colors = new colorref[imagesize[0] * imagesize[1]]; (int = 0; < imagesize[1]; i++) { (int j = 0; j < imagesize[0]; j++) { colors[imagesize[0] * + j] = rgb(/* ... */); } } // create bitmap hbitmap hbitmap = createbitmap(imagesize[0], imagesize[1], 1, 32, (void*)colors); delete[] colors; in order copy bitmap clipboard, use small piece of code: openclipboard(hwnd); emptyclipboard(); setclipboarddata(cf_bitmap, hbitmap); closeclipboard(); when execute app, able copy bitmap , paste somewhere, example in ms paint. if try copy second time, clipboard content can't pasted anymore unless first piece of code above executed again. in msdn documentation , said if setclipboarddata succeeds, system owns object identified hmem parameter. i don't understand means, guess source of problem. found example of func

netlogo - How can I simulate a moving patch? -

i'm trying make frogger -like game patches move around , turtle can move onto safe patch. if have few patches red, how can 'move' them around if turtles? have this, seems move more 1 patch @ time , result, red patches destroyed if there more 1 red: if pcolor = red [ ask patch-at 0 1 [ set pcolor red] set pcolor black ] you ask neighbor patch (left or right) painted red , actual patch painted black or whatever default color is. for you'll want actual patch coordinates. using patch-at asks patch @ 0,1 relative whole world.

python - Keras error with merge layer -

i trying build model colorize images. using lab color space. input model l channel , model trained predict , b channels. want run l channel through few convolutions , split off 2 other models independently calculate , b channels. @ end want merge them output. model = sequential() model.add(inputlayer((1, h, w))) model.add(convolution2d(64, 5, 5, border_mode = 'same', activation = 'relu')) model.add(convolution2d(64, 5, 5, border_mode = 'same', activation = 'relu')) last = convolution2d(64, 5, 5, border_mode = 'same', activation = 'relu') model.add(last) a_model = sequential() a_model.add(last) a_model.add(convolution2d(64, 5, 5, border_mode = 'same', activation = 'relu')) a_model.add(convolution2d(64, 5, 5, border_mode = 'same', activation = 'relu')) a_model.add(convolution2d(1, 3, 3, border_mode = 'same', activation = 'sigmoid')) b_model = sequential() b_model.add(last) b_model

java - Inject a EntityManagerFactory through @PersitenceContext or @PersitenceUnit? -

i've thought @persistencecontext injecting entitymanager container-managed application, while @persistenceunit injecting entitymanagerfactory. javadoc says for persistenceunit ( http://docs.oracle.com/javaee/7/api/javax/persistence/persistenceunit.html ) expresses dependency on entitymanagerfactory , associated persistence unit. and persistencecontext ( http://docs.oracle.com/javaee/7/api/javax/persistence/persistencecontext.html ) expresses dependency on container-managed entitymanager , associated persistence context. so far good, reading jpa tutorial (see https://docs.oracle.com/cd/e19798-01/821-1841/bnbqy/index.html ) contains example this the following example shows how manage transactions in application uses application-managed entity manager: @persistencecontext entitymanagerfactory emf; entitymanager em; @resource usertransaction utx; ... em = emf.createentitymanager(); try { utx.begin(); em.persist(someentity); em.merge(anotherentity);

r - Cleaning and editing a column -

i've been trying figure out how clean , edit column in data set. the dataset using supposed city of san francisco. column in data set called "city" contains multiple different spellings of san francisco, other cities. here looks like: table(sf$city) brentwood ca 30401 18 370 daly city foster city hayward 0 0 0 novato oakland oakland 0 40 0 s f s.f. s.f. ca 0 31428 12 san bruno san francicso san franciisco 0 221 54 san francisco san

Log4net remoteAppender output -

i using remoteappender inside of config file , sending logs remotely computer. while sending information using tcp worked, found remoteappender sending large chunk of random symbols , characters rather log string want. suspect being sent remoteappender not log string, rather logger itself. method used read in incoming broadcast simple , taken msdm website. know of way convert networkstream received string , avoiding strange outputs? public void startlistener() { try { // set tcplistener on port 13000. int32 port = 32100; // tcplistener server = new tcplistener(port); server = new tcplistener(ipaddress.any, port); // start listening client requests. server.start(); // buffer reading data byte[] bytes = new byte[256]; string data = null; // enter listening loop. while (true) { console.write("wai

How can I get rid of NA values on data import in R? -

follow post: http://r.789695.n4.nabble.com/importing-csv-gets-me-all-16-000-columns-with-quot-na-quot-td3006480.html some background: developing program allows user upload csv files. currently, testing dataset looks like: type date lively count sm 1/13/2010 10 10 sm 1/14/2010 10 20 sm 2/15/2010 20 30 4/16/2010 5 42 1/17/2010 10 34 3/18/2010 40 54 sm 1/19/2010 10 65 sm 4/20/2010 5 67 sm 3/21/2010 40 76 sm 3/21/2010 70 76 when user imports this, fine. import method is: dataset <- read.csv(input$file$datapath) dataset <- na.omit(dataset) however, let's user saved above table in excel, saving csv. deleted last 2 columns. type date sm 1/13/2010 sm 1/14/2010 sm 2/15/2010 4/16/2010 1/17/2010 3/18/2010 sm 1/19/2010 sm 4/20/2010 sm 3/21/2010 sm 3/21/2010 if looked @ str() of table, last 2 columns wold contain na values because in excel, columns have been formatted. c

parsing - PHP Parse/Syntax Errors; and How to solve them? -

Image
everyone runs syntax errors. experienced programmers make typos. newcomers it's part of learning process. however, it's easy interpret error messages such as: php parse error: syntax error, unexpected '{' in index.php on line 20 the unexpected symbol isn't real culprit. line number gives rough idea start looking. always @ code context . syntax mistake hides in mentioned or in previous code lines . compare code against syntax examples manual. while not every case matches other. yet there general steps solve syntax mistakes . references summarized common pitfalls: unexpected t_string unexpected t_variable unexpected '$varname' (t_variable) unexpected t_constant_encapsed_string unexpected t_encapsed_and_whitespace unexpected $end unexpected t_function … unexpected { unexpected } unexpected ( unexpected ) unexpected [ unexpected ] unexpected t_if unexpected t_foreach unexpected t_for unexpected t_while unexpected t_do