Posts

Showing posts from September, 2014

ruby on rails - Error: Unpermitted parameters with nested attributes -

i'm having problem saving contents of nested field. have 2 models incorporation , company . relate follows: class company < activerecord::base belongs_to :incorporation end class incorporation < activerecord::base has_one :company accepts_nested_attributes_for :company end my aim create new company , incorporation entry in same form, using both incorporations controller , view. ( problem ) however, each time attempt submit form, incorporation entry goes through company entry held unpermitted parameters error: started post "/incorporations" 127.0.0.1 @ 2014-12-15 22:40:59 -0700 processing incorporationscontroller#create html parameters: {"utf8"=>"✓", "authenticity_token"=>"lcj/ztnne/9l/ualycna8eae8vmmn010tos4t5e+zka=", "incorporation"=>{"title"=>"test", "company"=>{"name"=>"test"}}, "button"=>""} un

java - How to browse subdirectories at ftp server -

Image
i building swing ftp client. here code jframe :- package jframe; import jframe.swing.download.*; import org.apache.commons.net.ftp.ftpclient; import org.apache.commons.net.ftp.ftpfile; import test.ftpclient; import javax.swing.*; import javax.swing.table.tablemodel; import javax.swing.tree.defaultmutabletreenode; import javax.swing.tree.defaulttreemodel; import java.awt.event.*; import java.awt.*; import java.io.ioexception; import java.util.arraylist; import java.util.enumeration; import javax.swing.tree.defaultmutabletreenode; public class undecoratedframedemo { private static point point = new point(); arraylist arraylist; static string server = ""; static int port = 21; static string user = ""; static string pass = ""; jpopupmenu popup; public undecoratedframedemo() { final ftp_by_apache ftpbyapache=new ftp_by_apache(server,user,pass); arraylist=ftpbyapache.getallfile("/"); final jframe frame = new jframe("

Rails 4 routing error for hash_for*(hash_for_path_name) -

i migrating application rails 2.3.18 rails 4.0.0. application works fine till rails 3.2.21. when migrate rails 3.2.21 rails 4.0.0 gives me error hash_for* helper. i got error: undefined method `hash_for_home_status_path' #<#<class:0xb636bb0c>:0xb636b0a8> i found below method in https://github.com/rails/rails/blob/3-2-stable/actionpack/lib/action_dispatch/routing/route_set.rb not available in rails 4 stable. def hash_access_name(name, kind = :url) :"hash_for_#{name}_#{kind}" end is there patch removal or replacement pass options hash in rails 4? in advance review rails routing outside in . you'll need update of view files (removing hash_for_* , replacing link_to or method).

c# - Cannot update data from Excel sheet to Access database -

here code need save data excel sheet database access using c#. don't error excel data not updated in database access.. have this? my database access tablename "addsales1". my excel sheet name "addsales1". string file_name = application.startuppath + "\\" + "databaseset.txt"; system.io.streamreader objreader; objreader = new system.io.streamreader(file_name); string sh = objreader.readline(); string con = "provider=microsoft.ace.oledb.12.0;data source=" + textbox9.text + ";extended properties=excel 8.0;"; oledbconnection connection = new oledbconnection(con); oledbcommand cmd = new oledbcommand("insert [ms access;database=" + sh + "].[addsales1] select * [addsales1$]"); cmd.connection = connection; connection.open(); cmd.executenonquery(); connection.close(); messagebox.show("sales details imported successfully!");

javascript - Highcharts proper usage of datetime? -

my current setup static xaxis categories , tickinterval(cant see graph without tickinterval). if change screen resolution looks bad , have x-axis dynamic. what i've gathered should use data http://www.highcharts.com/samples/data/usdeur.js , xaxis below? xaxis: { type: 'datetime' } but example uses yymmdd, use hh:mm:ss. currently looks this: i.imgur.com/v649otj.png xaxis: { categories: getjson('date'), tickinterval: 20 }, series: [ {name:'cars', data: getjson('values')}, ] data: getjson('date') equals: array [ "2014-11-09 02:36:00", "2014-11-07 07:35:00", "2014-11-08 20:29:00", "2014-11-08 20:30:00", "2014-11-10 11:06:00", "2014-11-08 08:12:00", "2014-11-08 20:31:00", "2014-11-08 20:23:00", "2014-11-08 20:24:00", "2014-11-08 20:25:00", 190 till… ] getjson('values') equals: array [ 13, 20

node.js - Karma: Catch errors using jasmine & grunt -

i have problems me special grunt-karma-requirejs-jasmine setup. have , running , long test defined in spec-files ist working perfect, resulting in junit-xml-file showing me test success , test failures. now problem: if there problem scripts tests run on (e.g. variables undefined, modules not available --> causes normal browser throw error), karma stops throwing error, default behaviour. want karma is, not stop, log it's errors junit-xml-file => have 3 types of states (success, failure, error) in xml , not on console. how can i: - karma custom handle errors? - karma tell karma-junit-reporter log? any appreciated! lot guys!

java - Significance of class loader in loading resource bundle -

i having difficulty in understanding significance of classloader in resourcebundle.getbundle(bundlename, locale, classloader) api . what practical scenario want provide custom loader api? a java application might have multiple class loaders. example, j2ee application running on tomcat or glassfish has multiple tiers of classloaders - belonging j2ee server itself, being made webapp (otherwise webapp able access classes belonging other webapps) , custom classloaders might have instantiated yourself. standalone java apps might have multiple classloaders. example, if application supports plugins , each of these plugins contained in own jar file (local or remote) in order load plugin's classes @ runtime have create own classloaders so. therefore, when load resourcebundle have select appropriate classloader ensure resource loaded correct source. here's simple example... imagine application contains /version.properties file , jvm has similar, yet different, /vers

c++ - error: no class template named 'rebind' in 'class std::basic_string<char>' -

i getting error when define function.i'm not using template class yet getting error. #include <string> #include <vector> using namespace std; void myclass::setoptions(vector<std::string,std::string> opts) { // int size = opts.size(); // this->dropdown = new string[size][size]; } and there no error in header file if declare function: void setoptions(vector<string,string> ); std::vector<std::string, std::string> should be: std::vector<std::string> (one dimension) or std::vector<std::vector<std::string>> (two dimension). the second template argument of std::vector allocator use, , std::string not allocator.

Removing space from string with regex -

i can find spaces in following string: "____input abc" << please note there 4 spaces @ beginning of string using regex: [a-z] [a-z] how can replace"t f" "tf" , "m a" "ma"? guess have use groups don't remember how. advice appreciated. p.s. please note there 4 spaces @ beginning of string don't want remove them. depending on language using, should have "replace" function you have use capturing group, : ([a-z]) ([a-z]) http://www.regular-expressions.info/refcapture.html and use function them in pattern want : newstring = oldstring.replace("([a-z]) ([a-z])", "\1\2") \x reference xth group of parenthesis

java - Turning off IE 8 compatiblity mode -

my company uses ie8 default browser , default compatibility mode set intranet sites. i have checked application on ie8 , , feel totally hap hazard. on chrome , mozilla , feel fine. some 1 suggested me turn off compatible mode. there 2 ways : 1) ie>tools>compatible view settings > ( unchecked ) display intranet sites... 2) put <meta http-equiv="x-ua-compatible" content="ie=edge" /> on jsp pages. i checked , application looks fine when turn off compatibility mode. my questions : 1) use of compatibility mode. 2) if turn off through jsp page, other impact. ( on ie11 , if change compatible ie9 application not work expected.) 3) turning off compatible mode solution or there else can do 4) there other impact. from linked msdn page: internet explorer 8 supports many compatibility modes enable different supported features , affect manner in content rendered. example, ie5 mode renders content if displayed windo

unit testing - How to test hbase mapreduce code? -

class reduce { private htable table = null; protected void setup() { table = new htable(context.getconfiguration,"tablename"); } public void reduce() { ... } } i'd write unit test above code, not know how mock htable, run error (not find hbase-default.xml error..). think happened in new htable(). there methods mock object , pass reduce class? now i'm using junit, mrunit, powermock+mockito.

windows - Disable terminal escape sequences in node.js output -

Image
i'm using karma on node.js run tests part of build script. when running command standalone, looks this: however, when run part of build job becomes this: testjs: node node_modules\karma\bin\karma start lib\tests.conf.js ←[33mwarn [karma]: ←[39mport 19876 in use ←[32minfo [karma]: ←[39mkarma v0.12.28 server started @ http://localhost:19877/ ←[32minfo [launcher]: ←[39mstarting browser phantomjs ←[32minfo [phantomjs 1.9.8 (windows 8)]: ←[39mconnected on socket tw-csawb8prcsvl-qysr id 81276065 which gets bit hard read. apparently node has sort of support translating ansi escape sequences windows console apis, gets lost when redirecting or capturing output (the file written when doing shell redirect contains escape sequences well). is there way suppress colours? node --help mentions $env:node_disable_colors , however, seems repl , doesn't me running script. nevermind, found line in karma config: // enable / disable colors in output (reporters , lo

ios - launch screen xib -

Image
i found easy way adaptive iphone4/4s,5,6,6p size. delete launchscreen.xib in projecttagets->app icons andlaunch images add default images (iphone4/4s,5) size after can adaptive iphone size ever have not use autolayout . question: why can adptive ever have not use autolayout ? what harm there in way ? which best way adaptive iphone size ? autolayout layout engine, has nothing resolution of device. when ios launches app, check if app has launch image targeted on specific device(prior ios 8) or launch screen xib file (ios 8). if finds it, ios run app in native resolution of current device. because launch screen xib uses size class, can use 1 launch screen xib adopt different resolution devices. since launch screen works in ios 8, if use support different resolution, have sure support ios 8. if want support older ios versions can not use launch screen xib. if want app run on ios 8 devices, it's fine use launch screen xib. if that's not case, sho

xml - how to force android to read newst file from server? -

in app read xml online using following code , works fine: url url = new url("http://dl.1kolbe.ir/adv.xml"); documentbuilderfactory dbf = documentbuilderfactory.newinstance(); documentbuilder db = dbf.newdocumentbuilder(); document doc = db.parse(new inputsource(url.openstream())); doc.getdocumentelement().normalize(); nodelist nl = doc.getelementsbytagname("item"); node node = nl.item(i); element fstelmnt = (element) node; nodelist namelist = fstelmnt.getelementsbytagname("title"); element nameelement = (element) namelist.item(0); namelist = nameelement.getchildnodes(); final string adv_title = ((node) namelist.item(0)).getnodevalue(); but when change xml data on server, app display old xml data. think have clear cache, don't know how! i find trick solve it! add random , unused argument url, android think of new url: time = new time(); now.settonow(); string time = "" + now.hour + now.minute + now.second; int time_int = in

php - Checkbox value does not show in confirm popup javascript -

i have made email sending form , in confirmation popup window show preview email information user. in code form text input show correctly, no data show checkbox in preview pop window.i need show checkbox data in confirm box. thanks all here code index.php <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title></title> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport"> <script src="js/jquery_003.js"></script> <script src="js/mail.js"></script> </head> <body style="margin: 0px;"> <div class="onedari_form_wrapper info_form_wrapper ajast_onedari_form mgt0"> <form id="contactform"> <div class="form_

Make function shorter in Haskell -

is possible away variable x in function?: numocc x = map (length.filter(==x)) for example if have function: numocc x l = map (countt x) l i can away variable l , this: numocc x = map (countt x) thanks help. you can use "pointfree" program answer questions this > pointfree "numocc x = map (length . filter (==x))" numocc = map . (length .) . filter . (==) edit here in action > let numocc x = map (length . filter (==x)) > let numocc' = map . (length .) . filter . (==) numocc 'a' ["aa", "bb"] --outputs [2, 0] numocc' 'a' ["aa", "bb"] --also outputs [2, 0] basically, counts number of param1's in each element in list items of param2 numocc 'a' ["aa", "bba"] --outputs [2, 1] numocc' 'a' ["aa", "bba"] --also outputs [2, 1]

java - Does Hibernate SQLQuery restrict the results with native features when using setMaxResults to limit results -

when using sqlquery setmaxresults() method limit number of records returned, hibernate limit results using native features of database top or limit keywords or hibernate limit results @ library layer after results returned? thanks, keshav the number of records returned done @ query level. uses database keywords limit restrict number of rows returned. you can turn on hibernate.show_sql fetature , see generated query. code: sqlquery sqlquery = session.createsqlquery("select * request_t"); sqlquery.setmaxresults(10); list results = sqlquery.list(); hibernate generated query: /* dynamic native sql query */ select * request_t limit ? hibernate: /* dynamic native sql query */ select * request_t limit ?

How to generate random string with no duplicates in java -

i read answers , use set or other data structure ensure there no duplicates. situation , stored lot random string in database , have make sure generated random string should not existed in database . and don't think retrieve random string database set , generated random string idea... i found system.currenttimemillis() generate "random" number , how translate number random string question...i need string length 8. any suggestion appreciated you can use apache library this: randomstringutils randomstringutils.randomalphanumeric(8).touppercase() // alphanumeric randomstringutils.randomalphabetic(8).touppercase() // pure alphabets randomalphabetic(int count) creates random string length number of characters specified. randomalphanumeric(int count) creates random string length number of characters specified.

C++ Program with JNI invoking failed to run in gdb -

this question has answer here: why java app crash in gdb runs in real life? 1 answer i wrote c++ program. invokes functions provided libhdfs(hdfs api c++, implemented jni) , runs ok when executed. when use gdb launch program , input run command. program fails run , got following error message in gdb context: [thread debugging using libthread_db enabled] [new thread 0x40100940 (lwp 18482)] [new thread 0x40201940 (lwp 18483)] ... [new thread 0x41514940 (lwp 18502)] program received signal sigsegv, segmentation fault. 0x00002aaaac26c862 in ?? () i use command shell echo $classpath in gdb context. shows correct hdfs related environment. i searched google , stackoverflow. did not idea. any tip? why java app crash in gdb runs in real life? provided solution: handle sigsegv nostop noprint pass while, not elegant.

.net - Outlook.MailItem fails sometimes -

while iterating through email items, system cannot mail item same email item in next run. below sample of code using mail items. var oapplicationclass = new application(); namespace namespace = oapplicationclass.getnamespace("mapi"); outlook.mapifolder inbox = namespace.getdefaultfolder(oldefaultfolders.olfolderinbox); outlook.mapifolder deleteditems = namespace.getdefaultfolder(oldefaultfolders.olfolderdeleteditems); mailitem mailitem; var safemail = new redemption.safemailitem(); items outlookitems = inbox.items.restrict("[messageclass] = \"ipm.note\""); int totalcount = outlookitems.count; string subject = ""; bool filtermessage = filters.count > 0; if (totalcount > 0) { (int = 1; <= totalcount; i++) { outlookitems.sort("[receivedtime]", sortascend

asp.net - Gridview Footer Button Disbale it show Error as Object reference not set to an instance of an object -

hai every 1 new asp.net. question have gridview textboxs in itemtempleates , single button in footer.when click button in gridview rows added manually, , ny coding <asp:gridview id="gridview2" runat="server" showfooter="true" autogeneratecolumns="false" onselectedindexchanged="gridview2_selectedindexchanged"> <columns> <asp:boundfield headertext="s.no" datafield="rownumber" /> <asp:templatefield headertext="description"> <itemtemplate> <asp:textbox id="textbox132" runat="server"></asp:textbox> </itemtemplate> </asp:templatefield> <asp:templatefield headertext="smv"> <itemtemplate> <asp:textbox id="textbox133" runat="server&qu

language agnostic - Is floating point math broken? -

0.1 + 0.2 == 0.3 -> false 0.1 + 0.2 -> 0.30000000000000004 why happen? binary floating point math this. in programming languages, based on ieee 754 standard . javascript uses 64-bit floating point representation, same java's double . crux of problem numbers represented in format whole number times power of two; rational numbers (such 0.1 , 1/10 ) denominator not power of 2 cannot represented. for 0.1 in standard binary64 format, representation can written as 0.1000000000000000055511151231257827021181583404541015625 in decimal, or 0x1.999999999999ap-4 in c99 hexfloat notation . in contrast, rational number 0.1 , 1/10 , can written as 0.1 in decimal, or 0x1.99999999999999...p-4 in analogue of c99 hexfloat notation, ... represents unending sequence of 9's. the constants 0.2 , 0.3 in program approximations true values. happens closest double 0.2 larger rational number 0.2 closest double 0.3 smaller rational number 0.3 . sum

javascript - Angular custom directive: a strange error occurs when set controller attribute to `function(scope){}` -

when wrote custom directive, strange error blocks me. angular.module('app.directives', []) .directive('cymenu', ['recursionhelper', function(recursionhelper) { function postlink(){}; return { restrict: 'e', templateurl: 'views/component/cy-menu.html', replace: true, transclude: false, require: '?^cymenu', controller: function ($scope) { // when set argument($scope) scope, error occurs. this.getlist = function() { return $scope.list; } }, scope: { list: '=', issubmenu: '@' }, compile: function(telement) { return recursionhelper.compile(telement, postlink); } } } as pointed out(see comment), when set controller attribute controller: function (scope) {} , error occurs: error: [$injector:unpr] unknown provider: scopeprovider <- scope http:/

Clojure: map as function parameter -

i'm trying running codes book "web development clojure". there function can not understand: (defn handle-upload [{:keys [filename] :as file}] (upload-page (if (empty? filename) "please select file upload" (try (upload-file (gallery-path) file) (save-thumbnail file) (db/add-image (session/get :user) filename) (image {:height "150px"} (str "/img/" (session/get :user) "/" thumb-prefix (url-encode filename))) (catch exception ex (str "error uploading file " (.getmessage ex))))))) where (defn upload-page [info] (layout/common [:h2 "upload image"] [:p info] (form-to {:enctype "multipart/form-data"} [:post "/upload"] (file-upload :file) (submit-button "upload")))) what meani

Setting value in variable provided while creating paypal buy button -

i have paypal buttom generated buy.the scripts contains variable values provided want provide value variables dynamically. this buy button generated. <script data-callback="http://sajilobazar.com" data-tax="3" data-shipping="1" data-currency="usd" data-amount="45" data-quantity="1" data-name="helo" data-button="buynow" src="https://www.paypalobjects.com/js/external/paypal-button.min.js?merchant=*****@yahoo.com" async="async"> </script> as seen in above code variables data-tax pre populated.i want provide own value. this tried var x= "3"; data-tax=x but won't work.please help!!! you can use data-tax-editable makes tax editable , enter value pass dynamic tax variable. eg: <script data-callback="http://sajilobazar.com" data-tax-editable="3" data-shipping="1" data-currency="us

php - Pass array as var -

i have function using based on example @ https://wordpress.org/plugins/custom-list-table-example/ this sets array this... var $example_data = array( array( 'id' => 1, 'title' => '300', 'rating' => 'r', 'director' => 'zach snyder' ), array( 'id' => 7, 'title' => 'watchmen', 'rating' => 'r', 'director' => 'zach snyder' ) ); i trying replace own function creates array this... function create_array() { $count1 = $wpdb->get_results("select count(*) totalvaluecount, value thevalue, date(date_created) thedate wp_rg_lead inner join wp_rg_lead_detail on wp_rg_lead.id = wp_rg_lead_detail.lead_id

javascript - Cordova multiple image upload with File Transfer -

i'm on cordova , jquery mobile project. i've been able upload 1 image file transfer plugin. try upload 2 or 3 images following. here html code: <label for="image">pictures:</label> <a href="" id="image1button" class="ui-btn" onclick="getphoto(picturesource.photolibrary);">get first picture</a><br> <a href="" id="image2button" class="ui-btn" onclick="getphoto(picturesource.photolibrary);" style="display:none;">get second picture</a><br> <a href="" id="image3button" class="ui-btn" onclick="getphoto(picturesource.photolibrary);" style="display:none;">get third picture</a><br> <img id="image1" style="display:none;width:25%;"> <img id="image2" style="display:none;width:25%;"> <img id="image3" styl

process - CPU scheduling algorithms and arrival time -

i looking @ examples found on website : http://www.tutorialspoint.com/operating_system/os_process_scheduling_algorithms.htm and there's doesn't make sense examples. take shortest-job-first example. premise take process least execution time , run first. the example runs p1 first , p0. why? @ t = 0 process exists in queue p0. wouldn't start running @ t = 0, , p1 start @ t = 6? i've got same issue priority based scheduling. you right , since process p0 has arrived @ queue @ 0 sec , before p1 , start executing before p1 . their answer correct if there no arrival time corresponding process , in case , considered processes have reached @ queue @ same time .so, process shortest executing time executed cpu first .

python - End of line in CSV -

i trying read csv file processing in python. want associate values of cities state in dictionary present in csv comma separated. after getting name of state want cities values want know end of line of file. my structure of csv : state,city1,city2,city3,city4,city5,..,cityn since states may not have values cities, city values empty. if iterate on file, automatically yield each line; in other words don't need know line ends: from collections import defaultdict d = defaultdict(list) open('somefile.csv') f: line in f: # automatically step on each line correctly bits = line.split(',') d[bits[0]] += bits[1:] state,cities in d.items(): print('{} has {} cities: '.format(state, len(cities)) city in cities: print('\t{}'.format(city))

ruby - Rails editing migration to ignore an error -

i have app posts, users, tags , such. i've been working on locally , have not been able push heroku because of issue. in end, succeeded in pushing app heroku, realised never migrated database there. ran heroku run rake db:migrate and got error: == 20141116151429 createposts: migrating ====================================== -- drop_table(:posts) pg::undefinedtable: error: table "posts" not exist : drop table "posts" rake aborted! standarderror: error has occurred, , later migrations canceled: pg::undefinedtable: error: table "posts" not exist i looked migration , reason, had drop tables line before else: class createposts < activerecord::migration def change drop_table :posts create_table :posts |t| t.string :title, null: false, default: "" t.text :description, null: false, default: "" t.timestamps end end end i commented out drop table line, deleted , commit using

c# - InMemoryMultiaprtFormDataStreamProvider and Azure file sizes -

i'm using solution post , it's working me image sizes when testing locally. when deploy azure cloud service can handle files 50k, larger , solution hangs. i've attempted debug using remote azure debugger , code hanging on following line of code. var provider = await request.content.readasmultipartasync<inmemorymultipartformdatastreamprovider>(new inmemorymultipartformdatastreamprovider()); i've found exception thrown of: first chance exception of type 'system.accessviolationexception' occurred in system.net.http.formatting.dll as said, works fine locally in emulator not on azure platform..? can provide insight this? i've tried adding following web.config no luck... <system.web> <httpruntime targetframework="4.5" maxrequestlength="32768" /> </system.web> <system.webserver> <security> <requestfiltering> <requestlimits maxallowedcontentlength="4294967295"

scripting - More precedence- Shebang line or perl command? -

i have multiple perl scripts shebang line outdated. thats is, shebang points older version of perl. old per path: #!/data/oracle10.0/perl/bin/perl the new version of perl in #!/data/**oracle11.0**/perl/bin/perl i have softlinked perl command location of new version of perl. perl -> /data/oracle11.0/perl/bin/perl now, shebang points older version , perl command points newer version. so, when perl sample.pl , shebang gets ignored. i wrote sample scripts see that. seems shebang line ignored when used perl command. remember not case older version of perl (shebang considered on perl command). so question is, did new version of perl(5.10) , older version (5.8) have different behaviour respect shebang line? new version of perl ignore shebang line if perl command passed it? when run perl myscript.pl starts perl binary , gives myscript.pl input, runs. in case, always first perl binary $path , regardless of perl version. mpapec said in comment, can d

Design Pattern for extensible entity -

i developing application hotel reservation have model called "hotel" has name, description, rate, @ moment want design in way able plugin more simple , complex properties model example address, amenities, or user model , right have name , lastname user , password , want able add other properties in plugable way . is there pattern ? builder pattern / observer pattern? take @ martin fowler's description of dynamic properties (pdf) , user defined fields . can use simple hash table (aka dictionary) hold dynamic properties, depending on language (and implementation) "class schema" won't clear.

Access query: Where IIF function -

i have query select invoice.number, invoice.amount, invoice.paid, iif (invoice.paid='y', max(payments.datepay), '') invoice_paid payments inner join invoice on (invoices.number = payments.numberdoc , payments.type = 'invoice') payments.type= 'invoice' group number, amount, paid runs fine. sample results: number | amount | paid | invoice_paid 00000003 | 347,94€ | y | 23/05/2014 00000004 | 462,65€ | n | 00000005 | 462,65€ | y | 13/08/2014 00000006 | 453,88€ | y | 03/09/2014 00000007 | 155,57€ | y | 04/09/2014 00000008 | 500,00€ | n | but need filter "invoice_paid" date. if execute this: select invoice.number, invoice.amount, invoice.paid, iif (invoice.paid='y', max(payments.datepay), '') invoice_paid payments inner join invoice on (invoices.number = payments.numberdoc , payments.type = 

laravel - How make multiple subqueries with Eloquent? -

a have code: db::select(' select sum(count) count ( select count(*) count ad_banners union select count(*) count ad_context union select count(*) count ad_content union select count(*) count ad_decoration union select count(*) count ad_front union select count(*) count ad_universal ) ad' ); how make query using eloquent orm methods , make sense? in advance! edit: i wrote code, attempts use eloquent ended fail. don't understand how make sub queries union , count. didn't wont write code me, enough small example. , sorry bad english. have tried using db::raw() method? sometimes, if know sql want use don't know how use eloquent accomplish it, may use db::raw() results need. here's example, can tailor needs: $query = db::connection('connection_name')->select(db::raw(

sql server - What is the best way to toggle user defined column name or default column name in stored procedure -

what best approach stored procedure toggle between user defined column names or default column name here have done far. fine small query, there better way of doing larger query. -- drop stored procedure if exists if exists(select * sys.procedures schema_id = schema_id('dbo') , name = n'sp_test') drop procedure dbo.sp_test go create procedure [dbo].[sp_test] -- /* declare parameters */ @columnname bit =0 begin -- select statement fetch record if(@columnname =1) ( select top 100 im.inc_ref, im.id dbo.test im ) else ( select top 100 im.inc_ref ref, im.id id dbo.test im ) end go -- ============================================ -- execute stored procedure -- ============================================ declare @columnnam

php - Can't call ajax POST request inside FB.api -

for facebook login i'm using code fb.api('/me', {fields: 'birthday,cover,devices,email,first_name,gender,id,last_name,link,location,name,name_format,timezone,verified,website,locale'}, function(response) { $.ajax({ url: '/login/facebook', type: 'post', data: { fb: response, window: window.ui}, datatype: 'json', success: function (data) { console.log(data); }, error: function (xhr, ajaxoptions, thrownerror){ notice(xhr); notice(ajaxoptions); } }); }); if i'm calling without {fields: '...'} working when added fields ajax sending request server instead of post, how response desired fields fb.api

javascript - how to call external .js which is inside document.ready by passing in variables from html to call the .js file below -

i'm trying modify function found online. inside document.ready function , if try use function functionname(variable1,... variablen){} instade of $(document).ready(function(){} it fails. code works pass in variables more stuff. here code , pass in variable. highly appreciated $(document).ready(function(){ $(".content-slider").slider({ animate: true, change: handlesliderchange, slide: handlesliderslide }); }); function handlesliderchange(e, ui) { var maxscroll = $("#content-scroll").attr("scrollwidth") - $("#content-scroll").width(); $("#content-scroll").animate({scrollleft: ui.value * (maxscroll / 100) }, 1000); } function handlesliderslide(e, ui) { var maxscroll = $("#content-scroll").attr("scrollwidth") - $("#content-scroll").width(); $("#content-scroll").attr({scrollleft: ui.value * (maxscroll / 100) }); } all functions above in 1 .js

php - Select all items for category and all from its subcategories -

i'm trying build own webshop. have 2 tables - products , categories. structure : categories : id name parent_id products : id title category_id at moment when user clicks on main category i'm selecting products display : url : www.mypage.com/?category_id=1 sql : 'select * products category_id = 1' the problem i'd make when user clicks on main category select products child categories. example category family sub category of category cars , in db looks categories : id name parent_id 1 'cars' 0 2 'family' 1 3 'sport' 1 products : id title category_id 1 'ferrari' 3 2 'honda' 2 as can see current select not select ferrari or honda because user looking @ category id=1 ... how modify select display products child categories of main category? "select * products category_id = '

Is it possible in MATLAB to create a 3D array from a function which returns 2D arrays without using a loop? -

i have matlab function f(w) returns (n x n) square matrix. have vector ws = [w_1, w_2, ... w_m] contains m parameters w_i . create 3d array contains m "planes" f(w_i) . possible in matlab using arrayfun() et al. create 3d array without using for loops iterate on parameter vector ws , concatenating results? if want see how few functions can used, here's approach arrayfun , cell2mat , reshape combined (i changed last line according daniel's comment): f = @(w) [w 2*w; 3*w 4*w]; %// random function returns array of fixed size w = 1:4; %// random input function out = cell2mat(reshape(arrayfun(@(x) f(w(x)), w, 'uniformoutput', 0),1,1,[])); you (probably fastest of these approaches, there faster approaches): out = f(reshape(w,1,1,[])) or use loop (notice order of loop): for ii = numel(w):-1:1 out(:,:,ii) = f(w(ii)); %// no pre-allocation necessary end or more traditional loop approach: out = zeros(2,2,4); %// pre-alloca

php - doesn't return exact value -

email value passed 1 page through following $.ajax({ type:'post', url:'email.php', data:{email: email}, success:function(msg){ alert(msg); } }); $s show email id.i echoed $echeck , $echk testing. $echk doesn't return 1. $s=$_post['email']; echo $echeck="select email register email=".$_post['email']; echo $echk=mysql_query($echeck); echo $ecount=mysql_num_rows($echk); you need quote string value in sql queries. echo $echeck="select email register email='".$_post['email']."'";

php - How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters? -

is there function in php can decode unicode escape sequences " \u00ed " " í " , other similar occurrences? i found similar question here doesn't seem work. try this: $str = preg_replace_callback('/\\\\u([0-9a-fa-f]{4})/', function ($match) { return mb_convert_encoding(pack('h*', $match[1]), 'utf-8', 'ucs-2be'); }, $str); in case it's utf-16 based c/c++/java/json-style: $str = preg_replace_callback('/\\\\u([0-9a-fa-f]{4})/', function ($match) { return mb_convert_encoding(pack('h*', $match[1]), 'utf-8', 'utf-16be'); }, $str);