Posts

Showing posts from September, 2014

complexity theory - Is the complement of the language CLIQUE element of NP? -

i'm studying np class , 1 of slides mentions: it seems verifying not present more difficult verifying present. ______ _________ hence, clique (complement) , subsetsum (complement) not members of np. was ever proved, whether complement of clique element of np? also, have proof? this open problem, actually! complexity class co-np consists of complements of problems in np . it's unknown whether np = co-np right now, , many people suspect answer no. just clique np -complete, complement of clique co-np -complete. (more generally, complement of np -complete problem co-np -complete). there's theorem if co-np -complete problem in np , co-np = np ,which huge theoretical breakthrough. if you're interested in learning more this, check out the wikipedia article on co-np , around online more resources.

c++ - Can I use an enum in a constructor for a class? -

i trying make class , inside of class want define enum called type. can use enum defined constructor class? if so, how access outside of class? class type { public: enum ttype { black, white, gray }; type(ttype type, std::string value); ~type(); ... this code doesn't give me errors when try create instance of class in class gives me error because black not defined: type piece(black, value); is there special way , still have ttype class constructor type class? first time using enums don't know how work exactly. yes can: type piece(type::black, value); enum ttype in scope of class type , have use scope resolution when accessing outside type 's body , member functions.

python - Merging txt files matchs conditions -

i have list of files in txt format in python in app this: ['pr00-1.txt', '900-2.txt', 'pr00-2.txt', '900-1.txt', 'pr900-3.txt', '00-3.txt'] i'm trying merge 00 files ['pr00-1.txt', 'pr00-2.txt', '00-3.txt'] in 1 00.txt file. same 900 files , on regardless on pr or -*.txt , * number. tried using split it's not helping. any idea how it? i think want. find 00 files regular expression open 00.txt , write files it. note solution isn't generalized xx pattern, , fails if 1 of files doesn't exist. i'll leave rest you. import re open('00.txt.', 'w') outfile: filenames = ['pr00-1.txt', '900-2.txt', 'pr00-2.txt', '900-1.txt', 'pr900-3.txt', '00-3.txt'] filename in filenames: match = re.search(r'(^|[^0-9])00.*.txt', filename) if (match): open(filename) infile:

python - Using a class field in another fields -

i have field in class depends on field in same class have problem code: class myclass(models.model): nation = [('sp', 'spain'), ('fr', 'france')] nationality = models.charfield(max_length=2, choices=nation) first_name = models.charfield(max_length=2, choices=name) i want put name = [('ro', 'rodrigo'), ('ra', 'raquel')] if nation = spain , name = [('lu', 'luis'), ('ch', 'chantal')] if nation = france. how can that? thanks! i think want change view user sees. have above underlying db model wrong place sort of feature. in addition (assuming web application), need in javascript, can change set of allowed names user changes nationality field.

c# - Control animation and execute script when animation ends -

Image
my project military fps , i'm having problems animations. i have 3 different weapons, 1 animator controller each 1 , every weapon has "enter" , "leave" animation. cs, cod, etc... i need know when "leave" animation ends disable gameobject, enable other 1 , play "enter" animation. i tryed this: http://answers.unity3d.com/questions/362629/how-can-i-check-if-an-animation-is-being-played-or.html without sucess. i'll leave here print of animator controller, hierarchy , script, if u need more details, need say. animator controller of weapon number 1 all transitions "sair" (leave animation) have trigger (ak47_sair) , transition "extit" state have trigger ("ak47_saircontrolador") on code, when press 2 (change weapon number 2) want transition. this hierarchy, script attached "jogador". with actual code, disable tha ak47 gameobject when leave animation still playing. using unit

language extension - How to customize comment block characters in visual studio code? -

i created language extension visual studio code , change comment block characters couldn't find way so.. has done or know how it? ok, figured out problem. there 2 ways can change comment blocks: 1 - config file i dont know why it's not in docs (or @ least couldn't find it) there optional property pass object inside contributes.languages array in package.json named configuration . the description found on vs code source code: a relative path file containing configuration options language. on files can create object 1 , it's gonna overwrite default comment characters { "comments": { "linecomment": "//", "blockcomment": [ "<!--", "-->" ] } } you can see properties on api references: https://code.visualstudio.com/docs/extensionapi/vscode-api#commentrule note: comment block command triggered different shortcut. can overwrite though (in general or specific lang

c# - Dynamically specifying lambda function parameters -

suppose have following line of code: context.load(itemcollection, item => item.include(i => i["title"], => i["name"])); is there way can dynamically specify parameters item.include() function instead of hard-coding them above? i ideally allow users select properties want retrieve of object such title , name , description , etc. fyi, here clientcontext.load function. function coming microsoft.sharepoint.client.dll public void load<t>(t clientobject, params expression<func<t, object>>[] retrievals) t : clientobject { if ((object) clientobject == null) throw new argumentnullexception("clientobject"); clientaction.checkactionparameterincontext(this, (object) clientobject); dataretrieval.load<t>(clientobject, retrievals); } i don't have necessary setup test it, work? string[] keys = ...; context.load( itemcollection , item => item .include(keys

scikit learn - Do test data for machine learning need to have column names? -

suppose have training data below: age:12 height:150 weight:100 gender:m age:15 height:145 weight:80 gender:f age:17 height:147 weight:110 gender:f age:11 height:144 weight:130 gender:m after train data , model, if need pass 1 test observation prediction, need send data column names below? age: 13 height:142 weight :90 i cases have seen people sending test data in array without column names. not sure how algorithms work. note: using python scikit-learn , training data dataframe. not sure whether test data should in dataframe format are predicting gender? if so, yes. input records columns: age , height , weight . otherwise, predicting on record missing gender value. keyerror if model not allow missing fields/columns. i not sure whether test data should in dataframe format in short: yes. usually this: # x input data, format depends on how model (pre)process data. # numeric matrix, list of dict's, list of s

Protractor - Change Browser Capabilities at RunTime -

is there way change browser capabilities within beforeeach of protractor suite. need set capabilities.name attribute before each spec execution. to create separate instances of desired capabilities, such capabilities.name, want try multicapabilities option available via protractor. example similar below , reside in conf.js file. allows submit unique name each test session. onprepare: function(){ var caps = browser.getcapabilities() }, multicapabilities: [{ browsername: 'firefox', version: '32', platform: 'os x 10.10', name: "firefox-tests", shardtestfiles: true, maxinstances: 25 }, { browsername: 'chrome', version: '41', platform: 'windows 7', name: "chrome-tests", shardtestfiles: true, maxinstances: 25 }], a complete example of can seen here: https://github.com/saucelabs-sample-test-frameworks/js-cucumberjs-protractor3.0/blob/master/conf.

ruby - How can I exclude external libraries in Rubymine -

rubymine taking on hour index new project because including every ruby file found on computer external libraries. i not want of these files included in project, cannot figure out how exclude them. if right click on them, have option delete them, deletes file instead of removing library , don't want that. have looked through settings , seen nothing setting external libraries. have ideas?

node.js - ffmpeg not working with piping to stdin -

i want stream file being uploaded ffmpeg. i'm using node.js , it's not working! i ended testing piping input ffmpeg local file, , doens't work either. here's code: var processvideo = function(videostream, resultpath) { var cmdparams = [ '-i', '-', '-y', '-f', 'mp4', '-vcodec', 'libx264', '-vf', 'scale=-1:720', '-f', 'mp4', resultpath ]; var ffmpeg = child_process.spawn('ffmpeg', cmdparams); var data = ''; ffmpeg.stdout .on('data', function(chunk) { data += chunk; }) .on('end', function() { console.log('result', data); }); var err = ''; ffmpeg.stderr .on('data', function(chunk) { err += chunk; }) .on('end', function() { console.log('error', err);}); videostream.pipe(ffmpeg.stdin); }; processvideo(fs.createreadstream(pathtolocalmp4file), localpa

Externalize mongo json query using spring boot -

i have started using spring data mongodb spring-boot . i have mongo based json queries added in interface using @query annotation when using spring data repository. i want know if possible externalize or separate out json query outside codebase can optimized separately , also not having mixed code. thanks suggestions. this code have added in interface , annotated @query annotation. @query("{ 'firstname' : ?0 ,'lastname': ?1}") list findbycriteria(string firstname,string lastname); the above simple example. have complex conditions involving $and , $or operators . what want achieve externalize above native mongo json query config file , refer in above annotation. spring data supports similar when using jpa hibernate. not sure if can same using spring data mongodb spring boot. do (i explaining api) suppose have entity user at top there user domain public class user extends coredomain { private static final long serialvers

vba - Import text files to excel and create master workbook -

i grad student , collect lot of data stored in txt files. want import text files fixed width, columns a, b , c 12, save files excel files , move them master workbook. found following code worked making master workbook not import them in numerical order. i using microsoft 2010. sub merge2multisheets() dim wbdst workbook dim wbsrc workbook dim wssrc worksheet dim mypath string dim strfilename string application.displayalerts = false application.enableevents = false application.screenupdating = false mypath = "c:\users\kyle\desktop\scan rate study 1-14-16" set wbdst = workbooks.add(xlwbatworksheet) strfilename = dir(mypath & "\*.xls", vbnormal) if len(strfilename) = 0 exit sub until strfilename = "" set wbsrc = workbooks.open(filename:=mypath & "\" & strfilename) set wssrc = wbsrc.worksheets(1) wssrc.copy after:=wbdst.worksheets(wbdst.worksheets.count) wbsrc.close false strfilename = dir() loop wbdst.worksheets(1).delete applica

web2py how to import module at the same directory? -

i have file name default.py in controllers,and file getmsg.py @ same directory, can't import getmsg in default.py . why not? how import it? the error: traceback (most recent call last): file "f:\xampp\htdocs\web2py\gluon\restricted.py", line 212, in restricted exec ccode in environment file "f:/xampp/htdocs/web2py/applications/tools/controllers/default.py", line 11, in <module> import getmsg file "f:\xampp\htdocs\web2py\gluon\custom_import.py", line 81, in custom_importer raise importerror, 'cannot import module %s' % str(e) importerror: cannot import module 'getmsg' in web2py, controllers not python modules -- don't import them. can put modules in application's /modules folder , import there. in theory, (assuming there __init__.py file in /controllers folder) can do: import applications.myapp.controllers.getmsg but wouldn't considered standard practice. in particular, contr

ios - Swift: Create array with different custom types -

i'm making registration form app. lets users create questions , display created questions in uitableview. users can create 2 types of questions, text input(using textfields) , multiple choice(using segmentedcontrol). here class created make happen. class question { var label: string var required: int // create question init (label: string, required: int) { self.label = label self.required = required if (self.required == 0) { self.label = self.label + " *" } } } class textinput: question { var placeholder: string init (placeholder: string, label: string, required: int) { self.placeholder = placeholder super.init(label: label, required: required) } } class multichoice: question { var answers: [string] init(answers: [string], label: string, required: int) { self.answers = answers super.init(label: label, required: required) } } i need populate array textinput or multichoice types displayed in uitableview. in c++ can use t

javascript - mochajs referenceerror when testing function not in test file -

i have mochajs test file , javascript code file in setup below: /js/module/codefile.js /js/test/testfile.js the codefile.js contains javascript functions eg: function addnumbers(a, b){ return a+b; } the testfile.js calls functions in codefile test them: describe("add numbers test", function() { it("checks valid result", function() { var = 2; var b = 1; var result = addnumbers(a, b); expect(result).to.equal(3); }); }); from command line cd js folder (parent of test , module directories) run mocha , following error: referenceerror: addnumbers not defined @ context <anonymous> (test/testfile.js). i can't see how defined how can mocha know function comming from? (nb using client side js can't use import, , havent see way specificy (in mocha or karma or js in general) functions defined in python or java). ideas on how can simple unit tests running in mocha? i tried getting mocha run in webstorm

html - Make table data corners touch -

Image
i'm trying make chess board , having slight issue squares' appearances. checkerboard color scheme working correctly reason corners of each square don't seem touching. here's snippet of code have 2 rows, each data entry either belongs class "light" or "dark": <tr><td id="1"><span class="dark"></span></td><td id="2"><span class="light"></span></td><td id="3"><span class="dark"></span></td><td id="4"><span class="light"></span></td><td id="5"><span class="dark"></span></td><td id="6"><span class="light"></span></td><td id="7"><span class="dark"></span></td><td id="8"><span class="light"></span></t

php - How to addressing package view on Laravel 5.1 -

i have modules folder in root directory laravel 5.1. , located package test1 in this. have file view1.blade.php in directory resources/views/view1.blade.php how can access in view1.blade.php address modules/test1/view/test.blade.php i use command in view1 file not work correctly @include "modules/test1/view/test"; and command @include('modules::test') you must define name view in packageseviceprovider this: // define path view files $this->loadviewsfrom(__dir__.'/view','packageview'); and in blade template use: @include ('packageview::addpage')

How to get max count of foreign key SQL Server -

i have 2 tables noroom varchar(50) primary key, kindroom nvarchar(50), price float, pricecurrent float, r_status nvarchar(50), nametour nvarchar(50), checkin date, checkout date, company nvarchar(50), idroom nvarchar(50) foreign key references rooms(noroom) and here code select rooms.noroom, rooms.kindroom, count(checkintour.idroom) numberoforder rooms left join checkintour on( rooms.noroom = checkintour.idroom ) group rooms.noroom, rooms.kindroom order numberoforder desc output this +-----------+----------+----------------+ | no room | kindroom | numberoforder | +-----------+----------+----------------+ | po0051 vip 1 | po0053 single 1 | po0054 vip 1 | po0055 vip 1 | po0056 vip 1 | po0057 vip 1 | po0058 vip 1 | po0059 vip . | po0060 . ..

c# - Can't retrieve value from template field -

im trying value templatefield id in gridview. <itemtemplate> <asp:label id="lblid" runat="server" text='<%# bind("cr_id") %>'></asp:label> </itemtemplate> i need retrieve id update it. following codes aspx.cs gridview mygrid = (gridview)sender; // gridview label lblprodid = (label)mygrid.findcontrol("lblid"); string colid = lblprodid.tostring(); bllcredentials updateid = new bllcredentials(); int ds; ds = updateid.updstatus(colid, 1); gv_credentialslist.editindex = -1; bind(); sendemail(); the error object reference not set instance of object. description: unhandled exception occurred during execution of current web request. please review stack trace more information error , originated in code. exception details: system.nullreferenceexception: object reference not set instance of object.

python - Using Unison "-repeat watch" in FreeBSD (10.2) after installing from ports yields error -

after installing unison /usr/ports/net/unison x11 disabled via make config, running command unison -repeat watch /dir/mirror/1 /dir/mirror/2 yields message: fatal error: no file monitoring helper program found from here decided try using pkg install unison-nox11 , yields same error message. i've tried copying fsmonitor.py file unison-2.48.3.tar.gz /usr/bin/unison-fsmonitor , got following error: fatal error: unexpected response 'usage: unison-fsmonitor [options] root [path] [path]...' filesystem watcher (expected version) running command unison-fsmonitor version shows message unsupported platform freebsd10 anyone have ideas on how fix this? i think message pretty clear: unison-fsmonitor can't run on freebsd10 because it's not supported, can't use unison -repeat option. since it's written in python, though, don't see why shouldn't supported. maybe message developer.

android - how to make listview from JSON -> Sqlite? -

i working in android application in data in form of json , json data saved in sqlite. till have saved json sqlite when trying data in listview , application crashes mainactivity public class mainactivity extends activity { private string[] navmenutitles; private typedarray navmenuicons; private edittext edittextname; sharedpreferences sp; private string jsonresult; private listview listview; private button b; edittext etname, et; textview tv; string myjson; private static final string tag = "mainactivity.java"; private static final string tag_name = "notice"; private categoryhelper databasehelper; button get, store, select; jsonarray peoples = null; arraylist<hashmap<string, string>> personlist; listview list; public static final string user_name = "username"; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.noticelist); //select = (button) find

excel - is there any formula that can be used to duplicate a particular cell specified numer of times? -

Image
im working on data have list of company names 1 below other . eg. 1. 2. b 3. c and many more... result needed 1. 2. 3. 4. 5. 6. b 7. b 8. b 9. b 10. b 11. c 12. c 13. c 14. c 15. c and on... data huge task manually.therefore great if can suggest formula can simplify work :) with data in column a , in b1 enter: =index(a:a,roundup(rows($1:1)/5,0)) and copy down: to 6 repeats, use 6 in place of 5

python - Scapy send function without output -

does know how send packet using scapy , not receive output? this command: send(packet,iface="eth0") this output sent 1 packets. i'm trying not print packet count line @ all. try verbose parameter. scapy documentation says verbose should "make function totally silent when 0". both false , 0 appear work. example: >>> send(ip(dst="1.2.3.4")/icmp()) . sent 1 packets. >>> send(ip(dst="1.2.3.4")/icmp(), verbose=0) >>> send(ip(dst="1.2.3.4")/icmp(), verbose=false) >>> you can little more information using help() : >>> help(send) on function send in module scapy.sendrecv: send(x, inter=0, loop=0, count=none, verbose=none, realtime=none, *args, **kargs) send packets @ layer 3 send(packets, [inter=0], [loop=0], [verbose=conf.verb]) -> none (end)

ios - UIView is sizing properly in dynamic UITableViewCell only after click -

Image
i'm trying implement cardviews in uitableview , every table cell has uiview (named cardview) , context in uiview . i'm adding shadow every cell in layoutsubviews() this: cardview.layer.cornerradius = 3 cardview.layer.shadowcolor = uicolor.darkgraycolor().cgcolor cardview.layer.shadowoffset = cgsizemake(0,1) cardview.layer.shadowradius = 3 cardview.layer.shadowopacity = 0.5 cardview.layer.shadowpath = uibezierpath(rect: cardview.bounds).cgpath but result get: shadow sizing after click on it. suppose it's problem dynamically cells heights, can't handle this. i created working example . add code view controller: override func tableview(tableview: uitableview, willdisplaycell cell: uitableviewcell, forrowatindexpath indexpath: nsindexpath) { let cel = cell as! tablecell cel.setup() } add code tablecell: func setup() { cardview.layer.maskstobounds = false cardview.layer.cornerradius = 3 cardview.layer.shadowoffset =

javascript - How to remove email validation in opencart 2.1 for register account form? -

i trying register customer phone number instead of email id remove email address validation thanks!! you may try this: in catalog/controller/checkout/register.php find (line 149): if ((utf8_strlen($this->request->post['email']) > 96) || !filter_var($this->request->post['email'], filter_validate_email)) { $json['error']['email'] = $this->language->get('error_email'); } and comment out. in catalog/controller/checkout/guest.php find (line 203): if ((utf8_strlen($this->request->post['email']) > 96) || !filter_var($this->request->post['email'], filter_validate_email)) { $json['error']['email'] = $this->language->get('error_email'); } and comment out. hope you.

javascript - Garbage Collection on circular objects? -

in ws node.js server, have when client connects, assigns "user" object websocket object, , inside user object reference websocket object. lets me send data client when know user object (all game logic deals in user objects, not websockets), , lets me client's user information when data comes in websocket object. i've heard circular objects can cause issues garbage collection never clean them because have references each other, so question is, need make sure when client disconnects, websocket , user objects both removed memory? also, let me know if i'm going in wrong way! :p edit: code: function onconnect(client) { users.push({connected: true, client: client, name: "", messages: 0}); client.user = users[users.length - 1]; send("please enter username.", [client.user]); } you have manually remove closed connections list. otherwise, garbage collector not remove them memory. function onconnect(client) { use

networking - how many TCP connections used to download 2 MB file? -

typically, how many tcp connections used download 2 mb file? if file size 200 mb, how many connections then? in general, single tcp connection used transfer file, regardless of size. way works on http example; 1 connection opened , stays open duration of transfer. (in fact http can transfer multiple files on same connection, 1 after other). there protocols can use multiple connections doesn't depend on file size. example, ftp uses 1 connection control commands can use second connection each file transfer. example amazon's aws client can "chunk" large file separate bits , transfer them in parallel. that's unusual , in general 1 file = 1 connection.

c++ - Extract letters from a string and convert to upper case? -

here program in c++ string accepts characters outputs letters; if letters lower case should make them upper case. #include<iostream> #include<cstdlib> #include<cctype> #include <iomanip> #include <cstring> using std :: cin; using std :: cout; using std :: endl; using std::setw ; const int max_str_len=100; int main() { char str1 [max_str_len]; int i; cin >> setw(max_str_len) >> str1; (int i=0; <max_str_len; i++) { if (isalpha(str1[i])) { if (str1[i]>='a'&& str1[i]<= 'z') cout << str1[i]; if (str1[i]>='a'&& str1[i]<= 'z') { str1[i]= toupper(str1 [i]); cout << str1[i]; } } } return exit_success; } this tends work fine gives letters, seems i'm overlooking something. also, when input numbers gives letters such phuyxp

c# - I'm not getting return value of stored procedure. var @id is not supplied.? -

this sql server stored procedure insert data: alter proc insert_stud1 @name varchar(20), @mobile int, @id int output begin insert stud1 values (@name, @mobile) set @id = @@identity; end corresponding c# cmd.commandtype = commandtype.storedprocedure; cmd.parameters.add("@name",sqldbtype.varchar,20); cmd.parameters.add("@mobile",sqldbtype.int); var ret = cmd.parameters.add("@i", sqldbtype.int); cmd.parameters["@name"].value=textbox1.text; cmd.parameters["@mobile"].value=int.parse(textbox2.text); cmd.commandtext="insert_stud1"; con.open(); cmd.executenonquery(); messagebox.show(ret.value.tostring()); con.close(); you send "@i" instead of "@id"

javascript - How does Facebook implement it's "see more" feature on post text content. -

Image
i want cut off post text content @ either 6 lines or number of word characters. fortunately, after using this jquery plugin , have managed cut off post text content @ number of word characters. what remaining cut off post text content @ 6 lines. it's unfortunate this jquery plugin can't it. need anyone's on this. image below illustrates want implement. you can set div's height: 6em , restore height: auto when "read more" link clicked. example: http://jsfiddle.net/jv7dj/1/ .

javascript - Can I give the text and line elements that make up a D3 axis unique classes? -

in d3, when creating axes, possible assign class each line , text element in g.tick? i'm looking end axis rendered this: <g class="yaxis" style="transform: translate(617px, 2em);"> <g class="tick" style="opacity: 1;" transform="translate(0,0)"> <line class="foo" x2="-555" y2="0"> <text class="foo" dy=".32em" style="text-anchor: start;" x="3" y="0">2012</text> </g> <g class="tick" style="opacity: 1;" transform="translate(0,21.64860000000002)"> <line class="bar" x2="-555" y2="0"> <text class="bar" dy=".32em" style="text-anchor: start;" x="3" y="0">2013</text> </g> </g> i see can select svg, append g element , call yaxis. how generate cl

jQuery POST/GET in same function -

with function send data form external file: function save() { var data = $('#formid').serialize(); var url = 'test.php'; $.post(url, data, function (response) { alert("good"); }); } in test.php save values witch take $_post, after inserting values make query db return me json. want take json data , push same jquery function beginning , show in div id="reza" i try add $.get json response function , script is: function save() { var data = $('#formid').serialize(); var url = 'test1.php'; $.post(url, data, function (response) { //----------this new part------ $.getjson("test.php", function(result) { $.each(result, function(i, field) { $("#reza").append(field.name); }); }); }); } please me catch response data. first give me tips first question on stackoverflow, solved problem, solution is: function save() { var data = $('#formid&

iphone - can you share photo to your application from photo library in ios -

hello new in iphone , ipad development. have heard in ios 6 there 1 feature allow user share photo library particular ios applications . open photo in photo library , push button sharing found there icons of facebook,twitter , many more standard option.can put our app icon there share photo our app ? waiting response. in advance. well don't think easy not impossible.to achieve have changes in socialframework.

Arranging Elements in HTML and using Javascript -

i quite new javascript. have been making forms here website , have unusual problem. i want elements names, male/female, dob side side..!! when float them side side ,give width them, doesn't seem change it..!! tried searching on google , stackoverflow, isnt working here. let me paste html , css code below people can me out..!! html code : <div id="form_container" class="warpshadow wlarge wnormal"> <img src = "header.png" width="100%" /> <form id="form_3" class="appnitro top_label" method="post" data-highlightcolor="#f5d678" action="#main_body"> <div class="form_description"> <h2>swim team registration fees</h2> <p>(one check can written children including required fees junior memberships.)</p> </div> <ul

php - Display a custom Wordpress taxonomy tag automatically based on the day of the week? -

i've got client wants display custom taxonomy tags automatically day of week in wordpress. basically, we'll have custom post type called "products" , have taxonomy called "day." within "day" we'll have 7 tags, 1 each day of week, , tagged specific day of week display on day on home page. so, example, if product a, b & c assigned tag of "wednesday" within taxonomy "day" , today wednesday, items display on home page. if products d, e & f assigned thursday, they'll show on thursday, , on. with said, part need writing loop can detect day of week , query proper taxonomy tag. have idea how go this? can't find reference on , php skills rudimentary @ best. :-/ here's loop i'm using display products manually custom post type, taxonomy & term: <?php query_posts('post_type=products&taxonomy=day&term=wednesday&posts_per_page=10'); ?> <?php if(have_posts()) : while (hav

model view controller - ruby on rails forces show after submit -

i'm editing record , receive constraint related error after hitting "save". correct form field involved , click "save". ruby on rails forces me show action whilst i'd rather stay on edit form. design or i'm (hopefully) missing here ? controller def update @profile_field = safe_find profilefield, params[:id], "profile field" if @profile_field.update_attributes(input_params) logger.tagged("#{self.class} #{__method__}") {logger.info @profile_field.inspect } flash[:success] = "profile field updated" redirect_to(request.referrer || root_path) else render 'edit' end end view = form_for @profile_field |f| = render 'shared/error_messages', object: f.object .field = f.label :name_en = f.text_field :name_en = f.label :name_et = f.text_field :name_et = f.label :name_ru = f.text_field :name_ru = f.label :field_type

java - Working with objects in array -

i got text file hundred of lines. this: unitname unitpackage unitprice . got sort , sum up. example got these 4 lines: foo1 01abc 30.00 foo2 02abc 31.50 foo1 04abc 35.00 foo1 01abc 30.00 after work on have this: foo1 2 (01abc) 60.00 foo2 1 (02abc) 31.50 foo1 1 (04abc) 35.00 my idea make product class ( string unitname, string unitpackage, double unitprice ) , put arraylist that: list<product> products = new arraylist<>(); while (inputfile.hasnextline()) { product product = new product(inputfile.next(), inputfile.next(), inputfile.nextdouble()); products.add(product); } until moment works fine, dont idea, how sort things. it's overall concept way? please advice. there many ways array list sorted. in particular case, put every item list, maybe simplest form use map implementation, i.e. hashmap, instead of arraylist. after loop of insertions can sorted list through values() method of map.

How to get user's media through Instagram Api? -

i can see media using https://api.instagram.com/v1/users/self/media/recent/?access_token=**my_access-token** i want user's media, use https://api.instagram.com/v1/users/**id_user**/media/recent/?access_token=**my_access_token** i error, because account private {"meta":{"error_type":"apinotallowederror","code":400,"error_message":"you cannot view resource"}} but follow him, should see media. should ? the following link works me without authentication https://www.instagram.com/{username}/media/

What is the output of this simple java code 6 and not 4? -

what output of simple java code 6 , not 4? since int x = 10 , int y = 15, how come able declare int x , int y again 5 , x-2? thought can declare value of int once? thanks, sorry i'm new java. here's code: public class shortq { public static void main (string args[]) { int x = 10 , y =15; x = 5; y = x-2; system.out.println(x+1); } } also since int x = 10 , int y = 15, how come able declare int x , int y again 5 , x-2? thought can declare value of int once? thanks, sorry i'm new java. x = 5; y = x-2; with above not declaring variable doing assignment. in post there 1 time declaration i.e int x = 10 , y =15; how output of simple java code 6 , not 4? as x 5 , adding 1 while printing x = 5; system.out.println(x+1);

php - Xdebug Netbeans waiting for connection -

xdebug using netbeans seems crashing every other page load. on second load netbeans sits waiting connection without opening designated browser - firefox. on restarting netbeans (a pain) works fine 1 page load. above issues. xdebug configured okay works once, why necessary re-start netbeans everytime ? i realised while script working on had manual execution point, there auto 1 triggered task scheduler every minute. explains restarting netbeans , xdebug worked 1 run - seems shortly after triggered auto schedule somehow crashing xdebug silently , preventing restarting without complete restart of netbeans - not sure why though.

Lyrics for additional verses in LilyPond? -

is there way in lilypond list lyrics corresponding additional verses after end of music, 1 paragraph per verse? (n.b. exact question has been asked before , in 2001, first answer ("read book") references dead url, while second (use \context lyrics ) not work me, lilypond syntax errors.) here's song under want write additional verses. \header{ title = "hello world" } \score { \relative { \time 2/4 \clef treble \key \major cis''2 | a4 fis \bar "|." } \addlyrics { -- | llo world } \layout { } \midi { } } \version "2.18.2" (sorry syntax highlighting , <!-- language: lang-lilypond --> not yet supported in google code prettyfier uses.) i'd add verses 2, 3, , 4 underneath, separated music, words. i got answer knute snortum on liliypond mailing list here after score block can add markup block this \markup { \column { \line { \null } \line { 2. he

maven - mvn testng can't run test suite while Idea can -

i have testng suite looking this <?xml version="1.0" encoding="utf-8"?> <!doctype suite system "http://testng.org/testng-1.0.dtd"> <suite name="blahserversuite"> <test name="creating customer test"> <classes> <class name="com.node.service.scripts.server.customertest" /> </classes> </test> </suite> it runs when run ide. when trying execute console "mvn test" have following error: [testngclassfinder] warning: can't link , determine methods of class com.node.service.scripts.server.customertest my pom looks this: <?xml version="1.0" encoding="utf-8"?> <project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0

c# - Renewing forms authentication ticket - strange timing -

i'm using forms authentication successfully, have run strange issue. i've looked around web, , haven't found answer far. i'm using javascript determine when current session 60 seconds away timing out, , if - pop dialog box button which, if pressed, extend current formsauthentication ticket. this code i'm using renew ticket. i'm add 5 minutes current expiration date of ticket. when output new expiration date, it's under 5 minutes; 4 minutes , seconds. the code: string userid = httpcontext.current.user.identity.name; httpcookie cookie = formsauthentication.getauthcookie(userid, true); formsauthenticationticket ticket = formsauthentication.decrypt(cookie.value); datetime new_expiry = datetime.now.addminutes(formsauthentication.timeout.minutes); formsauthenticationticket newticket = new formsauthenticationticket( ticket.version, userid, datetime.now, new_expiry, ticket.ispersistent,

html - .htaccess file config for google-apps domain verification exception -

my current htaccess content : # @package mambo open source # @copyright (c) 2005 - 2006 mambo foundation inc. # @license http://www.gnu.org/copyleft/gpl.html gnu/gpl # # mambo developed miro (www.miro.com.au) in 2000. miro assigned copyright in mambo mambo foundation in 2005 ensure # mambo remained free open source software owned , managed enter code herethe community. # mambo free software ## # # mod_rewrite in use # rewriteengine on # uncomment following line if webserver's url # not directly related physical file paths. # update yourmambodirectory (just / root) # rewritebase /yourmambodirectory # # rules # rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^content/(.*) index3.php rewriterule ^component/(.*) index3.php rewriterule ^mos/(.*) index3.php i verify google apps domain using html upload. receive error page 404 when access url mydomain.com/google00ff0108e32428b8.html. i still receiving same error page after follow g

linq - Why decrementing one variable modifies incrementing of another one in C# Parallel.ForEach loop? -

running code parallel.foreach keeps spawning new threads few modifications the output commented line: //threadsremaining = interlocked.decrement(ref concurrentthreads); is "obvious", i.e. expected one: [00:00] job 0 complete. 2 threads remaining. unsafecount=2 [00:00] job 1 complete. 1 threads remaining. unsafecount=1 [00:00] job 2 complete. 3 threads remaining. unsafecount=3 [00:00] job 3 complete. 4 threads remaining. unsafecount=4 [00:00] job 4 complete. 5 threads remaining. unsafecount=5 [00:00] job 5 complete. 6 threads remaining. unsafecount=6 [00:01] job 6 complete. 7 threads remaining. unsafecount=7 [00:01] job 8 complete. 8 threads remaining. unsafecount=8 [00:01] job 7 complete. 9 threads remaining. unsafecount=9 [00:01] job 9 complete. 10 threads remaining. unsafecount=10 while output of same code upon uncommenting above line is: [00:00] job 0 complete. 1 threads remaining. unsafecount=1 [00:00] job 1 complete. 0 threads remaining. unsafeco

jquery - How to deserialize JSON string received in controller -

i have received json string received in controller , unable deserialize it. please help. have attached jquery code , controller method in json string received. json received : "[\"account2\",\"account1\"][\"bcs\"][\"yes\"]" image $("#btn1").on("click", function () { alert(j + " " + k); $.ajax({ type: 'post', url: '/todolist/searchdata', traditional: true, datatype:"json", data: "myarray1="+json.stringify(i) +json.stringify(j)+json.stringify(k), success: function (data) { alert(data); } }) }); controller code:- [httppost] public jsonresult searchdata(string myarray1) { console.writeline(myarray1); // console.writeline(myarr

specifications - how to write spec for responsive website? -

i'm write spec responsive website has web, tablet , mobile versions. first spec i'm writing responsive site, , i'm not sure format best understood: - should write different spec each version (pc, tablet , mobile)? - should write in 1 ducument , describe differences in each version? - there further things think it's important take in mind when writing kind of ducument? examples or tips welcomed, thanx! check out html5 rocks tutorial resposive web design. if want dive deep in part, need read blog ethan marcotte ..

jsf 2 - javascript file not loading -

trying import js file page. my page in webcontent/mydomain/templates/page.xhtml my js in webcontent/mydomain/test/scripts in page.xhtml <script type="text/javascript" src="../test/scripts/test.js"></script> but still script not getting picked. can tell how need give path in src. provided webcontent root of public web content , /mydomain public folder , javascript standalone available http://localhost:8080/context/mydomain/test/scripts/test.js , assuming domain of http://localhost:8080 , context path of /context , following should do: <script src="#{request.contextpath}/mydomain/test/scripts/test.js"></script> this generate domain-relative url dynamically inlined context path, more robust fiddling ../ make uri relative current request uri (as see in browser's address bar) , not physical location of template file many starters incorrectly assume.

Syntax error case postgresql -

select utilizzo.dataconsegna case when utilizzo.dataconsegna<=current_timestamp sum((extract(epoch utilizzo.dataconsegna)::integer)-(extract(epoch utilizzo.dataritiro)::integer)/36000) else sum(((extract(epoch utilizzo.dataconsegna)::integer)-((extract(epoch utilizzo.dataconsegna)::integer)-(extract(epoch current_timestamp)::integer)))- (extract(epoch utilizzo.dataritiro)::integer))/36000 end vettura join prenotazione on prenotazione.targa=vettura.targa join utilizzo on utilizzo.smartcard=prenotazione.smartcard , utilizzo.dataora=prenotazione.dataora vettura.targa='cn533sr' and(current_timestamp-prenotazione.dataritiro<=interval '7 days') hi, i'm having syntax error on case, can me out? :/ you can't put sum() into case . you need sum result of case: sum(case when utilizzo.dataconsegna<=current_timestamp (extract

jquery fancybox, get a variable out of the initial function -

this out there have taken apart fancybox little bit, or can understand jquery stuff behind better me (shouldn't hard) :) coming situation described in this article , have added new value fancybox main function retrieves link being clicked on. ; (function($) { var tmp, loading, overlay, wrap, outer, content, close, title, perma, nav_left, nav_right, perma being variable; used in _start function retrieve value <a> : perma = selectedopts.perma || (obj.nodename ? $(obj).attr('perma') : obj.perma) || ''; if @ point quick alert(perma) confirmation variable being retrieved expected. now, has happened inside function _start , inside main function $; but, need use variable outside of such functions, down in script within $.fancybox.init , use such: $('#permabox').bind("click", function(){ window.location.replace(perma); }); however here perma value returns undefined . how value have in other function use one???

python pandas filter out rows does not work -

i want filter pandas dataframe 1 column called 'mid' , retain rows has field 'mid' within particular range. my code follow: df_org dataframe of structure ['uid','mid','cv1','cv2','cv3'] , , series_moviesid pandas series contain values want use filter df_org dataframe. filterout(self, df_org, series_movieid, colname='mid'): mask=((df_org[colname]).isin(series_movieid)) df_filterout = df_org[mask] assert set(df_filterout['mid']).issubset(set(series_movieid)) return df_filterout.reset_index().drop(labels='index', axis=1) but assert expression not pass, know potential mistake? hm. code works me. tried dupes in s, df, , both , ran. more details can share? in [2]: s = pd.series(range(4), index=['a', 'b', 'c', 'd']) in [3]: df = pd.dataframe({'a': range(10), 'b': range(10, 20)}, index=range(20, 30)) in [4]: in [4]: print