Posts

Showing posts from July, 2010

Is there a Data Type in Python which cannot be typecast in string -

lets ' a ' of type (which want know!) doing thing like: b = str(a) this should favorably raise typeerror there no builtin python class raises typeerror str , define custom class: class foo(object): def __str__(self): raise typeerror('can not stringified') foo = foo() b = str(foo) raises typeerror .

c# - How to simulate pressing Fn+F6? -

method sendkeys.send not allow press fn key, exists on laptop's keyboards. how can simulate pressing key c#? you can't, , don't need to. fn key exists key far keyboard circuit concerned. when key code sent operating system, looks if function keys regular keys on regular keyboard. operating system doesn't know fn key exists, taken care of special keyboard circuit in laptop. to make function key press on laptop, send regular key code function key on regular keyboard. if there other key combinations fn key used, either have own key codes, or not possible send because handled laptop, not operating system.

c++ - About Qt MessageBox::warning() overloading -

qmessagebox::warning(this,tr("error"), tr("file existed")); i use qtcreator msvs2012,win7. "this" points class public inherited qwizard class, compiler output is error c2665: “qmessagebox::warning”: 4 个重载中没有一个可以转换所有参数类型 d:\qt\qt5.1.0\5.1.0\msvc2012_64\include\qtwidgets\qmessagebox.h(197): 可能是“qmessagebox::standardbutton qmessagebox::warning(qwidget *,const qstring &,const qstring &,qmessagebox::standardbuttons,qmessagebox::standardbutton)” 尝试匹配参数列表“(const newwizard *const , qstring, qstring)”时 it means none of 4 overloads convert argument types. can give me help? replace this 0 , should work. basically, dialog box doesn't need parent. can stand alone , not have problem. https://qt-project.org/doc/qt-4.8/objecttrees.html and comments question said, can't call warning in const method either. another option rid of const 'ness of newwizard() method. hope

nested - Within same regex expression , performing multiple regex operations -

how can perform new regex operation regex group , within same regex expression ? "nested regex operations maybe?" greetings , kind of understand how regex works havent been able perform operation yet using regex , can c# combined regex. as in example. "the quick 1234brown fox jumps on lazy 1234dog" the regex (quick 1234brown fox jumps on lazy) yields "quick 1234brown fox jumps on lazy" and im looking "1234" . first result. using regex (1234) "quick 1234brown fox jumps on lazy" return "1234". in c# im able make work using regex multiple times. string test_string = "the quick 1234brown fox jumps on lazy 1234dog"; string clipped_text = ""; string end_result = ""; var match = regex.match(test_string, "quick 1234brown fox jumps on lazy", regexoptions.singleline); if (match.success) { clipped_text = match.value; match = regex.mat

sql - Can Rails array be "unzipped"? -

