Posts

Showing posts from March, 2010

javascript - Detect when tracking pixel is returned from server -

customers use service install script (javascript) server. have tracking pixel inserted onto page via script picks click info. when asp.net server intercepts pixel.aspx inserts login information fake image's querystring database , returns pixel.gif...all works (see below). imports microsoft.visualbasic imports system.web public class helloworldmodule implements ihttpmodule private pattern string = "/images/(?<key>.*)\.aspx" private logofile string = "~/images/pixel.gif" public sub new() end sub public readonly property modulename() string return "helloworldmodule" end end property ' in init function, register httpapplication ' events adding handlers. public sub init(byval application httpapplication) implements ihttpmodule.init addhandler application.beginrequest, addressof getimage_beginrequest end sub public sub getimage_beginrequest(byval sender object, byval args system.eventargs) 'cast sende

ios - Function for UIBarButtonItem -

i'm using core data , i'm making save button code: self.navigationitem.setrightbarbuttonitem(uibarbuttonitem(barbuttonsystemitem: .add, target: self, action: selector("savetapped")), animated: true) the save function: func savetapped(){ if (cell!.textfield.text.isempty) { let alert = uialertview() alert.title = "nevyplnené údaje" alert.message = "musíš vyplniť všetky údaje o knihe." alert.addbuttonwithtitle("ok") alert.show() } let appdel: appdelegate = uiapplication.sharedapplication().delegate as! appdelegate let obsah: nsmanagedobjectcontext = appdel.managedobjectcontext! let entity = nsentitydescription.entityforname("list", inmanagedobjectcontext: obsah) var pridat = model(entity: entity! , insertintomanagedobjectcontext: obsah) pridat.kniha =

java - Delete an Item from a List/Search for an Item in a list -

i'm working on lab have phonebook program. program opens box open .bat file containing list of names , numbers. i can't figure out how deletemi function , searchmi function work. any immensely appreciated import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.joptionpane; public class phonebook extends frame implements actionlistener, itemlistener { menuitem newmi, openmi, savemi, saveasmi, exitmi; menuitem searchmi, deletemi, updatemi, newentrymi, sortmi; string filename; list namelist, numberlist; textfield lastname, firstname, phonenumber; /** * constructor */ public phonebook() { super("white pages"); // set frame title setlayout(new borderlayout()); // set layout // create menu bar menubar menubar = new menubar(); setmenubar(menubar); // create file menu menu filemenu = new menu("file"); menubar.add(filemenu); newmi = filemenu.add(new menuitem("new")); newmi.

Mapkit Pin Annotations with Swift -

i trying display map of world several pins. when left button tapped, should perform phone call each pin associated different phone number. searched around , came following code calls same number. how can assign specific phone number each pin annotation? import uikit import mapkit import corelocation class crewdesksviewcontroller: uiviewcontroller, mkmapviewdelegate { @iboutlet weak var mapview: mkmapview! @iboutlet weak var callcrew: uisegmentedcontrol! let locationmanager = cllocationmanager() override func viewdidload() { super.viewdidload() // ask authorisation user. self.locationmanager.requestalwaysauthorization() // use in foreground self.locationmanager.requestwheninuseauthorization() if cllocationmanager.locationservicesenabled() { // locationmanager.delegate = self locationmanager.desiredaccuracy = kcllocationaccuracynearesttenmeters locationmanager.startupdatin

c++ - Memory management pointers -

this question has answer here: is worth setting pointers null in destructor? 12 answers i saw common practice of deleting pointer amd making null in destructor if no memory allocated pointer on heap. consider below c++ code: dummy.h class dummy { int* a; } dummy.cpp dummy::dummy():a(null) { cout<<inside const"; } dummy::~dummy() { if(a!=null) { delete a; = null; } } bool func() { = func1(); } in above code although memory not allocated on heap, deleted. should not lead memory leak? making null pointless, since it's destroyed. your code isn't deleting if it's null, due if (a!=null) . however, that's pointless: applying delete null pointer nothing, can reduce destructor unconditional delete a; (assuming know it's either null, or points object created new ). yo

spring - CXF Rest with Maven and tomcat -

i try first rest application , running in tomcat. use maven build process. build works without errors. tomcat extract rest.war without raising error , try request http://hostname:8080/rest/categoryservice/category/01 . leads 404 response. enclosed web.xml, beans.xml , snippet of service class. pom contains dependencies. hope have suggestions or hints find out mistake. service class: @path("/categoryservice") @produces({"application/json","application/xml"}) public class categoryservice { @get @path("/category/{id}") @produces({"application/json","application/xml"}) public category getcategory(@pathparam("id") string id) { ... web.xml: <?xml version="1.0" encoding="iso-8859-1"?> <!doctype web-app public "-//sun microsystems, inc.//dtd web application 2.3//en" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <

ruby on rails - $http service adding unwanted JSON key to request data -

Image
i have simple service i'm using post data rails controller. my service looks this: app.service('autorulesservice', function($http) { return({ createrule: createrule }); function createrule() { var request = $http({ method: 'post', url: '/rules.json', data: { one: 'two } }); return request.then(handlesuccess, handleerror); } function handlesuccess() { // body omitted... } function handleerror() { // body omitted... } }); i use service in controller in pretty standard way: $scope.saverule = function() { rulesservice.createrule().then(function() { // stuff... }); } the problem weird unwanted key in parameters when inspect sent data in rails log. "rule" parameter coming from? processing autoanalysis::rulescontroller#create json parameters: {"one"=>"two", "rule"=>{}} it doesn't appear in request payload (as inspected in

javascript - How to push elements of an object into another object? -

like in arrays can add new elements using array .push(item) . how same objects ? , can done inside object? like: var myobject={apple: "a", orange: "o"}; var anothobject = {lemon: "l", myobject}; you can use jquery's extend function: http://api.jquery.com/jquery.extend/ var object1 = { apple: 0, banana: { weight: 52, price: 100 }, cherry: 97 }; var object2 = { banana: { price: 200 }, durian: 100 }; // merge object2 object1 $.extend( object1, object2 );

java - Spring rest. Abstract JSON tree payload -

is there way abstract json payload parameter of spring rest controller method. want like: @requestmapping(value = "/my/url", method = requestmethod.post) public bean method(jsonnode requestraw) jsonnode com.fasterxml.jackson.databind.jsonnode node complex, map<string, object> not quiet convenient. thank you!

c++ - Will I get a performance boost when compiling with a C++14 compiler instead of C++11? -

i know can performance boost when compiling c++11 compiler instead of c++03 compiler (see question ). but can expect performance boost when going c++11 compiler c++14 compiler? if so, can show me code sample faster when compiled c++14 instead of c++11. there core language change in c++14 allows implementation merge memory allocations, see n3664 . if compiler/optimizer takes advantage of allowance, may see performance improvement.

Initializing array of structs in c -

i've initialized array of structs 3 items , it showing 2 me !!! #include <stdio.h> typedef struct record { int value; char *name; } record; int main (void) { record list[] = { (1, "one"), (2, "two"), (3, "three") }; int n = sizeof(list) / sizeof(record); printf("list's length: %i \n", n); return 0; } what happening here? getting crazy? change initialization to: record list[] = { {1, "one"}, {2, "two"}, {3, "three"} }; /* ^ ^ ^ ^ ^ ^ */ your initialization (...) leaves effect similar {"one", "two", "three"} , creates struct array elements { {(int)"one", "two"}, {(int)"three", (char *)0} } comma operator in c evaluates expressions left right , discard except last. reason why 1 , 2 , 3 discarded.

excel - Find function not returning value with number format -

i have code searches through each worksheet within active workbook , returns sheet name whenever value found. unfortunately case when range formatted "general". not return name of sheet if range formatted "number". instead set range nothing , exit loop. want keep number format intact. function findsheetname(srch string) string dim ws worksheet dim rng range findsheetname = "cannot find gl code" each ws in activeworkbook.worksheets if ws.visible = xlsheetvisible ws.range("b:b") set rng = .find(what:=srch, _ after:=.cells(.cells.count), _ lookin:=xlvalues, _ lookat:=xlwhole, _ searchorder:=xlbyrows, _ searchdirection:=xlnext, _ matchcase:=false) if not (rng nothing or _ ws.name = &q

Make Multiple Subdirectories In Python -

i doing kind of special code right here. making code create 1 - 10 directories called box1, box2... until 10. in these directories there other directories. , in these directories more subdirectories... . @ end, generate key. here have now: import time import random import subprocess import os import os.path liste = [] old = [] key = false numberofboxes = 5 files = -1 number = random.randint(1, 10) def random_generator(): looper in range(1, numberofboxes): rand = random.randint(1, 10) liste.append(rand) def calculate(): c = liste[0] looper in range(1, c): print(looper) newpath = 'box' + str(looper) if not os.path.isdir('./' +newpath+'/'): os.mkdir('./' +newpath+'/') def subdir_true(): files = -1 read = liste[0] chance = random.randint(1, 2) looper in range(1, read): if chance == 1: looper in range(1, read): exist = os.pat

PHP reading through json -

we have created json follows {"deliveries":[{"cn":"1498","airlinetype":" airbus a330-200 ","registration":" g-vygk ","airline":"thomas cook airlines","date":" 29. apr 2015 "}]} we trying loop through each delivery extracting data insert database. ran data through json validator , says ok. need use json_encode convert having problems trying access each of elements. best approach this? thanks in advance rich you want decode json string have posted. a quick way since know name of each json branch following $json = '{"deliveries":[{"cn":"1498","airlinetype":" airbus a330-200 ","registration":" g-vygk ","airline":"thomas cook airlines","date":" 29. apr 2015 "}]}'; $out = json_decode($json,true); foreach($out["deliveries"] $deliveries

serialization - Ruby Yaml serialisation issue -

strange problem serialisation, doing wrong not sure is. thanks in advance help. input yaml document --- ssl_user_clients: - first_name: donnald surname: duck email: donnald.duck@acme.corp country: fantasyland state: desert locality: disney org_name: acme corp expected yaml document --- ssl_user_clients: - first_name: donnald surname: duck password: k)nzzc+&dg?-ry|0 email: donnald.duck@acme.corp country: fantasyland state: desert locality: disney org_name: acme corp strange result of code: --- ssl_user_clients: - &1 first_name: donnald surname: duck email: donnald.duck@acme.corp country: fantasyland state: desert locality: disney org_name: acme corp *1: first_name: donnald surname: duck email: donnald.duck@acme.corp country: fantasyland state: desert locality: disney org_name: acme corp password: k)nzzc+&dg?-ry|0 my ruby code: #!/usr/bin/env ruby require "yaml&qu

java - Ascii not converted in commons lang3 -

stringescapeutils.escapexml("cortés") working in commons-lang2.3 not working in 3.2.1. expected output "cort&#233;s" actual output "cortes" . escapexml() deprecated in 3.2.1. use escapexml10() or escapexml11() instead. alternatively, documentation: note unicode characters greater 0x7f of 3.0, no longer escaped. if still wish functionality, can achieve via following: stringescapeutils.escape_xml.with( numericentityescaper.between(0x7f, integer.max_value) );

python - Convert from bin to int/char without loosing leading "0" -

is there anyway that >>> int('0000001',2) 1 could save leading 0s ? what want is, huge string of bits, in 8 , 8 bits convert int, , char, , write in file. later want read file, char, use ord(), int, , bits entered, leading 0s. you can preserve number of initial zeroes finding first index of 1 (as binary string). >>> s = '0000001' >>> '{}{}'.format('0'*s.index('1'),int(s,2)) '0000001' >>> s = '0000011' >>> '{}{}'.format('0'*s.index('1'),int(s,2)) '000003' as can see, leading zeroes preserved , not number of digits. another implementation (only zeroes included) >>> def change(s): ... try: ... return '{}{}'.format('0'*s.index('1'),int(s,2)) ... except valueerror: ... return s ... >>> change('000000') '000000' >>> change('000001&#

web api - CORS Not working for OPTIONS -

public void configuration(iappbuilder app) { app.usecors(microsoft.owin.cors.corsoptions.allowall); } in our webapiconfig.cs have following line @ top of register: public static void register(httpconfiguration config) { config.enablecors(); in our web.config have following under <handlers> <remove name="extensionlessurlhandler-isapi-4.0_32bit" /> <remove name="extensionlessurlhandler-isapi-4.0_64bit" /> <remove name="extensionlessurlhandler-integrated-4.0" /> <add name="extensionlessurlhandler-isapi-4.0_32bit" path="*." verb="get,head,post,debug,put,delete,patch,options" modules="isapimodule" scriptprocessor="%windir%\microsoft.net\framework\v4.0.30319\aspnet_isapi.dll" precondition="classicmode,runtimeversionv4.0,bitness32" responsebufferlimit="0" /> <add name="extensionlessurlhandler-isapi-4.0_64bit

javascript - Look behind replace all occurrences -

i want replace occurences of .digit 0.digit. i'm new regular expressions far understand use behind this. js not support that, i'd know if knows solution. show problem wrote following code. str = "0.11blabla.22bla0.33bla.33" allow = "\\.\\d*" str.match(new regexp(allow,"g")) [".11", ".22", ".33", ".33"] deny = "0\\.\\d*" str.match(new regexp(deny,"g")) ["0.11", "0.33"] diffreg= new regexp("(?!"+deny+")"+allow,"g") // translates to: /(?!0\.\d*)\.\d*/g str.match(diffreg) [".11", ".22", ".33", ".33"] obviously allow matches decimal values whereas deny matches values preceding 0. result should of course set difference between two: [".33", ".33"]. i think looking regex instead [0]?(\.\d*) so in code have: intersectionreg = new regexp("[0]?("+allow+&q

matlab - Memory issue with UIGETDIR -

recently, have noticed odd behavior uigetdir function of matlab. if have string values, has no effect on memory. >> memory maximum possible array: 860 mb (9.014e+08 bytes) memory available arrays: 1287 mb (1.349e+09 bytes) memory used matlab: 435 mb (4.557e+08 bytes) physical memory (ram): 3317 mb (3.478e+09 bytes) >> folder = 'c:\users\mrawesome'; >> memory maximum possible array: 860 mb (9.014e+08 bytes) * memory available arrays: 1289 mb (1.352e+09 bytes) ** memory used matlab: 434 mb (4.553e+08 bytes) physical memory (ram): 3317 mb (3.478e+09 bytes) but if use uigetdir instead, drains down whole lot of memory: >> folder2 = uigetdir; >> memory maximum possible array: 727 mb (7.628e+08 bytes) * memory available arrays: 1153 mb (1.208e+09 bytes) ** memory used matlab: 458 mb (4.806e+08 bytes) physical memory (ram): 3317 mb (3.478e+09 bytes) and if clear these 2 variables memory, not release memory!

java - Spring data findFirst5xxxx returns more than just 5 -

i have repository has method: list<subgroup> findfirst5bysubgroupid(biginteger groupid, sort sort); when call findfirst5bysubgroupid returns more 5. why spring data doing this??? here example of repository: @repository public interface subgrouprepository extends crudrepository <subgroup, biginteger> { list<subgroup> findfirst5bysubgroupid(biginteger sectorid, sort sort); }

php - Trustpilot API not sending invitation e-mails -

we have application calling trustpilot api send out invitation e-mails customers can review recent orders. creating review link etc. works correctly. however, when calling final step send out invitation e-mail, "status" field of response "notsent" , e-mail not sent. the url https://invitations-api.trustpilot.com/v1/private/business-units/business_unit_id/invitations the json response follows: { id: "<response id>", businessunitid: "<business unit id>", businessuserid: "<business user id>", recipient: { name: "<recipient name>", email: "<recipient email>" }, referenceid: "<order id>", templateid: "<default en-gb template code>", locale: "en-gb", sender: { email: "noreply.invitations@trustpilot.com", name: "<client name>" }, replyto: &q

C++ overloading += operator with double pointers -

so i'm trying overload += operator dictionary program assignment. function: definition& definition::operator += (const string& input) { string** temp; temp = new string*[numdefs + 1]; temp[0] = new string[numdefs]; (int = 0; < numdefs; i++) { temp[i] = def[i]; } temp[0][numdefs] = input; delete[] def; def = temp; numdefs++; return *this; } however when try put 'input' 'temp' doesn't seem work. string class function allocating string string: string& string::operator=(const string& input) { data = null; (*this) = input.getdata(); return *this; } and: string& string::operator=(const char* input) { if (data != input) { if (data != null) { delete[] data; data = null; } data_len = strsize(input); if (input != null) { data = new char[data_len + 1]; strcopy(data, inp

greenfoot - Testing if random number equals a specific number -

i know might have been answered, places found it, wouldn't work properly. i'm making game in greenfoot , i'm having issue. i'm generating random number every time counter reaches 600, , testing if randomly generated number equal 1, , if is, creates object. reason, object created every time counter reaches 600. i'm new java it's simple. import greenfoot.*; import java.util.random; /** * write description of class level_one here. * * @cuddlyspartan */ public class level_one extends world { counter counter = new counter(); /** * constructor objects of class level_one. * */ public level_one() { super(750, 750, 1); prepare(); } public counter getcounter() { return counter; } private void prepare() { addobject(counter, 150, 40); ninad ninad = new ninad(); addobject(ninad, getwidth()/2, getheight()/2); fail fail = new fail(); addobject(fail, greenfoot.getrandomnumber(getwidth()), greenfoot.getrandomnumber(getheig

erp - Why RowPersisted is executed twice in Acumatica? -

let's i've added in graph kind of rowpersisted implementation dac. set debugger point on rowpersisted. if attach in debugging mode, rowpersisted executed twice. why rowpersisted event executed twice in acumatica during save? first of it's consider, when executed. it's executed twice, first time during database transaction, , second time after transaction been commited or aborted. so, done purpose modification of data before commit, , maybe make additional actions after commited or aborted.

First Java project distinguishing between different instances of class -

this first java application have built, have created class products, need declare 4 different instances of products can access each individual product in different parts of code. code have @ moment shown below can seem acces last product have created: products = new products(1,2.50,"coke",15); products = new products(2,1.50,"crisps",5); products = new products(3,2.00,"juice",2); products = new products(4,2.50,"chocolate",0); system.out.println(products.getproductid()+ " " + products.getproductname()); is there way 'where product id equal to' or assign individual name each instance of product? appolagies if question has been asked elsewhere had through related posts couldn't find on related java. code below shows products class: public class products { private int productid; private double productprice; private string productname; private int productstock; public products(int id, double pri

Segmentation fault (core dumped) using boost::split in C++ -

i have std::string wktstring: projcs["osgb 1936 / british national grid",geogcs["osgb 1936",datum... and trying split string #include <boost/algorithm/string.hpp> ... std::vector<std::string> proj_list; boost::split(proj_list, wktstring, boost::is_any_of("[")); std::cout << "split finish"; and when compile have segmentation fault before "split finish". why? definitely need more information. program compiles , runs w/o error: #include <iostream> #include <vector> #include <boost/algorithm/string.hpp> int main () { std::string wktstring = "projcs[\"osgb 1936 / british national grid\",geogcs[\"osgb 1936\",datum..."; std::vector<std::string> proj_list; boost::split(proj_list, wktstring, boost::is_any_of("[")); ( int = 0; < proj_list.size(); ++i ) std::cout << proj_list[i] << std::endl; }

java - How to convert this code into runnable jar file -

Image
i want make jar file code in eclipse. have googled made exporting not running. helps? import java.util.scanner; public class s { public static void main(string[] args) { scanner scan = new scanner(system.in); system.out.println("enter a: "); int = scan.nextint(); system.out.println("enter b: "); int b = scan.nextint(); int result = (a + b) / 2; system.out.println("(a+b)/2 is: " + result); } } you should click file , click export , click java , save runnable jar file . to run .jar file, open cmd or terminal, make sure in right path , type java -jar <jar-file-name>.jar note if cant run it, file path not correct

jquery - update textbox when paragraph changes value -

i trying populate textbox value of paragraph element when value changes. using jquery. when text in changes, nothing happens. below jquery. $(document).ready(function(){ $('#textbit').change(function(){ var isbn = $('#textbit').val(); alert(isbn); $('#isbn').val(isbn); }); }); try: $(document).ready(function(){ $('#textbit').change(function(){ var isbn = $('#textbit').text(); $('#isbn').val(isbn); }); });

android - Multiple dex files define Landroid/support/test/espresso/contrib/DrawerActions -

this question has answer here: android tests build error: multiple dex files define landroid/support/test/buildconfig 7 answers when trying migrate espresso 2.1 hit following road-block com.android.dex.dexexception: multiple dex files define landroid/support/test/espresso/contrib/draweractions$1; @ com.android.dx.merge.dexmerger.readsortabletypes(dexmerger.java:596) @ com.android.dx.merge.dexmerger.getsortedtypes(dexmerger.java:554) @ com.android.dx.merge.dexmerger.mergeclassdefs(dexmerger.java:535) @ com.android.dx.merge.dexmerger.mergedexes(dexmerger.java:171) @ com.android.dx.merge.dexmerger.merge(dexmerger.java:189) @ com.android.dx.command.dexer.main.mergelibrarydexbuffers(main.java:454) @ com.android.dx.command.dexer.main.runmonodex(main.java:303) @ com.android.dx.command.dexer.main.run(main.java:246) @ com.android.dx.comma

alter - Is it ALWAYS transparent to increase the size of a MYSQL column? -

it appears me if make column larger (i.e. varchar(255) varchar(512) ) these kinds of changes transparent. existing data in column identical, , selects , other mysql statement work same in either case, , require no changes? it's valid assumption? i'm make field larger has data in (with alter ) , want sure after change, things function , appear (except after, can push in larger fields). data remain same if column made larger (e.g. varchar(100) varchar(200) ). queries, such select s should work expected, should consider relationships field has others, internally , externally. is field displayed in external application set handle displaying n characters , expected handle n+x characters? is field input query or procedure expecting field of length n not able handle length n+x ?

Java 8 lambda Void argument -

let's have following functional interface in java 8: interface action<t, u> { u execute(t t); } and cases need action without arguments or return type. write this: action<void, void> = () -> { system.out.println("do nothing!"); }; however, gives me compile error, need write as action<void, void> = (void v) -> { system.out.println("do nothing!"); return null;}; which ugly. there way rid of void type? the syntax you're after possible little helper function converts runnable action<void, void> (you can place in action example): public static action<void, void> action(runnable runnable) { return (v) -> { runnable.run(); return null; }; } // somewhere else in code action<void, void> action = action(() -> system.out.println("foo"));

javascript - Bootstrap JS Print the same view -

i want print website's view. when printing website, it's showing one: http://alierdemsunar.com/printpage.png but want real view's print. because real view of website this: http://alierdemsunar.com/realview.png any ideas? bootstrap default has settings designated print media, check line 192 in bootstrap css. best bet @ these and/or override them create own style sheet print. if looking print full page single time own purposes there plenty of free tools snapshot web page. check out http://www.shrinktheweb.com/

javascript - How to manipulate filestream in memory before uploading -

i'm working on uploader needs censor few bytes in uploaded data overwriting them predetermined value, before uploading them. right now, i've hooked onsubmit event because allows non-blocking work performed. below can see event handler. before call promise.success(); note heavily commented part, problem need with. how can return/set byte array there? onsubmit: function (id, name) { // http://docs.fineuploader.com/branch/master/api/events.html#submit // called when item has been selected , candidate uploading. // return false prevent submission uploader. // create promise var promise = new qq.promise(); // configure file reader var reader = new filereader(); reader.onerror = function (e) { promise.failure("error occured reading file"); }; reader.onabort = function (e) { promise.failure("file reading aborted"); }; reader.onload = function (e) { var buffer = reader.result;

c# - Adding DbContextOptions in Startup.cs not registering data store -

my problem below code not register data store during startup. specific "error" statement in response application: an unhandled exception occurred while processing request. invalidoperationexception: no data stores configured. configure data store overriding onconfiguring in dbcontext class or in adddbcontext method when setting services. microsoft.data.entity.storage.datastoreselector.selectdatastore(serviceprovidersource providersource) in configureservices(iservicecollection services) trying specify dbcontextoptions dbcontext in lambda. code: services.addentityframework(configuration) .addsqlserver() .adddbcontext<mydbcontext>( options => options.usesqlserver(configuration.get("data:defaultconnection:connectionstring")) ); in dbcontext, have constructor sends option base, code: public mycontext(dbcontextoptions options) : base(options) { } my configuration file config.json, read @ startup, contains connecti

ruby on rails - FactoryGirl - can't write unknown attribute, and undefined method `name' -

i'm trying create photo factory that's in many 1 association gallery . , i'm getting 2 errors, depending on how specify association between 2 models. here's models: photo belongs_to :gallery, class_name: "sevengallery::gallery" gallery has_many :photos, class_name: "sevengallery::photo", foreign_key: "seven_gallery_gallery_id", dependent: :destroy and migrations create_table :seven_gallery_galleries |t| t.string :title t.timestamps null: false end create_table :seven_gallery_photos |t| t.string :caption t.string :image t.references :seven_gallery_gallery, index: true t.timestamps null: false end add_foreign_key :seven_gallery_photos, :seven_gallery_galleries, on_delete: :cascade now here's factories: gallery : factorygirl.define factory :gallery, class: 'sevengallery::gallery' title "an event gallery" factory :gallery_with_photos after(:build) |gallery|

python - In what directory does virtualenvwrapper store site packages by default? -

virtualenvwrapper provides several variables: $virtualenvwrapper_env_bin_dir $virtualenvwrapper_project_filename $virtualenvwrapper_script $virtualenvwrapper_virtualenv_clone $virtualenvwrapper_hook_dir $virtualenvwrapper_python $virtualenvwrapper_virtualenv $virtual_env i believe finding virtual environment cd $virtualenvwrapper_hook_dir , going name of environment created ( cd my_environment ). that has 3 directories: bin , include , lib . unfortunately, none of these seems contain site-packages directory. where go find these site-packages? site-packages located in lib/python{major}.{minor}/ subdirectory of virtualenv. e.g. in python 2.7 virtualenv: $ ls -d lib/python?.?/site-packages/ lib/python2.7/site-packages/ but in python 3.4 virtualenv version number again matches: $ ls -d lib/python?.?/site-packages/ lib/python3.4/site-packages/ you can use: $virtual_env/lib/`$virtual_env/bin/python -c &q

python - how to use User class in Django -

i wrote user-login function, not work this models.py class userprofile(models.model): userinfo = models.onetoonefield(user) join_time = models.datetimefield() def __unicode__(self): return self.userinfo.username and userlogin in views.py def userlogin(request): uf = userform(request.post) if request.method == "post": if uf.is_valid(): uf = userform(request.post) username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] user = models.userprofile.authenticate( username=username,password=password) if user not none: if user.is_active: login(request, user) return render(request, 'userlogin/index.html',{'username':username}) else: return httpresponse('password not matched') return render(r