Posts

Showing posts from May, 2015

mysql - How to join tables with no primary key in rails? -

Image
i have 2 tables both have no primary key. below 2 tables structure. how can use in join table on column date in rails ? meanwhile, date columns not unique in both tables. from understanding (which may wrong), need use primary key, in order identify foreign keys in rails foreign keys however, try using association_foreign_key , foreign_key arguments in associations definitions ( only works habtm ): #app/models/table_a.rb class tablea < activerecord::base has_and_belongs_to_many :table_b, foreign_key: "country_id", association_foreign_key: "hour" end #app/models/table_b.rb class tablea < activerecord::base has_and_belongs_to_many :table_a, foreign_key: "hour", association_foreign_key: "country_id" end table_as_table_bs hour | country_id would difficult include id column in tables??

virtualbox - Oracle virtual box inaccessible -

i using oracle virtual box version 4.2.16 r86992. fine until yesterday shutdown. today, shows inaccessible , throws error: runtime error opening c:\users\xxxxxx\virtualbox vms\vboxxxxxubuntu_beta\vboxxxxxubuntu_beta.vbox reading: -102 (file not found.). d:\tinderbox\win-4.2\src\vbox\main\src-server\machineimpl.cpp[725] (long __cdecl machine::registeredinit(void)). it's restore working, save lot of time , restore configuration settings , data. thanking support. this happens if host os crashes or pull plug on it, leaving .vbox file unsaved. in location: c:\users\xxxxxxx\virtualbox vms\vboxxxxxubuntu_beta\ you should find 2 files: vboxxxxxubuntu_beta.vbox-prev vboxxxxxubuntu_beta.vbox-tmp copy vboxxxxxubuntu_beta.vbox-prev vboxxxxxubuntu_beta.vbox . select vboxxxxxubuntu_beta.vbox , in vbox manager, right click, , left click on refresh. observe shows powered off. now go.

javascript - Meteor Deps.autorun doesn't get triggerd - what's its use compared to observe()? -

