Posts

Showing posts from September, 2012

memory leak on delay job what's the better alternative on rails -

i send mails delay job worker. the web app runs on ec2 instance 2gb ram, somehow, instance runs out of memory after booting while i guess root cause delayed job . what's alternative that. can send mail in thread.new , therefore user won't blocked on sending email here's how run servers , worker on boot every :reboot command " cd #{project} ; git pull origin develop " command " cd #{project} ; memcached -vv " command " cd #{project} ; bundle exec rake delayed::backend::mongoid::job.create_indexes " command " cd #{project} ; bundle exec rake jobs:work " command " cd #{project} ; bundle exec puma config/puma.rb" command " cd #{project} ; ruby app_periodic_tasks.rb" end try sidekiq seems more solid.

ubuntu 14.04 - Unable to run logstash config file (permission denied) -

my config file stored in /etc/logstash/ and ran command $ /etc/logstash -f /etc/logstash/logstash.conf as root. however, told me permission denied when tried that. there way solve this? as said, need run /opt/logstash/bin/logstash -f /etc/logstash/logstash.conf instead of /etc/logstash -f /etc/logstash/logstash.conf . this caused default directory structure of linux system logstash uses put files in. wikipedia: filesystem hierarchy standard /opt stands optional , contains third party packages not part of default linux distribution. therefore logstash puts binaries , dependencies there (e.g. jruby stuff). here can find logstash program /opt/logstash/bin/logstash or plugin manager /opt/logstash/bin/plugin . /etc means et cetera , used configuration files (like logstash uses it). there other system folders used logstash. example /var/log/logstash can find logstash's own logs. so, when run logstash installation (in ubuntu perhaps apt-get or dpkg

javascript - How to access outer function variable in nested inner function in JS -

