Posts

Showing posts from January, 2014

node.js - How to Execute SQLite Queries on Firefox Mobile Profile Data -

thanks time. i on firefox mobile. i plan use restartless approach using add-on node.js tools. i need pull profile data in app, of requires direct sql due spotty mobile support according to: https://developer.mozilla.org/en-us/add-ons/sdk/tutorials/mobile_development i plan use indexed-db, thinking give me ability run sqlite queries against existing user profile data (mostly needed reading). am on right track? have seen simple-storage. better tool?

javascript - Have only 1 div toggle instead of all -

running issues of trying have 1 div toggle instead of them toggle. i've tried using next() , setting selector children opposed parent element, won't toggle open @ all. fiddle: http://jsfiddle.net/l415g07n/2/ what trying accomplish? have selected div toggle when .toggle clicked instead of of them being toggled @ once. var c1 = $("#o"); var c2 = $("#t"); var c3 = $("#th"); $(document).ready(function () { $(c1).hide(0).delay(500).fadein(1500); $(c2).hide(0).delay(1500).fadein(1500); $(c3).hide(0).delay(2500).fadein(1500); }); var content = $("#main .column .body"); $(content).hide(); var t1 = $(".toggle"); $(t1).click(function () { $(content).slidetoggle('slow'); $(t1).toggleclass("toggle"); $(t1).toggleclass("toggle-d"); }); try use this object , traverse required nodes, $(t1).click(function () { $(this).toggleclass("toggle") .toggl

java - Why do my program files say (x86) but my processor and operating system is a x64 bit -

i'm trying allocate more ram minecraft server , i'm wondering if i'm having problems thy java @ pc info , says have 64 bit operating system , 64 bit processor when go program files says have 32 bit. i've tried downloading java 7 , 8 still wont wok should trying download 32 bit java i've downloaded 64 bit version of everything. you have 2 catalogues: 'program files' , 'program files (x86)'. first 1 should contain 64-bit applications. other 1 contains 32-bit applications. normal , doesn't mean have 32-bit system.

c++ - boost::signals2::signal gives wrong output? -

i'm new boost library, while practicing example on bind, wrote following code. but, seems 'res' computed but, correct result not transmitted signal. kindly help, wrong in following snippet. the code compiled , run on http://cpp.sh/ #include <iostream> #include<boost/signals2.hpp> using namespace std; class mathobject{ public: int addops(int op1, int op2); }; int mathobject::addops(int op1, int op2){ int res = op1 + op2; cout << "result of addops: " << res << endl; return res; } int main(void){ mathobject mobj; boost::signals2::signal<int(int)> incrementer; incrementer.connect(boost::bind(&mathobject::addops, &mobj, 1, _1)); boost::signals2::signal<int(int)> doubler; doubler.connect(boost::bind(&mathobject::addops, &mobj, _1, _1)); cout << "incrementer of 5" << incrementer(5) << endl; cout << "doubler of 5" <

ionic framework - Change background transparency of Chart.js chart -

i'm using chart.js wrapped within angular-charts.js create bar chart in ionic framework app. i want make bar background totally opaque. this code have create chart. <canvas id="bar" class="chart chart-bar" data="data" labels="labels" legend="true" series="series" options="{showtooltips: false}" colours="[ '#ffff00', '#0066ff']"></canvas> have idea of how achieve that? thanks lot! colours should array of color objects (not array of color strings). need [ { fillcolor: '#ffff00' }, { fillcolor: '#0066ff' } ] <canvas id="bar" class="chart chart-bar" data="data" labels="labels" legend="true" series="series" options="{showtooltips: false}" colours="[ { fillcolor: '#ffff00' }, { fillcolor: '#0066ff' } ]"></canvas> fiddle - http

Command linux "Date" into perl script -

i must implement perl script makes use inside linux command 'date' use current date reference date identification of events stored in file. please. know function localtime() don't need explicitly linux command date. this not way current time in perl, answer narrowly defined question above. here working: $ perl date-test <<mon aug 31 06:52:08 pdt 2015>> here code: $ cat date-test #!/usr/bin/perl use strict; use warnings; $static_date = `date`; chomp($static_date); print "<<$static_date>>\n";

javascript - How to reload page without _layout query string parameter -

page url in form http://example.com/myapp?param1=1&otherparam=somevalue1&_layout=somevalue2&someother=something page contains button "reset layout" invokes javascript code: window.location.reload(); how reload page without _layout=somevalue2 parameter ? possible/reasonable use javascript ? asp.net mvc3 application. if javascript not reasonable, how call server side controller ? jquery , bootstrap 3 used. you can use regular expression , remove instance of _layout location.href=location.href.replace(/&?_layout=([^&]$|[^&]*)/i, "");

Angular 2.0 lifecycle and Typescript -