i have test collection ("initdata") contains documents , following code on meteor client: meteor.subscribe("initdata"); meteor.startup(function () { console.log(initdata.findone("randidtest").key); deps.autorun(function() { var allinitdata = initdata.find(); allinitdata.foreach(function(entry) { console.log("deps foreach: " + entry._id); }); var randomobject = initdata.findone("randidtest"); console.log("deps call " + randomobject.key); }); }); var initdataobserver = initdata.find().observe({ added: initdatachange, changed: initdatachange, removed: initdatachange }); function initdatachange () { var allinitdata = initdata.find(); allinitdata.foreach(function(entry) { console.log("observer foreach: " + entry._id); }); var randomobject = initdata.findone("randidtest"); console.log("observer ca

powershell - Check if AD User was part of the AD Group which could be in its sub group -

i query user whether part of group, issue here is.. hard identify whether part of because in many level of group sub group. example if wanted check if user in "all sales users". in subgroup of "all sales users" > "sales us" > "sales sj" > "prod a" > "item b" the issue is, there many sub group had open search him. how know whether part of "all sales users"? best if query show hierarchy. i tried powershell show memberof. not sure how on this. a recursive powershell implementation, assumes have activedirectory powershell module installed. return common name groups user member of, including nested in example 5 groups returned. function findgroup($n){ $g = get-adgroup $n; $parents = get-adgroup -filter {members -eq $g.distinguishedname} if($parents -eq $null){ return $g.name; } else{ $g.name; $parents | % { findgroup $_ } } } and second fun

function - Haskell - type classes -

i new haskell, , trying learn how type classes work. typed following code ghci compiler. let (+) :: num => -> -> a; (+) b = a+b; the code compiles, whenever call function, stuck , have ctrl+c stop process. am doing wrong here? thank in advance! you calling function + function + recursively, it's same if wrote: add :: num => -> -> add b = add b

jquery - Need suggection on html CSS javascript hover & slide -

i need little suggestion, fiddle , , html: <div style="width: 100%; border: 1px solid #000000;"> <div style="float: left; width: 20%;">logo + <a href="#">sub nav icon</a></div> <div style="float: left; width: 60%;">canter header portion</div> <div style="float: left; width: 20%;">right postion</div> <br clear=all> </div> <div style="width: 100%; border: 1px solid #000000; margin-top: 10px;"> <div style="float: left; width: 20%">sub menu hidden</div> <div style="float: left; width: 80%"> <div style="float: left; width: 60%">image area</div> <div style="float: left; width: 40%">text area</div> <br clear=all> </div> <br clear=all> </div> (note copied , pasted in edit not o

google maps - Global variable javascript not working appropriately -

i working on website in trying incorporate google maps. page fetches values database using php. passes 1 of column values javascript function plots using google maps. now, want display plots of values in single map. i attaching javascript function , php call. here code: <script type="text/javascript"> var myoptions; var map; var geocoder; var first_call = 0; function map_function(addr){ // define addresses want map. var clubs = addr; // create new geocoder if (first_call == 0){ var geocoder = new google.maps.geocoder(); } // locate address using geocoder. geocoder.geocode( { "address": clubs }, function(results, status) { // if geocoding successful if (status == google.maps.geocoderstatus.ok) { if (first_call == 0){ // create google map @ latitude/longitude returned geocoder. // create once alert("initializing map");

html - Is it possible to make server push without using javascript? -

is there mechanism provide server push technology using plain html, without using javascript (or other script languages on client side). under "server push" mean process server update part of page content when needed. i don't know of way true server push can used without javascript in page. without javascript, thing i'm aware of meta refresh tag tell browser refresh page after particular time interval. tag applies whole page only. if wanted part of page updated, use iframe , have iframe updated. of course, not server push, client-driven auto-update , run on predetermined interval, not when there new data. smarter this, need javascript. the efficient server-push use javascript page connect server on websocket , have server send data page via websocket whenever wants (true server-push). client's javascript can respond receipt of websocket data updating particular piece of page.

javascript - Toggle hide/show <tr> using jQuery -

i have code show <tr> in table every click, hides textbox must shown when button clicked. below jquery code show textbox: $(function() { $('#btnadd').click(function() { $('.td1').show(); }); }); and code in <table> : <button id="btnadd" name="btnadd" onclick="toggle();" class="span1">add</button> <tr class="td1" id="td1" style=""> <td><input type="text" name="val1" id="val1"/></td> <td><input type="text" name="val2" id="val2"/></td> </tr> you have invalid markup. need wrap tr in table.something this: <button id="btnadd" name="btnadd" class="span1" >add</button> <table class="td1" style="display: block;" > <tr id="td1" > <td><inp

c# - WPF Canvas-based ItemsControl with minimum recycled items? -

i'm using itemscontrol canvas backing panel . need .clear() observablecollection itemscontrol's itemsource , , add new information it, causes controls destroyed , new usercontrol s created, sluggish. how can force itemscontrol retain amount of containers after call .clear(), , reuse them when new items added itemsource? i not sure how efficient in use case, might create derived itemscontrol , override getcontainerforitemoverride , clearcontainerforitemoverride methods put , take item containers cache collection. public class cachingitemscontrol : itemscontrol { private readonly stack<dependencyobject> itemcontainers = new stack<dependencyobject>(); protected override dependencyobject getcontainerforitemoverride() { return itemcontainers.count > 0 ? itemcontainers.pop() : base.getcontainerforitemoverride(); } protected override void clearcontainerforitemoverride( dependencyob

html - Call a php and return immediately -

i have call php "build.php" button action , php call python script , should return immediately. the action: <form method="get" action="build.php"> <input type="hidden" name="branch" value="master"> <input type="submit" value="build master" id="btnmaster"> </form> the build.php <?php if(isset($_get['branch'])) { $output = shell_exec('/usr/bin/python /users/testuser/gitroot/buildonguest.py --dest /users/testuser/builds --branch ' . $_get['branch'] . ' 2>&1 &'); } elseif (isset($_get['tag'])) { $output = shell_exec('/usr/bin/python /users/testuser/gitroot/buildonguest.py --dest /users/testuser/builds --tag ' . $_get['tag'] . ' 2>&1 &'); } ?> so python script executed in background (&) , php should return main page. poss

java - Spring storing an object in session -

after logging user object, user able choose 1 of multiple accounts, once user select 1 of accounts want application work specific account. there way store object account in session spring any controller can have access variable @ time? you use session beans . first interface set , object: public interface accountholder { public void setaccount(account account); public account getaccount(); } then implementation of interface: public class accountholderimpl implements accountholder { private account account; public void setaccount(account account) { this.account = account; } public account getaccount() { return account; } } define session-scoped bean in @configuration : @bean @scope(value="session", proxymode=scopedproxymode.interfaces) public accountholder accountholder() { return new accountholderimpl(); } after can use following in controllers: @autowired private accountholder accountholder;

xml - Printing all the entities(domain) in log file -

i using log4j2.xml web application , working fine. problem is, printing domain information also. using hibernate+spring.since domain contains user class printing password in log file.. log4j.xml below.. <?xml version="1.0" encoding="utf-8"?> <configuration status="trace"> <appenders> <rollingrandomaccessfile name="onboarding_log" filename="c:/jetty-distribution-9.0.6.v20130930/logs/onboarding.log" filepattern="c:/jetty-distribution-9.0.6.v20130930/logs/onboarding.log.%i" append="true" immediateflush="true"> <patternlayout> <pattern>%d{iso8601} %-5p [%t]: [%c{1}] %m%n-%x{elapsedtime}-%x{bytesize}-%x{uniqueid}-%x{httpmethod}-%x{url}-</pattern> </patternlayout> <policies> <sizebasedtriggeringpolicy size="250 mb&q

php - Prepared statements doesn't return results -

i trying querys prepared statements new me , have troubles. first query , doesn't echo result table. i've done far. may realy newbie question new me. if(isset($_get['joke_id'])){ $joke_id = $_get['joke_id']; $qry = $con->prepare("select * joke joke_cat = ?"); $qry->bind_param('i', $joke_id); $qry->execute(); $result = $qry->get_result(); $result->fetch_array(); $result = mysqli_query($con, $qry) or die("query failed: " . mysqli_errno($con));*/ $line = mysqli_fetch_array($result, mysql_both); if (!$line) echo ''; $previd = -1; $currid = $line[0]; if (isset($_get['id'])) { $previous_ids = array(); { $previous_ids[] = $line[0]; $currid = $line[0]; if ($currid == $_get['i

c# - HTTP request with POST - data will not be displayed -

i'm trying post data php page using c#. i tried msdn example (i changed postdata "xml=test") , tried example of this post . the php page simple. contains: <?php echo "postdata<br>"; echo "<pre>"; print_r($_post); echo "</pre>"; ?> i wrote simple html file testing. contained form post data. <html> <body> <form action = "https://myurl/upload/uploadtest.php" method = "post"> <input name = "xml" value="test"><p> <input type = "submit" value="absenden"> </form> </body> </html> the response of html site is: postdata array ( [xml] => test ) this means me connection , php file ok. but response of c# code is: ok postdata<pre>array ( ) </pre> the "ok" comes "(((httpwebresponse)response).statusdescription)" , rest "reader.readtoend()". can

caching - Cache for java-backend which can accept multiple keys & return multiple values -

currently using hazelcast distributed cache application. takes in key , gives me values. but, more helpful in application if cache can accept multiple keys , return corresponding values, in 1 function call. can hazelcast it? or there alternate solution, ehcache or redis ? i not sure redis or hazle cast ehcache has this. check out http://ehcache.org/apidocs/net/sf/ehcache/ehcache.html it has method map getall(collection keys) , bunch of more bulk operation methods check out more explanation http://dancing-devil.blogspot.com/2011/04/ehcache-bulk-operation-apis.html the upcoming jsr107 / jcache standard has bulk operations defined. every standards compliant cache have this.

f# - optional parameters in abstract class type signature -

the class: type notabstract () = member this.withoptionalparameters (x, ?y) = let y = defaultarg y 10 x + y has following type signature: type notabstract = class new : unit -> notabstract member withoptionalparameters : x:int * ?y:int -> int end however, not work: [<abstractclass>] type abstractexample () = abstract withoptionalparameters: int * ?int -> int /// ouch... type notabstract () = inherit abstractexample () override this.withoptionalparameters (x, ?y) = let y = defaultarg y 10 x + y how write proper type signature in abstract definition of function optional parameters? did not find hint here . ps: aware (similar) result achieved polymorphism declaring argument option type doesn't make argument optional. notabstract().withoptionalparameters(2) // expression expected have type // int * option<int> // here has type // int the spec §8.13.6 ha

eclipse - Google Maps Android API V2 showing current location with marker(where am i in google android maps api v2) -

i beginner in android , developing android app displaying current location on google maps.but run application display message "unfortunately stopped" on emulator physical device. attaching code .plz have look. pls me ....i not able resolve this thanks mainactivity.java package com.example.mapp; import android.app.dialog; import android.location.location; import android.os.bundle; import android.support.v4.app.fragmentactivity; import android.view.menu; import android.widget.textview; import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.googleplayservicesutil; import com.google.android.gms.maps.cameraupdatefactory; import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.googlemap.onmylocationchangelistener; import com.google.android.gms.maps.supportmapfragment; import com.google.android.gms.maps.model.latlng; public class mainactivity extends fragmentactivity implements onmylocationchangelistener { g

github api - List of all supported languages and their file extenstions for .gitignore and gist -

Image
is possible list of github supported languages gist files , projects (.gitignore)? list of .gitignore supported languages displayed on image below on left side. , list of gist languages on right side. also greatfull list of appropriate extenstions these languages.

android - javacTask: source release 1.7 requires target release 1.7 -

i have setup android project through sbt (0.13.1) in idea 13.0.2. mixed java 7 , scala 2.10.3. uses sbt support in idea. even though in build.sbt have following: scalacoptions += "-target:jvm-1.7" javacoptions ++= seq("-source", "1.7", "-target", "1.7") here result when make project idea: java: javactask: source release 1.7 requires target release 1.7 any please? finally solved. you need this: javacoptions in compile <<= (javacoptions in compile) map { _ collect { case "1.5" => "1.7" case s => s } } i suppose due fact, default javacoptions supplied plugin 1.5, , adding setting doesn't work, replacing it.

cpu - how many instructions can it execute in one second? -

a processor has 4 cores each core has 2 - hyper threads its clock frequency 2 ghz on average, instruction needs 4 cpu cycles execute on each hyperthread how many instructions can execute in 1 second? need equations use. know 1 ghz has 1 cpu cycle @ 1 nano second therefore 2 ghz 1 cpu cycle in .5 nano seconds. well, i'll started, it's basic math problem. 2ghz - frequency, in [cycles/second]. 4 - instruction duration, in [cycles/ops]. so 2ghz [cycles/second] / 4 [cycles/ops] = 0.5ghz [ops/second] . note cycles unit cancels out , "feels right" because we're left units being asked :) do similar math account hyper-threads , cores - multiplication. (you can carry through units, e.g. [ops*threads*cores/second] , can dropped in context of answer asking ops/second across all v-cores.)

java - Hibernate GenericJDBCException : Field 'KeyID' doesn't have a default value -

hi trying create 1 many relationship string object different key id on same table. but when insert data show exception "general error message server: "field 'qid' doesn't have default value". how resolve problem in hibernate. please refer below code. <class name="com.db.hrquestion" table="hrquestion"> <id name="id"> <generator class="increment"></generator> </id> <property name="qname"></property> <list name="answers" table="answer"> <key column="qid"></key> <index column="type"></index> <element column="answer" type="string"></element> </list> </class> <class name="com.db.javaquestion" table="javaquestion"> <id name="id">

Adding methods to class and use them in other groovy code -

i'm new groovy. have class i'm adding methods using metaclass . here code have parser.groovy: privateclass.metaclass.convertddttomap { obj,filelocation -> } where privateclass class coming jar. in other file named hack.groovy have following code: class hack extends privateclass { //.. code convertddttomap(param,param) } when run hack.groovy, exception method convertddttomap not there. however parser.groovy in same classpath , gets compiled. not adding method. where i'm making mistake? parser.groovy being compiled doing nothing, code there needs called. example using new parser().run()

c++ - Code debugging error Arduino -

i facing 2 errors below program: on serial monitor not printing in main() . when enter lcd_call() function. if key being pressed goes next case. per program should stay in same window going case 1. void setup() { serial.begin(9600); } void loop() { serial.println("in main"); lcd_call(); } void lcd_call() { int menuoption=0; int button; { switch(menuoption) { case 0: serial.println("set+date:"); display_date_time(); timedbeep(shortbeep,1); break; case 1: serial.println("display:"); lcdclear(); lcd.print("display menu"); timedbeep(shortbeep,1); break; case 2: serial.println("set menu:"); lcdclear(); lcd.print("set menu"); timedbeep(shortbeep,1); break; } button=read_lcd_buttons(); if(button==btnright) { menuoption=menuoption+1; if(menuoption>2) {

Save dirty editors in Eclipse -

we have developed eclipse rcp applicatoin. have requirement check dirty editors , prompt user save same before launch our dialog. please let me know if have reusable dialog achieve same. thanks in advance, harish use org.eclipse.ui.ide.ide.savealleditors : iresource [] resources = array of ifile, ifolder, iproject boolean ok = ide.savealleditors(resources, confirm); from javadoc: save dirty editors in workbench editor input child resource of 1 of iresource's provided. opens dialog prompt user if confirm true. return true if successful. return false if user has canceled command.

ios7 - NSThread High CPU usage -

im trying using continually running thread perform tasks @ high rate in app. in app have list of 1000 or time stamps. poll them until it's time , instruct ausampler play. the problem have seem fundamentally not understand how nsthread works. in simple example below cpu shoots 100% despite no tasks being run. in way using nsthread incorrectly? better way create a fast polling mechanism doesnt hog cpu? mythread =[[nsthread alloc]initwithtarget:self selector:@selector(test) object:nil]; [audiothread setthreadpriority:0]; [audiothread start]; -(void)test { while(mycondition) { // work // cpu == 100% } } the solution find minimum interval between sampler fire times (based on bpm/ resolution) , make thread sleep amount.

serialization - Java Serializable object contains non-Serializable fields -

i use findbugs in eclipse, , there tons of "troubling" warnings. here sketch code: public class serializableobject implements serializable { private nonserializableobject nso; .. setter, getter, else } can cause troubles? or can ignore it? or should serialization everywhere touches? it in jsf web project. you have mark them transient when declare field transient ignored during serialization , deserialization process. keep in mind when deserialize object transient field field's value it's default (usually null.)

android - Facebook php api: share facebook app message -

i have create facebook app interact android app, , have server user register himself (for using app) facebook account. want when user register himself firs time server, link (with app logo , link app page) automatically shared on facebook wall. how can do? the best way without spamming: https://developers.facebook.com/docs/reference/dialogs/feed/ although not open dialog after user registration, include button user can click share. as commented already: never post automatically on wall of user, let user decide. that website, or "web app". if talking native app, may you: https://developers.facebook.com/docs/android/share

database - Error 1215 MySQL (Error Code: 1215 Cannot add foreign key constraint) -

good morning. i've problem database i'm designing. have 5 tables , 1 many many relation. table has multiple foreign key others tables. create database mysql worckbecnh , when it's creating table "partido" gives me error 1215 foreign keys. looking attributes differents types, primary keys doesn't defined think don't find nothing wrong in code put here code yoy can me. thank you. create table pabellon ( codigo_pabellon int not null, nombre varchar(30), codigo_localidad int(3), primary key (codigo_pabellon), foreign key (codigo_localidad) references localidad (codigo_localidad) ); create table jornada ( codigo_jornada int not null auto_increment, numero int(2), codigo_competicion int not null, primary key (codigo_jornada) ); create table equipo ( nif varchar(9) not null, nombre varchar(30), direccion varchar(20), telefono varchar(20), primary key (nif) ); create table equipo_arbitral (

Echo a php function in a javascript -

i have following javascript function showit(item,i,j,max){ var id; actualitem=item; for(var x=1;x<=i;x++){ id=item+"_"+x; document.getelementbyid(id).src="<?= suburl(); ?>/b.gif"; } for(var x=i+1;x<=max;x++){ id=item+"_"+x; if(x<=j) document.getelementbyid(id).src="<?= suburl(); ?>/y.gif"; else document.getelementbyid(id).src="<?= suburl(); ?>/w.gif"; } } i have tried <?= suburl(); ?> , <?php echo suburl(); ?> function suburl(); looks this: function suburl() { $suburl = 'http://localhost/www.site.com/static'; echo $suburl; } and it's not working on echoing in javascript. appears pure html. it's appreciated thank you. you try this: function showit(item,i,j,max){ var id; actualitem=item; var url = suburl(); //this new for(var x=1;x<=i;x++){ id=item+"_"+x; document.getelementbyid(id).src=ur

python - pyCharm Debugging: Variable Inspection, how to get more values? -

i dealing rather large arrays , when debug, need inspect them. problem though pycharm shows minority of values within array. instance, if debug code, following shown in "variables" window large numpy array of boolean values: [ true true true ..., true true true] even right click on variable , choosing "inspect..." open new window showing exact same shortened array. how can rid of ... in middle, or @ least extend display more first , last 3 entries? thanks!

php - File upload issue. using the w3school tutorial -

i @ w3school tutorial upload file. can understand code. first 2 version of code works, while doesn't. <?php $allowedexts = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $_files["file"]["name"]); $extension = end($temp); if ((($_files["file"]["type"] == "image/gif") || ($_files["file"]["type"] == "image/jpeg") || ($_files["file"]["type"] == "image/jpg") || ($_files["file"]["type"] == "image/pjpeg") || ($_files["file"]["type"] == "image/x-png") || ($_files["file"]["type"] == "image/png")) && ($_files["file"]["size"] < 20000) && in_array($extension, $allowedexts)) { if ($_files["file"]["error"] > 0)

Cannot connect Webstorm to FTP project -

Image
i trying connect webstorm web site, can work on files on network via ftp, can't seem ftp connection work. if connect website via filezilla : ... works perfect. however when try webstorm nothing seems work. here screenshot : error : note : username , password identical in both cases. on webstorm have tried number of things ftp host: www.blue-walrus.com, ftp.blue-walrus.com . , web server root url, have tried http://blue-walrus.com , , http://www.blue-walrus.com . where going wrong? please check if turning 'passive mode' (deployment/advanced options) on makes difference. if doesn't, please try following: shut down webstorm delete idea.log enable debug logging 'com.jetbrains.plugins.webdeployment' category (see devnet.jetbrains.com/docs/doc-1202 details) recreate problem , send idea.log jetbrains support

laravel - Linking elFinder stylesheet and JavaScript -

i have problem importing laravel elfinder. when use normal links: <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/smoothness/jquery-ui.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" ></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="/laravel4_test2/public/filemanager1/css/elfinder.min.css"> <script type="text/javascript" src="/laravel4_test2/public/filemanager1/js/elfinder.min.js"></script> <!-- mac os x finder style jquery ui smoothness theme (optional) --> <link rel="stylesheet" type="text/css&quo

java - Declare and iterate through ArrayList of classes that extend a class -

i may going wrong way, possible iterate through collection of classes extend specific class? i'm thinking of declaring : arraylist<? extends interfacecomponent> components = new arraylist<? extends interfacecomponent>(); but throws error. possible? edit : , iterate though : (<? extends interfacecomponent> t : components) { t.callsomemethod(); } right? try this: arraylist<interfacecomponent> components = new arraylist<interfacecomponent>(); and on list can have object implements interfacecomponent . edit: iterate this: for (interfacecomponent t : components) { }

java - Displaying frames in an applet -

i writing java swing application. consists of graphing tool added library. works fine desktop application. however, i'm trying convert application applet , graphing frame won't come on browser. code invoking graphing frame is: double x[] = {1,2,3,4,5,6,7,8}; double y[] = {1,0,1,0,1,0,1,0}; plot.addlineplot("plot", color.blue, x, y); jframe frame = new jframe("a plot panel"); frame.setsize(1400, 730); frame.setcontentpane(plot); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); i typed same lines in applet won't work in browser. how make work in applet? extend applet class, add gui elements accordingly, can not show frame in browser applet provided main container frame or jframe in desktop application. example:- public class myapplet extends applet{ public void paint(graphics g){ /* applet code here */ g.setcolor(color.red); g.drawrec

How to sort an list first letter ascending and last letter decending in java? -

i have list values 1alfreda 1alfredb 1alfredc 2benb 2benc 2benb i want list sorted out first letter ascending , last letter descending sorted list 1alfredc 1alfredb 1alfreda 2benc 2benb 2bena how can in java ? plz help. not tested it, this, should work. collections.sort(list, new comparator<string>() { public int compare(string e1, string e2) { int c = new character(e1.chartat(0)).compareto( e2.charat(0) ); if( c!=0 ) return c; return new character(e2.chartat(e2.length()-1)).compareto( e1.charat(e1.length()-1) ) } });

linux - Why are gethostbyname and gethostbyaddr considered obsolete? -

the man page gethostbyname (3) states functions gethostbyname , gethostbyaddr obsolete, , getaddrinfo (3) , getnameinfo (3) should used instead. doesn't, however, explain reason why former obsolete. can please point me resource explains matter further? from opengroup the gethostbyaddr() and gethostbyname() functions may return pointers static data, may overwritten subsequent calls of these functions. the getaddrinfo() , getnameinfo() functions preferred on gethostbyaddr() , gethostbyname() functions. posix cautions gethostbyaddr() and gethostbyname() may withdrawn in future version of spec. other reason these 2 functions can't work ipv6 well, getaddrinfo() , getnameinfo() should used instead.

java - Unable to write to Text File Exist in FTP server -

i use below code write text file exists in ftp server.but got java.net.malformedurlexception url url = new url("ftp://p@g.com:g@1234@ftp.xyz.com/testjar/2014-03-06-p.txt;type=i"); urlconnection urlc = url.openconnection(); outputstream os = urlc.getoutputstream(); // upload outputstream buffer = new bufferedoutputstream(os); objectoutput output = new objectoutputstream(buffer); output.writeobject("hiiiii"); buffer.close(); os.close(); output.close(); above username , password not real demo looks real. know how solve issue or other method write .txt file,let me inform. edit1:also username , pass contains @ char , in pass number there. full error: java.net.malformedurlexception: input string: "g@1234@ftp.xyz.com" @ java.net.url.<init>(url.java:619) @ java.net.url.<init>(url.java:482) @ java.net.url.<init>(url.java:431) @ createfolder.uploadfile(createfolder.java:3

sql - How to query MySQL if data in one field look like 32;13;3;33 and the condition is where 3 -

i have table in 1 column filled data 32;3;13;33;43 so select * table; gives like name ids vegetables 13;3;63 fruits 37;73;333 when i'm querying mysql like select * table ids '%3%' it gives me both records want containing 3. how query mysql correctly? try use: select * table concat(';',ids,';') '%;3;%'

java - XMPP and ANDROID -

i trying make xmpp client android using http://davanum.wordpress.com/2007/12/31/android-just-use-smack-api-for-xmpp/ i have been facing multiple issues in it first of host name , service name both same i.e. web.vlivetech.com then not know jar file ned include in lib folder have included 1- asmack-android-7 giving me error on classes noclassdeffound then have removed , included smack-3.4.1-0cec571.jar but giving me error networkonmainthread here code xmppclient public class xmppclient extends activity { private arraylist<string> messages = new arraylist(); private handler mhandler = new handler(); private settingsdialog mdialog; private edittext mrecipient; private edittext msendtext; private listview mlist; private xmppconnection connection; /** * called activity first created. */ @override public void oncreate(bundle icicle) { super.oncreate(icicle); setcontentview(r.layout.activity_xm

How to identify if a .ppt file is in 2003 format or 97 format or 95 format -

i have xxx.ppt file. need identify if file in 2003 format or 97 format or 95 format or version older that. tried checking file properties, says microsoft powerpoint. no version mentioned. tried apache poi , got version number "ppt version[50334156]" . couldn't find specification documents pre 97 format files either. working these binary files such pain. i have no idea why need found extreamly interesting (can done?) wrote ugly powershell hack. $shell = new-object -com shell.application rename-item c:\temp\presentation1.ppt c:\temp\presentation1.zip $zip = $shell.namespace(“c:\temp\presentation1.zip”) mkdir c:\temp\ziptest foreach($item in $zip.items()) { $shell.namespace(“c:\temp\ziptest”).copyhere($item) } $file = get-content c:\temp\ziptest\docprops\app.xml | select-string -pattern ("<appversion>([\s\s]*?)</appversion>") remove-item -recurse -force c:\temp\ziptest\ clear echo $file.matches[0].groups[1].value to u

How do I add a product specific facebook share button to order confirmation page? -

i've looked high , low around web looking answer question answers don't quite give me i'm looking for... i have e-commerce site i'd add share button order confirmation page that, when clicked, shares specific product have purchased. how go doing this? each product needs have unique url in order shared. url use when generating share button. when implementing share button , you'll need javascript sdk (as mentioned in link) , once have that, you'll need have html on page: <div class="fb-share-button" data-href="http://your-product-url" data-type="button_count"></div> the data-href attribute want dynamic , swap out each product want share.

SQL server 2008 R2 cannot attach database -

Image
basically want attach .mdf file located in d(you can see picture), got error. idea why happened , how fix it? there may 2 solutions that 1) may start sql server management studio application right clicking , selecting "run administrator" run , try attach database in d: 1) may put database in default directory of database c:\program files\microsoft sql server\mssql10_50.mssqlserver\mssql\data etc ....

algorithm - How to find all subsets of a multiset that are in a given set? -

say have set d of multisets: d = { {d, g, o}, {a, e, t, t}, {a, m, t}, } given multiset m , like m = {a, a, m, t} i algorithm f give me elements of d subsets (or more precisely, "submultisets") of m : f = {{a, m, t}} if 1 such query, scanning on elements of d (in o(#d) time) optimal. if want answer many such queries same d , different m , might able make faster preprocessing d smarter data structure. we toss of d hashtable , iterate on possible subsets of m , looking each in hashtable, that's o(2^#m) . fine small m , not fine medium large m . is possible in polynomial time in #m ? or maybe reduce known np-complete problem one, prove it's impossible fast? edit: realized in worst case, need output of d , #d still going appear in time complexity. let's assume size of output bounded constant. here quick implementation of ternarysearchtree (tst) can in problem. number of years ago, inspired article in drdobbs. can read more

javascript - AngularJS: directive to toggle class depending on array value -

i'm new angular , have ng-grid table. want save clicked elements in array (so elements uniquely correspond table cells) , strike cells through, in array. has happen in "toggleable" way. so far cells like: <div ng-click="myfunc(args)" ...><span>text</span></div> and myfunc takes care of array, in factory. did dom manipulation same function thought angular way should create directive span element, evaluates array , depending on whether object corresponds cell containing particular span css class attached. fyi: elements in array contain coordinates of cells (x,y), stored interaction server. bind array scope , use ng-class syntax bind class matching condition. condition not straightforward, wrote function evaluate condition , works fine ng-class

c++ - Why doesn't removing the last scene in cocosd2d-x trigger the scenes destructor? -

i've added player* _player pointer helloworldscene scene in cocos2d-x v.2.2.2. i've defined class player : public cocos2d::object , it's referenced counted. create method helloworldscene looks scene* helloworldscene::createscene(player* player) { auto scene = scene::create(); auto layer = helloworldscene::create(); layer->_player = player; player->retain(); scene->addchild(layer); return scene; } where player instantiated in appdelegate::applicationdidfinishlaunching() . now, since i've retained _player (and feel nice guy today), i've decided release well: helloworldscene::~helloworldscene() { if (_player) { _player->release(); } } so far good. however, when helloworldscene popped, following called void director::popscene(void) { ccassert(_runningscene != nullptr, "running scene should not null"); _scenesstack.popback(); ssize_t c = _scenesstack.size(); if (c == 0) { end(); } else

pointers - How to use inteface blocks to pass a function to a subroutine? -

i understand interface command can used pass a function subroutine. example in main program i'd define function , pass subroutine like: mainprogran use .... implicit none type decorations etc interface function test(x,y) real, intent(in) :: x, y real :: test end function end interface call subroutine( limit1, limit2, test, ans) end mainprogram is correct way of doing this? i'm quite stuck! within subroutine there need put let know function coming in? subroutine in case library don't want have keep recompiling change function. module: module fmod interface function f_interf(x,y) real, intent(in) :: x, y real :: f_interf end function end interface contains function f_sum(x,y) real, intent(in) :: x, y real f_sum f_sum = x + y end function function f_subst(x,y) real, intent(in) :: x, y real f_subst f_subst = x - y end function subroutine subr(limit1

Select with two tables in MySQL -

this question has answer here: sql select multiple tables 6 answers i have 2 tables hits , posts . in hits table have id_post,hits , posts table have id,title i need build report posts related hits , order hits. can me select ? thanks select posts.id id, posts.title title, hits.hits hitsdate posts inner join hits on hits.id_post = posts.id order hits.hits

windows server 2012 r2 - Remote Desktop Services required? -

i'm running windows 2012 r2 server set in november 2013. while started getting warnings icon in notification area informing me "[the] remote desktop service trial period end in x days". warning pops every time or of co-workers connect machine in question. has me bit puzzled. @ first, assumed wouldn't have worry it, deadline comes ever nearer, i'm growing bit concerned. do need "remote desktop service" in order connect machine remote location or can still manage machine after trial period expires? physical location of server in question makes troublesome me manage without form of remote desktop tool. thanks in advance! yes. there licensing specific rds on servers. check microsoft online , should able tell required.

c# - Acessing custom property with AddComponent -

in unity3d i've got script adds variable 'eaten' component. using unityengine; [addcomponentmenu("my game/iseaten")] public class iseaten : monobehaviour { public bool eaten; } yay! can add script access 'eaten' using unityengine; using system.collections; public class test : monobehaviour { private eaten somescript; // use initialization void start () { somescript = getcomponent<iseaten>(); bool temp = somescript.eaten; print(temp); // false } } which works fine. have access variable dot notation script? ie if (mycube.eaten == true) { // } you know, in unity 1 create whole script add single property object. common approach think of scripts 'components' (which are, in fact). let me explain this, component single piece of code add functionality gameobject , ability animate, or behave laws of physics. so, maybe, better reform iseaten class form true component, pi