Posts

Showing posts from May, 2010

validation - How can I set bounds for a Django Model DateField? -

in model : birth_date = models.datefield(verbose_name='d.o.b') how can set bounds this, such as: 01-01-1990 (current date - 18 years) i'm assuming there's way set in model it's included default in forms, i've never used dates in project before, i'm not sure how done. it useful know how datetimefield , timefield if isn't same. thanks! datetimefield , timefield not have options set lower , upper bounds. however, possible write validators type of field. a validator check date of birth like: from datetime import date django.core.exceptions import validatonerror def validate_dob(value): """makes sure date been 1990-01-01 , 18 years ago.""" today = date.today() eighteen_years_ago = today.replace(year=today.year - 18) if not date(1990, 1, 1) <= value <= eighteen_years_ago: raise validationerror("date must between %s , %s" % (date(1990,1,1,), eighteen_years_a

How to check the output of word2vec in R -

i using word2vec train sentences nearest words. trying using word2vec using r language. input: "you best friend" output: model generated in 'c:/users/acer/pictures/internship'! i have used following code in r: g <- word2vec("mydata.txt","word.txt") but have check output after training text word2vec in r. can please in trying out same r?

ios - Switch from back camera to front camera while recording -

so have custom camera works. can record video , file etc. can choose camera use; front or back. however, when press record can switch between front camera , camera , still records file until hit stop recording. hope makes sense. my code switching cameras: @ibaction func changecamera(sender: anyobject) { println("change camera") self.recordbutton.enabled = false dispatch_async(self.sessionqueue!, { var currentvideodevice:avcapturedevice = self.videodeviceinput!.device var currentposition: avcapturedeviceposition = currentvideodevice.position var preferredposition: avcapturedeviceposition = avcapturedeviceposition.unspecified switch currentposition{ case avcapturedeviceposition.front: preferredposition = avcapturedeviceposition.back case avcapturedeviceposition.back: preferredposition = avcapturedeviceposition.front case avcapturedeviceposition.unspecified: prefe

c - Turn on MSB of 8 bit integers -

how show mask , turn on msb of 8 bit integer? have tried different logical opeartors not getting right answers if have 8 bit integer turning msb set '1' bit 7. so mask 0x80 (only bit 7 on). in order set bit can use bit-wise or | : #define msb_mask 0x80 // or #define msb_mask (1 << 7) int x; x = x | msb_mask; // or x |= msb_mask; make shorter

ruby - How to create a shortlisting feature in rails? -

i want add shortlisting feature applications model. i have jobs model each job belongs employer , application model belongs job , user. employer can view responses jobs on dashboard. want allow him shortlist applications likes , view them later or somewhere else in dashboard. it similar "add cart" feature, each item added cart here belong job , employer, not employer. i not able figure out start. have create shortlist model, or add shortlist boolean attribute each response, or else? correct way go? i looking guidance, prefer not spoil me lot of code :) note:i using rails 4, , devise employer model. you can create separate table add application id. like cart, can go page , users shorted. you can create model shortlist this.

place tags on android imageview objects -

is there way can place multiple on image in android activity like instagram shows people's names tag on images i have x , y position of tags in pixel format of original image use relative layout , put imageview , textview inside overlapping

c - In Sun's libm, what does *(1+(int*)&x) do (where x is of type double)? -

the expression #define __hi(x) *(1+(int*)&x) is defined in sun's math library , in fdlibm.h . used in programs of sun's math library, e.g., in its implementation of sin(x) double y[2],z=0.0; int n, ix; /* high word of x. */ ix = __hi(x); /* |x| ~< pi/4 */ ix &= 0x7fffffff; if(ix <= 0x3fe921fb) return __kernel_sin(x,z,0); in code above, variable x of type double. can 1 explain me syntax expression in __hi(x) . the readme of sun's library says __hi(x) "the high part of double x (sign,exponent,the first 21 significant bits)". i not understand syntax of *(1+(int*)&x) , , why corresponds x 's higher part. clarification? this: *(1+(int*)&x) means: take address of x ( &x ), cast pointer-to-int (int*) , add 1, , dereference resulting pointer. assuming sun using this format , means value in memory looks like: <sign (1 bit)><exponent (11 bits)><significand

android - service sending string to another activity without opening it -

i have service working in background - service a . when open activity - activity a , want service change text displayed on edittext field of activity a . thought maybe if context of opened activity able use , work on views. possible? also related question: if don't have name of field, can use loop run , search views in activity , properties? it seems less direct method preferred getting this, rather have activity directly updated service. in fact, in general service/activity communications best handled in 1 of following ways: messagehandlers- basically, 1 can send message other, in turn other sets actions of text. broadcastreceivers (localbroadcastreceiver okay)- 1 part sends broadcast message listening, other sets listener message. intent passed, can contain message. i suggest use second. application sends broadcast service upon opening, , service returns broadcast pass requested data activity. see service docs android sdk.

wifi - Android WifiManeger Class startCustomizedScan(ScanSettings requested) function application force stop -

i must use startcustomizedscan(scansettings requested) function. request scan access points in specified channel list. each channel specified frequency in mhz, e.g. "2437" wifichannel mrtchannel; mrtchannel = new wifichannel(); mrtchannel.freqmhz = 2437; mrtchannel.channelnum = 6; scansettings set ; mrtcollection = null; mrtcollection.add(mrtchannel); set = (scansettings)mrtcollection; mainwifi.startcustomizedscan(set); but application force stop. application not laucnh. logcat 08-30 23:09:36.547: e/androidruntime(14327): fatal exception: main 08-30 23:09:36.547: e/androidruntime(14327): process: com.muratucan.murat5hidden, pid: 14327 08-30 23:09:36.547: e/androidruntime(14327): java.lang.runtimeexception: unable start activity componentinfo{com.muratucan.murat5hidden/com.muratucan.murat5hidden.mainactivity}: java.lang.nullpointerexception: attempt invoke interface method 'boolean java.util.collection.add(java.lang.object)' on null object refere

javascript - Regex to match mostly alphanumeric paths -

i tried creating regular expression verify path names filesystem api write using gridfs. my current regex ^[a-za-z0-9\-\[\]()$#_./]*$ can fulfill criteria: allow a-z , a-z , 0-9 , -[]()$#_./ however doesn't meet these additional criteria: first character has / there mustn't occurrence of multiple / in row. questions: can me fix regex? are there possible issues using criteria path names? (did miss important?) not sure path criteria, regarding regexp, pretty simple: ^\/(?!\/)([a-za-z0-9\-\[\]()$#_.]|(\/(?!\/)))*$ \/(?!\/) means slash / not followed slash (?!\/) . used twice, once first character, , again 1 of possible matches after first character.

javascript - How send keystrokes using internet explorer? -

what need, trigger keyboard shortcut on client. if nothing appends user know my software work , can download (as page text explain) . shortcut confusing because several keys have same name. nice trigger á´¡indows® shortcut clicking on link. so don’t want simulate keypress event pull keys remotely. activex seems solution, seems trivial using flash player. i’ve read on stack overflow anwser internet explorer have javascript extensions allowing kind of os control. can’t find similar stack overflow post again. this isn't possible. sorry. (if were, pose huge security risk. consider happen if web page trigger win+r , type in command!)

how to add try and catch validation and how to fix my switch, do-while error java -

i cant post code in here not sure why error post on reddit https://www.reddit.com/r/javahelp/comments/3izvy2/how_to_add_try_and_catch_validation_and_how_to/ your try/catch syntax fine, what's problem? however, do/while wrong, see while way down there, remove last curly bracket , put right before while: do{ try{ system.out.println("choose option"); system.out.println(" 1. create list of used car"); system.out.println(" 2. print list of used car"); system.out.println(" 3. search "); system.out.println(" 4. exit"); int choose = read.nextint(); if ( choose <= 4){ throw new exception(); } }catch (exception e){ system.out.println("please enter input option 1-4"); ..rest of code... }while(choose <= 4); and in switch, choose not avaliable - choose local variable try/catch only, nothing other try/catch can access it. best make choose global variable

Git throws 400 Bad Request when executed with sudo -

there weird error have been getting. i have compiled git 2.5.1 source on centos 6.5 have atlassian stash running control , pushed code repo. when try fetch or pull repo regular user or su works well. when use sudo git fetch --all fails error: requested url returned error: 400 bad request while accessing http://stash.domain.com/scm/myr/myrepo.git/info/refs what problem here?

xml - How to assign glyphs to control characters? -

it seems xml doesn’t accept values in range from &#0; to &#x1f; inside attributes allow #x7f to &#xa1; . trigger kind of error in parser : parser error : xmlparsecharref: invalid xmlchar value 18 <glyph glyph-name="uni00000f" unicode="&#x12;" ^ i tried opening file in several web browsers , got similar error messages same lines. couldn’t find in standard purpose of behaviour. seems escaped unicode control characters allowed. so know reason of design ? there alternative defining , using glyphs outside svg file ?

subset - R: Undefined Columns Selected Error when Subsetting DF -

i have dataframe data following structure: classes ‘tbl_df’ , 'data.frame': 4391 obs. of 53 variables when try subset top 100 rows using data100 = data[1:100,] i error: error in `[.data.frame`(x[[i]], ...) : undefined columns selected what reason? found answer - needed use as.data.frame(data) before subsetting because tbl_df not subsettable same way data frame. needed due using dplyr earlier , outputting table instead of df.

Exception error of "main" java.util.NoSuchElementException -

i have these below 2 classes , trying trying run app class can take command line arguments instead of having fixed file name in code when execute code, following errors: c:\javatest>java readfiletestapp resume.doc exception in thread "main" java.util.nosuchelementexception @ java.util.scanner.throwfor(unknown source) @ java.util.scanner.next(unknown source) @ readfile.getfile(readfile.java:26) @ readfiletestapp.main(readfiletestapp.java:8) import java.io.file; import java.util.scanner; import java.io.filenotfoundexception; public class readfile { private string filename = ""; private long maxsize = 102400; readfile(){}; readfile(string filename, long maxsize) { this.filename = filename; this.maxsize = maxsize; } public string getfile() throws filenotfoundexception { file file = new file(this.filename); if (file.exists()) { double filesize = file.

Java convert unicode code point to string -

how can utf-8 value =d0=93=d0=b0=d0=b7=d0=b5=d1=82=d0=b0 converted in java ? i have tried like: character.tocodepoint((char)(integer.parseint("d0", 16)),(char)(integer.parseint("93", 16)); but not convert valid code point. that string encoding of bytes in hex, best way decode string byte[] , call new string(bytes, standardcharsets.utf_8) . update here more direct version of decoding string, provided "sstan" in answer. of course both versions good, use whichever makes more comfortable, or write own version. string src = "=d0=93=d0=b0=d0=b7=d0=b5=d1=82=d0=b0"; assert src.length() % 3 == 0; byte[] bytes = new byte[src.length() / 3]; (int = 0, j = 0; < bytes.length; i++, j+=3) { assert src.charat(j) == '='; bytes[i] = (byte)(character.digit(src.charat(j + 1), 16) << 4 | character.digit(src.charat(j + 2), 16)); } string str = new string(bytes, standardcharsets.utf_8); system.ou

actionscript 3 - Why isn't my exception being caught? -

Image
this stack trace get: [fault] exception, information=error: directory id 3 in use @ cantrips.assets.index::assetindex/diridchanged()[/home/luismasuelli/proyectos/flash-assets-index-ritual/assets-index-loader/src/cantrips/assets/index/assetindex.as:72] @ flash.events::eventdispatcher/dispatcheventfunction() @ flash.events::eventdispatcher/dispatchevent() @ cantrips.assets.index::assetdirectory/set id()[/home/luismasuelli/proyectos/flash-assets-index-ritual/assets-index-loader/src/cantrips/assets/index/assetdirectory.as:68] @ main/updateselecteddirectory()[/home/luismasuelli/proyectos/flash-assets-index-ritual/assets-index-editor/src/main.mxml:192] @ main/__dirupdatecurrent_click()[/home/luismasuelli/proyectos/flash-assets-index-ritual/assets-index-editor/src/main.mxml:401] this implementation of main/updateselecteddirectory(): private function updateselecteddirectory():void { try { var newid:uint = uint(dirid.text); var newname:string = stri

javascript - Why isn't the scrollTo() method working for iframes? -

no matter do, iframe not auto scroll bottom. can't scrollto() iframe. i've checked lot of other pages on stack overflow dealing similar problems. none of solutions have worked me. may case i'm not implementing them correctly. scrolling iframe javascript? working example given in above post not in fact work me. no matter numbers input scrollto() method in example nothing changes. <!doctype html> <html> <body> <div id="divy"> <iframe id='cat' src='test.html'></iframe> </div> <script> console.log(document.getelementbyid('cat')); document.getelementbyid("cat").onload = function () { this.contentwindow.scrollto(0, 200) }; conslole.log( document.getelementbyid("cat").onload = function () { this.contentwindow.scrollto(0, 200)) }; //setinterval(function(){ document.getelementbyid("divy").innerhtml=" <iframe src='test.html'>&

python - Screen Width too small in iPython terminal -

this question has answer here: how make ipython output list without line breaks after elements? 3 answers my ipython show list 1 tall column if long. want take full use of terminal's screen width. know not terminal issue because terminal output take use of full screen. have tried editing '.ipython/profile_default/static/custom/custom.css' have '.container { width:100% !important; }' no luck. if understand correctly, want have output like [1,2,3,4] instead of [1, 2, 3, 4] ? if so: start ipython --no-pprint flag or use %pprint (see here ).

c - Autonomically sending a message from kernel-module to user-space application without relying on the invoke of input. from user-space -

i give detailed exp of program , lead issue regarding use of netlink socket communication. the last paragraph asks actual question need answer for, might wanna start peeking first. disclaimer before start: - have made earlier search before asking here , did not find complete solution / alternative issue. - know how initialize module , insert kernel. - know handle communication between module , user-space without using netlink sockets . meaning using struct file_operations func pointers assignments later invoked module program whenever user attempts read/write etc. , answer user using copy_to_user / copy_from_user. - topic refers linux os, mint 17 dist. - language c okay, building system 3 components: 1. user.c : user application (user types commands here) 2. storage.c : storage device ('virtual' disk-on-key) 3. device.ko : kernel module (used proxy between 1. , 2.) the purpose of system able (as user) to: - copy files to virtual disk-on-key device

facebook - FacebookSDK iOS v3.24.0-beta1 -

i'm testing facebooksdk ios v3.24.0-beta1 facebook developer site. test environment ios9 beta5 on iphone6+ , test app built on xcode7 beta-6. i have set info.plist ios9 app transport security. , have installed facebook app in device. i try login facebook using [fbsession openactivesessionwithpublishpermissions:defaultaudience:allowloginui:completionhandler:] when invoke method. facebook app not launched. can see login dialog in webview (i guess). question: want know whether after v3.24.0-beta not support app app login. this design. in order provide best experience users on ios 9, new sdk determines best login flow automatically. if you're running on ios 8 or earlier, app switch still preferred.

django - Do I need to edit the wsgi.py file to install the New Relic Agent using Gunicorn/Python? -

i have django project deployed through digitalocean. trying install new relic python agent , have followed of instructions, when edit wsgi.py, receive 502 error. website using django , unicorn, i'm not sure if should editing wsgi.py file? instructions quite confusing. have wsgi.py file in project directory, , works correctly. import os os.environ.setdefault("django_settings_module", "project.settings") django.core.wsgi import get_wsgi_application application = get_wsgi_application() now when change following (following new relic quick start), receive 502 error, , nothing in django/nginx/wsgi logs tells me why. import os os.environ.setdefault("django_settings_module", "project.settings") import newrelic.agent newrelic.agent.initialize(os.path.join(os.path.dirname(os.path.dirname(__file__), 'newrelic.ini') django.core.wsgi import get_wsgi_application application = get_wsgi_application() my guess i'm not supposed

Maya API frame rate -

is there way query frame rate during playback? i'm writing simple hud node , i'd include frame rate, similar default maya 1 found in >> display/heads display/frame rate. not sure api there's mel version playbackoptions -q -fps edit: found this http://download.autodesk.com/us/maya/2011help/api/class_m_anim_control.html try using playbackspeed?

erlang - YAWs embedded with appmod not working for me -

alright, doing wrong here. i'm trying simple example of embedded yaws http://yaws.hyber.org/embed.yaws appmod. i've added my_app.erl file , compiled it. works if not in embedded yaws think specific embedded. -module(ybed). -compile(export_all). start() -> {ok, spawn(?module, run, [])}. run() -> id = "embedded", gconflist = [{ebin_dir, ["/users/someuser/yawsembedded/ebin"]}], docroot = "/users/someuser/yawstest", sconflist = [{port, 8888}, {listen, {0,0,0,0}}, {docroot, docroot}, {appmods, [{"/", my_app}]} ], {ok, sclist, gc, childspecs} = yaws_api:embedded_start_conf(docroot, sconflist, gconflist), [supervisor:start_child(ybed_sup, ch) || ch <- childspecs], yaws_api:setconf(gc, sclist), {ok, self()}. getting error: error erlang code threw uncaught exception: file: appmod:0 class: error exception: undef req:

How to empty temp folder at the end of each loop in R? -

i running model in r. know how empty temp folder. for example: c:\users\***\appdata\local\temp at end of each loop in r. file.remove(list.files("c:/users/***/appdata/local/temp",full.names = t)) this should help.

sql - Primary key and composite unique index behavior -

i'm doing little custom membership system , i'm having issues. have these tables (users, roles, applications, membership). i want this: users |userid | applicationid | username | ... |1 | 1 | abc | ... |1 | 2 | abcd | ... "is same user in several apps, despite different username" roles |roleid | applicationid | rolename | ... |1 | 1 | xxx | ... |1 | 2 | xxx | ... "is same role in several apps" with userid/roleid primary key , userid/roleid-applicationid composite unique index know system won't allow me create user in 2 applications. i tried composite primary keys head ache after make correct fks because membership table needs recognize application (one user can have several credentials several apps). what best way do, if possible?

Java: writing on XML file problems -

i working on application using java , xml file save settings language.. setting.xml <?xml version="1.0" encoding="utf-8"?> <parametre> <param name="langue" id="1"> <val>1</val> </param> <param name="controle" id="2"> <val>0</val> </param> </parametre> this class should read , write xml file. import java.io.file; import javax.xml.parsers.documentbuilderfactory; import javax.xml.parsers.documentbuilder; import org.w3c.dom.document; import org.w3c.dom.nodelist; import org.w3c.dom.node; import org.w3c.dom.element; public class dialxmlfile { private static boolean _initialized = false; private static boolean _init = false; private static document _docx,_docy; public static void initlang() { if(_initialized) { return; } try { file fxmlfile = new file("res/files/strings.xml&q

django - Gunicorn sync workers spawning processes -

we're using django + gunicorn + nginx in our server. problem after while see lot's of gunicorn worker processes have became orphan, , lot other ones have became zombie. can see of gunicorn worker processes spawn other gunicorn workers. our best guess these workers become orphans after parent workers have died. why gunicorn workers spawn child workers? why die?! , how can prevent this? should mention we've set gunicorn log level debug , still don't see thing significant, other periodical log of workers number, reports count of workers wanted it. update line used run gunicorn: gunicorn --env django_settings_module=proj.settings proj.wsgi --name proj --workers 10 --user proj --group proj --bind 127.0.0.1:7003 --log-level=debug --pid gunicorn.pid --timeout 600 --access-logfile /home/proj/access.log --error-logfile /home/proj/error.log in case deploy in ubuntu servers (lts releases, 14.04 lts servers) , never did have problems gunicorn daemons, create

android lollipop root not working for root requited apps -

eventhough required permissions has been given for: /system/xbin/su (chmod 06755 su) root not working apps. tried root checker , showing device not have proper root access, , need solution out flashing zip file in recovery mode need modify aosp source make root work.

How to fix java spring mvc web application run time in Apache Tomcat 6 server? -

i developed web application using java spring mvc. want deploy application on tomcat server , want application run in period of time in day. say, application run 10:00 6:00 pm everyday , other time of day application cannot used. have searched if can done tomcat server 6 want deploy application unable solution or clue how achieve purpose. so, question how can implement wanted do? solution, samples or ideas helpful complete task. i think trying solve problem using infrastructure instead of using application should solved.if requirement not have application available during period of time, business requirement, code solution it. example not allow logins if login falls outside specified time period , instead display message user. existing sessions intercepted using handler , invalidating session forcing re-login. another solution run cron job on server, stops tomcat @ specified time , starts again. not advisable users not know of operating times , assume wrong.

Android in TabLayout, ViewPager Fragments not updating consistantly -

i have tablayout , viewpager in android application. when use swipe changing "tab1" "tab2" , use click on "tab1" go first tab fragment inside viewpager not updated. similar problem exist if use swipe move "tab2" "tab3" , try click on tab move tab2. otherwise tablayout works fine tabs updated , proper fragments shown if use other combination of swipes or clicks. //set tabs , viewpager viewpager viewpager = (viewpager) findviewbyid(r.id.mviewpager); viewpager.setadapter(new myfragmentpageadapter(getsupportfragmentmanager(), mainactivity.this)); //layout tablayout tablayout= (tablayout) findviewbyid(r.id.mtabs); tablayout.setupwithviewpager(viewpager); you should implement setontabselectedlistener : tablayout.setontabselectedlistener(new tablayout.ontabselectedlistener() { @override viewpager.setcurrentitem(tab.getposition()); } });

c# - MVC with angular Node.js and mongodb -

Image
i building e-commerce application using mvc angular , node.js the architecture diagram below in mvc, using partial views contain sections " featured products ", " favourite products " etc. these used in pages ever required using @html.partial("layoutname") . header/footer etc in shared folder layouts the authentication handled using oauth , provide token user. request data sent node.js , validate token again for requests requires user details fetching favourites etc i doing configuring app.js in node.js if (req.method == "post") { try { authenticationfunction(); //this authenticate token , call next() if success } catch (ex) { res.send("some message"); } } for data binding use angular are there better alternates should used in architecture? i use mvc ability route requests, normal iframe , plain html faster cshtml pages? (i tried ang

javascript - Reload modules on the fly in Node REPL -

i testing module repl this: repl.start({ input: process.stdin, output: process.stdout }) .context.mymodule = mymodule; is there way reload module automatically, when change , save it, without having exit , run repl again? you can use chokidar module , force reload (you lose runtime context in module, should auto-reload). var ctx = repl.start({ input: process.stdin, output: process.stdout }) .context; ctx.mymodule = require('./mymodule'); chokidar.watch('.', {ignored: /[\/\\]\./}).on('all', function(event, path) { delete require.cache['./mymodule']; ctx.mymodule = require('./mymodule'); }); if doesn't work, i'm happy play little , working solution. edit: if doesn't garbage-collect cleanly (there open handles/listeners), leak each time reloads. may need add 'clean-exit' function mymodule stop gracefully, , call inside watch handler.

android - Transparent Overlay ActionBar with AppCompat? -

i have actionbar following properties: overlay bar, layout's parent view stretch full whole window. a white title color actionbar. transparent background. i'm targeting api 14+, appcompat-v7:22.2.1. prepare styles this: <style name="theme.mytheme" parent="base.theme.appcompat.light.darkactionbar"> <item name="android:actionbarstyle">@style/theme.mytheme.myactionbar</item> <item name="actionbarstyle">@style/theme.mytheme.myactionbar</item> <item name="colorprimary">#5af142</item> <item name="colorprimarydark">#06dd09</item> <item name="coloraccent">#20f304</item> </style> <style name="theme.mytheme.myactionbar" parent="@style/widget.appcompat.actionbar"> <item name="android:background">@android:color/transparent</item> <item name="background

javascript - Advanced sibling selector -

this question has answer here: how select element based on state of element in page css? 3 answers i can't quite head around this. have following construct: <div class="container"> n = 0 ... <a href="some url">link n</a> endfor each link in ".container" <div class="poptip"></div> endfor </div> and example be: <div class="container"> <a href="some url">link 1</a> <a href="some url">link 2</a> <a href="some url">link 3</a> <div class="poptip">some content related link 1 retreived ajax</div> <div class="poptip">...</div> <div class="poptip">...</div> </div> now h

Sharepoint 2013 file copy -

i have requirement.when file uploaded document library,if pdf file uploaded should routed site collection’s library.with of ootb or workflows or rest calls or csom. please let me know if body worked on type of problem. you can create 1 event receiver, when item added in list can check extension.if pdf file can write code copy file desired location in site collection , after successful copy ,you can delete file.

ruby - Updating a rails attribute through a model association -

i have 2 models shop , user . shop has_many users , user has_one shop. i'm trying create button on shop/show allows user choose shop. button should send parameter shop_id users_controller#update_shop changes user.shop_id id of shop on page. the current method in users_controller#update_shop following: def update_shop @user = user.find(params[:id]) @user.update_attributes(shop_id: params[:shop][:id]) flash[:success] = "added shop!" end and button on show/shop this: <%= form_for user.update_shop, remote: true |f| %> <%= f.hidden_field :shop_id, value: @shop.id %> <%= f.submit 'add shop', :class => 'button blue-button' %> <% end %> i'm getting error nomethoderror in shopscontroller#show undefined method update_shop' #`. method defined in users controller though. i understand there more efficient way update user.shop_id through association, tips on doing or getting work appreci

rest - Difference between new and create (or edit and update) Rails -

i know question has been asked many times on stackoverflow, have more specific question: i know new used create form , doesn't save nothing on db. instead, create action saves , validates data on db. let's see these: def new @country = country.new end def create @country = country.new(params[:country]) respond_to |format| if @country.save format.html { redirect_to countries_index_path, notice: 'provincia creata.' } format.json { render :json => countries_index_path, :status => :created, :location => @country } else format.html { render :action => "new" } format.json { render :json => @country.errors, :status => :unprocessable_entity } end end end i want know , why framework doesn't permit use single variable , passed new create handle creation of resource? mean , in new , create create every time 2 different variable, country.new : use

java - Concurrent SQS queue listeners -

i don't understand how sqs queuelistener works. this config: /** * aws credentials bean */ @bean public awscredentials awscredentials() { return new basicawscredentials(accesskey, secretaccesskey); } /** * aws client bean */ @bean public amazonsqs amazonsqsasyncclient() { amazonsqs sqsclient = new amazonsqsclient(awscredentials()); sqsclient.setregion(region.getregion(regions.us_east_1)); return sqsclient; } /** * aws connection factory */ @bean public sqsconnectionfactory connectionfactory() { sqsconnectionfactory.builder factorybuilder = new sqsconnectionfactory.builder( region.getregion(regions.us_east_1)); factorybuilder.setawscredentialsprovider(new awscredentialsprovider() { @override public awscredentials getcredentials() { return awscredentials(); } @override

c# - Is removing a MessageBodyMember in a MessageContract considered a breaking change? -

consider following servicecontract-interface: [servicecontract] public interface itest { [operationcontract] void mymethod(myclass obj); } with myclass beeing: [messagecontract] public myclass { [messagebodymember(order = 0)] public int { get; set; } [messagebodymember(order = 1)] public int b { get; set; } [messagebodymember(order = 2)] public int c { get; set; } } myclass changed following: [messagecontract] public myclass { [messagebodymember(order = 0)] public int { get; set; } [messagebodymember(order = 2)] public int c { get; set; } } would client consuming wcf-service need make additional changes work new service definition? additionaly, happen if additionally change c have new order = 1 ? if client updates wsdl file, gets syntax error in code of client, when client calls method. the order element set on position in communication bodymember sending server/client. can see svc log. example.: <ns

css - What is the difference between width in % and width in px? -

if create div child of div, should set width in px or in % designing responsive website. can please tell me 1 best? pixels (px): pixels fixed-size units used in screen media (i.e. read on computer screen). 1 pixel equal 1 dot on computer screen (the smallest division of screen’s resolution). many web designers use pixel units in web documents in order produce pixel-perfect representation of site rendered in browser. 1 problem pixel unit not scale upward visually-impaired readers or downward fit mobile devices. percent (%): percent unit “em” unit, save few fundamental differences. first , foremost, current font-size equal 100% (i.e. 12pt = 100%). while using percent unit, text remains scalable mobile devices , accessibility. “ems” (em): “em” scalable unit used in web document media. em equal current font-size, instance, if font-size of document 12pt, 1em equal 12pt. ems scalable in nature, 2em equal 24pt, .5em equal 6pt, etc. ems becoming increasingly popular in web

unit testing - How to stub out a generic method definition in an interface using Microsoft Fakes in c# -

i have unit test stubs out following interface using microsoft fakes: public interface itable { task<tableresult> retrieve(string tablereference, string partitionkey, string rowkey); } the stub looks this: itable table = new messagesapi.azure.fakes.stubitable() { retrievestringstringstring = delegate { tableresult tableresult = new tableresult(); return task.fromresult(tableresult); } }; this works fine. i'd change interface more generic so: public interface itable { task<tableresult> retrieve<t>(string tablereference, string partitionkey, string rowkey) t : itableentity; } question how stub new version of interface out? i'm having trouble getting syntax right. any ideas? you set behavior following: var table = new messagesapi.azure.fakes.stubitable(); table.retrieveof1stringstringst

ios - How to add a border to this delimited layer? -

Image
i have image above delimitate transparent rectangle using layer , mask. i transparent rectangle red bordered . find way achieve : here have done : my viewcontroller has darkenedview property. - (void)loadview { uiview *const rootview = [[uiview alloc] initwithframe:cgrectmake(0, 0, 50, 50)]; rootview.backgroundcolor = [uicolor whitecolor]; self.view = rootview; [self addcontentsubviews]; } - (void)addcontentsubviews { uiimageview *const imageview = [[uiimageview alloc] initwithimage:[uiimage imagenamed:@"dsc_0823.jpg"]]; imageview.contentmode = uiviewcontentmodescaleaspectfill; imageview.frame = self.view.bounds; imageview.autoresizingmask = uiviewautoresizingflexibleheight | uiviewautoresizingflexiblewidth; [self.view addsubview:imageview]; } - (void)viewdidload { [super viewdidload]; [self adddarkenedsubview]; } - (void)viewdidlayoutsubviews { cgrect const bounds = self.view.bounds; darkenedview.center = cgp

jquery - How to open another submit form after submitting one on html or javascript? -

i trying open form inputs after submitting one. in code, want edit node in array , getting first input make program find node edit. if input valid -the input 1 of nodes in array-, want open on same place first one. how can that? <p> <a href="#" style="font-size: 20px" onclick="toggle_visibility('editnodeform');">edit existing node</a> </p> <form action="#" style="display: none;" id="editnodeform">id or name: <input type="text" id="toedit" size="20" style="width: 50%; height: 2em;"> <br /> <br /> <button type="button" class="mybutton" form="editnodeform" style="width: 50%;" onclick="editexistingnode();">submit</button> <br /> <br /> </form> what put fields inside form, , separate steps divs. on page load, hide steps (excep

process - Matrices multiply, Cannon algorithm implementation using MPI -

first of all, of course saw similar questions , solutions, implementation little bit different. main problem that, code works 1 process, doesn't work more processes. don't know cause of this... in communication between processes can't figure out ;/ #include <mpi.h> #include <stdio.h> #include <math.h> #include <iostream> using namespace std; int main(int argc, char **argv) { int x = 0; double kk; int proces; int numprocs; int right_neigh, left_neigh, up_neigh, down_neigh; int tag = 99; static const int n = 6; //size of matrices int psa[n][n]; //nxn int psb[n][n]; int pra[n][n]; int prb[n][n]; int c[n][n]; (int = 0; < n; i++) { //let's make fist matrix (int j = 0; j < n; j++) { psa[i][j] = (int)rand() % 100 + 1; psb[i][j] = (int)rand() % 100 + 1; c[i][j] = 0; } } (int = 0; < n; i++) { //an 2nd 1 (int j = 0; j &

vb.net - Translation program from VBA to vb NET -

generally have working program macro in excel , wanted extract 1 button simple windows application. there simple way or better try recognize differences between vba , vb.net , try write scratch? sub zapisywanie_txt_biesse_wr() dim textfile integer dim filepath string dim filecontent string, strcontent() string dim newname string dim strfile string dim filenum string dim last_dot long dim posstart integer dim poslength integer dim integer dim j integer dim lpx integer dim mytxtfile on error goto errorhandle 'zmienic domyslna lokacje na lokacje aplikacji 'chdir "c:\users\marcin.perz\desktop\makro zmieniajace pliki" chdir activeworkbook.path 'spytac sie o plik przerobienia filepath = application.getopenfilename("text files (*.txt),*.txt") 'nastepny wolny numer dla txt textfile = freefile 'otworzenie txt w trybie odczytu open filepath input textfil

winforms - Open a web browser using C# win application and add request headers in the request -

i have situation want simulate web request comes application. contains url values , request headers. i know can start browser using var url = "http://test.com"; var sinfo = new processstartinfo(url); process.start(sinfo); but want add header values in url want open in browser. have tried using different things not able open in browser. i have used webclient below webclient client = new webclient(); var url = "http://test.com"; client.headers.add("user", "abc"); string text=client.downloadstring(url); but how use string in web browser don't know. i have tried webbrowser not able simulate. there no standard this. if want pass custom headers, need consult web browser using. don't think of major browsers have such feature, though - however, there extensions both chrome , firefox allow globally add headers every request. maybe that's enough you, maybe not.

javascript - File upload jquery instead of preview the file it show the link in the below new window -

working on jquery file upload don't want use plugin.using pure jquery / javascript. instead of preview file want link (view) needs display once image & pdf upload if user click link has open in new page. here html code any guidance here please <div class="mob_pass"> <label class="ctm_fnt">attach document</label> <br> <div class="custom-file-input"> <input type="file"> <input type="text" class="txt_field ctm_widt" placeholder="attached file"> <button class="cst_select"> <i class="fa fa-rotate-90"></i> attach </button> </div> </div> kindly me. thanks in advance here fiddle link add markup : <a href="#" target="_blank" class="preview">view</a> in js, capture event of input change, pre