i have angular 2.0 component , wanted add lifecycle events (angular 2.0 alfa 35). i looking @ post reference, typescript gave me errors using import {component, view, eventemitter, oninit} 'angular2/angular2'; (error on oninit ). quick @ angular2 code revealed export uses oninit (with capital o ). changed import code lifecycle event still oninit . component (i cannot make oninit event happen): import {component, view, eventemitter, oninit} 'angular2/angular2'; @component({ selector: 'theme-preview-panel-component', properties: ['fontsize'], lifecycle: [oninit] }) @view({ templateurl: '../components/theme-preview-panel-component/theme-preview-panel-component.tpl.html', }) export class themepreviewpanelcomponent { fontsize: string; constructor() { } oninit() { //this code not being called } } edit as @eric martinez mentioned below, solution is: import {component, view, eventemitter, lifecycleevent} 

javascript - Meteor checkbox - Display Value of expression as String, not interpreted as Boolean -

Image
i have checkbox implemented , it's working fine. html: <form> <ul> {{#each checkbox}} <li> <input type="checkbox" checked="{{checked}}" class="toggle-checked"> {{name}}: {{checked}} </li> {{/each}} </ul> </form> js: cbtest = new mongo.collection('cbtest'); template.checkbox.helpers({ checkbox: function () { return cbtest.find(); } }); template.checkbox.events({ "click .toggle-checked": function () { var self = this; meteor.call("setchecked", self._id, !self.checked); } }); meteor.methods({ setchecked: function (checkboxid, setchecked) { cbtest.update(checkboxid, { $set: { checked: setchecked } }); } }); i want display value ("true" or "false") depending on checkbox's state. seems expressio

objective c - iOS parse black strip on profile picture (PFImageView) -

Image
i using parse backend of app, , seems profile photo not displaying properly, shown in image: there black strip on john_appleseed's photo. here code saving profile image: nsdata *profiledata = uiimagepngrepresentation(cell1.profileview.image); pffile *profilefile = [pffile filewithname:@"profilephoto" data:profiledata]; [profilefile saveinbackgroundwithblock:^(bool succeeded, nserror *error) { if (!error) { if (succeeded) { [user setobject:profilefile forkey:@"profilephoto"]; [user saveinbackgroundwithblock:^(bool succeeded, nserror *error) { if (!error) { } else { } }]; } } }]; here how retrieve image:(inside pfquerytableviewcontroller) - (pfquery *)queryfortable { //n

python - Pull from a list in a dict using mongoengine -

i have document in mongo engine: class mydoc(db.document): x = db.dictfield() item_number = intfield() and have data document { "_id" : objectid("55e360cce725070909af4953"), "x" : { "mongo" : [ { "list" : "lista" }, { "list" : "listb" } ], "hello" : "world" }, "item_number" : 1 } ok if want push mongo list using mongoengine, this: mydoc.objects(item_number=1).update_one(push__x__mongo={"list" : "listc"}) that works pretty well, if query database again this { "_id" : objectid("55e360cce725070909af4953"), "x" : { "mongo" : [ { "list" : "lista" }, { "list" : "li

android - TabLayout versus pagerTabStrip for convenience and functionality -

when using viewpager, there advantage using tablayout instead of pagertabstrip or vice versa? or equivalent? 1 more convenient other? 1 offer greater functionality? again questions asked, , answers expected, in context of viewpager. thanks. tablayout material concept replaced deprecated actionbar tabs in android 5.0. extends horizontalscrollview, can keep adding tabs horizontally can include text, icons, or custom views , scroll through them linearly without paging. tablayout provides setupwithviewpager(viewpager viewpager) method attach viewpager instead of being part of viewpager pagertabstrip. a pagertabstrip more of indictor current page of viewpager, , "it intended used child view of viewpager widget". scrolling not act tablayout since each tab part of page instead of individually horizontally scrollable.

ruby - &: syntax for methods with arguments -

i have nested array: a = [[1, "aldous huxley"], [3, "sinclair lewis"], [2, "ernest hemingway"], [4,"anthony burgess"]] a.collect { |author| author.drop(1) } outputs [["aldous huxley"], ["sinclair lewis"], ["ernest hemingway"], ["anthony burgess"]] while a.collect(&:drop(1)) gives me sintax error. syntaxerror: (irb):18: syntax error, unexpected '(', expecting ')' a.collect(&:drop(1)) ^ is possible define original block expression in &: syntax? the colon part of symbol in ruby, & magic makes syntax work, calling to_proc on object , using block. so, while can't use symbol :drop(1) , can accomplish without using symbol in 2 ways: 1) return proc method , pass in: def drop(count) proc { |instance| instance.drop(count) } end a.collect(&drop(1)) 2) pass in object responds to_proc : class drop def i

cmd - Batch File toggle menus -

im writing batch file , make toggle menu choices execute instead of common question , answer execution is there way make list of choices , toggle "run" or "off" them , hit enter start i found file seemed me in right direction dont know how make work batch file the code found is... @echo off set _on=0 :top cls if %_on%==0 (set _nlb= &set _nrb= &set _flb=[&set _frb=]) else (set _nlb= [&set _nrb=]&set _flb= &set _frb= ) echo '_on' flag currently: %_nlb% on %_nrb% %_flb% off %_frb% echo. echo press key toggle '_on' flag pause>nul if %_on%==0 (set _on=1) else (set _on=0) goto top id netusers [run] [off] netuseradministrator [run] [off] virus.exe [run] [off] press enter initiate selected. in type of layout if makes sense use choice command. example echo 1] settings echo 2] start echo 3] quit choice /c 123 /n if %errorlevel%==1 goto settings if %errorlevel%==2 goto start if %errorlevel%==3 got

Batch Invalid Number error? -

this strangest error i've ever encountered. while i've seen the: invalid number. numeric constants either decimal (17), hexadecimal (0x11), or octal (021). error million times, can't understand what's wrong code: if "%ss%" == "00" ( set /a 3n%1+=%3 set /a 3n%1+=%4 ) this gives: c:\users\...>if "00" == "00" ( set /a 3n2+=1 set /a 3n2+=3 ) invalid number. numeric constants either decimal (17), hexadecimal (0x11), or octal (021). i can't figure out why happening. note: when expression false, error still fires. the error comes fact variable name 3n2 starts number. while variable name technically valid, starting number bad idea , should never it . to avoid error, change first character of variable name letter or underscore. if "%ss%" == "00" ( set /a _3n%1+=%3 set /a _3n%1+=%4 )

html - CSS Flexbox on mobile messes up boxes -

i working on converting on flexbox , struggle lot. of so, able started , struggle part. works perfectly, far, except when view page on iphone 4 or samsung 3, messes up. on desktop, can resize , peachy, mobile, well, doesn't work well. have reduced as possible make shorter here. logo works fine, head_area , head_note drop underneath logo obviously. don't want. sure simple fix, daunting me @ moment. great appreciated. * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } html,body,address,blockquote,div, form,fieldset,caption, h1,h2,h3,h4,h5,h6, hr,ul,li,ol,ul,dd,dt, table,tr,td,th,p,img { margin: 0; padding: 0; } img,fieldset { border: none; } body { color: #cf6; margin: 0 auto; font-size: 1.0em; max-width: 1280px; overflow-y: scroll; text-transform: uppercase; font-family: "tahoma", verdana, sans-serif; background: #777 url(../homepics/home

How can I start a RTF editor from scratch(using Java) -

i know may sound silly of experienced guys out there it’s important me , group @ school, need create software allows user create new rtf document scratch (like editor can center, change font size, style, save, insert picture), needs able read docx document images , format included , save rtf document. what have done far being able open .docx document, extract text without format , put rtf document out. in other words using docx4j library have been able transform .docx document text .rtf, no pictures included, no formatting, plain text surrounded [ ]. we have made progress today can’t figure out next steps, considering delivery date in 72 hours, thought it’d idea ask more experienced people us. please leave answers or request info project, we’ll glad learn guys  to convert .docx .rtf use library https://code.google.com/p/jodconverter/ . heavy lifting you. anyway, editor itself. if had fast could, use javafx make interface. there control called "rich text edi

Exporting A Libgdx Game as Executable Jar from Android Studio -

okay made game using libgdx , intended android app(which why use android studio) want let friend without android phones try out. project setup both desktop , android there way export executable jar file? type command below in terminal. remember have in libgdx root directory, before issuing command. gradlew desktop:dist more at: https://github.com/libgdx/libgdx/wiki/gradle-on-the-commandline#packaging-for-the-desktop

php - Edit form for custom loop post -

so, have custom loop post. on page, have 10 posts below: <?php $args = array( 'post_type' => 'mail', 'paged'=>$paged, 'posts_per_page' => 10, 'mail_cat' => '', 'orderby' => 'date', 'order' => 'desc', ); $loop = new wp_query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); ?> each post gets title, content , price based on data-mail_id below: <div data-mail_id="' . esc_attr( $mail->id ) . '"> <?php the_title(); ?> <?php the_content(); ?> <?php echo $mail->get_price_html(); ?> </div> now, how can add edit form ( <form> ) edit post contents? i guessing need following: get <form> targeted post-mail_id data such title. change contents of post submit change update data specific post-mail_id . what guys think? edit 1: we

command line - How to define regions on an image and pass to tesseract-ocr? -

how can define regions on image, pass data tesseract-ocr's command-line , text within defined regions extracted? i'm guessing may similar use of image-map in html . thank in advance responses. i found out how pass in regions on image tesseract. although cannot done through command line, tesseract 3.02 api supports function setrectangle(int left, int top, int width, int height) allows restrict text extraction region specified. it must called after setimage() function. thanks again.

python - Add months to xaxis and legend on a matplotlib line plot -

Image
i trying plot stacked yearly line graphs months. have dataframe df_year below: day number of bicycle hires 2010-07-30 6897 2010-07-31 5564 2010-08-01 4303 2010-08-02 6642 2010-08-03 7966 with index set date going 2010 july 2017 july i want plot line graph each year xaxis being months jan dec , total sum per month plotted i have achieved converting dataframe pivot table below: pt = pd.pivot_table(df_year, index=df_year.index.month, columns=df_year.index.year, aggfunc='sum') this creates pivot table below can plot show in attached figure: number of bicycle hires 2010 2011 2012 2013 2014 1 nan 403178.0 494325.0 565589.0 493870.0 2 nan 398292.0 481826.0 516588.0 522940.0 3 nan 556155.0 818209.0 504611.0 757864.0

python - Post sentence - Info not reaching to web server -

the thing info i'm sending (alexis ahumada 1990) never stays on server log (www.inf.utfsm.cl/~mvaras/tarea1.log) i'd want know i'm doing wrong. #!/usr/bin/env python import socket import sys host = 'www.inf.utfsm.cl' = '/~mvaras/tarea1.php' ua = 'tarea1' port = 80 try: sock = socket.socket(socket.af_inet, socket.sock_stream) except socket.error, msg: sys.stderr.write("[error] %s\n" % msg[1]) sys.exit(1) try: sock.connect((host, port)) except socket.error, msg: sys.stderr.write("[error] %s\n" % msg[1]) sys.exit(2) sock.send("get %s http/1.0\r\nhost: %s\r\n\r\nuser-agent: %s\r\n\r\n" % (get, host, ua)) sock.send("post /~mvaras/tarea1.php http/1.0 user-agent:tarea1 nombre=alexis+ahumada&rut=1990") data = sock.recv(1024) string = "" while len(data): string = string + data data = sock.recv(1024) print string sys.exit(0) you cannot post server, have post

javascript - Rails 4 - Coffee script form helper & cross browser compatibility -

im using rails 4 make web app. i have form in projects view folder, has nested questions. if answer top level question true, further sub questions displayed. if answer false, sub questions related top level question remain hidden. i have form helper in javascripts folder has hide/show functions form. works fine when use chrome browser. doesn't work @ in safari. in safari, form elements, including supposed hidden @ start, displayed. how adjust form helper works on browsers? in js form helper file have: # source input attrs: {class: 'toggle_div', target: <target_id_or_class>} # toggle_radio attr : {class: 'toggle_div', target: <target_id_or_class>, toggle_reverse: <anything> } #$ -> # $(document).on 'change', 'input.toggle_div', ()-> # $($(this).attr('target')).toggle this.checked # # $(document).on 'change', 'input.toggle_radio', ()-> # reverse = $(this).attr('toggle_reverse

python - Trouble installing "distribute": NameError: name 'sys_platform' is not defined -

Image
i'm trying install python package "distribute". i've got downloaded , begins work, quits out error seen here: i have feeling solution somehow related me going in , defining sys_platform, don't have enough of grasp on what's actually wrong know fix. help! i'm blown away @ how helpful are. as stated burhan have install setuptools package: use command: pip install setuptools most importantly, do not forget uninstall distribute package (since tools provided package included setuptools ). just use command: pip uninstall distribute

Can this python code be expressed with list comprehension? -

i find following readable, wondering if more pythonesque manner accomplish (perhaps list comprehension)? import re cgi_keys = [ '_none___total', '_george___total', 'greg__total', '_geoff___total', '_gillian_total' ] pattern = re.compile(r"_(.+)___(.+)") totals = [] key in cgi_keys: m = pattern.match(key) if m: totals.append(m.groups()) totals which display: [('none', 'total'), ('george', 'total'), ('geoff', 'total')] but hoping figure out way above using construct such as: [key key in cgi_keys if pattern.match(key)] displaying strings in less useful form: ['_none___total', '_george___total', '_geoff___total'] is worth trying achieve breaking filtered strings tuples, or lists list comprehension? actually use: totals = (pattern.match(key) key in cgi_keys) totals = [match.groups() match in totals if match] which shorter

ruby - git submodules with rails directory structure -

i'd split rails using git submodule, far can tell, works directory. while works file structure similar python's django, each module has models.py, views.py, etc, doesn't appear work rails, gives directory structure there views folder, controllers folder, etc, each folder having 1 file module. is there way convert file structure similar django's, or if not, how use git submodules rails? how use git submodules rails? you not use them, not directly @ least. git submodule repo, checked out in own folder. if couple deployment script linked (symlink) files rails directory structure files submodule folder, rail app.

Greasemonkey script to replace text in html -

this question exact duplicate of: how relink/delink image urls point full image? 2 answers i want make greasemonkey script replace text in html this: <img src="http://example.com/image.jpg" data-gifsrc="http://example.com/image.gif"> to <img src="http://example.com/image.gif"> in website thechive.com please me, thanks. while cannot find data-gifsrc attribute on mentioned website, youi cannot assume jquery present , available greasemonkey. // attribute name var attrname='data-gifsrc'; // list images var imgs=document.getelementsbytagname("img"); // loop every images for(var i=0;i<imgs.length;i++) { // check attribute if(imgs[i].attributes[attrname]) { // set image source imgs[i].src=imgs[i].attributes[attrname].value; // remove attribute imgs[i].attributes.remove

python - how to make django module fully independent? -

look @ model class from django.db import models meeting.models import meeting # create models here. class agenda(models.model): name = models.charfield(max_length=255) meeting = models.foreignkey(meeting, on_delete=models.protect) priority = models.integerfield() here agenda, class needs meeting class foreign key. possible agenda class work if importing meeting class fail. if meeting class not found create default meeting object. you can conditionally, heavy caveats break , break between server restarts. from django.db import models try: meeting.models import meeting has_meetings = true except: has_meetings = false # create models here. class agenda(models.model): name = models.charfield(max_length=255) if has_meetings: meeting = models.foreignkey(meeting, on_delete=models.protect) priority = models.integerfield()

Why use sizeof(int) in a malloc call? -

i new c++ , in mpi programming. have confused code block in c++ int count; count=4; local_array=(int*)malloc(count*sizeof(int)); why using sizeof(int) here in mpi programming? i see you're trying allocate 4 int s here. if @ malloc 's signature, takes number of bytes first parameter. stated here , int data type takes 4 bytes. therefore, if want 4 int s, have typed local_array=(int*)malloc(count*4); . not remembers int actualy takes 4 bytes. that's why use sizeof find out actual size of object or type.

c# - .net core 2.0 error running console app on ubuntu -

i'm trying run first .net core 2.0 console app on ubuntu 16.04-x64. followed steps publish app ubuntu: dotnet publish -c release -r ubuntu.16.04-x64 and tried visual studio changing .csproj file so: <project sdk="microsoft.net.sdk"> <propertygroup> <outputtype>exe</outputtype> <targetframework>netcoreapp2.0</targetframework> <runtimeidentifiers>ubuntu.16.04-x64</runtimeidentifiers> </propertygroup> <itemgroup> <packagereference include="sharpadbclient" version="2.1.0" /> <packagereference include="system.io.ports" version="4.4.0" /> </itemgroup> </project> and publish publish profile. i followed instruction microsoft install .net core on ubuntu . copied published output pc running ubuntu ans when i'm trying run .dll file of console app i'm getting error: unhandled exception: system.io.fileloadexc

qt - Latest selected directory as default directory in QFileDialog -

how can set latest selected directory default directory in qfiledialog? you should store last selected directory in variable , use during next call of qfiledialog:: getopenfilename : qstring path = "/"; qstring filename = qfiledialog::getopenfilename(this, "open file", path); path = qfileinfo(filename).path(); // default directory directory previous call qstring anotherfilename = qfiledialog::getopenfilename(this, "open file", path);

java - How to set Timer when button clicked? -

i mean stopwach, when button clicked timer on until stop button pressed startbutton= (button)findviewbyid(r.id.black1); startbutton.setonclicklistener(new view.onclicklistener() { public void onclick(view v){ //start timer } }); stopbutton= (button)findviewbyid(r.id.black1); stopbutton.setonclicklistener(new view.onclicklistener() { public void onclick(view v){ //stop timer } }); and second question, if timer show 90 second how make show imageview or button in screen? if statement make button visible each timer count 90 second (90, 180, 270, etc..) set button visibility visible. thanks before. use chronometer in xml <chronometer android:id="@+id/chronometer1" android:layout_width="wrap_content" android:layout_height=&qu

c# - Is it possible that I can draw the Form window title text by myself? -

i want draw winform title text . there can it? only title text. i find out there way draw title : drawing own title bar , code confuse me, it's not form, , need re-draw title text. sorry short question. update: i'm using krypton toolkit form window skin now. that's why want draw title text keep other skin , style. you can't owner-draw only title text. either draw whole title bar (although it's more typical hide , draw custom component title bar , handle moving/resizing), or let windows draw it, can't just change way string title drawn. you draw title bar windows (and draw title text wanted), involves tons of api calls metrics , colors , it's not easy if want support several windows versions (even microsoft doesn't right time!) you can use ( custom window frame using dwm ) through p/invoke, , set form text nothing, draw whatever want on non-client area... that's how office it, again, it's lot of pain possibly not g

android - show pdf in webview not works -

i showing pdf google docs in webview. using url google drive. tried many formats google drive, have no luck. url link below https://drive.google.com/drive/u/0/folders/0bxd-5rffh6bufmniys16nfzkn2jmyzd3tjgtwmxleez2snlma2l2rdhmylnytdgtuxzodnm my activity class foloows" public class formwebviewactivity extends customwindow { int value; static string position_id = "position"; // webview webview; progressbar progressbar_webview; @suppresswarnings("deprecation") @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); try { webview webview = new webview(formwebviewactivity.this); webview.getsettings().setjavascriptenabled(true); webview.getsettings().setpluginstate(pluginstate.on); string pdfurl = "https://drive.google.com/drive/u/0/folders/0bxd-5rffh6bufmniys16nfzkn2jmyzd3tjgtwmxleez2snlma2l2rdhmylnytdgtuxzodnm"; // https://drive.google.com/file/d/0bxd-5rf

ruby on rails - Getting only file name as string -

Image
i trying upload file in rails i have created model following code def self.save(upload,id) name = upload[:img].original_filename directory = "public/user_db" # create file path path = file.join(directory, id) # write file file.open(path, "wb") { |f| f.write(upload['img'].read) } end end my view have following field. <div class="field"> <input type="file" name="img" id="img" placeholder="upload dp" /> </div> my controller calling save function following : post = datafile.save(params,@fbuser.id) but getting error do favor , don't reinvent wheel. in rails there 3 awesome gems handle file-uploading eatch having great community support , tons of shared code. carrierwave https://github.com/carrierwaveuploader/carrierwave paperclip https://github.com/thoughtbot/paperclip dragonfly https://github.com/markevans/dragonfly just fol

mysql - Update table if conditions met. (update the value from table b to a) corresponding value required -

this question has answer here: match 2 sql columns if = update different column 1 3 answers how 3 table join in update query? 4 answers i have table in have fields 'date', 'time', cost , order_id table b has fields 'year' 'month' 'hour' 'cost' , order_id fields. both tables linked "order_id" field. want update table if year, month, hour , order_id same in both tables , update corresponding value table b table field "cost" i have used statement, query not working? wrong in it? need help update item a, cost b set a.cost = b.cost a.order_id = b.order_id , year(a.date) = b.year , month(a.date) = b.month , hour(a.time) = b.hour update item join cost b on a.order_id = b.order_id

How to print multiple strings(with spaces) using gets() in C? -

in c program, call gets() twice input user. first time user asked enter fullname , second time user asked enter friends fullname. however, on second call of gets() , doesn't wait input user skips on , finishes program. here complete code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> int main() { char fullname[30]; char friendsname[30]; char sentence[70]= ""; char gender; printf("enter full name: "); gets(fullname); printf("\n"); printf("%s , please enter gender(m/f)? : ", fullname); scanf("%c", &gender ); puts("\n"); if(gender =='m') { printf("mr. %s , please enter friends name:", fullname); gets(friendsname); puts("\n"); } else if(gender =='f') { printf("mrs. %s , please enter friends name:", fullname); gets(friendsname); puts("\n"); } strcat(sentence, "hello mr.

pdf - Intriguing pdfgrep situation -

i'm having strange problem pdfgrep can't explain. have 400 kb ocr-scanned pdf-file. in file have placed 4 markers (mark_01, mark_02, mark_03 , mark_04). when open file in evince or adobe reader , search find match these 4 markers. however, when using command: pdfgrep -n "mark_01" file.pdf ....it returns nothing. though if edit command pdfgrep -n "mark_0" file.pdf ....it find 4 matches. it has same behaviour no matter marker search for. any ideas? /paul this behaviour indeed bug in poppler , rendering library pdfgrep uses. the fix committed on august 27 , in upcoming 0.36.0 release.

charts - Highcharts:Heatmap not show rectangle when single data-point -

i plotting heatmap using highcharts. when there many data data-points works when there signle point :[[1.4409601e12,0,92]] fails show rectangle of heatmap. on hovering show value in tooltip doesn't render heatmap. observed in console of developer tool of chrome shows there plotted x cordinate -2073599976 , when made 0 on browser's inspect element console started appearing on code side unable locate make change. when there 2 or more points x sets 25 or 26 , plots well. any solution great help.

jsf - Button inside p:contentFlow not working -

following code: <p:contentflow value="#{fileondeskviewdlgbacking.filescontentflowlist}" var="row"> <p:panel styleclass="filepanel" > <p:outputlabel value="#{row.srno}" /> <p:panelgrid styleclass="borderless" columns="2"> <p:graphicimage name="/dashboard/images/file_64px.png"/> <p:panelgrid styleclass="borderless" columns="1"> <p:outputlabel value="(#{row.subject})" /> </p:panelgrid> </p:panelgrid> <p:outputlabel style="color:#3d83b5;" value="files#{row.date}"> <f:convertdatetime pattern="dd/mm/yyy hh:mm" /> </p:outputlabel> <h:panelgrid styleclass="borderless" columns="2"> <p:outputlabel value="fileid:" /> <p:ou

autosuggest - How to make solr suggestion work for a specific field? -

i trying implement auto suggest of solr changes made in solrconfig.xml file <requesthandler class="org.apache.solr.handler.component.searchhandler" name="/suggest"> <lst name="defaults"> <str name="spellcheck">true</str> <str name="spellcheck.dictionary">suggest</str> <str name="spellcheck.onlymorepopular">true</str> <str name="spellcheck.count">5</str> <str name="spellcheck.collate">true</str> </lst> <arr name="components"> <str>suggest</str> </arr> </requesthandler> <searchcomponent class="solr.spellcheckcomponent" name="suggest"> <lst name="spellchecker"> <str name="name">suggest</str> <str name="classname">org.apache.solr.spelling.suggest.suggester</str> <str name="looku

apache - htacces failing to remove index.php completely leaves /? in url -

my site went https , having trouble remove /index.php?/ urls . when try open website so: example.com/links page redirects https://example.com/?/links cannot seem remove /? part. have tried many different approaches, not htaccess/regex hero. closest have come getting right. appreciated. rewriteengine on rewriterule cache/ - [f] rewritebase / rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^(.*)$ index.php?/$1 [l,qsa] rewritecond %{the_request} ^[a-z]{3,}\s(.*)/index\.php [nc] rewriterule ^ %1 [r=301,l] rewritecond %{server_port} 80 rewritecond %{https} !on rewriterule (.*) https://%{http_host}%{request_uri} rewritecond %{request_uri} !=/favicon.ico rearrange rules this: rewriteengine on rewritebase / rewriterule cache/ - [f] rewritecond %{the_request} ^[a-z]{3,}\s(.*)/index\.php [nc] rewriterule ^ %1 [r=301,l] rewritecond %{server_port} 80 rewritecond %{https} !on rewriterule (.*) https://%{http_host}%{request_uri} [l,r=301]

sql server - Enforce link tables -

i have 2 tables, 1 called season other 1 episode. between them link table stores seasonid , episodeid. how make sure when new episode added link table updated well? assuming using sql service. can achieve of trigger this query create trigger trig_update_episode on [episode] insert begin if not exists (select 1 [dbo].[tblepisodesession] (nolock) [episodeid] = [inserted.id]) print n'you must update entry in tblsessionepisode well'; end for both table should create trigger given above. in example query can replace message actual query should create entry in tblepisodesession. hope helps.

R - d3heatmap color palette, 2-sided -

i trying create heatmap using d3heatmap package colors red values below -2 yellow between -2 , -1.65 green between -1.65 , 1.65 yellow again between 1.65 , 2 red above 2 i have used search , found solutions palette 1-sided palette. not sure whether problem, using: d3heatmap(mydata, dendrogram = "none", colors = c("red", "yellow", "green", "yellow", "red"), breaks = c(seq(-10, -2), seq(-2, -1.65), seq(-1.65, 1.65), seq(1.65, 2), seq(2, 10)), ) (there no values above 10) unfortunately, yields funny results not understand colors in heatmap, e.g. yellow 0.125 or green 1.69. tried varying length of colors -sequences , colorramppalette similar results.

java ee - How to store entity with relation without loading to memory other entities with hibernate -

i have 2 entities: myclassa , myclassb. second 1 big , havy. @entity @table(name = tablea) public class myclassa { @id private long id; @onetoone @joincolumn(name = "id_b") private myclassb connetctedb; ... //some other values } i want create , store new entity of abouve class. service class pass values , id of myclassb entity. usual solutaion saw was: public void createnewa(long idb, string name) { myclassa = new myclassa(); a.setname(name); myclassb b = getbbyid(idb); // <- want avoid a.setconnetctedb(b); entitymanager.persist(a); } the problem fact myclassb havy , operation getbbyid consume lot of resources. how can create , store new object of myclassa in case? have id of myclassb, should easy, whould have use native query, unfortunately hibernate not support native inserts.

Are CSS selectors without properties of any effect? -

i got maintenance job , there huge css file, in found lot of things following: .xxxx {} that is, selector absolutely nothing in it. think useless, there many of them start doubt myself. right can removed safely? or doing , should keep them? i'd it's worst design in history (or stronger contender title...) could used. see below: document.stylesheets[0].cssrules[0].style.setproperty('color', 'red'); .randomclass {} <div class="randomclass">no styling?</div> you can acces, process, , modify stylesheets. if selector empty of styles, can modified using code. so, it's safe remove, if want 100% certain, either leave there, or go through possible code branches.

java - Are URLEncoder and URLDecoder not compatible? -

Image
i use system.out.println(urldecoder.decode(urlencoder.encode("й", "utf-8"), "utf-8")); , expecting see "й" in output. output filled "?"... trouble? your character getting saved encoding "cp1252" getting blank. when execute program following pop in eclipse

c++ - How to set up object transformations,properties? -

i'm new opengl, , doing homework online lessons. first task fill skillet code for: rotate, scale, translate, perspective, move left/right, up/down. did it, met problem next task: setting transformations. show me example or links how it? appreciate. (int = 0 ; < numobjects ; i++) { object* obj = &(objects[i]); // set object transformations // , pass in appropriate material properties // again gluniform() related functions useful // draw object // provide actual glut drawing functions you. // remember obj->type notation accessing struct fields if (obj->type == cube) { glutsolidcube(obj->size); } else if (obj->type == sphere) { const int tessel = 20; glutsolidsphere(obj->size, tessel, tessel); } else if (obj->type == teapot) { glutsolidteapot(obj->size); } } const int maxobjects = 10 ; extern int numobjects ; extern struct object { shape type ; glf

java - Get the real size of a JFrame content (NEW) -

i writing game in java, , don't want use layout manager jframe. class extends jframe, , looks this: //class field static jpanel contentpane; //in class constructor this.contentpane = new jpanel(); this.contentpane.setlayout(null); this.setcontentpane(contentpane); i want jpanel 600x600 px, when set size of jframe calling this.setsize(600,600) method, jpanel size less 600x600 px because border of jframe window included too. how can set size of jpanel 600x600 px? p.s. have seen of previous post , none of them work me. example: get real size of jframe content not work me. else can do? how can set size of jpanel 600x600 px? override getpreferredsize() method of custom game panel return size want panel be. @override dimension getpreferredsize() { return new dimension(600, 600); } then basic code create frame be: gamepanel panel = new gamepanel(); frame.add(panel, borderlayout.center); frame.pack(); frame.setvisible(true); now game logic co

html - Create new form fields on click using javascript -

i have form asks general information (i called gen-info) , fieldset inside form in ask other information. what i'm trying create new fieldset asking same other info , rename it, know how create copy of whole form (which asks general info too). by i'm creating button this: <button type="button" id="btnaddform" onclick="cloneform('gen-info');">add other info</button> and i'm using javascript function: function cloneform(formname) { var formcount = document.forms.length; var oform = document.forms[formname]; var clone = oform.clonenode(true); clone.name += "new form " + formcount; document.body.appendchild(clone); } click here see whole code as can see, duplicate whole form, want duplicate part says "other information 1" , rename "other information 2" when click , add 1 name every time create new one. difference i'm duplicating whole form every time, , wa

HTML to PDF: CSS for multiple-page report (wkHtmlToPdf) -

i using rotativa wrapper wkhtmltopdf in order render invoice or multiple page report pdf. however, when styling document encountered 2 problems. the @page element not seem compatible, when write example @page:first, vs2013 complains not valid pseud-class css3 , , see no effect in results, both in chrome , in resulting pdf when using rule in body of document (or wrapper element, matter) stating height 297mm (i set a4 in @page element , in wkhtmltopdf parameter page size), see element not reach end of document. hand tunning value gives me practical page height of 351mm. what have multiple page report each page has in bottom summary of running total of page, , grand total in last page. need element can position in bottom , guess have manually tune how many rows fit each page.

mysql - java query select data from two table and insert into another table -

i have 2 table, 1 traininfo other personalinfo personal info contain pid , train info contain tid ( traininfo ) when user book train pid , tid selected , insert third table named book info , booking id generate when booked. so if want perform should use separate query add 1 one or join information want , add together? there other item within both table , want select 2 item

webserver - Sizing CPU and RAM for website -

how count ram , cpu site? accoriding number of unique visitors per day , sustained visitors memory , cpu not visitors. see how memory site uses, check how memory uses on server's monitoring systems. to see how cpu uses, check server logs.

ios - CoreData - many-to-many relationship with priorities -

Image
i have conceptual question db schema. have 2 entities: team , member . 1. member can belong many teams , 2. team can have many members . so it's many-to-many relationship , i've implemented successfully. client wants have ordered members within team . member can have priority in 1 team different in other. how implemented db schema should like? considering 2 options: with minimum work effort the proper solution any hints more welcome. thanks. you should create new table, eg membersort , has memberid , teamid , position . way, can determine position both member , team key , position.

javascript - Jquery File Upload Reset in Internet Explorer -

i using jquery in classic asp webform. form basic , uploads 5 files. when uploading files have provided option users delete 1 of files being uploaded. jquery code have used $('#delete_attachment').click(function() { if (confirm('are sure want delete file?')) { $('#file_format').val('');//this textbox , works fine $('#document_attachment').val('');//this line deletes file $('#document_comment').val('');//this textbox , works fine } }); }); this works fine in chrome , file removed. in internet explorer, file remains , gets uploaded. there other way avoid file being uploaded , delete upload que using regular html file-upload control you can't change value of file input type, because introduce security vulnerability. instead of $('#document_attachment').val(''); can do: $('#document_attachment').replacewith('<input name="file" type=

silktest - How can I run a Silk4J test from the command line? -

i have read official microfocus article "how can run silk4j test command line?" doing described results in message exception in thread "main" java.lang.noclassdeffounderror: org/slf4j/logger @ org.apache.logging.slf4j.slf4jloggercontext.getlogger(slf4jloggercontext.java:41) so seems there more jars added class path described in article, 2013. it turns out had many jar files in classpath. removing following jars enhanced situation: log4j-to-slf4j-2.0.2.jar log4j-to-slf4j-2.0.2-javadoc.jar log4j-to-slf4j-2.0.2-sources.jar log4j-slf4j-impl-2.0.2.jar log4j-slf4j-impl-2.0.2-javadoc.jar log4j-slf4j-impl-2.0.2-sources.jar (where javadoc , sources not issue).

c# - How can I prevent navigation back using CEFSharp library? -

i want prevent navigation application using cefsharp library , winforms. have found no solutions this, links here: how disable backspace "go back" navigation? it`s not work me. me? --> requesthandler.cs class requesthandler : irequesthandler { public bool onbeforebrowse(iwebbrowser browser, irequest request, bool isredirect, bool ismainframe) { if ((request.transitiontype & transitiontype.forwardback) != 0) { return true; } return false; } public bool oncertificateerror(iwebbrowser browser, ceferrorcode errorcode, string requesturl) { return false; } public void onplugincrashed(iwebbrowser browser, string pluginpath) { } public cefreturnvalue onbeforeresourceload(iwebbrowser browser, irequest request, bool ismainframe) { return cefreturnvalue.continue; } public bool getauthcredentials(iwebbrowser browser, bool isproxy, string host, int port, str

How to add ActionBarActivity in Android Project? -

i'm not able add actionbaractivity in android project. there no options of appcpmpat-v7 in of project. what now? public class mainactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); actionbar mactionbar = getactionbar(); mactionbar.setdisplayshowhomeenabled(false); mactionbar.setdisplayshowtitleenabled(false); layoutinflater minflater = layoutinflater.from(this); view mcustomview = minflater.inflate(r.layout.custom_actionbar, null); textview mtitletextview = (textview) mcustomview.findviewbyid(r.id.title_text); mtitletextview.settext("my own title"); imagebutton imagebutton = (imagebutton) mcustomview .findviewbyid(r.id.imagebutton); imagebutton.setonclicklistener(new onclicklistener() { @override public void oncl`enter code here`ick(view view) { toast.ma

go - upload file with same format using beego -

file uploading done not same name filename have tried in html file <html> <title>go upload</title> <body> <form action="http://localhost:8080/receive" method="post" enctype="multipart/form-data"> <label for="file">filename:</label> <input type="file" name="file" id="file"> <input type="submit" name="submit" value="submit"> </form> </body> </html> and in beego/go receive.go package main import ( "fmt" "io" "net/http" "os" ) func uploadhandler(w http.responsewriter, r *http.request) { // formfile function takes in post input id file file, header, err := r.formfile("file") if err != nil { fmt.fprintln(w, err) return } defer file.close() out, err := os.create("/home/vijay/desktop/

iis 8 - IIS 8 not running embedded javascript -

can please help. i have javascript code on master page , working fine in visual studio , running fine on production server . not working on new server (in iis8). code sample <script type="text/javascript" language="javascript"> $(document).ready(function(){ $(document).gmediashadows(); $('.lightbox').lightbox(); $('.success').hide(); $('.unsuccess').hide(); $(".datepicker").datepicker({ dateformat:'dd/mm/yy', changemonth: true, changeyear: true, showon: "button", buttonimage: "../images/calendar.gif", buttonimageonly: true, onselect: function() {} }); $(".radio-set").buttonset(); $(".jquery-button&qu

How to convert string abcabc to abc in C# -

how convert string "abcabc" to "abc" here want achieve andsqlp47andsqlp47\ctoprod8r2 to andsqlp47\ctoprod8r2 you can use regex find repeating pattern , replacement: var regex = new regex(@"(\w+)\1\\(\w+)"); var result = regex.replace(@"andsqlp47andsqlp47\ctoprod8r2", @"$1\$2"); //result: andsqlp47\ctoprod8r2 regex explanation: (\w+) : match sequence of characters (first capture group $1) \1 : match same sequence of characters first capture group \\ : match '\' character (\w+) : match sequence of characters (second capture group $2) you can more info regex on msdn edit: to match string 2 repeated words, use following regex: var regex = new regex(@"^(\w+)\1$"); var result = regex.replace(@"abcabc", @"$1"); //result: abc ^ , $ denote start , end of string, matches if whole text repetition of 2 words.

sql - Combine several values from text file to one value in postgresql database -

i need copy content of textfile (not csv) postgres/postgis database simple sql script. the textfile looks like #date value 2007 11 29 9 29 14.830 4.1 2007 12 7 21 46 25.560 5.3 so date compound 6 values (year, month, day, hour, minute, second). have 1 timestamp field in db date should stored (as one single value ). i know can use copy command copy each column value of file column value in database, copy mydb myvalues.txt; but need combine several values text file 1 value in database. sorry if question has been asked, don't know how search started sql.

javascript - Convert weighted linear regression code from Python to JS -

i'm trying convert code user3658307 math site kindly shared me (in python format) here . i'm not great @ maths think i'm doing wrong here output seems increasing linearly instead of doing original python code should doing. doing wrong or can more experienced kind of calculus me convert javascript? thanks! python code: import os, sys, numpy np sklearn import linear_model x = np.array([13,14,15,16,17,18]).reshape((6,1)) yraw = [0.015,0.01,0.005,0.002,0.001,0.0005] y = np.array([ np.log(v) v in yraw ]) w = [100] + ([1]*4) + [10] # weight various data points print("transformed data\n"+str(x)+"\n"+str(y)) # fit linear function transformed data regr = linear_model.linearregression() regr.fit(x,y,sample_weight=w) print('coefficient: \n', regr.coef_) print('intercept: \n', regr.intercept_) # @ function explicitly a,b = regr.coef_[0],regr.intercept_ f = lambda x: np.exp( a*x + b ) print('outputs of function') x in range(1,19): pri