i using following queries in customer model call obtain desired set of transactions. transactions = sub_account.transactions transaction_items = transactions.map{|transaction| [transaction.transaction_items]} however, returning array of array of hashes. rails console [ [# <transactionitem id: 29, amount: 20>, #<transactionitem id: 35, amount: 40>],<br> [# <transactionitem id: 31, amount: 30>, #<transactionitem id: 38, amount: 30>],<br> [# <transactionitem id: 43, amount: 30>, #<transactionitem id: 21, amount: 40>],<br> ] this process works well. trying run query on transaction_items can't becuase they're embedded in array. here final desired query unable run. transaction_items.where(:amount => 30).sum("amount") i know can zip array, can unzip it? can't find documentation on it. if no unzip, can adapt query work on embedded arrays? thanks. what about: transactions_items =

JavaScript Settings missing in PHP project settings -

Image
i'm using netbeans 7.3.1. i can see javascript files section in netbeans projects settings when create html5 project. but want same php projects. after want able add dependencies could, when using html5 project. is there workaround show javascript files in php projects? regards,

c++ - How to emit signal through a few class objects in Qt? -

Image
i have few classes: class - highest class, class b , class c initialized in class constructor. in class b constructor initialized class b1 , in class c constructor initialized class c1. c1 object , b1 object not see each other. every time need send signal c1 class b1 class, connecting c1 , c, c , b, finally, b , b1. every time programm emitting signal in c1 class object, sending c class object b , b1. (on image) right qt way? or there better way that? you add class c interface returns c1 , similar interface class b, too. after creating classes c , b, class ask c1 , b1 , connect c1's signal b1's slot. or, if have lots of these kind of cases , don't want expose classes c1 , b1 a, create own signaling mechanism. kind of "post office" classes register receivers , classes send messages. in case, class b1 register receiver , class c1 send messages. c1 , b1 know nothing each other. post office class send c1's message b1. kind of "post office&q

css - Is there a way to animate to the next or previous -ms-scroll-snap-points-x? -

i'm using webview in xaml app, , i'm using snap points panning through list of objects. possible tell element scroll next/previous snap point? i'm using jquery , animating scrollleft property. isn't smooth when panning touch. i'm looking more native solution. thanks it looks it's possible ie11, not support in ie10. using mszoomto, zooms and/or pans animation http://msdn.microsoft.com/en-us/library/ie/dn254949(v=vs.85).aspx

Dedicated Initializer in Objective-C -

i newbie objective-c. have 'xyzperson' class attributes {firstname, lastname, dateofbirth} , want when write "xyzperson *person=[[xyzperson alloc] init]" in main, should call overridden 'init' method should in-turn call designated initializer , initializes object defined values. my code snippets. http://pastebin.com/ffxnddhf #import <foundation/foundation.h> #import "xyzshoutingperson.h" int main(int argc, const char * argv[]) { @autoreleasepool { xyzperson *person=[[xyzperson alloc] init]; if(person) { [person sayhello]; } else { nslog(@"person object null"); } } return 0; } -(id)init { self=[super init]; return [self initwithfirstname:@"ankit" lastname:@"sehra" dob:01/01/2000]; } -(id)initwithfirstname:(nsstring *)afirstname lastname:(nsstring *)alastname dob:(nsdate *)adateofbirth { _firstname=afirstname; _last

php - how to store date coming from paypal -

i have date coming paypal payment_date , date formatted 07:39:49 jul 05, 2013 pdt,how can insert table. or how insert jul 05, 2013.. using php thank in advance. <?php $date="01:07:13 may 07, 2011 pdt"; echo date('y-m-d h:i:s',strtotime($date)); ?> try above code

java - matcher.group(1) return no result -

public class getprop extends activity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); string file_proc = readfile(); textview tv = (textview)findviewbyid(r.id.tv); tv.settext("read file contents sdcard : \n" + file_proc); } public string readfile(){ bufferedreader rdr; string proc = ""; string line; int linenumber = 0; try { rdr = new bufferedreader(new filereader("/proc/cpuinfo")); while ((line = rdr.readline()) != null) { linenumber++; matcher matcher = pattern.compile("processor: (.*)").matcher(line); if (matcher.find()) { proc = matcher.group(1); } } } catch (exception e) { e.printstacktrace(); } return proc

numpy - FFT python result -

i trying plot fft of current waveform. getting result not make sense me. don't understand why getting 10^6 peak current 4. here? using numpy fft calculations. i post plots, not allowed here yet. there several ways normalise result of dft/fft (see discussion normalisation here ). it looks like numpy uses convention forward dft not divided n .

html - iframe src to be massaged by javascript -

to novice in javascript insult novice. limited html knowledge self-taught. here's problem: trying massage src in simple iframe, so: <html> <head> <script type="text/javascript"> function embedkey() { var url = window.location.href; var symbol = url.split('?')[1]; if(symbol=="inno"){ uniquekey = "&resid=27a14c5de396792c%21235&authkey=andfobkroksklqg" return "https://skydrive.live.com/embed?cid=27a14c5de396792c" + uniquekey +"&em=2&wdallowinteractivity=false&activecell='sheet1'!b3&wdhidegridlines=true&wdhideheaders=true" } else { alert(url); return false; } } </script> </head> <body> <iframe width="402" height="346" frameborder="0" scrolling="no" src=javascript:embedkey();></iframe> </body> </html> i adding many more conditions/symbols/return strings embedkey() function.

C++ Makefile %.c works, %.cpp not? -

i wrting simple makefile c++ files here problem not understand. have 2 folders /src .cpp files main.cpp check cpp /include .hpp files check.hpp my makefiles looks this libs = -lsfml-graphics -lsfml-window -lsfml-system cc = g++ vpath = src include cppflags = -i include ### files ### obj = main.o check.o ### rules ### all: sfml-app sfml-app: $(obj) $(cc) -o sfml-app $(obj) $(libs) %.o: %.c $(cc) -c $< clean: rm -rf *o $(obj) if use makefile likes this, works fine. if change %.o: %.c %.o: %.cpp said src/main.cpp:2:21: critical error: check.hpp: file or folder not found is wrong write .cpp instead of .c c++ project? confused me bit. why .c works finde , .cpp not. thanks :) ! the flags variable c++ language called cxxflags , , should using $(cxx) instead of $(cc) in code. cppflags variable preprocessor arguments.

colors - Anyway to make the uBaseColor value transparent? Three.js && ShaderToon.js -

don't know if possible, using shadertoon.js in three.js, there anyway make ubasecolor value transparent??? , leave ulinecolor value opaque? function createshadermaterial( id, light, ambientlight ) { var shader = three.shadertoon[ id ]; var u = three.uniformsutils.clone( shader.uniforms ); var vs = shader.vertexshader; var fs = shader.fragmentshader; var material = new three.shadermaterial( { uniforms: u, vertexshader: vs, fragmentshader: fs } ); material.uniforms.udirlightpos.value = light.position; material.uniforms.udirlightcolor.value = light.color; material.uniforms.uambientlightcolor.value = ambientlight.color; return material; } geometry = new three.torusknotgeometry(106.68, 200, 12, 2, 8.44, 5.4, 1); material = createshadermaterial( "dotted", directionallight, ambientlight ); material.uniforms.ubasecolor.value.sethex( 0xffffff ); // want transparent material.uniforms.ulinecolor1.value.se

batch file - Using one variable in the SET statement of another variable -

i writing batch script uses sqlcmd dump tables database server onto local machine. construct query such have flexibility specify table name. query gets constructed depending on table name, gets used in sqlcmd command. code snippet construct query shown below: @echo off set tablename = testdb set dumptable="set nocount on; select * %tablename%" echo %dumptable% on running script getting following output "set nocount on; select * " the tablename variable not getting substituted in set statement. how should modify script achieve output: "set nocount on; select * testdb" you must not have whitespace around = sign in variable assignments. replace this: set tablename = testdb with this: set tablename=testdb also, shouldn't have double quotes around value in variable assignment, because way double quotes become part of value. it's better practice put double quotes around whole assignment, , quote variable necessary when

html - What logic goes where: express + jade/ejs + html5 + css + websockets -

ok. i'm trying learn node.js/express , want clarify how jade/ejs, html, , css fit together. correct me if i'm wrong: application logic done in node.js/express some of logic/variables passed jade/ejs html engine dynamically serve html css still formats served html depending on requesting device. forgive me, seems lines starting blur js; it's hard tell logic should done in node.js/express , logic should done in jade/ejs. this gets blurrier when using websockets, since there logic going on client-side. there's display control logic going on @ 5 different places. you pretty have it! here tutorial think clear confusion if have time take @ it. uses of modules mentioned , job explaining role of each element is. http://net.tutsplus.com/tutorials/javascript-ajax/real-time-chat-with-nodejs-socket-io-and-expressjs/

vb.net - How can I have a sub that accepts a variable as byref without declaring what type of variable it is? -

how can have sub accepts variable byref without declaring type of variable (it int, string, etc.) still have of other parameters defined? i want sub this: private sub example(byref variable, byref reader mysqldatareader, byval columnname string) you can make generic method: private sub example(of t)(byref variable t, byref reader mysqldatareader, byval columnname string)

Rails 4 Active Model Validations -

i'm trying create contact form on website using active model. the problem having errors messages never returned. i'm using remote form. routes: resource :front_contacts, only: :create, controller: :front_contact controller: class frontcontactcontroller < applicationcontroller def create contact = frontcontact.new(params[:front_contact]) @errors = contact.errors.size end end front_contact: class frontcontact include activemodel::model attr_accessor :name, :email, :message validates_presence_of :name, :message validates_format_of :email, with: /[a-za-z0-9._%-]+@(?:[a-za-z0-9-]+\.)+(com|net|org|info|biz|me|edu|gov)/i end js.erb: alert(<%= @errors %>); the alert alerting zero. please advise. if you're using rails 4, there's new inclusion of strong params may preventing models getting created. do have following anywhere in controller? params.require(:front_contact).permit! i had same pr

Is there a openid-selector that supports Facebook, Twitter, and top sites in the 2010's? -

Image
here openid-selector implemented http://code.google.com/p/openid-selector/ works great except fact people on earth recognize first 2 buttons. is there openid selector helper includes endpoints sites people use? (facebook, twitter, qq, weibo, amazon) yes, i'll roll own. looking supported solution first. as mentioned sites mentioned don't use openid. use oauth instead. on wikipedia a description on how both of differ. and if closely: openid selector mentioned is capable handle this . here howto use facebook openid selector. additionally there comment in faq: comment project member andriy.gerasika, oct 19, 2010 [..] i make howto in v1.3 how plug-in facebook support maybe can remind andriy post there.

html - Background runs behind button -

Image
background behind button should block background. button can change width. how can realise this? this might done in lot of ways, here's first idea: use mask this: make sure background-image covers whole button insert 2 white divs above background-image: left & right of button insert mask above buttons background due transparent area (indicated texture) able display border-like part of background image while rest of stays invisible, because overlapped. i illustrated result of instructions above

excel vba - VBA Project Password-Protect with SendKeys not Working Correctly -

i've spent last 2 days working on problem. of content i've found on topic doesn't address issue i'm having, i'm hopeful here can me. i've been working on code following "master scorecard" workbook: takes each "student" sheet in workbook , copies sheet new workbook, does few minor manipulations of new workbook, imports module of code new workbook, adds workbook_open event , workbook_beforeclose event new workbook (to make sheets xlveryhidden depending on level of access), runs subprocedure newly imported module, saves , closes workbook. each scorecard uses code ensure person name on scorecard can access it. i've used environ("username") in workbook events ensure security, know, if 1 , understands how run macros, he/she merely open vbeditor , unhide xlveryhidden sheets in workbook easily. so, thought password protect new workbook's vbaproject programmatically (see above: step number five). found few s

objective c - AFNetworking cancelAllOperations prevents batch completionBlock from firing -

i'm using enqueuebatchofhttprequestoperations submit batch of requests. if of requests fail, want cancel other requests still going. so, i'm setting failure callback on individual operations [client.operationqueue cancelalloperations]; . this seems cancel remaining operations, it's preventing overall completionblock of batch executing... here's code i'm trying test behavior (one of requests set fail on server). afhttpclient *client = [afhttpclient clientwithbaseurl:[nsurl urlwithstring:@"http://arahlf.com"]]; nsmutablearray *requests = [[nsmutablearray alloc] init]; (int = 0; < 10; i++) { nsurlrequest *request = [client requestwithmethod:@"get" path:@"echo.php" parameters:@{ @"sleep": @(i) }]; afhttprequestoperation *operation = [client httprequestoperationwithrequest:request success:nil failure:nil]; [operation setcompletionblockwithsuccess:nil failure:^(afhttprequestoperation *operation, nserror

c++11 - Is this correct usage of move semantics -

i have function call class myclass { static std::string getname(void) { return getmyname(void); // returning value } }; now if use function in constructor of class class anotherclass { public: anotherclass(void) : m_name(std::move(myclass::getname())) {} // 1. std::move used const std::string& name(void) const { // 2. should use std::string&& (without consts) // .... need make sure value cannot changed (e.g, name() = "blah";) // if std::string&& used should use calling name() call function using move or should leave is? return m_name; } private: std::string m_name; } is correct usage of move semantics? how can ensure function using move semantics? i trying learn implement efficiency move semantics apology if dumb question. i have checked what move semantics? http://www.cprogramming.com/c++11/rv

mysql - Jquery, ajax post and get results? -

i making login, want ajax post each key stroke query. when login matches login in database (mysql), want password returned parent page. now. have in past used ajax post php databases, never had return variable back. not know if passing form info over, thanks! index.php script: $(function(){ $("#inputemail").keyup(function() { var usernameinput = $(this).val(); $.ajax({ type: "post", url: "pulluserdb.php", data: { 'usernameinput':usernameinput }, datatype: "text", success: function(data) { $('.body').html(data); } }); }); }); index.php html: <div class = "headerlogin"> <form class="loginform"> <div class="control-group"> <div class="controls"> <input style = "height

javascript - alert not displaying when using button onclick -

here 's fiddle. i'm trying make when click button alerts 'you tried search... ...whatever typed... !' , button doesn't alert message. i've tried using: var = document.getelementbyid('input').value; alert("you tried search " + + "!"); and still doesn't alert message, please answer? your function inaccessible outside of it's closure. should window.search = function() { var = document.getelementbyid('input').value; alert("you tried search " + + "!"); }

c# - IIS8 Unauthorized: Access is denied due to invalid credentials -

how can disable server asking credentials set directory , subdirectories? have got windows authentication installed. you might need clarify further on why want this, access permissions should controlled via application. however, right click folder in question , add everyone, read permissions. edit: based off new comment. disable windows authentication , enable anonymous access site. iis7 principle same: http://technet.microsoft.com/en-us/library/cc731244(v=ws.10).aspx

Conditional Conditons in SQL Server -

i have combobox 3 values: all , failed , completed . all : load rows , no condition. failed , completed : load condition on column 'status'. all: select * tbl_location failed , completed: select * tbl_location status = 'failed' or select * tbl_location status = 'completed' i have 2 statues 'failed' , 'completed'. 'all' combo-box value load rows without condition i want in 1 query. can do? declare @status varchar(15) --set status select * tbl_location status = @status or @status = 'all'

Why is my google apps script passing a value in one function and a NaN in the other? -

i'm using doget() example code passing values hidden object. works in first case of adding column on delcolumn nan/undefined in logger. trying figure out why code looks identical google tutorial. function onopen() { var ss = spreadsheetapp.getactivespreadsheet(); var menuentries = [ {name: "buildui", functionname: "buildui"} ]; ss.addmenu("buildui", menuentries); } function buildui() { var appheight =360 var app = uiapp.createapplication().setwidth(500).setheight(appheight).settitle('step 1: pickboxes'); var ss = spreadsheetapp.getactivespreadsheet(); var panel = app.createverticalpanel().setid("settingspanel"); var headerpanel = app.createverticalpanel().setid("headerpanel").setstyleattribute("background", "silver").setwidth(500); var columnpanel = app.createverticalpanel(); var maingrid = app.creategrid(5, 1).setid("maingrid"); var scroller =app.crea

html - Bug in Chrome wrapping of nested spans in Japanese? -

Image
chrome not seem wrapping japanese text when spans nested. see http://jsfiddle.net/mras4/2/ . reproducible in safari not firefox. in below, red circled area incorrectly left vacant , following shuffled down next line. the gray-shaded area first span, , blue-shaded area nested span. far can tell, seems chrome refusing break either before or after inner span, result gets pushed next line. i can set word-break break-all , "solves" problem, disables correct japanese line-breaking behavior, such full-stops not coming @ beginning of line. i suppose bug in webkit should report?

internet explorer - Is there any way to use WebBrowser Class (Band Objects) to write the DOM? -

i have created ie toolbar using bandobjects (using com assembly -interop.shdocvw.dll) implement custom search functionality. toolbar contains search box takes input , returns result. results has fetched 2 or more search engines , combined before showing them on browser. can see need write document object model of explorer window combined results. i unable see property or method provided webbrowser class let me write dom. please suggest best possible solution task. link api of bandobjects great me. you use document object of loaded page modify dom. having said that, writing internet explorer extensions in c# discouraged. http://blogs.msdn.com/b/ieinternals/archive/2009/08/21/agcore-addon-hangs-internet-explorer.aspx

java - How to teach eclipse to generate compact equals() and hashCode() from the jdk 7 Objects class? -

some days ago switched java 7 within company - finally! jay \o/ found out objects class , astonished how short methods hashcode() , equals() realized, reducing lot of boylerplate code compared ones generated eclipse per default (alt+shift+s --> h). i wondering if change default behaviour of eclipse generated hashcode() , equals() ? i'd love see this: @override public int hashcode() { return objects.hash(one, two, three, four/*, ...*/); } instead of this: @override public int hashcode() { final int prime = 31; int result = 1; result = prime * result + ((one == null) ? 0 : one.hashcode()); result = prime * result + ((two == null) ? 0 : two.hashcode()); result = prime * result + ((three == null) ? 0 : three.hashcode()); result = prime * result + ((four== null) ? 0 : four.hashcode()); // ... return result; } the same goes equals() . this article got from. any ideas how realize best? in eclipse preferences go java > editor > tem

android - Can I display a image in custom layout? -

i know can use below code display image in system layout, hope display image in custom layout, how can that? thanks! public void onclick(view v) { // todo auto-generated method stub int id = v.getid(); intent intent = new intent(); intent.setaction(intent.action_view); intent.setdataandtype(uri.parse("file://" + arrpath[id]), "image/*"); startactivityforresult(intent,forbrowse); } <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/border_ui" android:orientation="vertical" android:paddingtop="3dip" > <imageview android:id="@+id/imageview1" android:layout_width="wrap_content" android:l

asp.net mvc - Autofac DI .NET MVC controllers without default constructor -

when use ajax queries asp.net mvc controller have error: type 'web.implementation.controllers.mycontroller' not have default constructor. my code: //in controller private idataservice dataservice; //i try delete constructor, //because use di , don't want create currentcontext , dataservice. public mycontroller() { var currentcontext = new currentcontext(); dataservice = new dataservice(currentcontext); } public mycontroller(idataservice dataservice) { dataservice = dataservice; } //in autofac init builder.registertype<dataservice>().as <idataservice>(); how can use autofac di in case ? me please. upd: //in global.asax dependencyconfigure.initialize(); //in dependencyconfigure class public static void initialize() { var builder = new containerbuilder(); dependencyresolver.setresolver( new dependency(registerservices(builder))

cakephp - Multiple conditions in find all -

i'm tring enter conditions in find('all' on cake. that's logic: traduction.traductions = username , traduction.status = 1 or 8 or, traduction.check1 = username , traduction.status = 5 or 2 or, traduction.check2 = username , traduction.status = 6 or 3 or, trauduction.editions = username , traduction.status = 7 or 3 if 1 of these condition right, display content that's code far $conditions = array( 'and' => array( array( 'or' => array( array('traduction.traductions' => $this->session->read('auth.user.username')), array('traduction.status' => '1'), array('traduction.status' => '8') ) ), 'and' => array( array(

spring - JPA EntityManager values are not persisted in database when tested using Junit -

i using hibernate 4 spring 3 , when try junit test, values not persisted in database in dao implementation class @transactional @repository public class projectdaoimpl extends genericdaoimpl<project> implements projectdao { public void create(project project) { entitymanager.persist(project); system.out.println("val 2 -- "+project.getprojectno()); } @persistencecontext public void setentitymanager(entitymanager entitymanager) { this.entitymanager = entitymanager; } and in junit test have @transactionconfiguration @contextconfiguration({"classpath:applicationcontext.xml"}) @transactional @runwith(springjunit4classrunner.class) public class projecttest { @resource projectservice projectservice; @test public void createproject(){ project project = new project(); project.setprojectname("999---"); projectservice.create(project); } i able see value statement

java - What is the easiest way to change the behaviour of JTable multi-column sorting? -

by default, if have more 1 sortkey in jtable's row-sorter, every click on column header make column's sortkey primary one. i need change behaviour first click on column header makes sortkey primary one, click column header make column's sortkey secondary one, , on. also, when, maxsortkeys reached, click on (not sorted) column trigger shuffling of sort-keys. newly clicked column have sortkey lowest priority, primary key column lose sortkey, , column secondary sortkey become primary one, etc. at moment, implemented own tableheader in order capture event when user clicks on column header in order shuffle sortkeys appropriately. to illustrate example: [ 1 | 2 ↑1 | 3 ↓2 | 4 | 5 ↑3 ] [ | | | | ] after user clicks on first column's header: [ 1 ↑3 | 2 | 3 ↓1 | 4 | 5 ↑2 ] [ | | | | ] what wonder whether think approach or not? is required override sortkeys every columns, each of col

python - How to escape number in regex -

so replacing characters re module. have string 'abc_def' , need add 1 after _ . doing this. st = 'abc_def' re.sub(r'^(\w+_)('')(\w+)$',r'\11\3',st) but takes \11 11th captured group, not \1 , 1 separately. btw r\1,1\3 works should, returns abc_,1def . need ! you can use \g<number> instead of \number : re.sub(r'^(\w+_)('')(\w+)$',r'\g<1>1\3',st)

c# - Does a DataSets DataTable inherit structure when no records exist? -

i'm hooking dataset sql ce 3.5 database , chasing down exception (nullref). think issue may caused empty dataset i'm struggling understand way in structure of datatable works. if populate dataset against table structure exists, no records have been added, standard behavior? datatable of matching structure instantiated or dataset left empty? (assuming database contains 1 table i'm connecting in case). edit: cheap example database "contacts" 1 table "mycontacts". has 4 fields, contactid, name, phone, email (int, nvarchar x3) dataset data = new dataset() sqlceconnection connection = new sqlceconnection(); sqlcedataadapter adapter = new sqlcedataadapter("select * mycontacts ", connection); sqlcecommandbuilder builder = new sqlcecommandbuilder(adapter); adapter.fill(data, mycontacts); return data; what happends if table exists (its structure present) there no records?

string - Android: How to change TextView periodically -

i'm working on shoutcast radio project. using streamscrapper library i'm able current song name , current artist. here problem. once open app, gets song name , artist name, since not update it. tried timer couldn't figure out. and here method current song id: private void initializemediaplayer() { player = new aacplayer(); scraper = new shoutcastscraper(); try { streams = scraper.scrape(new uri("http://sunucu2.radyolarburada.com:5000/")); string str = "asd"; (stream stream: streams) { str = stream.getcurrentsong(); currplayview.settext("now playing: " + str); } } catch (scrapeexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (urisyntaxexception e) { // todo auto-generated catch block e.printstacktrace(); } } maybe runnable: private handler handler = new handler(); handler.postattime(ti

apache pig - Syntatic Error in code-block -

i encountered syntatic error not solve; grunt> describe x; x: {id: int,b: {(first: int,second: int)}} grunt> res = foreach x {f = flatten(b); generate id,f;} 2013-07-22 12:28:53,050 [main] error org.apache.pig.tools.grunt.grunt - error 1200: <line 11, column 21> syntax error, unexpected symbol @ or near 'flatten' how can that? see http://pig.apache.org/docs/r0.11.0/basic.html#foreach only cross, distinct, filter, foreach, limit, , order allowed in nested block. try res = foreach x generate id, flatten(b.(first, second));

php - Find white space in string -

i have following string. need find position of last white space. i have tried following code: for ($i = 410; $i < 420; $i++) { if ($body[$i] == ' ') { $lastcharacter = $i; break; } } but not return correct white space position. return position in middle of word. dans cette septième étape, les coureurs vont relier montpellier et albi, passant au milieu des vignes de l'arrière-pays pour faire la jonction entre les alpes et les pyrénées, traversant des paysages qui font toute la saveur du tour. dernière étape un peu plate avant un week-end placé sous le signe de la montagne. des ascensions de col, la foule amassée sur les côtés, souffrant avec leu... $lastspace = strrpos($string," "); doc: strrpos

multithreading - Java, Passing value to a constructor of class inplementing Callable -

so, have implemented following simple class parallelize independent encryption processes: public class selectionencryptor implements callable<biginteger> { private damgardjurik dj; private byte c; private int s; public selectionencryptor(damgardjurik dj, byte c, int s) { this.dj = dj; this.c = c; this.s = s; } @override public biginteger call() throws exception { dj.sets(s); biginteger r = dj.encryption(biginteger.valueof(c)); system.out.println("dj s: " + dj.s + ", given s: " + s + ", c: " + c); return r; } } s parameter of cryptosystem use, important 1 determining depth of encryption. i initialize , run threads following: int s = s_max; executorservice executor = executors.newfixedthreadpool(selectionbits.length); arraylist<future<biginteger>> list = new arraylist<future<biginteger>>(); // selectionbits byte array h

Android - Problems cropping a Bitmap to display in an ImageView -

thanks reading, have been trying going days , have searched code can. see below have tried number of approaches. i using 3rd party device returns bitmap of size 152 x 500. there black strip vertically down left side 24 wide. in actual fact needing 128 x 500 start 24 in left. whatever try cannot seem rid of black strip when image saved. here code, sorry it's thought show all. // scan button clicked , log.e("tag", "wait scan capture"); much appreciate on this. public class imagecaptureactivity extends activity implements onclicklistener { private linearlayout ll_root; private button btn_scan; private button btn_process; private linearlayout mlayout; private button mbutton; private fingerview mimageview; private fpcdevkitinterface mfpcdevkit; public view minutiaview; public bitmap tempbitmap; public bitmap scanbitmap; @override public void oncreate(bundle savedinstancestate) { super

css3 - Kendo Mobile - "flat" skin incorrectly displays footer tabstrip tabs on Android 2.3 -

when testing on both android 2.3 simulator , devices, tabstrip adds tab blank (black background). occurs when there more 1 tab in tabstrip. upon removing "skin" property of kendo mobile app initialization, tabstrip correct. does new skin have sort of differing flexbox implementation causing this? again, occurs on android 2.3. i using kendo ui mobile q2 2013 release w/ jquery 1.9.1. html : <div data-role="view"> <footer data-role="footer"> <div data-role="tabstrip"> <a href="tab1.html">tab1</a> <a href="tab2.html">tab2</a> <a href="tab3.html">tab3</a> </div> </footer> </div> javascript : var app = new kendo.mobile.application(document.body, { skin: "flat" }); update : interestingly enough, problem not occur when using template define footer.

sql - postgresql and INSERT variables -

i'm close stuck. pull user name drupal , store in variable called $username, want store in column called username. below code throws error $sql = "insert sheet_tbl (site_id, user_id, eventdate, eventtime, username) values ('$_post[site_id]','$_post[user_id]','$_post[eventdate]','$_post[eventtime]',$username)"; error warning: pg_query() [function.pg-query]: query failed: error: syntax error @ or near ")" @ character 112 in /var/www/html/drupal1/includes/common.inc(1743) : eval()'d code on line 30. i pull user name using: user name: <?php global $user; echo $user->name; $username = $user->name; ?> if echo variable result = admin you did not put username in quotes. replace ,$username)"; with ,'$username')"; and btw should not put unescaped user input in sql statements. can lead sql injections. see here

Installing Maven 3.0.5 in RedHat Linux -

can me installing maven 3.0.5 in linux please? i tried using wget , yum , tar command. commands saying not recognized external or internal command , blank how achieve it. need go start->cmd , apply these commands?? and please tell me how set environment variable. please me. thanks in advance. the first thing need download maven tar file , untar shared location on workstation wget http://mirrors.gigenet.com/apache/maven/maven-3/3.0.5/binaries/apache-maven-3.0.5-bin.tar.gz su -c "tar -zxvf apache-maven-3.0.5-bin.tar.gz -c /opt/" setup maven environment variables in shared profile. next step setup maven environment variables in shared profile users on system them import @ login time. su -c "vi /etc/profile.d/maven.sh" # add following lines maven.sh export m2_home=/opt/apache-maven-3.0.5 export m2=$m2_home/bin path=$m2:$path now test install of maven. logout of system , log it. enter following command: [jsmith@regan ~]$ mvn -version

java - Regex to match nested json objects -

i'm implementing kind of parser , need locate , deserialize json object embedded other semi-structured data . used regexp: \\{\\s*title.*?\\} to locate object {title:'title'} but doesn't work nested objects because expression matches first found closing curly bracket. for {title:'title',{data:'data'}} it matches {title:'title',{data:'data'} so string becomes invalid deserialization. understand there's greedy business coming account i'm not familiar regexps. please me extend expression consume available closing curly brackets. update: to clear, attempt extract json data semi-structured data html+js embedded json. i'm using gson java lib parse extracted json. as others have suggested, full-blown json parser way go. if want match key-value pairs in simple examples have above, use: (?<=\{)\s*[^{]*?(?=[\},]) for input string {title:'title', {data:'data', {foo: 'bar'

java - How to create forcibly new http session -

this question has answer here: httpservletrequest - create new session / change session id 2 answers i doing session sharing between 2 web app(app1 , app2).in app2 once user validate want forcibly create new session in app2.i able session.invalidate() , request.getsession(true); here after doing session.invalidate() app1 session getting expire. pls me. try: request.getsession().invalidate(); request.getsession(true);

Using HTML attributes in javascript -

i beginner in javascript. i'm trying add function generate new form elements using javascript, on page that's generated in php. the code works in creating new <tr>, <td>, <input type="text"> html elements. when try create buttons using css styles, find styles lost tags. if(document.createelement) var tr = document.createelement("tr"); var input = document.createelement("input"); // if ns passed, should become ns[2] etc input.id = field+"["+count+"]"; input.name = field+"["+count+"]"; input.type = "text"; //type of field - can valid input type text,file,checkbox etc. var td=document.createelement("td"); var newcontent = document.createtextnode("ns"); td.appendchild(newcontent); tr.appendchild(td); td=document.createelement("td"); td.appendchild(input); tr.appendchild(td); var btndel=document.createelement("

r - TeachingDemos: using etxtPlot with numerical results in loops -

when running code: library(teachingdemos) etxtstart(dir=getwd(), file="nofunciona.txt") etxtcomment('just test') for(i in 1:10){ cat("###",i,":\n") my.sample = sample(100) print(summary(my.sample)) qqnorm(my.sample) etxtplot(width=7.5) } etxtstop() i file named "nofunciona.txt" text line "just test" , commands include graphs, nothing results of cat() or print(summary()), although can see results on console. if change loop using these 2 loops: for(i in 1:10){ cat("###",i,":\n") my.sample = sample(100) print(summary(my.sample)) } for(i in 1:10){ qqnorm(my.sample) if(archivo) etxtplot(width=7.5) } etxtstop() then can obtain file text results of cat(), , summary() , commands include graphs @ end. know last loop obtain ten times same graph, not relevant. it seems cannot obtain graphical results , text results @ same time inside loop. why not first code work? any idea

javascript - Check if number is between 2 values -

i building filter based on div class's , contents. i wondering if possible pass string follows function: " £0.01 - £100.01 " and have function show div's html of div between range so have div class of "price" , contents were: £10.30 from running function , passing string of " £0.01 - £100.01 " it hide div's similar how have done in js below show div's div class "price"'s contents within selected price range. i have managed similar brand filter provide here: function brand(string){ var brand = string; $('.section-link').hide(); $('.section-link').children('.brand.' + brand).parent().show(); if (brand == "all brands"){ $('.section-link').show(); } } any general advice or code appreciated achieve :) thanks, simon edit: target div example: <div class="section-link"> <div class="price"> £56.99</div>

plot - Variable part in an expression( ... ) with R -

this question has answer here: use variable within plotmath expression 2 answers i display physical units in r plot. in order have better typography, use expression function way: plot(rnorm(10),rnorm(10),main=expression(µg.l^-1)) suppose unit not statically known, , given variable [unit]: unit = 'µg.l^-1' plot(rnorm(10),rnorm(10),main=expression(unit)) this of course not work because [unit] not substituted value. there means achieve anyway? edit: should stress main difficulty here unit displayed sent string plot function. contents of unit should interpreted expression @ point (that transformed string expression object), , answer texb comes handy. please unmark question duplicate, since use of parse fundamental here , not mentionned in post suggest. how about: unit = 'µg.l^-1' plot(rnorm(10),rnorm(10),main=parse(text=unit))

Google Map Pins Missing -

i have site using google map having pins disappear. code create pins valid , have been tested. inspector, seem pointing a.xa.fa property in http://maps.gstatic.com/intl/en_us/mapfiles/api-3/13/9/main.js believe injected (as have included no such script). i'm quite desperate , have no idea it. input appreciated. you try add markers without supplying proper pin-argument add() , therefore creation of new google.maps.markerimage(pin) fail in add() . this happens first time @ 6th marker(that's why see 5 markers, error stop script-execution @ point). solution: may either fix it(supply proper pin-argument), there latlng of 0,0 provided, guess went wrong data. or add begin of add() have default-pin these situations: pin=pin||'http://www.mychinaroots.com/wp-content/themes/mychinaroots/images/8-default.png';

regex - Why doesn't ^ $ in .NET multiline regular expressions match CRLF 0D0A? -

i have .net application makes use of .net regex features match epl label text string. use following: ^[a-z0-9,]+"(.+)"$ , match every line (it captures text in-between epl code). epl has changed , @ end of every epl line there line feed \x0d\x0a . so changed code pattern [((\r\n)|(\x0d\x0a))a-z0-9,]+"(.+)" , picks keep out of reach of children , doesn't recognise rest. how can match text between epl code?? this raw epl i'm trying match n 0d0a a230,1,0,2,1,1,n,"keep out of reach of children"0d0a a133,26,0,4,1,1,n," furosemide tablets 40 mg"0d0a a133,51,0,4,1,1,n," 1 in morning"0d0a a133,76,0,4,1,1,n,""0d0a a133,101,0,4,1,1,n,""0d0a a133,126,0,4,1,1,n,""0d0a a133,151,0,4,1,1,n,""0d0a a133,176,0,4,1,1,n,"19/04/13 28 tablet(s)"0d0a a133,201,0,4,1,1,n,"elizabeth m smith"0d0a lo133,232,550,40d0a a133,242,0,2,1,1,n,"any medical centr