i new js , having doubt below example. please see inline comments. function outer() { var x = 5; console.log("outer",x); // prints 5 console.log("-----------"); function inner() { var x = 6; console.log("inner",x); // prints 6 console.log("outer",x); // prints 6. how print 5 console.log("-----------"); function _inner() { var x = 7; console.log("_inner",x); // prints 7 console.log("inner",x); // prints 7. how print 6 console.log("outer",x); // prints 7. how print 5 console.log("-----------"); } _inner(); } inner(); } outer(); may helps you. assign variables nested functions because therefore clear varible should used have differ each other in way(name or via namespace): function outer() { var x = 5; // or via namespace // var out = { x : 5 }; console.log("outer",x); // 5 console.log(&quo

c# - How to prevent application shutdown on close window? -

i'm using wpf , i've got no main window (i've overwritten onstartup method). when user clicks on menu-item, want show settings window. app.xaml.cs: protected override void onstartup(startupeventargs e) { base.onstartup(e); new mainenvironment(); } mainenvironment.cs: notifyicon notifyicon; settings settings_wnd = new settings(); // wpf window public mainenvironment() { notifyicon = new notifyicon() { ... contextmenu = new contextmenu(new menuitem[] { new menuitem("settings", contextmenu_settingsbutton_click) }) }; } void contextmenu_settingsbutton_click(object sender, eventargs e) { if (!this.settings_wnd.isvisible) this.settings_wnd.show(); else this.settings_wnd.activate(); } problem when user closes window, whole application exits too. why? , how can prevent that? thanks the application defaultly set shutdown when windows closed. need add shutdow

javascript - Cannot read property 'prototype' of Undefined in Nodejs -

i using fast-csv module handle , parse csv data on server side. read data csv file , store contents in database. while running eclipse on local don't errors if try run on aws server following error. hasispaused = !!stream.transform.prototype.ispaused; ^ typeerror: cannot read property 'prototype' of undefined at object.<anonymous> (/home/ec2-user/imex-research-mass-mailer-v2/node_modules/fast-csv/lib/parser/parser_stream.js:11:37) @ module._compile (module.js:449:26) @ object.module._extensions..js (module.js:467:10) @ module.load (module.js:356:32) @ function.module._load (module.js:312:12) @ module.require (module.js:362:17) @ require (module.js:378:17) @ object.<anonymous> (/home/ec2-user/imex-research-mass-mailer-v2/node_modules/fast-csv/lib/parser/index.js:5:20) @ module._compile (module.js:449:26) @ object.module._extensions..js (module.js:467:10) initially thought there may issues of dependent packages not being

php - Authentication issues with the Twitter API -

i'm trying display latest tweets of twitter account on website, , i'm trying fetch data using curl , php. when use oauth tool (signature generator) on twitter developers website. there curl command generated , runs fine on terminal. however, when try use curl same parameters in php code, following error : { "errors": [ { "code": 215, "message": "bad authentication data." } ] } here curl command : curl --get 'https://api.twitter.com/1.1/statuses/user_timeline.json' --data 'count=2&screen_name=[my user name]' --header 'authorization: oauth oauth_consumer_key="[my key]", oauth_nonce="[my key]", oauth_signature="[the signature]", oauth_signature_method="hmac-sha1", oauth_timestamp="1439736924", oauth_version="1.0"' --verbose and here php code : $ch = curl_init("https://api.twitter.com/1.1/status

d3.js - Fix only one dimension of a node in force layout? -

this question - fix node position in d3 force-directed layout - covers how fix position of node in force-layout. my question how fix 1 dimension, x or y, of node , let other respond forces in layout. this isn't directly supported in d3, can manually resetting coordinate want remain constant in tick handler function. force.on("tick", function() { nodes.each(function(d) { d.x = d.px = d.savedx; // similar y }); // other stuff }); this requires store desired value data bound nodes, in example in attribute savedx (although can use other name long it's not used else).

mysql - I want to increase countoftask of category when a task of that category is inserted in task table -

create trigger tr_task_forinsert after insert on task each row begin set @count = (select countoftask category catid = new.catid , userid=new.userid); update category set countoftask = @count+1 catid=new.catid , userid=new.userid; end where error? task table +----------+--------------+------+-----+---------+----------------+ | field | type | null | key | default | | +----------+--------------+------+-----+---------+----------------+ | taskid | int(11) | no | pri | null | auto_increment | | taskname | varchar(255) | yes | | null | | | catid | int(11) | yes | mul | null | | | userid | int(11) | yes | mul | null | | | taskdate | date | yes | | null | | | tasktime | varchar(255) | yes | | null | | +----------+--------------+------+-----+---------+----------------+ category table +-------------+----

In AngularJS, how to force the re-validation of a field in a form when another value in the same form is changed? -

i have form few fields, select , input field coupled: validation on input depends on value user chooses in select field. i'll try clarify example. let's select contains names of planets: <select id="planet" class="form-control" name="planet" ng-model="planet" ng-options="c.val c.label c in planets"></select> in input apply custom validation via custom directive named "input-validation": <input id="city" input-validation iv-allow-if="planet==='earth'" class="form-control" name="city" ng-model="city" required> where directive: .directive('inputvalidation', [function() { return { require: 'ngmodel', restrict: 'a', scope: { ivallowif: '=' }, link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewvalue) { //input allowed if attribute not

android - java.lang.ClassNotFoundException: Didn't find class on path: DexPathList. Other answers did not solve -

i want use this library create searchview . project , tutorial given on github page android studio, but use eclipse . did created library project in eclipse , copied code custom-searchable module here. then created project named custom-searchable-demo , copied code module named demo there. have been getting weird errors day. right getting: 08-16 09:56:13.365: e/androidruntime(2071): java.lang.runtimeexception: unable provider br.com.edsilfer.custom_searchable_demo.content_provider.customsuggestionsprovider: java.lang.classnotfoundexception: didn't find class "br.com.edsilfer.custom_searchable_demo.content_provider.customsuggestionsprovider" on path: dexpathlist[[zip file "/data/app/br.com.edsilfer.custom_searchable_demo-1/base.apk"],nativelibrarydirectories=[/vendor/lib, /system/lib]] i have attached both eclipse projects on mediafire i.e. library project , demo project . note: have not posted code, because eclipse projects attached, , code here i

django - GeoDjango: Can I use OSMGeoAdmin in an Inline in the User Admin? -

profile contains pointfield . i've used osmgeoadmin in profileadmin, here: class profileadmin(admin.osmgeoadmin): model = profile but can't figure out how use in inline display in useradmin. have set below: # user admin, profile attached class profileinline(admin.stackedinline): model = profile can_delete = false verbose_name_plural = 'profile' # 1 displayed in view class useradmin(useradmin): inlines = ( profileinline, ) admin.site.unregister(user) admin.site.register(user, useradmin) is possible use class osmgeoadmin in situation? this feature request guess. as workaround, can take advantage of fact inlinemodeladmin quite similar modeladmin . both extend basemodeladmin . inheriting both stackedinline , modeladmin should not clash much. the issue both __init__() methods take 2 positional arguments , call super().__init__() without arguments. whatever inheritance order, fail typeerror: __init__() missin

PHP & MySQL - Problems with UTF-8 encode -

Image
i have form input accept utf-8 characters: <form method="post" action="faz-personagem.php" accept-charset="utf-8"> <div class="row"> <label for="nome">nome</label> <input type="text" name="nome"> </div> ... <button type="submit">enviar</button> </form> and script send data database: <?php header("content-type: text/html;charset=utf-8"); $conexao = mysql_connect('localhost', 'root', 'pass'); mysql_select_db('pan-tactics'); $nome = $_post['nome']; $nome = utf8_encode($nome); $sql = "insert personagens values"; $sql .= "('$nome')"; $resultado = mysql_query($sql); echo 'personagem criado com sucesso.'; mysql_close($conexao); ?> i have specified in creation of database collation utf8_unicode_ci , yet wrong special characters:

html - Created Dropdown menu with CSS in Dreamweaver, submenu items not linking -

i used video https://www.youtube.com/watch?v=qpo9hjjuktk create css dropdown menu submenus. i got right , have tried linking list items in submenus other .html files , actual websites, nothing works. when click on submenu item go whatever page, nothing loads , stays on current page submenu open. html: '<nav class="nav-main"> <div class="logo">kudler fine foods</div> <ul> <li> <a href="#" class="nav-item">departments</a> <div class="nav-content"> <div class="nav-sub"> <ul> <li><a href="bakery.html">bakery</a></li> <li><a href="#">meat & seafood</a></li> <li><a href="#">produce</a></li> <li><a href="#">cheese & dairy</a></li> <li><a href="#

xcode - Error "Thread 1: breakpoint 2.1" -

Image
i working on rest api manager. giving error , not able fix it. error got given below highlighted. import foundation import alamofire import swiftyjson class restapimanager { var resources: json = [ "resources": [ "resourcea": [] ] ] let apiurl: string let apiusername: string let apipassword: string init(apiurl: string, apiusername: string, apipassword: string) { self.apiurl = apiurl self.apiusername = apiusername self.apipassword = apipassword getapiresourcea() { responseobject, error in let resourcea = json(responseobject!) self.resources["resources"]["resourcea"] = resourcea } } func collectdatafromapi(completionhandler: (responseobject: nsdictionary?, error: nserror?) -> ()) { preparehttprequest(completionhandler) } func preparehttprequest(completionhandler: (responseobject: nsdi

sql server - Confused about UPDLOCK, HOLDLOCK -

while researching use of table hints , came across these 2 questions: which lock hints should use (t-sql)? what effect holdlock have on updlock? answers both questions when using (updlock, holdlock) , other processes not able read data on table, didn't see this. test, created table , started 2 ssms windows. first window, ran transaction selected table using various table hints. while transaction running, second window ran various statements see blocked. the test table: create table [dbo].[test]( [id] [int] identity(1,1) not null, [value] [nvarchar](50) null, constraint [pk_test] primary key clustered ( [id] asc )with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary] ) on [primary] from ssms window 1: begin transaction select * dbo.test (updlock, holdlock) waitfor delay '00:00:10' commit transaction from ssms window 2 (ran 1 of following): select * dbo.

dependency injection - How to disable resolving of un-registered types in simpleInjector? -

i trying use simpleinjector di container nservicebus. while trying so, ran problem caused resolving of un-registered types. need make sure un-registered types not resolved simpleinjector. i did try below code, didn't good. _context.resolveunregisteredtype += _context_resolveunregisteredtype; void _context_resolveunregisteredtype(object sender, unregisteredtypeeventargs e) { e.register(()=> null); } any ideas/suggestions welcome.

How to intercept Linq filters -

in linq objects, there anyway identify entities/objects qualified/disqualified @ each filter? for e.g) let's have entity called "product' (id , name) , if input 100 products linq query has 5 "where" conditon , 20 products output. is there way identify product got filtered @ condition ? this can generalized can this. don't see use case it. use tolookup() partition queries. "disqualified" items lumped under false group , can continue query true group. e.g., var numbers = enumerable.range(0, 100); var p1 = numbers.tolookup(n1 => n1 < 50); // p1[false] -> [ 50, 51, 52, ... ] var p2 = p1[true].tolookup(n2 => n2 % 2 == 0); // p2[false] -> [ 1, 3, 5, 7, ... ] var p3 = p2[true]... // , on

Android retrieve image from parse.com and use it -

actually, want use library"aphid-flipview-library"to animation of flipping. images want flip parse.com. got problems when doing this. please give me instruction.thanks! first, create class set , image's bitmap value. package com.example.bookard; import android.graphics.bitmap; public class useforflip { private bitmap photo; public bitmap getphoto(){return photo;} public void setphoto(bitmap photo){photo = photo;} } and, code below first half of rotate activity. want retrieve image parse.com , add arraylist called "notes". arraylist used in second half of rotate activity. public class rotate extends activity { useforflip forflip; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.rotate); forflip = new useforflip(); parsequery<parseobject> query = new parsequery<parseobject>("card");

android - Error while creating an AlertDialog -

i'm beginner in android. so, have icon on clicking alertdialog should appear. simple.----android:onclick = "oncreatedialog"---- package com.example.android.guardian; import android.app.alertdialog; import android.content.context; import android.content.dialoginterface; import android.os.bundle; import android.support.v7.app.actionbaractivity; import android.view.layoutinflater; import android.view.menu; import android.view.menuitem; import android.view.view; import android.widget.imageview; public class mainactivity extends actionbaractivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.menu_main, menu); return true; } @override public boolean onoptio

html - syntax error: bad string token -

i'm making hover boxes subreddit, keep getting syntax error: bad string token. i'm not sure causing error im starting write code. if vague or not formatted correctly let me know. <div class="outerbox"> <div class="innerbox" > what's sub about</div> lyle stevik lying in unmarked grave. believe might have friends or family out there looking 'closure'. can help! </div>

javascript - validating single set of fields on click using Jquery validate -

ive made form has several sections, later sections hidden displayed after user clicks next button on current section. im trying simple "must filled" validation on click before rest of form displayed. as far can gather other questions on here method should work.. var validate should equal true if errors found stop form progressing allow form progress once fields have been filled , button clicked again however seems @ moment validate first field , nothing. if field valid still not progress rest of actions on function. js library : http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.min.js method im trying use: http://jqueryvalidation.org/validator.element/ <div class="col-sm-8 sec-one"> <div class="form-group"> <select name="t1" required> <option value="" disabled selected>choose option...</option> <option value="b">b</option&

c# - What is a NullReferenceException, and how do I fix it? -

i have code , when executes, throws nullreferenceexception , saying: object reference not set instance of object. what mean, , can fix error? what cause? bottom line you trying use null (or nothing in vb.net). means either set null , or never set @ all. like else, null gets passed around. if null in method "a", method "b" passed null to method "a". the rest of article goes more detail , shows mistakes many programmers make can lead nullreferenceexception . more specifically the runtime throwing nullreferenceexception always means same thing: trying use reference, , reference not initialized (or once initialized, no longer initialized). this means reference null , , cannot access members (such methods) through null reference. simplest case: string foo = null; foo.toupper(); this throw nullreferenceexception @ second line because can't call instance method toupper() on string reference pointing null .

twitter bootstrap - How to make <p> within "jumbotron" responsive -

i'm pretty new coding , working on familiarizing myself html/css/bootstrap. element in "jumbotron" class doesn't resize correctly when change size of screen (it piles on top of each other). see here: http://www.bohmerconstruction.com/test.html/ . if resize screen lower width, you'll see element does. how shows on mobile. here html: <div class="jumbotron"> <div class="container"> <h1>let you</h1> <p><a href="http://www.bohmerconstruction.com/contact-bohmer-construction.html">contact free estimate</a></p> </div> </div> and here css: .jumbotron { background-image: url('http://constructotal.net/wp-content/uploads/2013/03/ist2_5357604-construction-background-1024x680.jpg'); background-size: cover; height: 100%; } .jumbotron h1 { color: white; margin-top: 95px; float: left; height: 100%; } .jumbotron p { font-size:18px; margin-top: 180px; margin-rig

Code Academy 4/26 Javascript Recursion -

i'm having great time learning recursion (or trying to) in javascript, , have done code academy has asked of me, there's wrong, anyway. can please (and thank you!) tell me have gone wrong? code academy reporting there's error, it's not telling me where. here code, , have pasted instructions below it. function multiplyby10(number) { console.log(number * 10); } function multiplesof10(limit) { for(i=1;i==limit;i++){ multiplyby10(i); } } multiplesof10(100); instructions: complete definition of multiplesof10() adding loop. the loop should start i = 1 , end when i equal value of limit. within loop, call function multiplyby10() , pass variable i argument. finally, call function multiplesof10() @ end of code, passing integer argument. in instruction found loop should start = 1 , end when equal value of limit condition for(i=1;i==limit;i++) false time . need change condition . here's right 1 : for(i=1;i<=limit;i++)

python - How start multiple tasks at once in tornado -

i have for .. in .. : loop, calling methond waiting result. how can make loop start @ once , wait results? this code: @gen.coroutine def update_all( self ): service in self.port_list: response = yield self.update_service( str( service.get( 'port' ) ) ) self.response_list.append( response ) self.response = json.dumps( self.response_list ) return self.response thank you! build list (of future objects returned update_service() ), , yield list: @gen.coroutine def update_all( self ): futures = [] service in self.port_list: futures.append(self.update_service(str(service.get('port')))) self.response_list = yield futures self.response = json.dumps( self.response_list ) return self.response

jquery - <ul> positioned at bottom of parent <div> -

i built jquery dropdown menu using elements position: absolute , , <ul> inside of menu located near bottom, rather @ top of dropdown. here snippet displaying webpage. problem <ul> in blue text (click on image): function main() { $('#arrow').click(function(){ $('.hidden').animate({ top: '200px' }, 400); $('#slide-wrapper').animate({ margintop: '250px' }, 400); $(this).attr('src','uparrow.jpg'); $(this).off(); $(this).click(function(){ $('.hidden').animate({ top: '-=250' }, 400); $('#slide-wrapper').animate({ margintop: '0px' }, 400); $(this).attr('src','downarrow.jpg'); $(this).off(); main(); }); }); } $(document).ready(main); body { font-family: arial; padding: 0px; margin: 0px; } /* menu elements *

How can a cacheline sized struct wrapping a mutable, volatile int64 be created in F#? -

i want create cacheline sized struct wrapping mutable, volatile int64 in f#. i’ve tried various struct definitions including 1 below, can't compile. [<struct; structlayout(layoutkind.explicit, size = 64)>] type mystruct1 (initval:int64) = [<volatilefield>] let mutable value = initval member x.value () = value , set(valin) = value <- valin which gives error: "structs cannot contain value definitions because default constructor structs not execute these bindings. consider adding additional arguments primary constructor type". can't see additional arguements add primary constructor above. any ideas? the struct definition be [<struct; structlayout(layoutkind.explicit, size = 64)>] type mystruct = [<fieldoffset(0)>] val mutable value : int64 new(initval:int64) = { value = initval } member x.value get() = x.value , set(valin) = x.value <- valin but then, [<

methods - Rails: How to check for attributes with polymorphic? (Prints okay, won't allow conditional) -

going accessing user attributes (name, e-mail, avatar, etc) comments section ("identify user commenter"), why let me print out values not use them in conditionals? why can this? (prints avatar next comment should) <%= image_tag comment.user.avatar.url, size: "64" %> but not this? (won't let me check if there's avatar or not first) <% if comment.user.avatar.url.empty/blank/nil/present? %> so if commenter hasn't uploaded avatar yet, returns: undefined method \'avatar\' nil:nilclass is there method need define in controller, or scope in model, or there way of checking in situation? thank you.

php - Sort an array of posts by distance -

i using google maps api wordpress project. using custom function gooogle maps in bounds , displaying information such name, address, distance, id, etc.. distance calculated $_get variable , googleapis distancematrix. so grab id's in viewport(bounds) , use them in query using get_posts() looks this $locations = ( $_get['ids'] ) ? $_get['ids'] : -1; $args = array( 'post_type' => 'location', 'posts_per_page' => -1, 'post__in' => $locations, ); $posts = get_posts($args); // etc, etc.. i need sort these posts(locations) distance stuck on trying figure out way so. address stored in posts post meta serialized array. possible evaluate , sort these posts before using `foreach'?

json - strange python issue, 'unicode' object has no attribute 'read' -

here code , have ideas wrong? open my json content directly browser , works, data = requests.get('http://ws.audioscrobbler.com/2.0/?method=library.getartists&api_key=4c22bd45cf5aa6e408e02b3fc1bff690&user=joanofarctan&format=json').text data = json.load(data) print type(data) return data thanks in advance, lin this error raised because data unicode/str variable, change second line of code resolve error: data = json.loads(data) json.load file object in first parameter position , call read method of this. also can call json method of response fetch data directly: response = requests.get('http://ws.audioscrobbler.com/2.0/?method=library.getartists&api_key=4c22bd45cf5aa6e408e02b3fc1bff690&user=joanofarctan&format=json') data = response.json()

How to add a Liquid tag into YAML front matter in Jekyll? -

i'm using plugin count page views posts , pages based on google analytics. display page view count i'm using liquid tag {% pageview %} . there way add data yaml front matter, can accessed in list of popular posts on other pages {{ page.views }} ? here code liquid tag in plugin: class pageviewtag < liquid::tag def initialize(name, marker, token) @params = hash[*marker.split(/(?:: *)|(?:, *)/)] super end def render(context) site = context.environments.first['site'] if !site['page-view'] return '' end post = context.environments.first['post'] if post == nil post = context.environments.first['page'] if post == nil return '' end end pv = post['_pv'] if pv == nil return '' end html = pv.to_s.reverse.gsub(/...(?=.)/,"\\&\u2009").reverse return html end #render end # pageviewtag how can instead

asp.net - Error handling for query string parameters -1%27, getting bombarded -

i not expert, not rookie either. i'm using asp.net webforms. set error catching routine in global.asax log error info in sql table , redirect friendly error page. began finding hundreds of exceptions per day in query string "?id=-1%27". use query strings items , categories allow integers of 3 digits or less. started geo-locating ips. vast majority of them russia , surrounding countries. started storing of ips in table. else experiencing , how best handle it. want catch legitimate errors, major annoyance. input appreciated. have googled 2 days , can't find related issue. the %27 ascii single quote ( ' ) , red flag trying perform sql injection via query string application's data access layer logic. i less concerned attacks coming , more focused on techniques protecting/processing data before attempted used data access layer , data storage (read: database). using parameterized sql , data sanitation (read: white-listing allowable text strings) gr

jquery - How to make part of a flexbox layout become sticky? -

i have decided switch flexbox layout project, , here problem : have div becoming sticky on top of page when scrolling down, div containing flexbox elements. practically, div contain nav menu, complicated enough me need flexboxes. want nav menu scroll up, stick top. classic behavior... i know flexbox , fixed position don't mix well, yet i'm still wondering if there way make div containing flexboxes sticky, without destroying flex layout inside it. let's div moves grey bar in website : look @ grey bar scrolling up , let's grey bar must contain flexboxes ! my first tests made using jquery basic solution provided here . destroys flex layout. 2013 plugin following (link on page) doesn't either. any idea how such sticky behavior without giving on flex content ? thx lot clue or alternative solution ! function sticky_relocate() { var window_top = $(window).scrolltop(); var div_top = $('#sticky-anchor').offset().top; if (window_top >