pid label text 39424767 0 android studio emulator: WARNING: Increasing RAM size to 1024MB

I am trying to build my first android application in Android Studio, following the tutorial https://developer.android.com/training/basics/firstapp/creating-project.html, using AndroidStudio 2.1.2.

Whenever I run the emulator, I get this error message:

Android Emulator could not allocate 1.0 GB of memory for the current AVD configuration. Consider adjusting the RAM size of your AVD in the AVD Manager. Error detail: QEMU 'pc.ram': Cannot allocate memory

Decreasing the size of the memory on the Nexus5x emulator has no effect, so the error message still says "could not allocate 1.0 GB", even when I adjust the memory of the AVD to 256MB. The app needs to run on Android 6.0, with a Nexus5x emulator, so I can't try with a different emulator. Any help would be much appreciated :)

8991182 0 Difference between different datasources

Him Please explain what is the difference between different datasources for SQL (shown in the pic.)

I mean difference between Microsoft SQL Server and Microsoft SQL Server Database File

enter image description here

26237094 0

Use a separate query analyzer with the KeywordTokenizerFactory, thus (using your example):

 <analyzer type="index"> <tokenizer class="solr.LowerCaseTokenizerFactory"/> <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="false" /> <filter class="solr.ShingleFilterFactory" maxShingleSize="5" outputUnigrams="false"/> <filter class="solr.RemoveDuplicatesTokenFilterFactory"/> </analyzer> <analyzer type="query"> <tokenizer class="solr.KeywordTokenizerFactory"/> <filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" enablePositionIncrements="false" /> <filter class="solr.LowerCaseFilterFactory"/> <filter class="solr.RemoveDuplicatesTokenFilterFactory"/> </analyzer> 
29714091 0 how to save and restore an object into a file in matlab?

I have a class like this:

classdef my_class properties prop_a prop_b end methods(Static) ... function o = load() ??? end end methods function save(o) ??? end ... end end 

Please help me to write save and load methods. name of methods is clear and they should save and restore an object from a text file...

the properties are quite dynamic and have different row/col number.

25989684 0 How to bind an alert message with the controller?

Hi guys I've been experimenting with a simple commenting app with AngularJS and I'm stuck on how to get an alert message popup in the view if a user inputs an empty string into an input field.

The HTML view and ng-show logic as below:

<div ng-show="alert===true" class="alert alert-warning alert-dismissible inner" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times; </span><span class="sr-only">Close</span></button> <strong>Warning!</strong> You did not submit a comment. </div> 

The controller view and $scope logic as below:

// pushes data back to Firebase Array $scope.addComment = function(){ if ($scope.newComment.text === ''){ $scope.alert = true; } else { $scope.alert = false; } $scope.comments.$add($scope.newComment); $scope.newComment = {text: '', date: ''}; }; 

The problem is that although I can bind the alert message logic to the HTML view, the alert message only shows up once and cannot be re-used again if the user types in an empty string again.

Should I use a while loop or something for this? Any help would be much appreciated!

EDIT:

Thanks to meriadec's feedback, I have made a fix using a more simple codebase, as follows.

The HTML view and ng-show logic as below:

<div ng-show="alert===true" class="alert alert-warning inner" role="alert"> <button type="button" class="btn" ng-click="alert=false"><span aria-hidden="true">&times; </span><span class="sr-only">Close</span></button> <strong>Warning!</strong> You did not submit a comment. </div> 

The controller view and $scope logic as below:

// pushes data back to Firebase Array $scope.addComment = function(){ if ($scope.newComment.text === ''){ return $scope.alert = true; }; $scope.comments.$add($scope.newComment); $scope.newComment = {text: '', date: ''}; }; 
4841203 0 how to create a pam module?

Can anyone tell me about this... I want to create a pam module similar to the login module in /etc/pam.d

20086791 0 How can I send an email with a layout

I am using grails mail plugin. When I submit my form, it will send an email from aaa@example.com to textField name="email successfully but how can I send an email with a layout...not blank like this picture http://www.4shared.com/photo/uT2YUCfo/Capture__2_.html or maybe some CSS..

FORM

<g:form action="send"> <table style="width:500px"> <tbody> <tr> <td>Your Email Address </td> <td><g:textField style="width:250px" name = "email"/></td> </tr> <tr> <td>Your Name</td> <td><g:textField style="width:250px" name = "user"/></td> </tr> <tr> <td><input type="submit"/></td> </tr> </tbody> </table> </g:form> 

MAIL CLOSURE

def send = { sendMail { to params.email from "aaa@yahoo.com" subject "Test Reset Password" body(view:"/user/layoutmail",model:[name:params.user]) } render "Email Terkirim" } 
30733824 0

Yes. The code is executed in serial.

25159920 0

You may start with that base : http://jsfiddle.net/8r99k/
I put sample text and only a few css :

html{ margin:0; padding:0; width:calc(100% - 100px); height:calc(100% - 100px); border:solid #eeeeee 50px; overflow:hidden; } body{ margin:0; padding:0; height:100%; overflow:auto; } 

Update
Adding width:100% and padding-right:70px to body
http://jsfiddle.net/8r99k/2/

11137452 0

Considering the fact that you want to get "select new " shown ... you still need to send something to the view. Take the entity with the most fields that are present in your new entity.

Create a partial class

namespace YourDomain.Model { [MetadataType(typeof(EntityWithinXList))] public partial class EntityWithinXList { [DataMember] public string DesiredFieldFromA{ get; set; } [DataMember] public int DesiredFieldFromB{ get; set; } } public class EntityWithinXList { } 

So you need to add 2 new fields from 2 other tables to your entity:

 var list = (from x in xList join a in AList on x.commonfield equals a.commonfield join b in BList on x.newCommonField equals b.newCommonField select new { x, a.DesiredFieldFromA, b.DesiredFieldFromB }).ToList(); list.ForEach(el => { el.x.DesiredFieldFromA= el.DesiredFieldFromA; el.x.DesiredFieldFromB= el.DesiredFieldFromB ; }); return list.Select(p=>p.x); 

Unless I've misunderstood your question this should do it . And the list that you are sending to the view is List<EntityWithinXList>

20357993 0 Creating mobile app in Symfony2

I read that there is an option to create a mobile app in symfony2 and I don't really understand how to create it. As much as I do understand the concepct of emulating HTML5 to native app I don't know HOW to do the same thing with symfony.

Lets say that we created the app in html5. We just go through the process with PhoneGap and it creates the native app ( yeah, I know, very simplified ). But how should I do it with Symfony? I mean.. is there any similar emulator for php and...all the files that symfony contains or.. or what? How to make it work on iOS, how on Android, how on Windows Phone and BlackBerry..

Sorry for dumb question but I couldn't find proper answer.

33034681 0

In the Jake Wharton U2020 application it is solved in the next way

Add to you gradle.build file

configurations.all { resolutionStrategy { force 'com.android.support:support-annotations:23.0.1' } } 
40416451 0 Query returing no results codename one

Query showing no results and not giving any error .control not entering inside the if block help me out that where is the mistake i am doing ? i have tried many ways to get the result but all in vain. When i tried the following before the if statement

int column=cur.getColumnCount(); Row row=cur.getRow(); row.getString(0); 

then i got the resultset closed exception

Database db=null; Cursor cur=null; System.out.print("Printing from accounts class "+Email+Password); String [] param={Email,Password}; System.out.print(param[0]+param[1]); try{ db=Display.getInstance().openOrCreate("UserAccountsDB.db"); cur= db.executeQuery("select * from APPUserInfo WHERE Email=? AND Password=?",(String [])param); int columns=cur.getColumnCount(); if(columns > 0) { boolean next = cur.next(); while(next) { Row currentRow = cur.getRow(); String LoggedUserName=currentRow.getString(0); String LoggedUserPassword=currentRow.getString(1); System.out.println(LoggedUserName); next = cur.next(); } } }catch(IOException ex) { Util.cleanup(db); Util.cleanup(cur); Log.e(ex); } finally{ Util.cleanup(db); Util.cleanup(cur); } 
5745113 0

If I understood your question, you want the duplicated row of selects to reset their values.

In this case you can just remove this:

dropdownclone.find('select').each(function(index, item) { //set new select to value of old select $(item).val( $dropdownSelects.eq(index).val() ); }); 

and replace it with:

dropdownclone.find('option').attr('selected', false); 
38242048 0 Expect not accepting negative values

I am trying to run expect with negative values. But I'm getting bad flag error.

Test File:

echo "Enter Number:" read num echo $num 

Expect File:

spawn sh test.sh expect -- "Enter Number:" {send "-342345"} 

I even tried to escape negative values with \ option still it's not working.

2230111 0 What to not include in Git repository?

Possible Duplicate:
Which files in a Visual C# Studio project don’t need to be versioned?

when creating a repository, what do you include in the repository, should folders like Resharper, Debug and Bin folder be included? if not, is it possible to exclude files/folders from the unstaged changes check?

12513218 0

This will definitely do the task for you.

tTable = {} OldIDX, OldIDX2, bSwitched, bSwitched2 = 0, 0, false, false for str in io.lines("txt.txt") do local _, _, iDx, iDex, sIdx, sVal = str:find( "^%| ([%d|%s]?) %| ([%d|%s]?) %| (%S?) %| (%S?) %|$" ) if not tonumber(iDx) then iDx, bSwitched = OldIDX, true end if not tonumber(iDex) then iDex, bSwitched2 = OldIDX2, true end OldIDX, OldIDX2 = iDx, iDex if not bSwitched then tTable[iDx] = {} end if not bSwitched2 then tTable[iDx][iDex] = {} end bSwitched, bSwitched2 = false, false tTable[iDx][iDex][sIdx] = sVal end 

NOTE

The only thing you can change in the code is the name of the file. :)

EDIT

Seems like I was wrong, you did need some changes. Made them too.

20801157 0

Normally it can't. It will complain about libc being too old, for one.

If you statically link with libstdc++ and carefully avoid newer glibc features, you may be able to get away with it. The latter is not always possible though. Static linking with libc is not officially supported and may work or not work for you.

1221935 0

I think you can't with the grouped style of the UITableView. You could however use the plain style, and create your own view to show as the cell, just like the grouped view.

22237682 0

You have to declare the overload in the header and define it in the cpp file. Ex.:

MyHeader.h:

Fraction& operator+(const Fraction& l, const Fraction& r); 

MyFile.cpp:

Fraction& operator+(const Fraction& l, const Fraction& r){ // ... 
40292211 0

Change the add to cart text on product archives by product types Here is a Complete Example

Change this line as per your needed !

case 'variable': return __( 'Select options', 'woocommerce' ); 

Complete code Add the following to your functions.php file and edit the buttons text.

add_filter( 'woocommerce_product_add_to_cart_text' , 'custom_woocommerce_product_add_to_cart_text' ); function custom_woocommerce_product_add_to_cart_text() { global $product; $product_type = $product->product_type; switch ( $product_type ) { case 'external': return __( 'Buy product', 'woocommerce' ); break; case 'grouped': return __( 'View products', 'woocommerce' ); break; case 'simple': return __( 'Add to cart', 'woocommerce' ); break; case 'variable': return __( 'Select options', 'woocommerce' ); // Change this line break; default: return __( 'Read more', 'woocommerce' ); } } 
19292671 0

Try this:

textarea { overflow-x: vertical; } 
21975919 0

That error means that Laravel is trying to write data to your storage/view file, but it doesn't have permissions (write access). Storage/view is a folder for caching view files.It is default Laravel behaviour, so change permissions on whole storage folder, becuse there is more files inside, that Laravel will try to use for other purposes. For example, services.json is used when you add new service provider, and if it is locked, Laravel will complain.

40545851 0 jQuery - Search on text entry - delay until full term entered

I have the following code, which detects any text entered into the #search-box field and then immediately runs the search (if greater than 2 characters):

$('#search-box').on('input', function() { var term = $(this).val(); if (term.length > 2) { //execute search and display results } }); 

This doesn't look pretty though, as if you were to type dollar for example, after 'doll' a load of dolls will appear, which will then be replaced with dollars once dolla is entered. This can happen in a split second.

What I'd like to do is determine whether the user has finished the search term. Is it possible to wait for a second or 2 before doing the search? And if in that waiting period the user enters another letter, it resets the clock?

3622549 0 Idiomatic way to write .NET interop function

I'm looking for a more idiomatic way, if possible, to write the following clojure code:

(import '(System.Net HttpWebRequest NetworkCredential) '(System.IO StreamReader)) (defn downloadWebPage "Downloads the webpage at the given url and returns its contents." [^String url ^String user ^String password] (def req (HttpWebRequest/Create url)) (.set_Credentials req (NetworkCredential. user password "")) (.set_UserAgent req ".NET") (def res (.GetResponse req)) (def responsestr (.GetResponseStream res)) (def rdr (StreamReader. responsestr)) (def content (.ReadToEnd rdr)) (.Close rdr) (.Close responsestr) (.Close res) content ) 

This is on ClojureCLR and works. (the fact that it's the CLR variant doesn't matter much)

I'd like to get rid of the defs (replace by lets? can they refer to each other?)

How about a better way to get to the stream - keeping in mind that .. chaining won't work because I need to Close the streams later on.

EDIT: After the answer, I found a much easier way in .NET to download a web page using the WebClient class. I still used many of Michal's recommended approaches - just wanted to record what I now believe to be the best answer:

(defn download-web-page "Downloads the webpage at the given url and returns its contents." [^String url ^String user ^String password] (with-open [client (doto (WebClient.) (.set_Credentials (NetworkCredential. user password "")))] (.DownloadString client url))) 
6267788 0 Making pre- and post-build event scripts pretty?

I have some moderately hefty pre- and post-build event scripts for my Visual Studio 2008 projects (actually it's mainly post-build event scripts). They work OK in that they function correctly and when I exit 0 the build succeeds and when I exit 1 the build fails with an error. However, that error is enormous, and goes something like this:

The command "if Release == Debug goto Foo if Release == Release goto Bar exit 0 :Foo mkdir "abc" copy "$(TargetDir)file.dll" "abc" [...] " exited with code 1. 

You get the idea. The entire script is always dumped out as part of the error description. The entire script is also dumped out in the Output window while the build is happening, too. So, why have I seen various references on the web to using echo in these scripts? For example, here's part of an example on one particular site:

:BuildEventFailed echo POSTBUILDSTEP for $(ProjectName) FAILED exit 1 :BuildEventOK echo POSTBUILDSTEP for $(ProjectName) COMPLETED OK 

Is there a way to get Visual Studio to suppress all script output apart from what is echoed (and therefore using echo only to output what you want would make sense), or are these examples just misguided and they don't realize that the whole script is always dumped out?

34633552 0

There are a few ways to do this:

1) PHP: Using PHP, you can simply include an html file into another one

<?php include('fileOne.html'); ?> 

2) jQuery: Using jQuery, you can load an HTML page dynamically into another (this is kind of hacky in my opinion):

<html> <head> <script src="jquery.js"></script> <script> $(function(){ $("#includedContent").load("b.html"); }); </script> </head> <body> <div id="includedContent"></div> </body> </html> 

Source: Include HTML Page via jQuery

3) Framework: Using a framework like Python/Django, you can use {% include %} blocks to create standalone html files that can be reused like blocks.

<html> {% include 'navbar.html' %} </html> 

My honest recommendation is #2 if you have to stay with just raw html, otherwise, if you are using PHP then includes are a no brainer. The last option is the frameworks, and that is really only if you have other heavy-duty functions you would need.

2430673 0

i think you must miss some proper argument which should be a pointer type in your method declaration.

16607326 0

480 * 800 is a mdpi device. You can can put these image resources in drawable-mdpi if you want the device to auto adjust for smaller and larger screen sizes. If you want these images to be of maximum size you can put it in drawable-xhdpi. If not i.e. if you want same image to be used in all the screen sizes then you can simply put in drawable folder in resource.

For more information you can check this :developer link

30421058 0 How to tell Faraday to preserve hashbang in site URL?

I'm working on a fork of a library that implements Faraday to build URLs.

site = "https://example.io/#/" path = "oauth/authorize" connection = Faraday.new(site) resource = Faraday::Utils.URI(path) URL = connection.build_url(resource) 

Notice that my site URL ends with a hashbang. But when the above code is executed, Faraday strips out the hashbang entirely:

https://example.io/oauth/authorize

But my application requires it to build this URL (with the hashbang):

https://example.io/#/oauth/authorize

Now before I go ripping out Faraday and monkey-patching something terrible.. can I do this by setting an option on Faraday?

5373508 0

You can simply overload the enqueue class to take both Dates and Integers. In either case, it sounds like you need a method getValue() in CInteger that lets you access the int value.

public class CInteger { //constructors, data public void getValue() { return i; } } 

and then you can have two enqueue() methods in your other class:

public void enqueue(Date d) { add(tailIndex, d); } public void enqueue(CInteger i) { add(tailIndex, new Integer(i.getValue()); //access the int value and cast to Integer object } 

And Java will know which one you are calling automatically based on the parameters.

14994030 0

To programmatically instantiate the component instead of a declarative implementation, use addElement() to add components to the display list.

For example, to add a visual element to a Spark Group named container.

<?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" creationComplete="creationCompleteHandler(event)"> <fx:Script> <![CDATA[ import mx.core.UIComponent; import mx.events.FlexEvent; protected function creationCompleteHandler(event:FlexEvent):void { var component:UIComponent = new UIComponent(); component.x = 5; component.y = 5; container.addElement(component); } ]]> </fx:Script> <s:Group id="container" /> </s:Application> 

Within script blocks, use package namespaces instead of MXML namespaces.

import com.msns.Component; var component:Component = new Component(); component.x = 5 
29693526 0 Are there any Java APIs for for planning or say creating time table

Some time back, while Googling, I found a Java API (as I remember it was an Apache project but I am not sure) for creating timetables. By time table I mean simple timetable used in schools and colleges

Unfortunately I didn't take note of that API and now I cannot find it.

Please tell me if you know any such open source API available in Java.

40956699 0 Hide attributes out of stock on product page PRESTASHOP 1.6

I need help with hiding attributes out of stock on product page when selected some of attributes. Prestashop 1.6.1.9 I did not find ready-made solution. I'm bad at programming in php and java script, I believe I should be the knowledge that would solve this problem.

For example.

Product combinations should disappear if a certain combo is not currently in stock. For example on one product we might have S M L and 5 color variations, so 15 options. But maybe we only have size M in one color. The customer has to click through each color to find what is available as all colors show up if there is even one size M color available. It's only a problem when combos are partially out of stock.

It is necessary to make it work for the block as in the screenshot.

I would be very grateful for any help. Thanks in advance. Best Regards. Aleksandrs

Screenshot

1502685 0

You can open an interactive shell by right-clicking on the project, selecting Scala-> Create interpreter in XYZ.

9960073 0

You can use mktime() or strtotime()

$input_time = mktime(0,0,0,$_POST['m']+1,0,$_POST['y']); if ($input_time < time()){ print '<p class = "error">Date has elapsed</p>'; } 
1769169 0

Toy can try something like this

 declare @t table (i int, d datetime) insert into @t (i, d) select 1, '17-Nov-2009 07:22:13' union select 2, '18-Nov-2009 07:22:14' union select 3, '17-Nov-2009 07:23:15' union select 4, '20-Nov-2009 07:22:18' union select 5, '17-Nov-2009 07:22:17' union select 6, '20-Nov-2009 07:22:18' union select 7, '21-Nov-2009 07:22:19' --order that I want select * from @t order by d desc, i declare @currentId int; set @currentId = 4 SELECT TOP 1 t.* FROM @t t INNER JOIN ( SELECT d CurrentDateVal FROM @t WHERE i = @currentId ) currentDate ON t.d <= currentDate.CurrentDateVal AND t.i != @currentId ORDER BY t.d DESC SELECT t.* FROM @t t INNER JOIN ( SELECT d CurrentDateVal FROM @t WHERE i = @currentId ) currentDate ON t.d >= currentDate.CurrentDateVal AND t.i != @currentId ORDER BY t.d 

You must be carefull, it can seem that 6 should be both prev and next.

19205962 0

I also get this error sometimes but only on the emulator - seems like an emulator bug to me.

Android - Emulator internet access helped me a lot. :)

3263295 0

This has worked for me

$(window).bind("resize", function(e){ // do something }); 

You are also missing the closing bracket for the resize function;

40045543 0 Rearrange and save images in gallery using jQuery,php,MySQL

I've a dynamic gallery created with php and MySQL. Images are loaded from database tables and are shown according to auto increment id. However I need to sort the images by drag and drop system. I've implemented drag n drop with jquery. I need to rearrange them and their order should be stored in database table.

I've used the below drag and drop jquery and is working properly.

<script type="text/javascript"> $(function() { $("#dragdiv li,#dropdiv li").draggable({ appendTo: "body", helper: "clone", cursor: "move", revert: "invalid" }); initDroppable($("#dropdiv li,#dragdiv li")); function initDroppable($elements) { $elements.droppable({ activeClass: "ui-state-default", hoverClass: "ui-drop-hover", accept: ":not(.ui-sortable-helper)", over: function(event, ui) { var $this = $(this); }, drop: function(event, ui) { var $this = $(this); var li1 = $('<li>' + ui.draggable.html() + '</li>') var linew1 = $(this).after(li1); var li2 = $('<li>' + $(this).html() + '</li>') var linew2 = $(ui.draggable).after(li2); $(ui.draggable).remove(); $(this).remove(); var result = {}; var items = []; $('#allItems').each(function () { var type = $(this).attr('data-type'); $(this).find('li').each(function (index, elem) { items.push(this.innerHTML); }); result[type] = items; }); // alert(items); alert($('.lb').attr('id')); initDroppable($("#dropdiv li,#dragdiv li")); $("#dragdiv li,#dropdiv li").draggable({ appendTo: "body", helper: "clone", cursor: "move", revert: "invalid" }); } }); } }); </script> 

The php n MySQL code for display images in gallery is given below

<div class="box-content" id="maindiv"> <br> <div id="dragdiv"> <?php $sql1=mysql_query("select bnr_img_id,bnr_img_name,img_cap from xhr_bnr_images where bnr_img_par='$id' order by bnr_img_id desc "); $n1=mysql_num_rows($sql1); if($n1>0) { ?> <ul id="allItems" runat="server" class="col-md-12" > <?php while($row1=mysql_fetch_array($sql1)) { ?> <li> <div class="lb" id="<?php echo $row1['bnr_img_id'];?>"> <img src="banner/<?php echo $row1['bnr_img_name'];?>" width="177px" height="150px"> <br/><br/> <div><input id="cap<?php echo $row1['bnr_img_id'];?>" value="<?php echo $row1['img_cap'];?>" onblur="update_caption('<?php echo $row1['bnr_img_id'];?>')" style="font-size:12px;font-weight:normal;width:180px;" type="text"></div> <a href="javascript:void(0);" onclick="del_this('<?php echo $row1['bnr_img_id'];?>','<?php echo $row1['bnr_img_name'];?>')">delete</a> </div> </li> <?php } ?> </ul> <?php } ?> </div> </div> 

I need to get the replaced image id and their values should be shuffled when dragged.

Captions of the images updated by onblur function and its id will be send to another php file via ajax

20977271 0

You have to enclose the value of pm in quotation marks too:

result = Evaluate({@DBlookup("":"";"":"";"admin";"} & pm & {";1)}) 

This way it is recognized as a string.

Example:

If pm has a string value "Domino" then Evaluate string has to look like this:

@DBlookup("":"";"":"";"admin";"Domino";1) 

but in your original formula version it would be

@DBlookup("":"";"":"";"admin";Domino;1) 

BTW, the code would break if pm would contain a quotation mark. If you are sure that can't happen then the code is fine.

2778629 0 TLS/SRP in browsers?

Is there a plan or existing implementation of RFC 5054 in any of the major browsers yet?

If nobody has an implementation yet, then which major browsers have it on their roadmap? Where?

22163107 0

No it is not equivalent

If you want to support only jQuery 1.8+ then you can use .addBack() - Demo

var foo = $some.find(theCriteria).addBack(theCriteria); 

else you can use .add

var foo = $some.find(theCriteria).add($some.filter(theCriteria)); 

It is not the same because of 2 reasons Demo: Fiddle

6917637 0 PHP Error only present in Internet Explorer

Okay this has baffled me. My script works in Mozilla but not IE. I get this error in IE:

Warning: move_uploaded_file(uploads/properties/yh96gapdna8amyhhmgcniskcvk9p0u37/) [function.move-uploaded-file]: failed to open stream: Is a directory in /homepages/19/d375499187/htdocs/sitename/include/session.php on line 602 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpJkiaF3' to 'uploads/properties/yh96gapdna8amyhhmgcniskcvk9p0u37/' in /homepages/19/d375499187/htdocs/sitename/include/session.php on line 602 

my code at Session.php is:

function addPhoto($subphotoSize,$subphotoType,$subphotoTmpname,$subphotoDesc,$subfieldID,$subsessionid){ global $database, $form; /* Get random string for directory name */ $randNum = $this->generateRandStr(10); $maxFileSize = 2500000; // bytes (2 MB) $filerootpath = PHOTOS_DIR.$subsessionid."/"; if($subphotoType == "image/png"){ $filename = $randNum.".png"; } else if ($subphotoType == "image/jpeg"){ $filename = $randNum.".jpg"; } $fullURL = $filerootpath.$filename; /* Image error checking */ $field = "photo"; if(!$subphotoTmpname){ $form->setError($field, "* No file selected"); } else { if($subphotoSize > $maxFileSize) { $form->setError($field, "* Your photo is above the maximum of ".$maxFileSize."Kb"); } else if (!is_dir($filerootpath)){ mkdir($filerootpath,0777); chmod($filerootpath,0777); } move_uploaded_file($subphotoTmpname, "$fullURL"); } /* Errors exist, have user correct them */ if($form->num_errors > 0){ return 1; //Errors with form } else { if($subfieldID == "1"){ // If the first field... $is_main_photo = 1; } else { $is_main_photo = 0; } if(!$database->addNewPhoto($ownerID,$subphotoDesc,$fullURL,$userSession,$is_main_photo, $subsessionid)){ return 2; // Failed to add to database } } return 0; // Success } 

It creates the folder no problem but doesnt do anything else.

4437653 0

There is no built-in looping for nested structures (given the depth of nesting could be arbitrary). You have several options.

Flatten the 2D vector into a single dimensional vector and iterate over that or, Use something like for_each, e.g.

template <typename T> struct do_foo { void operator()(T v) { // Use the v } }; template <typename Handler, typename Container> struct handle_nested { void operator()(Container const& internal) { // inner loop, container type has been abstracted away and the handler type for_each(internal.begin(), internal.end(), Handler()); } }; // outer loop for_each(foo.begin(), foo.end(), handle_nested<do_foo<int>, std::vector<int> >()); 
28601530 0

Change your menthod to

private void fadingAnimation() { Animation fadeIn = new AlphaAnimation(0, 1); fadeIn.setInterpolator(new DecelerateInterpolator()); //add this fadeIn.setDuration(2000); AnimationSet animation1 = new AnimationSet(false); //change to false final AnimationSet animation2 = new AnimationSet(false); //change to false final AnimationSet animation3 = new AnimationSet(false); //change to false animation1.addAnimation(fadeIn); animation1.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { text_1.setVisibility(View.VISIBLE); text_2.startAnimation(animation2); } }); animation2.addAnimation(fadeIn); animation2.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { text_2.setVisibility(View.VISIBLE); text_3.startAnimation(animation3); } }); animation3.addAnimation(fadeIn); animation3.setAnimationListener(new Animation.AnimationListener(){ @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { text_3.setVisibility(View.VISIBLE); } }); text_1.startAnimation(animation1); } 
35014427 0

You can use regex for your copy (under "Artifacts to copy")-

dev\downloadAgents\target\dependency\ios***.*

** - all folders under ios

*.* - all file types

You can also specify the target directory, and you also have a flag for "Flatten directories". This will move all the files without the hierarchy of the folders (flat to your target directory)

Feel free to look at the plugin's home page: https://wiki.jenkins-ci.org/display/JENKINS/Copy+Artifact+Plugin

33586292 0

MSIs can be authored per-user or per-machine. Per-user installs won't ask for elevation by default. Per-machine installs will ask for elevation once they hit the InstallExecuteSequence.

32058029 0 Function returning REF CURSOR

I have package like this:

CREATE OR REPLACE PACKAGE product_package AS TYPE t_ref_cursor to IS REF CURSOR; FUNCTION get_products_ref_cursor RETURN t_ref_cursor; END product_package; CREATE OR REPLACE PACKAGE BODY product_package AS FUNCTION get_products_ref_cursor is RETURN t_ref_cursor IS products_ref_cursor t_ref_cursor; BEGIN OPEN products_ref_cursor FOR SELECT product_id, name, price FROM Products; RETURN products_ref_cursor; END get_products_ref_cursor; END product_package; 

My question is, how can I use function get_products_ref_cursor (ref cursor) to get list of products?

2974184 0

Each one is a different type execution.

3663001 0

Check out this book, The Elements of Computing Systems: Building a Modern Computer from First Principles it takes you step by step through several aspects of designing a computer language, a compiler, a vm, the assembler, and the computer. I think this could help you answer some of your questions.

13186425 0

This gives the averages Medians are a pain in SQL. Simple way to calculate median with MySQL gives some ideas. The two inner queries give the result sets to median over were there a median aggregate.

Select times.eventName, avg(times.timelapse) as avg_to_fail, avg(times2.timelapse) as avg_to_start From ( Select starts.id, starts.eventName, TimestampDiff(SECOND, starts.eventTime, Min(ends.eventTime)) as timelapse From Test as starts, Test as ends Where starts.eventName != 'start' And ends.eventName = 'start' And ends.eventTime > starts.eventTime Group By starts.id ) as times2 Right Outer Join ( Select starts.id, ends.eventName, TimestampDiff(SECOND, starts.eventTime, Min(ends.eventTime)) as timelapse From Test as starts, Test as ends Where starts.eventName = 'start' And ends.eventName != 'start' And ends.eventTime > starts.eventTime Group By starts.id ) as times On times2.EventName = times.EventName Group By Times.eventName 

To aid understanding I'd first consider

Select starts.id, ends.eventName, starts.eventTime, ends.eventTime From Test as starts, Test as ends Where starts.eventName = 'start' And ends.eventName != 'start' And ends.eventTime > starts.eventTime 

This is the essence of the inner query times without the group by and the min statement. You'll see this has a row combining every start event with every end event where the end event is after the start event. Call this X.

The next part is

Select X.startid, X.endeventname, TimestampDiff(SECOND, X.starttime, Min(x.endTime)) as timelapse From X Group By X.startid 

The key here is that Min(x.endTime) combines with the group by. So we're getting the earliest end time after the start time (as X already constrained it to be after). Although I've only picked out the columns we need to use, we have access to start time id, end time id start event, end event, start time, min(end time) here. The reason you can adapt it to find the avg_to_start is because we pick the interesting event name, as we have both.

SQL Fiddle: http://sqlfiddle.com/#!2/90465/6

34774201 0

What I ended up having to do for this to work properly was do the logic for if the value was passed or not and then add an attribute manually to my button using Attributes.Add().

 'Logic for button enable If (username Is Nothing) Then eastOpen.Attributes.Add("disabled", "disabled") Else 
28750380 0

An alternative to emmanuel's answer is to add some padding to the a tag:

ul { list-style-type:none; } li { float:left; } a { background:grey; color:white; text-decoration:none; padding: 10px 20px 10px 20px; margin-right:1px; } 

See it in action here: http://jsfiddle.net/rufneu0w/1/

38595693 0

I think the following is a much more natural way to describe your domain

class Location { String name static hasMany = [preparedToWork: Assessor] } class Assessor { //Some Properties static belongsTo = [Location] static hasMany = [preparedToWork: Location] } 

Then you can retrieve all of the assessors who are prepared to work in a certain location with

Assessor.executeQuery( "from Assessor a join a.preparedToWork l where l.id = ?", [locationId]) 
25722817 0 Solr Qtime difference to real time

i am trying to find out what causes the difference between the Qtime and the actual response time in my Solr application. The SolrServer is running on the same maschine as the program generating the queries. I am getting Qtimes in average around 19ms but it takes 30ms to actually get my response. This may sound like it is not much, but i am using Solr for some obscure stuff where every millisecond counts.

I figured that the time difference is not caused by Disk I/O since using RAMDirectoryFactory did not speed up anything.

Using a SolrEmbeddedServer instead of a SolrHttpServer did not cause a speedup aswell (so it is not Jetty what causes the difference?)

Is the data transfer between the query-program and the Solr-instance causing the time difference? And even more important, how can i minimize this time?

regards

34903358 0

You don't need to refresh page.

Add callback to load. In callback initialize/apply your js library (for controlling datatable).

 $("#filebody").load("@Url.Action("Attachments", new {collaborationId = Model.Collaboration.Id})"); 

to

$("#filebody").load("@Url.Action("Attachments", new {collaborationId = Model.Collaboration.Id})", function( response, status, xhr ) { //Apply Datatable js library in here }); 

Because you are removing elements at #filebody and adding new elements. So you should apply your js library to the new elements.

38223729 0 How to suppress talkback programatically?

Is there any way to make talkback to suppress when I open my application and resume when I stop my Application?

22215248 0 Get user Geolocation when user uses modem

I have an application that detect user's positions, uses geolocation and show it in map (google maps API)

The application work properly when user using wifi, it show user's current positions but if the user using modem,the application show isp's (Internet service provider) position not the current user's position...

How i can solved this? anysolutions? thanks before..

20346999 0

FIM doesn't do authentication. Instead, it does the user management and synchronization piece.

You would want to integrate with one of the directories FIM is synchronizing. If your app is within the firewall, you would typically use AD or LDAP (Kerberos-based). If your app is outside of the firewall, you would typically use Azure Active Directory or another SAML-based Identity Provider.

9713898 0

I'm sorry but I don't use makegood but I do know that xdebug has a function you can call from the code to trigger a break.

xdebug_break(); 

bool xdebug_break()

Emits a breakpoint to the debug client. This function makes the debugger break on the specific line as if a normal file/line breakpoint was set on this line.

I hope this will be of some help.

597703 0

You could also use Commodore 64 emulator. It start's right from BASIC.

39925635 0

I think it's actually not need because WidgetsModule is same as FormsModule (@angular/forms). WidgetsModule is user-defined module and FormsModule provided by angular. That's the only difference. Both of this module are used for doing some functionality.

So just think about how we can declare FormsModule once and use it in all other module, if you understood that then the problem is solved.

Just vist the following link One single NgModule versus multiples ones with Angular 2

2767749 0

If you have control over both domains, you can try a cross-domain scripting library like EasyXDM, which wrap cross-browser quirks and provide an easy-to-use API for communicating in client script between different domains using the best available mechanism for that browser (e.g. postMessage if available, other mechanisms if not).

Caveat: you need to have control over both domains in order to make it work (where "control" means you can place static files on both of them). But you don't need any server-side code changes.

In your case, you'd add javascript into one or both of your pages to look at the location.href, and you'd use the library to call from script in one page into script in the other.

Another Caveat: there are security implications here-- make sure you trust the other domain's script!

21012601 0

I am not sure whether I understand your question correctly or not.

We can get the iframe document by calling

iframeEl.contentWindow.document

Then we can control the html, css inside it.

Be careful about the same origin policy:

We can only control the iframe the same origin as the main page.

1198893 0 Access to global data in a dll from an exported dll function

I am creating a C++ Win32 dll with some global data. There is a std::map defined globally and there are exported functions in the dll that write data into the map (after acquiring a write lock, ofcourse).

My problem is, when I call the write function from inside the dll DllMain, it works without any problems. But when I load the dll from another program and call the function that writes data into the global map, it gives me this error:

WindowsError: exception: access violation reading 0x00000008 

Is there something that can be done about this? The same function when called from DllMain has access to the global data in the dll, but when called from a different process, it doesn't have access to the global data. Please advice.

I am using the TDM-MinGW gcc 4.4.0 Compiler.

EDIT: Ok, I've figured out what the problem is, and thanks for the help guys, but the problem was not with a constructor issue or inability to have maps in global space, but an issue in the boost::python that I'm using. I had tested it, but since I was calling the dll from within python or maybe something, the urllib2 module wasn't getting loaded into the dll. Now I have to see how to fix it.

39834204 0 Multiple nested AJAX calls in jQuery: How to do it right, without falling back to synchronous?

I know, there already are a lot of questions concerning AJAX and Synchronicity here, but I somehow did not find the right answer to my cause. Please be gentle, I am a noob, so, this might be a duplicate. Still, even hinting to that might help me and others finding an appropriate answer.

The Function

$.fn.facebookEvents = function(options){ var fbEvents = 'https://graph.facebook.com/'+options.id+'/events/?access_token='+options.access_token+'&since=now&limit=500'; var events = []; $.when($.getJSON(fbEvents)).then(function(json){ $.each(json.data, function(){ $.getJSON('https://graph.facebook.com/'+this.id+'/?access_token='+options.access_token, function(jsonData){ events.push(jsonData); console.log(events); // here array "events" is filled successively }); console.log(events); // here array "events" remains empty }); }).done(function(){ $("#fb_data_live").html( $("#fb_events").render(events) ); }); }; 

What happens in this function, is an AJAX Call (via jQuerys getJSON shorthand) for the event list of a Facebook Page. This will return a list of JSON objects representing each date. Example of one object as response:

{ "end_time": "2017-03-16T23:00:00+0100", "location": "Yuca K\u00f6ln", "name": "K\u00f6rner // G\u00e4nsehaut Tour 2017 // K\u00f6ln", "start_time": "2017-03-16T20:00:00+0100", "timezone": "Europe/Berlin", "id": "985939951529300" }, 

Unfortunately, these are missing the details we need. They are hidden (nested) and can be found, after making a second getJSON (line 8 in the function), using the individual "id" of each object. Now Facebook replies:

{ "description": "http://www.eventim.de/koerner\nTickets ab sofort exklusiv auf eventim.de und ab MI 07.09. \u00fcberall wo es Tickets gibt sowie auf contrapromotion.com.", "end_time": "2017-03-16T23:00:00+0100", "is_date_only": false, "location": "Yuca K\u00f6ln", "name": "K\u00f6rner // G\u00e4nsehaut Tour 2017 // K\u00f6ln", "owner": { "name": "K\u00f6rner", "category": "Musician/Band", "id": "366592010215263" }, "privacy": "OPEN", "start_time": "2017-03-16T20:00:00+0100", "timezone": "Europe/Berlin", "updated_time": "2016-09-28T10:31:47+0000", "venue": { "name": "Yuca K\u00f6ln" }, "id": "985939951529300" } 

Et voila, the details I was looking for. After making this second (nested) AJAX call, I push the JSON data in the array "events" (line 12).

The Problem

This should fill up the array with every .each iteration. However, take a look at the two 'console.logs'. The first one returns the filled array, the second one returns an empty array... If the AJAX calls are being made synchronously (which is not how it is supposed to be), e.g. by adding $.ajaxSetup({async: false}); prior to the function, it works fine however. The array is filled and can be rendered (line 18).

The Question

How can this behaviour be explained and how can this function be done right? I know, there must be a way using deferred and promises? I thought i did, by using .when.then.done... obviously I erred.

With best regards, Julius

34653126 0

If SaveChanges fails, then you will need to rollback your entity's values back to what they originally were.

In your DbContext class, you can add a method called Rollback, it'll look something like this:

public class MyDbContext : DbContext { //DataSets and what not. //... public void Rollback() { //Get all entities var entries = this.ChangeTracker.Entries().ToList(); var changed = entries.Where(x => x.State != EntityState.Unchanged).ToList(); var modified = changed.Where(x => x.State == EntityState.Modified).ToList(); var added = changed.Where(x => x.State == EntityState.Added).ToList(); var deleted = changed.Where(x => x.State == EntityState.Deleted).ToList(); //Reset values for modified entries foreach (var entry in modified) { entry.CurrentValues.SetValues(entry.OriginalValues); entry.State = EntityState.Unchanged; } //Remove any added entries foreach (var entry in added) entry.State = EntityState.Detached; //Undo any deleted entries foreach (var entry in deleted) entry.State = EntityState.Unchanged; } } 

You can simply call this method in your catch:

try { dataEntities.SaveChanges(); } catch (Exception oops) { //Rollback all changes dataEntities.Rollback(); } 

Note that INotifyPropertyChanged will need to be implemented on properties that are bound to the view, this will ensure that any changes that the rollback performs will be pushed back to the view.

9478913 0 Determine display mode of sharepoint page

I have this question many times and bored while trying to find good solution. Dont understand why microsoft not include method which can easy determine mode of display page: "normal display" or in "design mode". It have many advices of check different variables, but it cant uniquely say that page in design on different type of page(webpart page and wiki page) and on postback or not.

Is finally tired me and i write this:

 public static bool IsDesignTime() { if (SPContext.Current.IsDesignTime) return true; if (HttpContext.Current.Request.QueryString["DisplayMode"] != null) return true; var page = HttpContext.Current.Handler as Page; if(page == null) return false; var inDesign = page.Request.Form["MSOLayout_InDesignMode"]; var dispMode = page.Request.Form["MSOSPWebPartManager_DisplayModeName"]; var wikiMode = page.Request.Form["_wikiPageMode"]; var we = page.Request.Form["ctl00$PlaceHolderMain$btnWikiEdit"]; if (inDesign == null & dispMode == null) return false; //normal display if (we == "edit") return true; //design on wiki pages if (page is WikiEditPage & page.IsPostBack & inDesign == "" & dispMode == "Browse" & wikiMode == "") return false; //display wiki on postback if (inDesign == "" & dispMode == "Browse" & (wikiMode == null | wikiMode == "")) return false; //postback in webpart pages in display mode if (inDesign == "0" & dispMode == "Browse") return false; //exiting design on webpart pages return true; } 

Does anybody have better solution?

21751558 0

i think it should be better to have a user skill mapping table with fields user_id & skill_id. Every time when a user adds a skill, enter it with in mapping table so it will be easier to use this data in future

29739501 0 Runtime error: Could not load file or assembly 'Microsoft.Owin, Version=3.0.0.0....Azure mobile services

I have downloaded the ToDOService project from the Azure managementprotal after I created a Mobile service. Initially it had a lot of errors as the Nuget packages were outdated. I Uninstalled the Azure mobile services .net backend package and its dependencies. Later I again installed all the packages manually and then I could build the project successfully. Somehow, when I run the service project I get this error:-

Could not load file or assembly 'Microsoft.Owin, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Owin, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. Source Error: Line 18: Line 19: // Use this class to set WebAPI configuration options Line 20: HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options)); Line 21: Line 22: // To display errors in the browser during development, uncomment the following Source File: ...\MyProject\MyService\App_Start\WebApiConfig.cs Line: 20 

My web.config looks like this

<dependentAssembly> <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" /> </dependentAssembly> 

I also tried to update the assembly to the latest, but could not be updated as Ver 3.0.1 is not compatible with its other dependencies.

any help would be appreciated. Thanks

1850127 0
  1. How large of a deployment is this? It might be better to execute the deployment of .net 3.5 as a previous enterprise deployment. And then follow up with your application. For enterprise wide deployments there are tools like Zenworks, and others that deploy applications and other file sets "invisibly" to the user.

  2. Have you confirmed that your application will not function with .net 2.0?

  3. If your application is only files, and does not have registry settings, etc. you may be able to copy the files to the users' computers, and copy a shortcut to their desktop, or startmenu certainly without their intervention, and probably with out their knowledge. If you have admin level credentials that apply to all your PCs and can get a list of all you r PCs' network names, you could "push" the files out through the C$ share, or if they log in to a domain you can have them "pull" them via a login-script.

There are actually lots of ways to do this. If you have server admins, they can help you with this.

8437176 0 App load screen in Android

On iOS you create a load screen for when the app loads, is there a similar thing in Android. When my app loads, I get a black screen until it opens.

26907654 0

From the source:

The solution is to edit the view by adding an Argument of Node: Nid. Set it to Display all values, Validator: Node, and Argument type of Node ID.

Set Action to take if argument does not validate: Hide view / Page not found (404). Update the Argument and save the view.

16374996 0 mysqldump.exe not taking full backup of mysql database

I have a procedure for backing up MySQL database.And also i have different MySQL servers. This procedure works on some of MySQL servers.But on some of servers it won't works proper and create a backup file with the size of 1kb.

Code

public void DatabaseBackup(string ExeLocation, string DBName) { try { string tmestr = ""; tmestr = DBName + "-" + DateTime.Now.ToString("hh.mm.ss.ffffff") + ".sql"; tmestr = tmestr.Replace("/", "-"); tmestr = "c:/" + tmestr; StreamWriter file = new StreamWriter(tmestr); ProcessStartInfo proc = new ProcessStartInfo(); string cmd = string.Format(@"-u{0} -p{1} -h{2} {3}", "uid", "pass", "host", DBName); proc.FileName = ExeLocation; proc.RedirectStandardInput = false; proc.RedirectStandardOutput = true; proc.Arguments = cmd; proc.UseShellExecute = false; proc.CreateNoWindow = true; Process p = Process.Start(proc); string res; res = p.StandardOutput.ReadToEnd(); file.WriteLine(res); p.WaitForExit(); file.Close(); } catch (IOException ex) { } } 

Can any one tell me what is the problem and how can i solve it.

38627339 0 Is it possible to nest SQL tables?

I am wondering if it is possible to nest SQL tables? Or it the best practise to give the id to for example a person in the first table that is the key to the second table?

33402810 0 How can I replace "true" and "false" in java?

i need change the values for boolean variables, for example:

change this: boolean x = true; System.out.print(x); //console: true for this:

boolean x = true; System.out.print(x); //console: 1 

Sorry for my bad engish, thanks.

This is my code

final boolean[] BOOLEAN_VALUES = new boolean [] {true,false}; for (boolean a : BOOLEAN_VALUES) { boolean x = negation(a); String chain = a+"\t"+x; chain.replaceAll("true", "1").replaceAll("false","0"); System.out.println(chain); } negation is a method: public static boolean negation(boolean a){ return !a; } 

as you can see, i try using .replaceAll, but its not working, when i executed, this is the output:

 a ¬a ---------------- true false false true 

i really dont see my error.

20802405 0

No need to call awk several times. You can do everything with a single awk script. Try the following command:

awk -f t.awk GW2.log 

where t.awk is:

NR==5 { RDS_T=$1 } NR==6 { RDS_P=$1" "$2 } NR==8 { RDS_C1=$1" "$2 } NR==9 { RDS_C2=$1" "$2 } NR==16 { ALGN_T=$1 } END { fmt="%-12s %-12s %-18s %-18s %-18s %-18s\n" printf fmt, "File", "Reads", "Paired reads", "Conc reads1", "Conc Reads2", "Total align" printf fmt, "GW2.log", RDS_T, RDS_P, RDS_C1, RDS_C2, ALGN_T } 

with output:

File Reads Paired reads Conc reads1 Conc Reads2 Total align GW2.log 3746112 3746112 (100.00%) 581094 (15.51%) 227387 (6.07%) 28.15% 
21458798 0

I have an idea. If you can get the element in evaluate you can fireEvent on it. So create a function that will fireEvent.

 function casperFireEvent(element, eventType) { if ("createEvent" in document) { var evt = document.createEvent("HTMLEvents"); evt.initEvent(eventType, false, true); element.dispatchEvent(evt); } else { element.fireEvent("on"+eventType); } } 

Then on you loop you can do this :

 this.evaluate(casperFireEvent(document.getElementById('links[i]'), 'click')); 

I'm not sure it it's conventional but that's a start.

6919874 0

Flymake sets a 1-second timer for each buffer that has flymake-mode enabled, to check to see if the buffer has been modified more than flymake-no-changes-timeout seconds ago.

If you have a lot of buffers open (several hundred) in flymake-mode then this can devour a surprisingly large amount of CPU, I've a patched version of flymake that has a single global timer which fixes this, and a few other issues: https://github.com/illusori/emacs-flymake

This might not be the same issue for you, but for me it would lock Emacs up when opening in desktop-mode with 600 files open, I'd be lucky to get one keypress processed every 15 minutes.

20602682 0 Background image looks brighter on Safari

Background image on Safari looks brighter compare to any other browsers.

When I remove background-size: cover, image colors looks like expected.

How do I keep normal colors and background-size: cover at the same time?

body { background-image: url('https://lh5.googleusercontent.com/-QpCNI9iXEEE/Uq5gxSpxOJI/AAAAAAAAABM/HwVK1nETGPE/I/philadelphia_night_view.jpg'); background-repeat: no-repeat; background-size: cover; } 

http://jsfiddle.net/xY9wK/

OS X Mountain Lion 10.8.3, Safari: 6.0.3

enter image description here

11958008 0

Do you mean words or characters? If you want to count words, a very naïve approach is splitting by whitespace and check the length of the resulting array:

if ($("#et_newpost_content").text().split(/\s+/).length < 250) { alert('Message must be at least 250 words.') } 

If you mean characters, then it's much easier:

if ($("#et_newpost_content").text().length < 250) { alert('Message must be at least 250 characters.') } 
14295380 0

SmartGWT has extensive built-in support for Selenium. Read about it here:

http://www.smartclient.com/smartgwtee-latest/javadoc/com/smartgwt/client/docs/UsingSelenium.html

Do not attempt to set your own DOM identifiers. This is unnecessary, and is the wrong approach.

35769329 0 Replace month number with month name using current phone format

I'm using joda-time to process DateTime. I got date format of phone using this:

SimpleDateFormat dateFormat = (SimpleDateFormat) DateFormat.getDateFormat(context); String datePattern = dateFormat.toPattern(); 

And then I format a DateTime to String using this:

DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(datePattern); dateFormatter.print(dateTime) 

Example, it will show DateTime as String:

3/1/2016

But i want it displays:

March/1/2016

or

Mar/1/2016

How can i do that?

15155844 0

Sounds like your data might be better suited to being in one index, in which case you could use and/or filters to combine a geo distance filter with a type filter.

Another option would be to use the indicies query

27709401 0

It turns out that Microsoft does not support SHA-2 for driver signing on Windows 7.

In some cases, you might want to sign a driver package with two different signatures. For example, suppose you want your driver to run on Windows 7 and Windows 8. Windows 8 supports signatures created with the SHA256 hashing algorithm, but Windows 7 does not. For Windows 7, you need a signature created with the SHA1 hashing algorithm.

Suppose you want to build and sign a driver package that will run on Windows 7 and Windows 8 on x64 hardware platforms. You can sign your driver package with a primary signature that uses SHA1. Then you can append a secondary signature that uses SHA256. You can use the same certificate for both signatures, or you can use separate certificates. Here are the steps to create the two signatures using Visual Studio.

10278431 0

As you mentioned, MobileTerminal is probably what you're looking for. This project is open-source and you can start of it. AFAIK now it runs only on jailbroken devices, but you can definitely cut out only the terminal emulation (& screen manipulation, handling input and output, ...) and build your project on it.

Building a terminal from scratch is quite complicated and complex, so I suggest you start with this or some other open source project.

I am not aware of any ready-to-use component, so you'll probably have to put some work into integrating the terminal into your app.

33427601 0

When the mouse is dragging a div element over a droppable area, pressing the ESC key should drag the element to an area that is not droppable

I´ve created a demo of a possible solution that you can check in plunker.

As stated by @ioneyed, you can select the dragged element directly using the selector .ui-draggable-dragging, which should be more efficient if you have lots of draggable elements.

The code used is the following, however, apparently it's not working in the snippet section. Use the fullscreen feature on the plunker or reproduce it locally.

var CANCELLED_CLASS = 'cancelled'; $(function() { $(".draggable").draggable({ revert: function() { // if element has the flag, remove the flag and revert the drop if (this.hasClass(CANCELLED_CLASS)) { this.removeClass(CANCELLED_CLASS); return true; } return false; } }); $("#droppable").droppable(); }); function cancelDrag(e) { if (e.keyCode != 27) return; // ESC = 27 $('.draggable') // get all draggable elements .filter('.ui-draggable-dragging') // filter to remove the ones not being dragged .addClass(CANCELLED_CLASS) // flag the element for a revert .trigger('mouseup'); // trigger the mouseup to emulate the drop & force the revert } $(document).on('keyup', cancelDrag);
 .draggable { padding: 10px; margin: 10px; display: inline-block; } #droppable { padding: 25px; margin: 10px; display: inline-block; }
<div id="droppable" class="ui-widget-header"> <p>droppable</p> </div> <div class="ui-widget-content draggable"> <p>draggable</p> </div> <div class="ui-widget-content draggable"> <p>draggable</p> </div> <div class="ui-widget-content draggable"> <p>draggable</p> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css">

15561669 0 Placing multiple Divs (side by side) within a parent Div

My goal is to place four divs within a single "container" div. Here's my code so far:

HTML

<body> <div id="navBar"> <div id="subDiv1"> </div> <div id="subDiv2"> </div> <div id="subDiv3"> </div> <div id="subDiv4"> </div> </div> </body> 

CSS

#navBar { width: 75%; height: 75px; margin-left: 25%; margin-right: auto; margin-top: 2%; border-width: 1px; border-style: solid; border-radius: 10px; border-color: #008040; overflow: hidden; } #subDiv1, #subDiv2, #subDiv3, #subDiv4 { width: 25%; height: 75px; border-width: 1px; border-color: #000; border-style: solid; } #subDiv1 { border-top-left-radius: 10px; border-bottom-left-radius: 10px; float: left; margin-left: 0%; } #subDiv2 { float: left; margin-left: 25%; } #subDiv3 { float: left; margin-left: 50%; } #subDiv4 { border-top-right-radius: 10px; border-bottom-right-radius: 10px; float: left; margin-left: 75%; } 

As far as I know this is the only part of my code that's relevant to my question so I left some other parts out.. Don't mind the width and margin of the navBar, because it's actually within another container as well.

P.S I searched Google and StackOverFlow and I could not find an answer that was helpful. There were many questions about placing two divs within a single div, but none for aligning multiple divs within a single div.

Thanks for any help in advance!

10566598 0

No. You can't use VideoView with authenticated RTSP, even with rtsp://User:Password@Server. It won't work. It is possible to use authenticated RTSP on android but it's hard and you will have to do a lot of things by yourself.

16222364 0

Use Arrays.toString(method.getParameterTypeas()) if you want to see the types. Use loop if you want to iterate over them and use them:

for (Class<?> type : method.getParameterTypeas()) { // use the type } 
25887050 0

I suppose, you want to INNER JOIN those tables like this:

 SELECT * FROM ( SELECT pi.FighterId, FName, LName, PaymentDay, PaymentDescr, PaymentAmount, Active, ROW_NUMBER() OVER (PARTITION BY fi.FighterId ORDER BY PaymentDay DESC) rn FROM FightersInfo fi LEFT JOIN PaymentInfo pi ON pi.FighterId = fi.FighterId WHERE NOT EXISTS (SELECT * FROM PaymentInfo WHERE FighterId = fi.FighterId AND DATEDIFF(month, PaymentDay, GETDATE()) = 0 ) AND Active =1) t WHERE rn = 1 

All the conditions on amount are removed for readability.

40277883 0 Positioning and then making it responsive

Hey I'm currently working on a responsive web design for school and it is a disaster. Currently setting up the website before making it responsive and the text and images aren't going where I need them to go. This is my coding for css so far:

body{ background-color: #cd76dd; font-family: 'Raspoutine Medium'; color:white; } #page-wrap{ width: 950px; margin: 0 auto; } #containerIntro h1{ font-family: 'AlphaClouds'; background-color: #7ac8ff; color:white; font-size: 45px; width: 100%; padding-bottom: 10px; position: static; bottom: 0; left: 0; } #containerIntro p{ font-family: 'AlphaClouds'; background-color: #7ac8ff; color:white; text-align: left; font-size: 70px; width: 100%; } h1: hover{ text-shadow: 0px 0px 20px white; } h1 p: hover{ text-shadow: 0px 0px 20px white; } h1{ position: absolute; left: 0; bottom: 0; } p{ background-color:#ffa1ff; color:white; text-align: left; padding-top: 20px; padding-bottom: 20px; padding-left: 10px; font-size: 17px; width: 450px; height: 100%; } h2{ background-color: #ffa1ff; color:white; text-align: left; padding-top: 20px; padding-left: 10px; font-size: 20px; border: 2px #ffa1ff solid; width: 450px; height: 100%; } h3{ background-color: #ffa1ff; color:white; text-align: left; font-size: 20px; padding-left: 10px; border: 2px #ffa1ff solid; width: 450px; height: 100%; } .gummy{ float: right; } .bubble{ float: right; position: relative; right: -130px; padding-top: 15px; } .pink{ float: left; position: relative; top: -145px; } .blue{ float: right; position: relative; top: -145px; } p.select{ background-color: #5d75ed; text-align: right; padding-bottom:10px; padding-top: 10px; font-size: 17px; width: 170px; float: right; margin-top: -850px; } p.archives{ background-color: #f9e075; text-align: right; padding-bottom: 10px; padding-top: 10px; padding-left: 10px; font-size: 17px; width: 170px; float: right; margin-top: -600px; } p.resources{ background-color: #ef5b66; padding-bottom: 10px; padding-top: 10px; font-size: 17px; width: 170px; float:right; margin-top: -500px; } div{ height: 287; width: 198; } 

mock up for what it will look like

enter image description here

39242333 0 Tensorflow : Implementing gradient for user op in C++?

I'd ideally like the operation to be wholly self-contained (gradient and operation defined in same file). The official tutorial only highlights a python implementation. Does anyone know if it's possible to implement the gradient in C++, and how to go about it?

7777487 0

If the file is not opened, the line file = open(filePath, 'w') fails, so nothing gets assigned to file.

Then, the except clause runs, but nothing is in file, so file.close() fails.

The finally clause always runs, even if there was an exception. And since file is still None you get another exception.

You want an else clause instead of finally for things that only happen if there was no exception.

 try: file = open(filePath, 'w') except IOError: msg = "Unable to create file on disk." return else: file.write("Hello World!") file.close() 

Why the else? The Python docs say:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

In other words, this won't catch an IOError from the write or close calls. Which is good, because then reason woudn't have been “Unable to create file on disk.” – it would have been a different error, one that your code wasn't prepared for. It's a good idea not to try to handle such errors.

17126231 0 icefaces project deployment error : org.apache.catalina.LifecycleException: java.lang.NoSuchFieldError: SKIP_ITERATION

I'm trying to make new icefaces project which generated using: ICEfaces 3.3.0 project integration for Eclipse. I didn't modify anything on the project. but when i try to run on the server, i got an error:

cannot Deploy MyProject

Deployment Error for module: MyProject:

Exception while loading the app : java.lang.Exception:

java.lang.IllegalStateException: ContainerBase.addChild:

start: org.apache.catalina.LifecycleException:

java.lang.NoSuchFieldError: SKIP_ITERATION

before that, I'm using ICEfaces 3.2.0 project integration for Eclipse and no problem.

I'm using Eclipse Indigo, GlassFish server 3, Mojarra 2.1.6

Thanks before

21263350 0

On Heroku, gems are installed within the vendor/bundle/ruby/<version>/gems directory. I just checked my Heroku instance and confirmed this.

9667115 0

CML files get rendered as XML from the server because the server is telling Chrome it is XML with header Content-Type:application/xml. When a local file is opened there is no Content-Type header so Chrome guesses off of the file extension and in this case is not aware of CML. You could open a feature request for Chrome to read CML files as XML but I don't know if they will implement it: http://new.crbug.com

447930 0

I assume you want to implement some sort of a loading screen or interface widget. (Did you know you can set the showBusyCursor on a remote object instance?)

There is no way to globally intercept the method calls on your remote objects though. You'll need to solve this by either:

  1. create a subclass of RemoteObject that sets some global flag on the result and fault events.
  2. write the same result and fault event handling code on each remote object call that sets a global flag.

Option 1 is a bit more advanced but will save you the boilerplate code that option 2 has.

145227 0

In my opinion, almost any release number scheme can be made to work more or less sanely. The system I work on uses version numbers such as 11.50.UC3, where the U indicates 32-bit Unix, and the C3 is a minor revision (fix pack) number; other letters are used for other platform types. (I'd not recommend this scheme, but it works.)

There are a few golden rules which have not so far been stated, but which are implicit in what people have discussed.

Now, in practice, people do have to release fixes for older versions while newer versions are available -- see GCC, for example:

So, you have to build your version numbering scheme carefully.

One other point which I firmly believe in:

With SVN, you could use the SVN version number - but probably wouldn't as it changes too unpredictably.

For the stuff I work with, the version number is a purely political decision.

Incidentally, I know of software that went through releases from version 1.00 through 9.53, but that then changed to 2.80. That was a gross mistake - dictated by marketing. Granted, version 4.x of the software is/was obsolete, so it didn't immediately make for confusion, but version 5.x of the software is still in use and sold, and the revisions have already reached 3.50. I'm very worried about what my code that has to work with both the 5.x (old style) and 5.x (new style) is going to do when the inevitable conflict occurs. I guess I have to hope that they will dilly-dally on changing to 5.x until the old 5.x really is dead -- but I'm not optimistic. I also use an artificial version number, such as 9.60, to represent the 3.50 code, so that I can do sane if VERSION > 900 testing, rather than having to do: if (VERSION >= 900 || (VERSION >= 280 && VERSION < 400), where I represent version 9.00 by 900. And then there's the significant change introduced in version 3.00.xC3 -- my scheme fails to detect changes at the minor release level...grumble...grumble...

NB: Eric Raymond provides Software Release Practice HOWTO including the (linked) section on naming (numbering) releases.

6556981 0

The using statement is really the preferred solution. It's idiomatic in C#. These classes implement IDisposable explicitly because they already provide a method that has closing semantics: Close. My bet is that Dispose calls Close, or vice-versa. But you shouldn't count on that, and should always call Dispose anyway.

In the end, all these are equivalent:

  1. Use using, which is preferred;
  2. Call Close on the finally block, and suppress the static analysis warnings or;
  3. Call Dispose on the finally: ((IDisposable)NewReader).Dispose();
7498755 0

Try cleaning the project. Also, are you using the google libraries for maps? You need to add a link to Google API.

30202774 1 Python - remove parts of a string

I have many fill-in-the-blank sentences in strings,

e.g. "6d) We took no [pains] to hide it ."

How can I efficiently parse this string (in Python) to be

"We took no to hide it"? 

I also would like to be able to store the word in brackets (e.g. "pains") in a list for use later. I think the regex module could be better than Python string operations like split().

25676448 0

You want to look at websockets. A good way to do this in PHP is with a library called "Ratchet":

http://socketo.me/

Unfortunately websockets don't have very good cross-browser compatibility.

561122 0

You definitely need some kind of 'in code' element, because a lack of DLL will break things in a worse way than simply disabling the modules you had intended.

9116346 0
struct C { A a; B b; C(double ta[2], vector<double> tb) { a = A(ta[0],ta[1]); // or a.x = ta[0]; a.y = ta[1] b = tb; } }; 

then you can initialize with something like

C c = C( {0.0, 0.1} , vector<double> bb(0.0,5) ); 
24428571 0 Asterisk: How can I filter the Dial event only to my extension

I am making a Asterisk Client in C# WinForms using Asterisk.NET. My client is listening to one extension only.We can view the calls, reject or transfer etc to the calls coming to my extensions. I need source channel to transfer the call, and source channel can be got only from Dial Event. Recently, I noticed that The Dial Event happens everytime when any of the extension connected to the server starts dialling. I want to filter it out, only the call coming to my extension only.

 void manager_Dial(object sender, DialEvent e) { CallingInfo.src_channel = e.Channel; } 

e.dialString is giving me the Destination Extension number; But I don't know if it become null according to the server status. Moreover, what will happen if some external calls coming to me, I wont get Dial event or Source channel, Then it cannot be transferred. Right ?

16604386 0 what is the function of attribute selected in combo box while fetching data from MYSQL in php

Hello i am beginner in PHP. I am trying to fetch data from MYSQL and want to show in combo box but if user does not re selects the item from item list it highlights error that nothing is selected. Is there any php function to do this particular task ? I want that when the data of particular id is loaded in form and if without making any change in combo boxes data user cliks on submit then it must submit but in my case it shows that the fields are empty while data is here. Here is my Code

<li id="foli3" class="notranslate "> <label class="desc" id="title3" for="Field3"> what is the current occupation of your guardian? <span id="req_3" class="req">*</span> </label> <span> <select id="Field3" name="occupation" class="field select addr" tabindex="8" required > <option value="" selected="selected"><?php echo $rows['occupation']; ?></option> <option>Private Sector Employee</option> <option>Social Sector Employee</option> <option>Agriculturalist</option> <option>Businessman</option> <option>Government Employee</option> <option>Other</option> </select> </span> </li> 
10089327 0

One method may be to select the appropiate column range using the Visual mode (control+v)

Once selected, the search and replace can be done using (see this question)

 %s/\%Vfoo/bar/g 

A regular expression for not test can be found here: Regular expression to match string not containing a word?

39429095 0 materialized view for for a duration with fast refresh such as last ten minutes

12015 while creating MV in my 3rd step:

  1. create table tab_2 as select * from tab_1; alter table tab_2 add constraint tab_2_pk primary key (col6,col7);

  2. create materialized view log on my_schema.tab_2 with primary key (my_date) including new values;

  3. create materialized view my_schema.ten_minute_data refresh fast as select * from my_schema.tab_2 mt where mt.my_date > sysdate-10/(24*60);

I am trying to create mv and mv_log in the same db as replacement of normal view to query and see the the result fast.

Please suggest if it such where clause is possible.

Thanks

8598171 0 Workaround for DELETE ... LIMIT clause (SQL)

I am working on a database query abstraction layer that supports SQLite.

Unfortunately, SQLite does not support the LIMIT clause in DELETE (and UPDATE etc.) queries - except if compiled with a special flag in more recent versions.

So is there any workaround that I could implement so that that query type can still be supported?

3395055 0

To store the history of a page, the most popular and full featured/supported way is using hashchanges. This means that say you go from yoursite/page.html#page1 to yoursite/page.html#page2 you can track that change, and because we are using hashes it can be picked up by bookmarks and back and forward buttons.

You can find a great way to bind to hash changes using the jQuery History project http://www.balupton.com/projects/jquery-history

There is also a full featured AJAX extension for it, allowing you to easily integrate Ajax requests to your states/hashes to transform your website into a full featured Web 2.0 Application: http://www.balupton.com/projects/jquery-ajaxy

They both provide great documentation on their demo pages to explain what is happening and what is going on.

Here is an example of using jQuery History (as taken from the demo site):

// Bind a handler for ALL hash/state changes $.History.bind(function(state){ // Update the current element to indicate which state we are now on $current.text('Our current state is: ['+state+']'); // Update the page"s title with our current state on the end document.title = document_title + ' | ' + state; }); // Bind a handler for state: apricots $.History.bind('/apricots',function(state){ // Update Menu updateMenu(state); // Show apricots tab, hide the other tabs $tabs.hide(); $apricots.stop(true,true).fadeIn(200); }); 

And an example of jQuery Ajaxy (as taken from the demo site):

 'page': { selector: '.ajaxy-page', matches: /^\/pages\/?/, request: function(){ // Log what is happening window.console.debug('$.Ajaxy.configure.Controllers.page.request', [this,arguments]); // Adjust Menu $menu.children('.active').removeClass('active'); // Hide Content $content.stop(true,true).fadeOut(400); // Return true return true; }, response: function(){ // Prepare var Ajaxy = $.Ajaxy; var data = this.State.Response.data; var state = this.state; // Log what is happening window.console.debug('$.Ajaxy.configure.Controllers.page.response', [this,arguments], data, state); // Adjust Menu $menu.children(':has(a[href*="'+state+'"])').addClass('active').siblings('.active').removeClass('active'); // Show Content var Action = this; $content.html(data.content).fadeIn(400,function(){ Action.documentReady($content); }); // Return true return true; 

And if you ever want to get the querystring params (so yoursite/page.html#page1?a.b=1&a.c=2) you can just use:

$.History.bind(function(state){ var params = state.queryStringToJSON(); // would give you back {a:{b:1,c:2}} } 

So check out those demo links to see them in action, and for all installation and usage details.


Edit: After seeing your code, this is all you would have to do to use it with jQuery History.

Change:

$('.tabbed_content .tabs li a').live('click', function (e){ e.preventDefault(); switchTab($(this)); }); 

To:

// Bind a handler for ALL hash/state changes $.History.bind(function(state){ switchTab(state); }); 

Or if you plan to use jQuery History for other areas too, then we would want to ensure that we only call switchTab for our tabs and not all hashes:

// Bind a handler for ALL hash/state changes $.History.bind(function(state){ if ( $('.tabbed_content > .content > li[id='+state+']').length ) switchTab(state); }); 

We no longer use a onclick event, instead we bind to jQuery History as that will detect the hashchange. This is the most important concept to understand, as for instance if we bookmark the site then go back to it, we never clicked it. So instead we change our clicks to bind to the hashchange. As when we click it, bookmark it, back or forward, the hashchange will always fire :-)

12627676 0 Passing Html tag in Update query

There is an existing table in database where I want to update one column. If I right click on the table--->select edit 200 rows and try to edit the cell data it says that the cell is read-only. I am using SQL management studio 2008R2. So I was trying to update it using an update Query but I am pretty new to the SQL queries and the whole database thing. Is this the proper way to pass an HTML tag in queries?

UPDATE OutputTemplate SET emailText='(<p>Thank you for your gift of {Amount} to the {CommunityName}</p><br />Support & Charity Campaign.<br /> -------------------------------------------- --- Transaction Detail --- -------------------------------------------- <span>Credit Card Details</span> <span style="text-decoration: underline;">Personal Info Details & Amount</span>)' WHERE id='2' 

It's showing some parsing error, incorrect syntax while executing the query.

Sorry to ask such a basic question but I tried to google it, unfortunatelly nothing showed up useful.

Thanks

29932443 0

It is solved. The code works as follows. I made a wrong drill down. Truly thanks, I have learned a lot:

 class func jsonAsUSDAIdAndNameSearchResults (json: NSDictionary) -> [(name: String, idValue: String)] { var usdaItemsSearchResults: [(name: String, idValue: String)] = [] var searchResult: (name: String, idValue: String) if json["hits"] != nil { let results:[AnyObject] = json["hits"]! as [AnyObject] for itemDictionary in results { let fields: NSDictionary = itemDictionary["fields"]? as NSDictionary let name:String? = fields["item_name"] as? String let idValue:String? = itemDictionary["_id"]? as? String if (name? != nil && idValue? != nil) { searchResult = (name: name!, idValue: idValue!) usdaItemsSearchResults += [searchResult] } } } return usdaItemsSearchResults } 
23401900 0

Figured it out (don't ask me how). For anyone else looking for the answer, here's what I did.

I changed this:

// Ajaxify our Internal Links $body.ajaxify(); 

to this:

// Ajaxify our Internal Links $('.menuLeft,.menuRight').ajaxify(); 

I kept trying to add the menu classes here without the parentheses and single quotes. Once I got those in, everything fell into place. Now, only those menus are ajaxified.

30174087 0

This solution below was tested and it works fine.

First:

Remove onkeydown event of digit. It should be like this:

 <input type="text" name="digit" id="digit" size="50" /> 

Remove onclick event of the button and set the id property.

<button class="btn" id="btnClick" title="send" type="button" > 

create a input hidden in your html to store $cuser php var

<input type="hidden" name="cuser" id="cuser" val="<?php echo $cuser ?>" /> 

Replace your javascript to the following:

 $(document).ready(function(){ $("#digit").keydown(function(event){ if (event.keyCode == 13 && event.shiftKey == 0) { alert("ok1"); filltxtarea($("#digit").val()); } }); $("#btnClick").click(function(){ filltxtarea($("#digit").val()); }); function filltxtarea(desctext) { var uchat = $("#cuser").val(); $(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">' + uchat + ': </span><span class="chatboxmessagecontent">' + desctext + '</span></div>'); $('#digit').val(''); $('#digit').focus(); alert("ok2"); jQuery.ajax({ type: 'POST', url: 'chat.php', dataType: 'json', data: { "newrow": "desctext" }, success: function(response) { alert(response); } }) } }); 

Any doubts please let me know.

Hope it help.

23975299 0

Thanks for the responses. Very helpful. I decided to go with a proxy approach for which I found a simple solution here: http://www.paulund.co.uk/make-cross-domain-ajax-calls-with-jquery-and-php

For cut and paste simplicity I've added my code here.

I created a file called crossdomain.html. Included jquery library. Created the following Javascript function:

function requestDataByProxy() { var url = "http://UrlYouWantToAcccess.html"; var data = "url=" + url + "&parameters=1&para=2"; $.ajax({ url: "our_domain_url.php", data: data, type: "POST", success: function(data, textStatus, jqXHR){ console.log('Success ' + data); $('#jsonData').html(data); }, error: function (jqXHR, textStatus, errorThrown){ console.log('Error ' + jqXHR); } }); } 

I also added a simple button and pre tag in HTML to load results:

<button onclick="requestDataByProxy()">Request Data By Proxy</button> <h3>Requsted Data</h3> <pre id="jsonData"></pre> 

And then, the PHP file our_domain_url.php which uses cURL (make sure you have this enabled!)

<?php //set POST variables $url = $_POST['url']; unset($_POST['url']); $fields_string = ""; //url-ify the data for the POST foreach($_POST as $key=>$value) { $fields_string .= $key.'='.$value.'&'; } $fields_string = rtrim($fields_string,'&'); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_POST,count($_POST)); curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string); //execute post $result = curl_exec($ch); //close connection curl_close($ch); ?> 

To me, this was a fairly straight-forward solution.

Hope this helps someone else!

Rob

37986563 0

Try to use this gem: https://github.com/net-ssh/net-ssh-gateway/

require 'net/ssh/gateway' gateway = Net::SSH::Gateway.new(@jumpoffIp, @jumpoffUser) gateway.open('ont-db01-vip', 1521, 1521) gateway.open('ont-db02-vip', 1521, 1521) res = %x[sqlplus #{@sqlUsername}/#{@sqlPassword}@'#{@sqlUrl}' @scripts/populateASDB.sql > output.txt] puts "populateDb output #{res}" gateway.shutdown! 
18745200 0

We did an htaccess edit for it.

 <FilesMatch "\.(ttf|otf|eot)$"> <IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule> </FilesMatch> 
17152024 0

Instead of looping through all your messages and calling the method that displays an alert for each of them, which results in the multiple alerts being displayed to the user, while looping, add all the 'priority' messages in an array. Then, check the number of alerts in your array and you can show one alert that reflects this information: e.g. for one message you could display the title of the message and some other information as title and message of the alertView, while, when you have multiple messages, you could have a title stating something like "You have x new messages with high priority" where x is the number of messages and some other description.

34829930 1 Is there a way to get function parameter names, including bound-methods excluding `self`?

I can use inspect.getargspec to get the parameter names of any function, including bound methods:

>>> import inspect >>> class C(object): ... def f(self, a, b): ... pass ... >>> c = C() >>> inspect.getargspec(c.f) ArgSpec(args=['self', 'a', 'b'], varargs=None, keywords=None, defaults=None) >>> 

However, getargspec includes self in the argument list.

Is there a universal way to get the parameter list of any function (and preferably, any callable at all), excluding self if it's a method?

EDIT: Please note, I would like a solution which would on both Python 2 and 3.

23673818 0

Remove () near values

INSERT INTO evraklar(evrak_tipi_grubu, evrak_tipi, evrak_konu, evrak_subeye_gelis_tarihi, evrak_gonderen, evrak_alici, evrak_tarihi, evrak_sayisi, evrak_aciklama, evrak_kurum_icindenmi, gelen_evrak_tarihi, gelen_evrak_sayi, gelen_evrak_etakip, evrak_kaydeden_ybs_kullanici_id,kaydeden_kullanici_birim_id) VALUES (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,566,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Antalya Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,612,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Mersin Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685), (6,43,'Test amaçlı girilen konu',STR_TO_DATE('12/12/2012', '%d/%m/%Y'),0,616,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555','YBS:110 nolu evrağa cevaben yazılan yazıdır. Alıcısı:Niğde Valiliği - İl Sağlık Müdürlüğü',0,STR_TO_DATE('12/12/2012', '%d/%m/%Y'),'5555555555',777777777,1,685); 
41067535 0

You can use sum function:

In [52]: m = np.random.randint(0,9,(4,4)) In [53]: m Out[53]: array([[8, 8, 2, 1], [2, 7, 1, 2], [8, 6, 8, 7], [5, 2, 5, 2]]) In [56]: np.sum(m == 8) Out[56]: 4 

m == 8 will return a boolean array contains True for each 8 then since python evaluates the True as 1 you can sum up the array items in order to get the number of intended items.

5381004 0

Thanks Equiso, I didn't find the question you refered to. So this is an exact duplicate of Linq query built in foreach loop always takes parameter value from last iteration.

14876110 0

Considering that all your filters are set to required=false I'll assume the PRO version is paid and guess an answer here:

There're 2496 - 2263 devices in the world that were only released in countries that does not accept the paid area of the Play Store.

5073928 0

http://developer.android.com/guide/topics/data/data-storage.html#db

4787264 0

I can't speak for all RDBMS systems, but Postgres specifically uses estimated table sizes as part of its efforts to construct query plans. As an example, if a table has two rows, it may choose a sequential table scan for the portion of the JOIN that uses that table, whereas if it has 10000+ rows, it may choose to use an index or hash scan (if either of those are available.) Incidentally, it used to be possible to trigger poor query plans in Postgres by joining VIEWs instead of actual tables, since there were no estimated sizes for VIEWs.

Part of how Postgres constructs its query plans depend on tunable parameters in its configuration file. More information on how Postgres constructs its query plans can be found on the Postgres website.

19356791 0

You want to use an unnamed form. Here is the correct syntax :

# List the forms that are in the page for form in br.forms(): print "Form name:", form.name print form # To go on the mechanize browser object must have a form selected br.select_form(nd = "form1") # works when form has a name br.form = list(br.forms())[0] # use when form is unnamed 

Python for beginners has a great cheat sheet about mechanize : http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/

33357067 0

Based on your case, I think you can try to use shellCommandActivity in data pipeline. It will launch a ec2 instance and execute the command you give to data pipeline on your schedule. After finishing the task, pipeline will terminate ec2 instance.

Here is doc:

http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-shellcommandactivity.html

http://docs.aws.amazon.com/datapipeline/latest/DeveloperGuide/dp-object-ec2resource.html

36848540 0

You can always use std::enable_if:

template <typename T, typename ... ARGS> std::enable_if_t<(sizeof...(ARGS)>0)> func(...) { ... } 

In this case, func will only appear as part of the overload set if the size of ARGS... is greater than 0. However, if the size is zero, you will be missing a function from your overload set. Maybe that's want you want, though.

11232507 0

Since you're using percentages for both top and margin-top, you can combine them, and simply use top: 10%.

See this demo: http://jsfiddle.net/jackwanders/DEn6r/3/

Also, if you'd like to drop the negative left margin, you can use this trick to center the div horizontally:

#inside { position: absolute; width: 300px; height: 80%; top: 10%; left: 0; right: 0; // set left and right to 0 margin: 0 auto; // set left and right margins to auto background: white; } 
5180846 0

This looks like a case of reference versus value comparison. If you have two different instances of objects with the same property values, by default they will never be 'equal' using default comparisons. You have to compare the values of the objects. Try writing code to compare the values of each instance.

3553540 0

The documentation has this line of code:

user_db=${user_www}/${filename}-db.sqlite3 

Is the filename variable defined? Does the database exist in that location?

19422892 0

The convoluted way :

var t = setTimeout((function(that){ return function(){ jQuery(that).find("ul.topnavsub").hide(); console.log(that); } })(this), 1000); 

The less-cool-but-still-works-(-and-is-probably-more-readable-) way :

var that = this; var t = setTimeout(function(){ jQuery(that).find("ul.topnavsub").hide(); console.log(that); }, 1000); 
27330540 0 How to use OperaChromiumDriver for opera version >12.X

I understand that to work on opera versions > 12.X, Operachromiumdriver has been developed. At the same time I couldn't get this to work. I downloaded the windows version of operachromiumdriver.exe from https://github.com/operasoftware/operachromiumdriver/releases but to no avail. Can someone help me with this . Please tell me if my understanding is right.

Thanks

20222305 0

There is a particular line-height property for h3 tag with bootstrap.

h1, h2, h3 { line-height: 40px;//line 760 } 

So you will have to add style to negotiate this additional height.

Also another set for your ul as :

ul, ol { margin: 0 0 10px 25px; //line 812 } 

Solution :

  1. Over-ride the ul margin as follows :

    .pull-right ul{ margin: 0; } 
  2. Over-ride the line-height for the h3 as follows :

    .pull-left h3{ line-height:20px; } 

First one is pretty straight forward and gives you correct alignment straighaway. Second solution will need you to work some more with tweaking the negative-margins for .pull-right.

Debugging URL : http://jsbin.com/oToRixUp/1/edit?html,css,output

Hope this helps.

31494182 0

Scanner has a nextFloat() for getting floats fashion to nextInt(). Just call it in its own loop:

System.out.print("Enter " + c.length + " float values: "); for(int index1 = 0; index1 < c.length; index1++) { c[index1] = input.nextFloat(); } 

Unfortunately, there is no nextChar() method, so you'd have to emulate it with next(String)'s variant that accepts a pattern:

System.out.print("Enter " + b.length + " char values: "); for(int index1 = 0; index1 < b.length; index1++) { b[index1] = input.next(".").charAt(0); } 
19070557 0

Try (35 >= strlen($line) rather than (35 <= strlen($line) if you want lines 35 chars or less. Personally, I prefer to order comparisons like that the other way around, e.g. strlen($line) <= 35, which I think is more readable and avoids mistakes like the one you just made :)

17962433 0

First of all your UI will hang on button 2 click because it's stuck on the while(true) loop so use BeginAcceptSocket(IAsyncResult r, Object state) for async.

Second you must use the loopback address or otherwise the firewall should block the port 10 assuming that it's not open. Also the TcpListener(int port) is obsolote and its better to use the TcpListener(IPAddress localddr, int port) and use both the loopback address.

26381810 0 Calculate 1 line value using 2 or more other lines

I have the following query.

How this works my client sells kits. Each kit can contains 3 to 5 lines.

LINTYP = 6 - Kit Item LINTYP = 7 - Components 

The sequence should always be 6-7-7 where 6 represents the start of an new kit. There will always be 1 line that would contain an gross price. In the sample below there is 2 kits each containing 2 lines with an line status of 7

So what needs to happen is I need to calculate the missing GROSPRI using LINTYP 6 and deducting all my LINTYP 7 lines

eq.

Grosprice on line 1 (Product 550412) = R1 795 Grosprice on line 3 (Product 501301) = R 185 Grosprice on line 2 (Product 650412) should be R 1795-185 = R1 610 ---------------------------------------------------------------- | Invoice No| Product| Line No| Line Type| Gross Price ---------------------------------------------------------------- |SI141000008| 550412| 1000| 6| 1795.00 ---------------------------------------------------------------- |SI141000008| 650412| 2000| 7| 0.00 | This needs to be R1610 ---------------------------------------------------------------- |SI141000008| 501301| 3000| 7| 185.00 --------------------------------------------------------------- |SI141000008| 550413| 4000| 6| 1855.00 -------------------------------------------------------------- |SI141000008| 650413| 5000| 7| 0.00 | This needs to be R1670 --------------------------------------------------------------- |SI141000008| 501301| 6000| 7| 185.00 ---------------------------------------------------------------- 
33820507 0 Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]

I am having this error when I run my code. Any help will be appreciated. Thanks.

Here is my dispatcher servlet.

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="tutorial.mvc"/> <mvc:annotation-driven/> <bean id="HandlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/" /> <property name="suffix" value=".jsp" /> </bean> </beans> 

Here is my web.xml

<servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> 

Here is the error that I end up getting.

 Nov 20, 2015 1:39:45 AM org.apache.catalina.core.ApplicationContext log SEVERE: StandardWrapper.Throwable org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125) at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:129) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:540) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:454) at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:658) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:624) at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:672) at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:543) at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:484) at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1284) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1197) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:864) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:134) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2462) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2451) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml] at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:141) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329) ... 35 more 
3410674 0

The builtin method you are looking for is Array#transpose

21259556 0

I believe I've come up with an alternate solution to this problem. There are certain circumstances with the other solution proposed where the label colours appear incorrect (using the system default instead of the overridden colour). This happens while scrolling the list of items.

In order to prevent this from happening, we can make use of method swizzling to fix the label colours at their source (rather than patching them after they're already created).

The UIWebSelectSinglePicker is shown (as you've stated) which implements the UIPickerViewDelegate protocol. This protocol takes care of providing the NSAttributedString instances which are shown in the picker view via the - (NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component method. By swizzling the implementation with our own, we can override what the labels look like.

To do this, I defined a category on UIPickerView:

@implementation UIPickerView (LabelColourOverride) - (NSAttributedString *)overridePickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component { // Get the original title NSMutableAttributedString* title = (NSMutableAttributedString*)[self overridePickerView:pickerView attributedTitleForRow:row forComponent:component]; // Modify any attributes you like. The following changes the text colour. [title setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, title.length)]; // You can also conveniently change the background of the picker as well. // Multiple calls to set backgroundColor doesn't seem to slow the use of // the picker, but you could just as easily do a check before setting the // colour to see if it's needed. pickerView.backgroundColor = [UIColor yellowColor]; return title; } @end 

Then using method swizzling (see this answer for reference) we swap the implementations:

[Swizzle swizzleClass:NSClassFromString(@"UIWebSelectSinglePicker") method:@selector(pickerView:attributedTitleForRow:forComponent:) forClass:[UIPickerView class] method:@selector(overridePickerView:attributedTitleForRow:forComponent:)]; 

This is the Swizzle implementation I developed based off the link above.

@implementation Swizzle + (void)swizzleClass:(Class)originalClass method:(SEL)originalSelector forClass:(Class)overrideClass method:(SEL)overrideSelector { Method originalMethod = class_getInstanceMethod(originalClass, originalSelector); Method overrideMethod = class_getInstanceMethod(overrideClass, overrideSelector); if (class_addMethod(originalClass, originalSelector, method_getImplementation(overrideMethod), method_getTypeEncoding(overrideMethod))) { class_replaceMethod(originalClass, overrideSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod)); } else { method_exchangeImplementations(originalMethod, overrideMethod); } } @end 

The result of this is that when a label is requested, our override function is called, which calls the original function, which conveniently happens to return us a mutable NSAttributedString that we can modify in anyway we want. We could completely replace the return value if we wanted to and just keep the text. Find the list of attributes you can change here.

This solution allows you to globally change all the Picker views in the app with a single call removing the need to register notifications for every view controller where this code is needed (or defining a base class to do the same).

35777586 0

One solution is to use a Lookup expression, with the minimum price as the value to match. This expression should give each vendor if there is a tie for the cheapest:

=Join(LookupSet(Min(Fields!PRICE.Value), Fields!PRICE.Value, Fields!VENDOR.Value, "pv"), " / ") 

There may be a more elegant solution out there, but is the first one I found.

26670693 0
<input type="name[]" value="1"> //row1 <input type="name[]" value="2"> //row2 <input type="name[]" value="3"> // row3 

this is wrong i think you are looking for this

<input type="text" name="name[]" value="1"> //row1 <input type="text" name="name[]" value="2"> //row2 <input type="text" name="name[]" value="3"> // row3 
29094706 0 jQuery - If first element has class then Function

I'm looking to add a piece of code sitewide to affect all of my pages.

Right now, it goes something like this.

if($('#container > div:first').attr('id') == 'filterOptions') { $('#container').prepend('<div class="banner"></div>'); } 

The output:

<div id="container"> <div class="banner"></div> <div id="filterOptions"><div> </div> 

Example, if the container looked like this:

<div id="container"> <div class="existingBanner"></div> <div id="filterOptions"><div> </div> 

Nothing would happen as the first div doesn't have the filterOptions ID.

Now I've hit a bump as I also have something that looks like this that the banner DOES get added to

<div id="container"> <a class="existingBanner" href="#"></a> <div id="filterOptions"><div> </div> 

This will essentially have a double banner which is something I want to avoid. because it's an anchor instead of a div.

So my question is. instead of targeting div:first how would I target ALL elements?

Something like...

if($('#container > any:first').attr('id') == 'filterOptions') { ... }

37589976 0 How to iterate array in json

How to iterate array in json:

$(document).ready(function(){ $('#wardno').change(function(){ //any select change on the dropdown with id country trigger this code $("#wardname > option").remove(); //first of all clear select items var ward_id = $('#wardno').val(); $.ajax({ type: "POST", cache: false, url:"get_wardname/"+ward_id, //here we are calling our user controller and get_cities method with the country_id success: function(cities) { try { $.each(cities,function(id,city) { var opt = $('<option />'); // here we're creating a new select option with for each city opt.val(id[0]); opt.text(id[1]); $('#wardname').append(opt); var opt1 = $('<option />'); // here we're creating a new select option with for each city opt1.val(city[0]); opt1.text(city[1]); $('#koottaymaname').append(opt1); }); //here we will append these new select options to a dropdown with the id 'cities' } catch(e) { alert(e); } }, error: function (jqXHR, textStatus, errorThrown) { alert("jqXHR: " + jqXHR.status + "\ntextStatus: " + textStatus + "\nerrorThrown: " + errorThrown); } }); }); }); 

The output from the code is:

[{"1":"St. Sebastian"},{"1":"kudumbakoottayma1","2":"kudumbakoottayma2"}] 

How to iterate into two different drop down list?

459747 0

There is still a good reason for a template system to use, however not Smarty, but PHPTAL. PHPTAL templates are valid XML (and hence XHTML) files. You can farther use dummy content in PHPTAL and so get valid XHTML file with the final appearance, that can be processed and tested with standard tools. Here is a small example:

<table> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> </thead> <tbody> <tr tal:repeat="users user"> <td tal:content="user/first_name">Max</td> <td tal:content="user/last_name">Mustermann</td> <td tal:content="user/age">29</td> </tr> </tbody> </table> 

PHPTAL template engine will automatically insert all values from users array and replace our dummy values. Nevertheless, the table is already valid XHTML that can be displayed in a browser of your choice.

25610893 0

If you want to avoid using valid values of float, you could use a NAN:

#include <limits> .... float min = std::numeric_limits<float>::quiet_NaN(); 

You can then use std::isnan to check:

#include <cmath> .... bool not_cool = std::isnan(min); 
9297352 0

You receive null at the end of the stream. The client correctly starts, sends Ready, and the the ends, so the stream ends.

Totally correct behaviour. If the client would end itself (but instead do something else like reading server messages on stdin), the server would never receive a null.

Edit: NEVER EVER (!!!!!) do this:

catch(IOException e){} 

At least write:

catch(IOException e){ e.printStackTrace() } 

This will show you your error!

In my company, this is one of the elementary rules of code style!

10412684 0 compiling your own glibc

I am trying to compile my own glibc. I have a directory glibc, which contain the glibc source code I downloaded from the internet. From that directory I typed mkdir ../build-glibc. Now from the build-glibc directory I typed ../glibc/configure, which performed the configuration. Now I'm not sure how to call make. I can't call it from glibc directory since it doesn't have the configuration set, neither I can call it from build-glibc, since makefile is not in that directory. How do I solve this problem?

39624683 0
var stuff= ["uyuuyu", "76gyuhj***", "uiyghj", "56tyg", "juijjujh***"]; for(var i = 0; i < stuff.length; i++) { if(stuff[i].indexOf('***') != -1) { stuff[i] = stuff[i].replace('***','0') // this is where i guess the replacing would go } console.log(stuff[i]); } 
4920668 0

Yes there's a standard method for creating these symbols known as name mangling.

11372530 0

I can't think of a good way to do this with qsub as there are no programmatic interfaces into the -o and -e options. There is, however, a way to accomplish what you want.

Run your qsub with -o and -e pointing to /dev/null. Make the command you run be some type of wrapper that redirects it's own stdout and stderr to files in whatever fashion you want (i.e., your broken down directory structure) before it execs the real job.

32902868 0 Swift set variable to another ViewController

I have two tabs. And i want to set data from one tab to another. For example i have a code that switch to another tab:

func foundCode(code: String) { print("Code has been found: \(code)") // MySecondViewController.codeSetter(code); self.tabBarController?.selectedIndex = 1; } 

What is the best way to set it? Or maybe delegate this variable... But how ?

10575459 0

For what you want this is not the best way of doing it. However what you're talking about requires knowledge of one of the fundamental tennets of PHP and programming in general aka scope, namely what the global scope is.

So, if you declare this in the global scope:

 $uom = new UOM_Class(); 

Then in any file afterwards you write:

global $uom; $uom->something(); 

it will work.

This is all wasteful however, instead you would be better with static methods, and something more like a singleton pattern e.g.:

UOM::Something(); 

I leave it as a task for you to learn what a singleton is, and what scope is, these are fundamental tennets of PHP, and you should not claim to know PHP without knowing about scope. The best way of putting it is when in everyday conversation, it is called context, the global scope is tantamount to shouting in everyones ear at the same time. Everyone can access it, and its not something you want to pollute

I'm sorry if I seem a bit harsh, here's some articles that should help, they talk about scope, singletons and some other methods of doing it, like object factories

http://php.net/manual/en/language.variables.scope.php http://www.homeandlearn.co.uk/php/php8p2.html

http://php.net/manual/en/language.oop5.patterns.php

39795421 0 Show in view only object with specified id

i am woking on a project about a restaurant and i need to show on my staff view only the Chef and Su-Chef which has id (Chef-2, Su-Chef 4). I need to show on my view all the Chefs and all the Su-Chefs. The view is organised at the form that is the number is odd (i have the image on left and text on right), if the number is even i have (i have the image on right and text on left) Here is my Controller

public function index() { $staff = Staff::where('visible','yes')->where('delete','no')->orderBy('name','DESC')->get(); return view('staff.staff', ['staff' => $staff]); } 

And this is my View

<section class="bg-deep-yellow"> <div class="container"> <div class="row"> <!-- section title --> <div class="col-md-12 text-center"> <span class="title-small black-text text-uppercase letter-spacing-3 font-weight-600">I NOSTRI CHEF</span> <div class="separator-line-thick bg-black no-margin-bottom margin-one xs-margin-top-five"></div> </div> <!-- end section title --> </div> <div class="row margin-ten no-margin-bottom"> <!-- chef --> <div class="col-md-12 sm-margin-bottom-ten"> <div class="col-md-5 chef-img cover-background" style="background-image:url({{URL::asset('external_assets/assets/images/images_downloaded/chef.jpg') }});"> <div class="img-border"></div> </div> <div class="col-md-7 chef-text bg-white text-center"> <img src="{{URL::asset('external_assets/assets/images/images_downloaded/kapele.png') }}" alt=""/><br> <span class="text-large black-text text-uppercase letter-spacing-3 font-weight-600 margin-ten display-block no-margin-bottom">Patrick Smith</span> <span class="text-small text-uppercase letter-spacing-3">Chef, Co-Founder</span> <p class="text-med margin-ten width-90 center-col" style="text-align: justify">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p> </div> </div> <!-- end chef --> <!-- chef --> <div class="col-md-12"> <div class="col-md-7 chef-text bg-white text-center"> <img src="{{URL::asset('external_assets/assets/images/images_downloaded/bari.png') }}" alt=""/><br> <span class="text-large black-text text-uppercase letter-spacing-3 font-weight-600 margin-ten display-block no-margin-bottom">Sancho Pansa</span> <span class="text-small text-uppercase letter-spacing-3">Bartender</span> <p class="text-med margin-ten width-90 center-col" style="text-align: justify" >Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p> </div> <div class="col-md-5 chef-img cover-background" style="background-image:url({{URL::asset('external_assets/assets/images/images_downloaded/chef2.jpg') }});"> <div class="img-border"></div> </div> </div> <!-- end chef --> </div> </div> </section> 

This is an image of my view

2480835 0 NHibernate paging for Telerik Extensions for ASP.NET MVC

How can I integrate Telerik Grid paging for ASP.NET MVC (http://demos.telerik.com/aspnet-mvc/Grid) with my NHibernate data access with minimal coding?

39010768 0

You cantry it this way, it should work:

$.ajax({ type: "GET", url: "/grafana/dashboard", contentType: "application/json", beforeSend: function(xhr, settings){ xhr.setRequestHeader("some_custom_header", "foo");}, success: function(data){ $("#output_iframe_id").attr('src',"data:text/html;charset=utf-8," + escape(data)) } }); 
33492944 0

Yes, you can do it in single query. Combine those condition in one query then sort YMonth DESC and limit by ROWNUM

SELECT COUNT(*) FROM ( SELECT XXX,YMONTH FROM MyTable WHERE XXX AND YMONTH IN( TO_CHAR(add_months(SYSDATE,0),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-1),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-2),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-3),'YYYYMM'), TO_CHAR(add_months(SYSDATE,-4),'YYYYMM') ) ORDER BY YMONTH DESC ) WHERE ROWNUM <= 3 

Please try the query above, and let see if it works.

40562875 0

You need to specify the inheritance with extends the base class http://php.net/manual/en/keyword.extends.php

Try this for your child class

//Child View Class class ChildView extends View{ public function html(){ //I get a fatal error here: calling img_cache on a non-object. //But it should have inherited this from the parent class surely? return '<img src="'.$this->img_cache->thumb($this->data['img-src']).'"/>'; } } 

Also as @ferdynator says, you are instantiating the parent, not the child, so your Main class also needs to be changed to instantiate ChildView, not the parent View

//Main class: class Main{ //construct public function Main(){ //get data from model $data = $model->getData(); //Get the view $view = new ChildView(); //Init view $view->init( $data ); //Get html $view->getHTML(); } } 
18099453 0 Why the data retrieved isn't shown

I would to retrieve the data from http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore . The tag under "title", "start_time", "longitude", "latitude". But I not sure why it couldn't be display out after I added the longitude and latitude.

This is from logcat:

08-07 17:17:44.190: E/AndroidRuntime(23734): FATAL EXCEPTION: main 08-07 17:17:44.190: E/AndroidRuntime(23734): java.lang.NullPointerException 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.example.eventfulmaptry.MainActivity$ItemAdapter.getView(MainActivity.java:147) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.AbsListView.obtainView(AbsListView.java:1618) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.ListView.measureHeightOfChildren(ListView.java:1241) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.ListView.onMeasure(ListView.java:1152) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.measureVertical(LinearLayout.java:531) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3143) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.View.measure(View.java:8513) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewRoot.performTraversals(ViewRoot.java:857) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.view.ViewRoot.handleMessage(ViewRoot.java:1878) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.os.Handler.dispatchMessage(Handler.java:99) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.os.Looper.loop(Looper.java:130) 08-07 17:17:44.190: E/AndroidRuntime(23734): at android.app.ActivityThread.main(ActivityThread.java:3691) 08-07 17:17:44.190: E/AndroidRuntime(23734): at java.lang.reflect.Method.invokeNative(Native Method) 08-07 17:17:44.190: E/AndroidRuntime(23734): at java.lang.reflect.Method.invoke(Method.java:507) 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 08-07 17:17:44.190: E/AndroidRuntime(23734): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:670) 08-07 17:17:44.190: E/AndroidRuntime(23734): at dalvik.system.NativeStart.main(Native Method) 

This is my code :

public class MainActivity extends Activity { ArrayList<String> title; ArrayList<String> start_time; ArrayList<String> latitude; ArrayList<String> longitude; ItemAdapter adapter1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView list = (ListView) findViewById(R.id.list); title = new ArrayList<String>(); latitude = new ArrayList<String>(); longitude = new ArrayList<String>(); try { URL url = new URL( "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore"); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(url.openStream())); doc.getDocumentElement().normalize(); NodeList nodeList = doc.getElementsByTagName("event"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); Element fstElmnt = (Element) node; NodeList nameList = fstElmnt.getElementsByTagName("title"); Element nameElement = (Element) nameList.item(0); nameList = nameElement.getChildNodes(); title.add(""+ ((Node) nameList.item(0)).getNodeValue()); NodeList websiteList = fstElmnt.getElementsByTagName("start_time"); Element websiteElement = (Element) websiteList.item(0); websiteList = websiteElement.getChildNodes(); start_time.add(""+ ((Node) websiteList.item(0)).getNodeValue()); NodeList websiteList1 = fstElmnt.getElementsByTagName("latitude"); Element websiteElement1 = (Element) websiteList1.item(0); websiteList1 = websiteElement1.getChildNodes(); latitude.add(""+ ((Node) websiteList1.item(0)).getNodeValue()); NodeList websiteList2 = fstElmnt.getElementsByTagName("longitude"); Element websiteElement2 = (Element) websiteList2.item(0); websiteList2 = websiteElement2.getChildNodes(); longitude.add(""+ ((Node) websiteList2.item(0)).getNodeValue()); } } catch (Exception e) { System.out.println("XML Pasing Excpetion = " + e); } adapter1 = new ItemAdapter(this); list.setAdapter(adapter1); } class ItemAdapter extends BaseAdapter { final LayoutInflater mInflater; private class ViewHolder { public TextView title_text; public TextView des_text; public TextView lat_text; public TextView long_text; } public ItemAdapter(Context context) { // TODO Auto-generated constructor stub super(); mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } //@Override public int getCount() { return title.size(); } //@Override public Object getItem(int position) { return position; } //@Override public long getItemId(int position) { return position; } //@Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; final ViewHolder holder; if (convertView == null) { view = mInflater.inflate(R.layout.mainpage_list,parent, false); holder = new ViewHolder(); holder.title_text = (TextView) view.findViewById(R.id.title_text); holder.des_text = (TextView) view.findViewById(R.id.des_text); holder.lat_text = (TextView) view.findViewById(R.id.lat_text); holder.long_text = (TextView) view.findViewById(R.id.long_text); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } holder.title_text.setText(""+title.get(position)); holder.des_text.setText(""+Html.fromHtml(start_time.get(position))); holder.lat_text.setText(""+Html.fromHtml(latitude.get(position))); holder.long_text.setText(""+Html.fromHtml(longitude.get(position))); return view; } } } 
15404711 0

in the javascript function. Then it will not postback.

 $j(".colorBoxLink").click((function () { $j("div#popup").show(); var editor = new wysihtml5.Editor("wysihtml5_textarea", { // id of textarea element toolbar: "wysihtml5-toolbar", // id of toolbar element parserRules: wysihtml5ParserRules, // defined in parser rules set stylesheets: ["Styles/wysihtml5.css", "Styles/wysihtml5.css"] }); $j.colorbox({ inline: true, href: "#popup", modal: true, scrolling: false, onCleanup: function () { $j("div#popup").hide(); } }); return false; })); 
11773518 0

Could it be because you want to measure the font before it's been fully loaded ?

In my example it seems to be working fine : Font example

10176059 0

The images you are using might be too large for an animation. How large are they? In an animation, Android loads all of the images into memory and uncompresses them meaning that every pixel will take 4 bytes. So 50k would mean that your image is 111px x 111px. It seems from the error each frame is about 480 x 640, which is really large. Try using smaller images.

28839887 0 number bytes read from gpio input is zero

I have some strange behaviour when trying to read gpio output pin. I get that the first read return 1 (1 bytes read), but all next read from same gpio return 0. I would assume that it should always read 1, because there is always something to read from input pin.

gpio = 8; fd = open("/sys/class/gpio/export", O_WRONLY); sprintf(buf, "%d", gpio); rc = write(fd, buf, strlen(buf)); if (rc == -1) printf("failed in write 17\n"); close(fd); sprintf(buf, "/sys/class/gpio/gpio%d/direction", gpio); fd = open(buf, O_WRONLY); rc = write(fd, "in", 2); if (rc == -1) printf("failed in write 18\n"); close(fd); sprintf(buf, "/sys/class/gpio/gpio%d/value", gpio); gpio_tdo = open(buf, O_RDWR); rc = read(gpio_tdo, &value, 1); <-- rc here is 1 rc = read(gpio_tdo, &value, 1); <-- rc here is 0 rc = read(gpio_tdo, &value, 1); <-- rc here is 0 

Should the read of one byte from the gpio input always return 1 ?

29310107 0

You want to use Mysql Join to join the two tables together which reference the user id.

Account Table

CREATE TABLE `account` ( `id` INT UNSIGNED AUTO_INCREMENT, `username` VARCHAR(10) NOT NULL, PRIMARY KEY(`id`) ); 

Suspension Table

CREATE TABLE `suspension` ( `user_id` INT UNSIGNED DEFAULT NULL, FOREIGN KEY (`user_id`) REFERENCES account(`id`) ON DELETE CASCADE ON UPDATE CASCADE ); 

Query

SELECT A.username, A.id FROM `account` AS A LEFT JOIN `suspension` AS S ON S.user_id = A.id WHERE A.id = 5 AND S.user_id IS NULL; 

If the user appears in Suspension, no results are returned. If the user isn't suspended then the user result is returned. To return the user and their suspension status, you can use the below query.

SELECT A.username, A.id, (S.user_id IS NOT NULL) AS `suspended` FROM `account` AS A LEFT JOIN `suspension` AS S ON S.user_id = A.id WHERE A.id = 5; 
35814790 0 8285825 0 How to change text or background color in a Windows console application

Which C++ function changes text or background color (MS Visual studio)? For example cout<<"This text"; how to make "This text" red color.

19047053 0 having a powers of 2 questions
 import acm.program.*; public class Practice3 extends ConsoleProgram { public static int powersOf2(int k) { int x = 0; while (k < 1000) { x = k; k *= 2; } return x; } public void run() { println(powersOf2(1)); println(powersOf2(0)); println(powersOf2(2)); println(powersOf2(-1)); println(powersOf2(3000)); } 

I don't think I really get right values from powersOf2. Only 512 is displayed when I run program. And if I run it by each println, it gives me:

512 none 512 none 0 

Is there something wrong? or values are correct?

18961158 0 Formatting data based on string or number - google visualization

I have database in PHPMyAdmin, Excel and CSV format (all the same just different formats). To put this data in a table in google visualization numbers are written as they are but string values need to have a ' either side of the text. For example:

['MESSI','FC BARCELONA','ARGENTINA',169,67,25,'Left foot','SS',98,99,38,74,9855704866], 

My database has over 2000 rows so manually doing this isn't an option. Is there a way in any of these formats to make all string variables have the ' either side and all numbers to be written by themselves. The CSV format already splits cells using a comma which I need but it would also be useful if each row started with [ and ended with ] . Anyone know how to do this using any of these formats?

3193062 0

You can make C++ callable from C by using the extern "C" construct.

34803298 0

You are forgetting an AND in this line.

SELECT * FROM users WHERE id ='" . $_SESSION['UserRow'] . "' AND note='$noteSequence'", $connection 
17293590 0 How efficient is .clone()?

I have a page with a canvas area (nothing to do wth HTML5) where people can create "art" by dragging in photos, creating divs that they can drag, stretch, color, etc. etc. etc. The canvas div is inside a canvasContainer div. Now I'd like to implement an UNDO option. My thought was to do a

 canvasBackup$ = $('#canvas').clone(); 

when an operation began, say at every dragStart event, and at the end of the operation an UNDO, if asked for with Ctrl-Z, would execute

 $('#canvas').remove(); canvasBackup$.appendTo($('#canvasContainer'); 

My concern is that the clone, and perhaps the append, might be a bit compute intensive as the page grows and start slowing down the page's responsiveness. I suppose it depends on how jQuery does the clone. If it just breaks off the section from the DOM and does a straight memory copy, it shouldn't be bad. But if there's a lot of calculation and building going on it could be a problem.

Does anyone have a feel for whether this is a reasonable approach to implementing UNDO?

Thanks

4024056 0 Threads vs. Async

I have been reading up on the threaded model of programming versus the asynchronous model from this really good article. http://krondo.com/blog/?p=1209

However, the article mentions the following points.

  1. An async program will simply outperform a sync program by switching between tasks whenever there is a I/O.
  2. Threads are managed by the operating system.

I remember reading that threads are managed by the operating system by moving around TCBs between the Ready-Queue and the Waiting-Queue(amongst other queues). In this case, threads don't waste time on waiting either do they?

In light of the above mentioned, what are the advantages of async programs over threaded programs?

32481778 0

Quick answer:

First af all you are starting from x=0 and then increasing it which is not the best solution since you are looking for the maximum value and not the first one. So for that I would go from an upperbound that can be

x=abs((b)^(1/4))

than decrease from that value, and as soon you find an element <=b you are done.

You can even think in this way:

for y=b to 1 solve(x^4+x^3+x^2+x+1=y) if has an integer solution then return solution 

See this

This is a super quick answer I hope I didn't write too many stupid things, and sorry I don't know yet how to write math here.

5167035 0 Excutereader is very slow when taking data by oledbcommand object

I am fetching data from dBase4 database by using object of oledbcommand and load it into datatable. but it is taking too much time to fetch 160 records around 5-10 minutes. Please Help me Out.

Code:

 using (OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;" + @"Data Source=" + TrendFilePath + "\\" + Pathname + ";" + @"Extended Properties=dBASE III;")) using (OleDbCommand cm = cn.CreateCommand()) { cn.Open(); for (int L = 0; L <= months; L++) { DataTable dt_Dbf = new DataTable(); From_Date = DateTime.ParseExact(frmdate, dateFormat2, provider); From_Date = From_Date.AddMonths(L); int month = From_Date.Month; string year = "1" + From_Date.Year.ToString().Substring(2, 2); if (L == 0) { cm.CommandText = @"SELECT * FROM 128.DBF where DATE_Y =" + year + " and DATE_M = " + month + " and DATE_D>=" + From_Day + ""; dt_Dbf.Load(cm.ExecuteReader(CommandBehavior.CloseConnection)); } } } 
20116797 0

Scala has implemented also the async/await paradigm, which can simplify some algorithms.

Here is the proposal: http://docs.scala-lang.org/sips/pending/async.html

Here is the implementation: https://github.com/scala/async

23311182 0 Convert JSON String to Object - jquery

I have a JSON String like this.

{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} 

I wanted to convert it to object like this

[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"}] 

I did figure that out like this.

'[' + {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"} + ']' 

And using $.parseJSON() to make it a JSON.

But instead of concatenating. Is there any elegant way to do it?

If so please do share me.

Thanks in advance.

25766028 0

What you want to do is not called "instantiation." You can instantiate a universally quantified hypothesis and you can instantiate an existentially quantified conclusion, but not vice versa. I'm thinking the proper name is "introduction". You can introduce existential quantification in a hypothesis and you can introduce universal quantification in the conclusion. If it seems like you're "eliminating" instead, that's because, when proving something, you start at the bottom of a sequent calculus deriviation, and work your way backwards to the top.

Anyway, use the tactic firstorder. Also, use the command Set Firstorder Depth 0 to turn off proof search if you only want to simplify your goal.

If your goal has higher order elements though, you'll probably get an error message. In that case, you can use something like simplify.

Ltac simplify := repeat match goal with | h1 : False |- _ => destruct h1 | |- True => constructor | h1 : True |- _ => clear h1 | |- ~ _ => intro | h1 : ~ ?p1, h2 : ?p1 |- _ => destruct (h1 h2) | h1 : _ \/ _ |- _ => destruct h1 | |- _ /\ _ => constructor | h1 : _ /\ _ |- _ => destruct h1 | h1 : exists _, _ |- _ => destruct h1 | |- forall _, _ => intro | _ : ?x1 = ?x2 |- _ => subst x2 || subst x1 end. 
9885459 0

In my case (label on a panel) I set label.AutoSize = false and label.Dock = Fill. And the label text is wrapped automatically.

22554399 0

You should set your categories in beforeFilter() of appController for that because navigation will be included in every page .

 function beforeFilter() { parent::beforeFilter(); ///set your categories here $this->set('Categories',$Categories); } 
21777508 0

I am not sure you are asking for this.

If the path of the folders are same you can use -or with find

find $CATALINA_HOME/webapps/myapp/WEB-INF/lib/ -name "*.jar" -or -type d

-type d will also find directories

3505889 0 Can I set the size attribute of StructLayout at runtime?

Im trying to use SendInput to simulate keyboard presses in my app and want to support both 32-bit and 64-bit.

I've determined that for this to work, I need to have 2 different INPUT structs as such

 [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; // Virtual Key Code public ushort wScan; // Scan Code public uint dwFlags; public uint time; public IntPtr dwExtraInfo; } [StructLayout(LayoutKind.Explicit, Size = 28)] public struct INPUT32 { [FieldOffset(0)] public uint type; // eg. INPUT_KEYBOARD [FieldOffset(4)] public KEYBDINPUT ki; } [StructLayout(LayoutKind.Explicit, Size = 40)] public struct INPUT64 { [FieldOffset(0)] public uint type; // eg. INPUT_KEYBOARD [FieldOffset(8)] public KEYBDINPUT ki; } 

I wanted to know if there was a way to set the StructLayout size and FieldOffsets at runtime so I could use just one INPUT struct and determine the size and fieldoffset depending on the machine.

I have tried the code below but I would like to know if the same is possible at runtime instead of compile time.

#if _M_IX86 [StructLayout(LayoutKind.Explicit, Size = 28)] #else [StructLayout(LayoutKind.Explicit, Size = 40)] #endif public struct INPUT { [FieldOffset(0)] public uint type; // eg. INPUT_KEYBOARD #if _M_IX86 [FieldOffset(4)] #else [FieldOffset(8)] #endif public KEYBDINPUT ki; } 
27625701 0

You did not even use a search engine to look for the error message.

In google, the first result is the MDB2 FAQ page which explains the error and the reason for it.

1673178 0 cvs2svn changes binary files

I'm using cvs2svn to migrate from CVS to SVN.

I've noticed a problem with my binary file after the conversion was completed.

I'm using auto-props file, which is very helpful.

After the conversion I took the file from CVS and compared it to the same file from SVN. The file is binary. Using WinMerge, I see that there is a difference between the files.

What can be the problem?

28022612 0

This might hepls you

declare @t table(a date,b time) insert into @t values (getdate(),'7:00:00 AM') select * from @t where a>'2015/01/19' or (a=getdate() and a>'6:00:00 AM') 
314693 0
select * from canonical_list_of_tags where tag not in (select tag from used_tags) 

At least that works in T-SQL for SQL Server ...

Edit: Assuming that the table canonical_list_of_tags is populated with the result of "Given a collection of user specified tags"

29112595 0 I want to copy files from one folder to another in my dedicated server

I placed files in my root folder and copy when user try to download the files like

/root/filelocation/file.mp3

when user on download page

copy("/root/filelocation/file.mp3","download/file.mp3"); 

i use this command but it takes too much load time

i have ffmpeg installed in server also

18265414 0 PHP login with PDO, doesnt seem to work

There aren't any errors given, but for some reason the code doesnt seem to work..

Here is the code:

<?php session_start(); require_once('inc/db.php'); if(isset($_SESSION['username'])) { header("location: index.php"); } else { try { $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $SQL = $dbh->prepare('SELECT * FROM users WHERE username =:username AND password =:password'); $SQL->bindParam(':username', $username); $SQL->bindParam(':password', $password); $SQL->execute(); $total = $SQL->rowCount(); $row = $SQL->fetch(); if($total > 0) { if($row['verified'] > 0) { $_SESSION['username'] = $username; } else { echo "Unverified"; } } else { echo "Incorrect"; } } catch(PDOException $e) { } } ?> 

Can anyone help me see what's wrong? Thank you a lot in advance :)

EDIT::::

Here is my db.php

<?php try { $DB_NAME = 'users'; $DB_USER = 'root'; $DB_PASS = ''; $dbh = new PDO('mysql:host=localhost;dbname='.$DB_NAME, $DB_USER, $DB_PASS, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Error?"; } ?> 
37164244 0 Do we need a second thread to process time-consuming jobs with inotify?

Referenc: How to monitor a folder with all subfolders and files inside?

I need to monitor a directory for any file with extension of *.log. If a new file is created or is moved in, I will process the file. it takes variable time to process each file.

Question> Do I need to create one thread to listen the inotify event and push the new file name into queue and use another thread to process the queue? My concern is that if I don't use separate threads, then the inotify may fail to track changes caused by some large files.

I have simulated the problem with sleep while processing each log file without any multi-thread code. It seems to me that inotify always corrects get all created/moved files in the directory.

Here is my simulation.

Terminate 1: I run the app and listen the inotify event within the main. Whenever processing one log file, I will sleep for 10 second then print the file name to console.

Terminte 2: I will copy multiple files at time T1 to the monitored directory. Before the app finishing processing all previous files, I will move multiple files at time T2. Then again time T3, I will copy multiple files to the directory before the app finishes.

Observation: The app processed all log files as I expected.

Question> Is this expected behavior of inotify or I just run lucky this morning? In other words, will inotify cache unprocessed events in case of simulation as above?

FYI: the code snippet I used:

#define EVENT_SIZE ( sizeof (struct inotify_event) ) #define BUFFER_LEN ( 1024 * ( EVENT_SIZE + NAME_MAX + 1) ) wd = inotify_add_watch( fd, root.string().c_str(), IN_CREATE | IN_MOVED_TO ); while ( true ) { length = read( fd, buffer, BUFFER_LEN ); for ( int i = 0; i < length; ) { const inotify_event *ptrEvent = reinterpret_cast<inotify_event *>(&buffer[i]); ... // processing the event sleep(10); // to simulate the long work i += INO_EVENT_SIZE + ptrEvent->len; } } 
13701479 0

You can simply extend your code:

if ( (str[i] == '-' && minus) || (str[i] >= '0' && str[i] <= '9') || (str[i] == 'e' || str[i] == 'E') ) 

to

char separator = ','; //or whatever you want int have_separator = 0; if ( (str[i] == '-' && minus) || (str[i] >= '0' && str[i] <= '9') || (str[i] == 'e' || str[i] == 'E') || str[i] == separator ) { if (str[i] == separator && have_separator == 0) { have_separator = 1; str_dbl[j++] = str[i]; continue; } ... 

Please note that this is only some try to show the idea - not the real working code (but it could work anyway). You can use similar concept.

27301946 0

As Jake Wharton said

You can use a "@FieldMap Map<String, String>" for that. 

Looks like Robospice Retrofit module is out of date.

18907389 0

For MySQL 5.7:

ALTER TABLE tbl_name RENAME INDEX old_index_name TO new_index_name 

For MySQL older versions:

ALTER TABLE tbl_name DROP INDEX old_index_name, ADD INDEX new_index_name (...) 

See http://dev.mysql.com/doc/refman/5.7/en/alter-table.html

11654411 0 Single criteria query with two separate sets of restrictions

I'm wondering if you can create a single criteria query then somehow create two separate sets of restrictions with two completely different sets of results without having to issue a second query?

35723634 0

Simplest way would be to use a wild card character (*) and add the wildcarded option

cts:search(fn:doc(),cts:word-query("*226", ('wildcarded'))) 

EDIT:

Although this matches the example documents, as Kishan points out in the comments, the wildcard also matches unwanted documents (e.g. containing "226226").

Since range indexes are not an option in this case because the data is mixed, here is an alternative hack:

cts:search( fn:doc(), cts:word-query( for $lead in ('', '0', '00', '000') return $lead || "226")) 

Obviously, this depends on how many leading zeros there can be and will only work if this is known and limited.

24274151 0

The "enhanced for loop" as you call it (it's actually called the foreach loop) internally uses an iterator for any iterable - including linked lists.

In other words it is O(n)

It does handle looping over arrays by using an integer and iterating over it that way but that's fine as it performs well in an array.

The only advantages of using an iterator manually are if you need to remove some or all of the elements as you iterate.

21697697 0

Yes, performing method calls like this is perfectly fine. They're marked as private so they remain encapsulated within your class and unexposed to the outside world.

If these method calls started to cause the class/object to deviate its main purpose, breaking single responsibility principle, then it would be worth looking at breaking the class into finer units and injecting this new dependency via dependency injection. An example of this would be if the checkBaz method was performing a database look-up.

In terms of unit testing, what you really want to do is program to an interface not implementation by creating an interface for your foo class and implementing it. This means whenever you program to it you're programming to a contract - allowing you to easily mock your IFoo implementation.

eg:

class Foo implements IFoo { } 

Your interface will look like this:

interface IFoo { public function setBaz($baz) public function setBar($bar) } 

I would also recommend following the PEAR coding standard and make your class names uppercase first. Though if this is a decision made by you or your team then that's entirely your call.

2674853 0 How to delete a string inside a file (.txt) in Java Programming

I would like to delete a string or a line inside a ".txt" file (for example filen.txt). For example, I have these lines in the file:

1JUAN DELACRUZ
2jUan dela Cruz
3Juan Dela Cruz

Then delete the 2nd line (2jUan dela Cruz), so the ".txt" file will look like:

1JUAN DELACRUZ
3Juan Dela Cruz

How can I do this?

36784340 0 Finding the last row with data using vba

I am creating a program in which everytime it generates, the generated data will appear in a specific sheet and arranged in specific date order . It looks like this.

Generated data

But when I generate again, the existing data will be replaced/covered by the new data generated. Looks like this.

enter image description here

Now my idea is, before I am going to paste another data, I want to find out first what is the last used cell with value so that in the next generation of data, it wont be replaced/covered by the new one. Can someone help me with this. The output should look like this.

enter image description here

Any help everyone? Thanks!

23514209 0

One of the first things you need to learn about SQL (and relational databases) is that you shouldn't store multiple values in a single field.

You should create another table and store one value per row.

This will make your querying easier, and your database structure better.

select case when exists (select countryname from itemcountries where yourtable.id=itemcountries.id and countryname = @country) then 'national' else 'regional' end from yourtable 
22104970 0

Looking at the source of Set::new:

# File set.rb, line 80 def initialize(enum = nil, &block) # :yields: o @hash ||= Hash.new enum.nil? and return if block do_with_enum(enum) { |o| add(block[o]) } else # you did not supply any block, when you called `new` # thus else part will be executed here merge(enum) end end 

it seems that Set.new calls method #add internally. In the OP's example, block is nil, thus #merge is called:

# File set.rb, line 351 def merge(enum) if enum.instance_of?(self.class) @hash.update(enum.instance_variable_get(:@hash)) else # in your case this else part will be executed. do_with_enum(enum) { |o| add(o) } end self end 

Hence add is called for each element of enum ([1,2]). Here, you overrode the original #add method, and within that method, you are calling the old #add method with the argument 5.

Set implements a collection of unordered values with no duplicates. Thus even if you added 5 twice, you are getting only one 5. This is the reason you are not getting #<Set: {1,2}>, but #<Set: {5}>. As below, when you call Set.new, the object #<Set: {5}> is created just as I explained above:

require 'set' class Set alias :old_add :add def add(arg) arg = 5 old_add arg end end s = Set.new ([1,2]) s # => #<Set: {5}> 

When you called s.add(3), your overridden add method was called, and it again passed the 5 to the old add method. As I said earlier, Set doesn't contain duplicate values, thus the object will still be the same as the earlier #<Set: {5}>.

25561125 1 Parsing and Storing HTML Tags Along With Text

I'm looking for a way to parse unicode strings of html and essentially split all of the elements of the string (html elements as well as individual tokens) and store them in a list. BeautifulSoup obviously has some nice functionality for parsing html, such as the .get_text method, but this doesn't preserve the tags themselves.

What I need is something like this. Given an html unicode string such as

s = u'<b>This is some important text!</b>,

what I would like to have as a result is a list like this:

['<b>', 'This', 'is', 'some', 'important', 'text!', '</b>']

There must be an easy way to do this with BeautifulSoup that I'm just not seeing in SO searches. Thanks for reading.

EDIT: since this has been getting some questions as to the purpose of storing the tags, I'm interested in using the tags as features for a project in text classification. I'm experimenting with using different structural features from an online discussion forum in addition to the n-grams present within forum posts.

13795206 0 Strange output from Java typecast

I am playing around with simple encryption using RSA algorithms and found a strange bug.

private static Integer testEnc(Integer value){ Integer val = (int)Math.pow(value, 37); return val % 437; } private static Integer testDec(Integer value){ Integer val = new Integer((int)Math.pow(value, 289)); return val % 437; } public static void main(String[] args) { System.out.print("Encode 55 = "); Integer encoded = testEnc(2); System.out.println(encoded + "\n"); System.out.print(encoded + " decoded = "); Integer decoded = testDec(3977645); System.out.println(decoded + "n"); } 

Both of the following functions return 97 regardless of input. If I comment out the modulus and just return val, the returned value is 2147483647.

Type casting double to int seems to be the issue but I am not sure why this is. These methods are static only because I was calling them from a main method.

26871943 0

You're looking for the extend method.

>>> l = [1, 2, 3] >>> l.extend([4, 5, 6]) >>> print l [1, 2, 3, 4, 5, 6] 
23109791 0

I had a similar problem recently, specifically making the width match the parent div and also respond. I couldn't work out why Trust Pilot thought it appropriate to set something to make the height of the frame dynamic and not the width, but anyway.

Firstly, I had some CSS for the parent div, like:

<style type="text/css"> div.trust-pilot{ width: 100% !important; height: auto; } </style> 

This may not actually be necessary, but I put it there anyway.

These are the 'trustbox' settings I used (see http://trustpilot.github.io/developers/#trustbox):

<div id="trust-pilot" class="trust-pilot"> <div class="tp_-_box" data-tp-settings="domainId: xxxxxxx, bgColor: F5F5F5, showRatingText: False, showComplementaryText: False, showUserImage: False, showDate: False, width: -1, numOfReviews: 6, useDynamicHeight: False, height: 348 "> </div> <script type="text/javascript"> (function () { var a = "https:" == document.location.protocol ? "https://ssl.trustpilot.com" : "http://s.trustpilot.com", b = document.createElement("script"); b.type = "text/javascript"; b.async = true; b.src = a + "/tpelements/tp_elements_all.js"; var c = document.getElementsByTagName("script")[0]; c.parentNode.insertBefore(b, c) })(); </script> </div> 

Replace the domainId with something valid (in the case of this question, it's 3660907). Note that the width: -1 parameter might work already for you except if you want the page to be responsive (that is below).

Firstly, to make the width match the parent div, I used:

<script type="text/javascript"> jQuery( window ).load(function() { _width = jQuery('#trust-pilot').innerWidth(); jQuery('#tpiframe-box0').attr('width',_width); }); </script> 

And then to make the box respond, I used:

<script type="text/javascript"> jQuery( window ).resize(function() { _width = jQuery('#trust-pilot').innerWidth(); jQuery('#tpiframe-box0').attr('width',_width); }); </script> 

I hope that this helps. Shaun.

16341343 0 Exactly which content-inserting block helpers have changed behaviour in Rails 3?

The release notes for Rails 3.0 include this change:

7.4.2 Helpers with Blocks

Helpers like form_for or div_for that insert content from a block use <%= now:

<%= form_for @post do |f| %> ... <% end %> 

Your own helpers of that kind are expected to return a string, rather than appending to the output buffer by hand.

Helpers that do something else, like cache or content_for, are not affected by this change, they need <% as before.

We're in the process of migrating a web application from Rails 2.3.18 to Rails 3.1.12, and it would be very useful to have a complete list of such helpers that have changed, so that we can check all of their occurrences in our source code, but I'm having trouble finding an authoritative list of this kind.

I've tried looking through the git history of the rails project, but there seem to be many commits with related changes, and they're not obviously grouped on particular branch. For example, it seems to be clear that this list includes:

... from 7b622786f,

... alluded to in e98474096 and:

... alluded to in e8d2f48cff

.... alluded to in 0982db91f, although it's removed in Rails 3.

However, I'm sure that's not complete - can anyone supply a complete list?

20669873 0

This cannot be done using only CSS3. CSS3 does not allow you to reference parent elements based on a hover of the child element. You'll need to use JavaScript for this.

Hopefully browsers will soon support the parent selector that is featured in the new CSS4 documentation

38444485 0 Use std::bind to remove arguments

I'm currently coding against a library that uses an event system to signify user interface interactions. Each listener can either be a pointer to an object and a function to call, or a std::function. For example, the MenuItem object defines an OnClick event that will call a function that takes a MenuItem*:

someMenuItem->OnClick.addListener( this, &myObj.doSomeAction ); ... void myObj::doSomeAction( MenuItem* menuItem ) {} 

or

someMenuItem->OnClick.addListener( []( MenuItem* menuItem ) {} ); 

It's often the case that doSomeAction is part of the public API of the class that we might want to call for some reason other than the user selecting the menu item. Is it possible to use std::bind to throw away the MenuItem* argument so that doSomeAction( MenuItem* menuItem ) could be defined as simply doSomeAction()?

PS - I do realize that I could use lambdas to do the same thing, but if bind can do the same thing then it might be more stylistically pleasing to some.

23350686 0

Spring Social Facebook is a module within the Spring Social family of projects that enables you to connect your Spring application with the Facebook Graph API.

Features:

More Information:

Getting Started Guides:

Related Tags:

17179304 0

You invoke the nextToken() method 3 times. That will get you 3 different tokens

int pos = productsTokenizer .nextToken().indexOf("-"); String product = productsTokenizer .nextToken().substring(0, pos+1); String count= productsTokenizer .nextToken().substring(pos, pos+1); 

Instead you should do something like:

String token = productsTokenizer .nextToken(); int pos = token.indexOf("-"); String product = token.substring(...); String count= token.substring(...); 

I'll let you figure out the proper indexes for the substring() method.

Also instead of using a do/while structure it is better to just use a while loop:

while(productsTokenizer .hasMoreTokens()) { // add your code here } 

That is don't assume there is a token.

33224978 0 Is there a way to a prevent a String from being interpolated in Swift?

I'm experimenting around the idea of a simple logger that would look like this:

log(constant: String, _ variable: [String: AnyObject]? = nil) 

Which would be used like this:

log("Something happened", ["error": error]) 

However I want to prevent misuse of the constant/variable pattern like the following:

log("Something happened: \(error)") // `error` should be passed in the `variable` argument 

Is there a way to make sure that constant wasn't constructed with a string interpolation?

30851800 0

You can add directly the content string

http://jsfiddle.net/0m5axpxx/

var iframe = document.createElement('iframe'); var html = '<body><scr'+ 'ipt>alert(1)</s' + 'cript>Content</body>'; iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html); document.body.appendChild(iframe); 
10710677 0 Login in JSF 2.0 with Glassfish 3.1.2 and JAAS

I'm having problems when I try to login with JSF 2. I am getting the following message:

WEB9102: Web Login Failed: com.sun.enterprise.security.auth.login.common.LoginException: Login failed: Security Exception

This is my login page:

<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" template="./modeloLogin.xhtml" xmlns:p="http://primefaces.prime.com.tr/ui" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> <ui:define name="content"> <p:growl id="growl" showDetail="true" life="3000" /> <div id="formulario"> <p:panel id="pnl" header="Login"> <h:form> <h:panelGrid columns="2" cellpadding="5"> <h:outputLabel for="username" value="Usuário:" /> <p:inputText value="#{beanLogin.username}" id="username" required="true" label="username" /> <h:outputLabel for="password" value="Senha:" /> <p:password value="#{beanLogin.password}" feedback="false" minLength="" id="password" label="password" /> <p:commandButton id="loginButton" value="Efetuar Login" update=":growl" action="#{beanLogin.login()}" ajax="false"/> <p:commandLink value="Esqueceu a senha?" ></p:commandLink> </h:panelGrid> </h:form> </p:panel> </div> </ui:define> </ui:composition> 

And this is my BeanLogin:

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sonic.action.login; import java.security.Principal; import javax.ejb.Stateless; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.inject.Named; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; /** * * @author 081315620876 */ @ManagedBean @SessionScoped public class BeanLogin { private String username; private String password; public BeanLogin() { } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String login() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); System.out.println(context == null); System.out.println(request == null); try { request.login(this.username, this.password); if(request.isUserInRole("admin")) { return "/pages/protected/admin/index.xhtml?faces-redirect=true"; } else if(request.isUserInRole("professor")){ return "/pages/protected/professor/index.xhtml?faces-redirect=true"; } } catch (ServletException e) { context.addMessage(null, new FacesMessage("Login failed.")); return "error"; } return "login.xhtml"; } public void logout() { FacesContext context = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); try { request.logout(); } catch (ServletException e) { context.addMessage(null, new FacesMessage("Logout failed.")); } } } 

Thanks in advance for help :)

30001286 0

It is because the whitespace between the <li> elements is significant. If you remove all whitespace, the elements will be right next to each other. Either you just do this:

<li class="orange start"><a href="">Home</a></li><li class="orange center"><a href="">Forum</a></li> 

Or, if you want to keep the line breaks in code, which I usually think is a good thing, you can insert an HTML comment like this:

<li class="orange start"><a href="">Home</a></li><!-- --><li class="orange center"><a href="">Forum</a></li> 

It's a matter of taste, but I tend to favor the latter because I find it more readable.

1653217 0 How do I figure out the smtp_port for my localhost?

I am using a script that is sending out emails and I am receiving the following error:

Warning: mail() [function.mail]: Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in C:\wamp\bin\php\php5.3.0\PEAR\Mail\mail.php on line 125

How to i figure out the stmp_port for my localhost?

EDIT:

I am sorry. I don't have my own server on my computer and I don't think I want to set one up either. I didn't realiza that it what it takes. I do have a hosting provider though and would like to figure out how to use their smtp information to send my mail though if anyone knows how to do that.

According to the reply by Nathan Adams, I can use my hosting provider's smtp information. What exactly do I need to find out where do I put that information in my php.ini file?

35382289 1 Controlling pygame animation through text input

I need to create a fighting game that gives prompts and accepts input through text, such as a raw input and then performs the animation, while still have the characters animated, e.g. moving back and forth in a ready to fight stance. How would I go about this?

18016725 0 Update specific object in array

I have a DataTable and an array of objects that I loop through.

For each row in a data table, I search through my collection of objects with Linq, and if found, that object needs to be updated. But how do I refresh my collection without reloading it from the database?

Car[] mycars = Cars.RetrieveCars(); //This is my collection of objects //Iterate through Cars and find a match using (DataTable dt = data.ExecuteDataSet(@"SELECT * FROM aTable").Tables[0]) { foreach (DataRow dr in dt.Rows) //Iterate through Data Table { var found = (from item in mycars where item.colour == dr["colour"].ToString() && item.updated == false select item).First(); if (found == null) //Do something else { found.updated = true; Cars.SaveCar(found); //HERE: Now here I would like to refresh my collection (mycars) so that the LINQ searches on updated data. //Something like mycars[found].updated = true //But obviously mycars can only accept int, and preferably I do not want to reload from the database for performance reasons. } 

How else can I search and update a single item in the array?

5004015 0
<s:HGroup gap="0"> <s:Label text="234 cm" fontSize="14"/> <s:Label text="2" baselineShift="4" fontSize="10"/> </s:HGroup> 

The HGroup might not actually be needed, depending on context.

8711744 0
function displaymessage() { $("select").each(function() { this.selectedIndex = 0 }); } 

this selects the first option (not necessarily having value = 0)

16891837 0 Restrict a user to visit a particular page only certain number of times

How to restrict a user (role) to visit a particular page only certain number of times?

I am using drupal 6. It's for premium content, I just want to give 5 premium content free.

1545284 0

i found this problem earlier and the work around was to use the builder directly

def test = { def sw = new StringWriter() def b = new MarkupBuilder(sw) b.html(contentType: "text/html") { div(id: "myDiv") { p "somess text inside the div" b.form(action: 'get') { p "inside form" } } } render sw } 

will render the following HTML

<html contentType='text/html'> <div id='myDiv'> <p>somess text inside the div</p> <form action='get'> <p>inside form</p> </form> </div> </html> 
23445517 0 calculate expected cost of final product using atleast k out of n items in c

Suppose I have 4 items and i have to pick at least 1 item to make a product out of them. I have cost corresponding to each item as Item1 -> 4 , Item2 -> 7 , Item3 -> 2 , Item4 -> 5.I have to to find expected cost of the final product means an average of all possible combinations Item used like if I use only 1 item then cost may be 4 , 7 , 2 , 5 and if if i use 2 items the cost would be 4+7 , 4+2 , 4+5 , 7+2 , 7+5 , 2+5 and similarly all combinations for using three items and 4+2+7+5 for using four items.Adding those all combinations and dividng them with no. of combination gives me expected cost of the final product.So I want to find sum of all these combinations then how can I go for it??

I think recursion will be used for calculating these combination but unable to apply ???

36428352 0

To make it works, you can use padding-left instead of margin-left and also adapt the width of the td

See it here

.modules-table > tbody > tr > td:nth-child(2) { width:256px; padding-left:80px; } 
18184897 0

HTML5 solution, min 5, max 10 characters

http://jsfiddle.net/xhqsB/102/

<form> <input pattern=".{5,10}"> <input type="submit" value="Check"></input> </form> 
22970292 0

A problem I ran into was related to the ordering in Application_Start(). Note the order of Web API configuraton below:

This does NOT work

protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configure(WebApiConfig.Register); } 

This does work

protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } 
11785670 0 Closing generic handlers before logging and other functionalities

I am working on a high volumne API that needs to provide substantial logging for reporting purposes. In order to limit the effect of this logging functionality to the api users, I would like to finish the request, and then start logging all the stuff that needs to be logged.

Will flush, then close cause this to occur or will the client system wait until all the "Business Stuff " (BS for short) is complete?

28901933 0

Ok, i found a way to do that.

Basically i changed trigger() function to debugEmail(), and inside the class-wc-email-customer-invoice.php file, copied the trigger() into debugEmail() and removed the this line to avoid the send of the email:

$this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() ); 
12958793 0 onclick to clear form fields JavaScript

I hope this question isn't duplicating something in the archives; I've looked but can't find an answer that solves my problem because I seem to be following the advice given.

I am making a dynamic form with JavaScript and would like to clear the prompts in each field when a user clicks in it. Here is part of what I have for one of the form fields. I can't figure out why onlick="this.value=' '"; isn't working. Any help would be much appreciated.

 var VMake1 = document.createElement("input"); VMake1.name = "veh_1_make"; VMake1.type = "text"; VMake1.value= "Please enter the make of vehicle 1"; if (VMake1.value=="Please enter the make of vehicle 1") { onclick="this.value=''"; } placeVeh1Make.parentNode.insertBefore(VMake1,placeVeh1Make); 

Thank you in advance for your help.

34448066 0 Time the execution of batch file commands of VB scripts without using WScript.sleep

I have a batch file which starts telnet server and stops telnet server with sleep time in between.

Script:

set OBJECT=WScript.CreateObject("WScript.Shell") WScript.sleep 5000 OBJECT.SendKeys "net stop TlntSvr{ENTER}" WScript.sleep 30000 OBJECT.SendKeys "net start TlntSvr{ENTER}" WScript.sleep 30000 OBJECT.SendKeys "exit" 

Like you see the above code stops telnet services using net stop TlntSvr and then starts telnet services using net start TlntSvr with a sleep time in between like WScript.sleep 3000.

Issue: Now I need to run this batch file in multiple systems PCs/laptop and in each execution cases, the time taken to start/stop telnet services/telnet service installation varies and hence I had to modify the sleep time every time when I am running the script in different systems.

Question: Is there a way to time the next execution such that as soon as the first execution completes only then it will start the next execution? Meaning I don't need to configure the sleep time for each laptops/PCS, the next execution will start only when the first execution is over according to each PC's own execution behavior.

7460474 0

Look at this post. It seems that the problem may be in the mapping of IUser in NH

32997838 0 Number of times one string occurs within another in C

I have written a function that uses the strstr() function to determine if string2 has any matches in string1. This works fine (I also convert both strings to lower case so that I can do a case-insensitive match.). However, strstr() only finds the first time the match occurs. Is there a way to use it to find each time a match occurs? For example:

string1[] = "ABCDEFABC"; string2[] = "ABC"; 

Would return 0 as a match is found in position 0, and 6 as it's found again in position 6?

Here's the original function as written (including call to function in main):

#include <stdio.h> #include <string.h> #include <stdlib.h> char *strstrnc(const char *str1, const char *str2); int main() { char buf1[80],buf2[80]; printf("Enter the first string to be compared: "); gets(buf1); printf("Enter the second string to be compared: "); gets(buf2); strstrnc(buf1,buf2); return 0; } char *strstrnc(const char *buf1, const char *buf2) { char *p1, *ptr1, *p2, *ptr2, *loc; int ctr; ptr1 = malloc(80 * sizeof(char)); ptr2 = malloc(80 * sizeof(char)); p1 = ptr1; p2 = ptr2; for (ctr = 0; ctr < strlen(buf1);ctr++) { *p1++ = tolower(buf1[ctr]); } *p1 = '\0'; for (ctr = 0; ctr < strlen(buf2);ctr++) { *p2++ = tolower(buf2[ctr]); } *p2 = '\0'; printf("The new first string is %s.\n", ptr1); printf("The new first string is %s.\n", ptr2); loc = strstr(ptr1,ptr2); if (loc == NULL) { printf("No match was found!\n"); } else { printf("%s was found at position %ld.\n", ptr2, loc-ptr1); } return loc; } 
35177242 0

Try to checkout your branch to a different folder than your original work folder, git will not delete the existing folders (from the different folder structure) to this new one - so you would still have folders in Tests\x-test and Tests\y-test.

However, git clean -fd could be used to remove untracked directories.

28406619 0 Which languages are required to learn animation designing?

I want to design animations, short animated video clips but even after Googling a little I got no clue about it.

I want ways that include programming rather than mouse clicks.

24368496 0

You, of course, could do this. You should loop all existing htmlElement instances with current class

$(".sel_region").each(function(index, element) { element.prototype.yourFunction = function() { console.log("exists!"); }; }); 

You should call this loop on Dom load

19572181 0 CSS Generated Content allows us to insert and move content around a document. We can use this to create footnotes, endnotes, and section notes, as well as counters and strings, which can be used for running headers and footers, section numbering, and lists. 30758924 0
  1. Do I really need to use a mutex in a thread each time I access the data from the read-only array? If so could you explain why?

No. Because the data is never modified, there cannot be synchronization problem.

  1. Do I need to use a mutex in a thread when it writes to the result array even though this will be the only thread that ever writes to this element?

Depends.

  1. If any other thread is going to read the element, you need synchronization.
  2. If any thread may modify the size of the vector, you need synchronization.

In any case, take care of not writing into adjacent memory locations by different threads a lot. That could destroy the performance. See "false sharing". Considering, you probably don't have a lot of cores and therefore not a lot of threads and you say write is done only once, this is probably not going to be a significant problem though.

  1. Should I use atomic data types and will there be any significant time over head if I do?

If you use locks (mutex), atomic variables are not necessary (and they do have overhead). If you need no synchronization, atomic variables are not necessary. If you need synchronization, then atomic variables can be used to avoid locks in some cases. In which cases can you use atomics instead of locks... is more complicated and beyond the scope of this question I think.

Given the description of your situation in the comments, it seems that no synchronization is required at all and therefore no atomics nor locks.

  1. ...Would my array elements in this example be aligned, or is there some way to ensure they are?

As pointed out by Arvid, you can request specific alignment using the alginas keyword which was introduced in c++11. Pre c++11, you may resort to compiler specific extensions: https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Variable-Attributes.html

24873633 0

Here's one possible way of reading a file and getting just the "chunks":

import java.io.*; import java.util.Scanner; public class ScanXan { public static void main(String[] args) throws IOException { Scanner s = null; try { s = new Scanner(new BufferedReader(new FileReader("xanadu.txt"))); while (s.hasNext()) { System.out.println(s.next()); } } finally { if (s != null) { s.close(); } } } } 

You can take a look at the Java Scanner Tutorial for other ideas.

20391612 0

Note: its not a tested code. but it tries to solve your problem. Please give it a try

import csv with open(file_name, 'rb') as csvfile: marksReader = csv.reader(csvfile) for row in marksReader: if len(row) < 8: # 8 is the number of columns in your file. # row has some missing columns or empty continue # Unpack columns of row; you can also do like fname = row[0] and lname = row[1] and so on ... (fname,lname,subj1,marks1,subj2,marks2,subj3,marks3) = *row # you can use float in place of int if marks contains decimals totalMarks = int(marks1) + int(marks2) + int(marks3) print '%s %s scored: %s'%(fname, lname, totalMarks) print 'End.' 
15237073 0 D3.js: "Uncaught SyntaxError: Unexpected token ILLEGAL"?

I've just downloaded D3.js from d3js.org (link to zip file), unzipped it, and referenced it in the following HTML page:

<html> <head> <title>D3 Sandbox</title> <style> </head> <body> <script src="/d3.v3.js"></script> </body> </html> 

But when I load this page, my console (in Chrome) is giving me this error:

Uncaught SyntaxError: Unexpected token ILLEGAL: line 2 

It doesn't like the pi and e symbols at the start of the file. Errrr... what can I do about this? I am serving the file with python's SimpleHTTPServer.

Update: yes I know I can just link to a CDN version, but I would prefer to serve the file locally.

30795069 0

While you could use AntiSamy to do it, I don't know how sensible that would be. Kinda defeats the purpose of it's flexibility, I think. I'd be curious about the overhead, even if minimal, to running that as a filter over just a regex.

Personally I'd probably opt for the regex route in this scenario. Your example appears to only strip the brackets. Is that acceptable in your situation? (understandable if it was just an example) Perhaps use something like this:

reReplace(string, "<[^>]*>", "", "ALL"); 
1143722 0

Does the machine running IE 6 have its security settings set to reject cookies? Alternatively, if you are using one of the various techniques that supposedly allow you to run multiple versions of IE on the same machine, be aware that the results are not perfect, and often cause subtle aspects of the browser to break on one or more of the versions: for example, see this comment on Tredosoft's Multiple IE page about cookies failing in IE 6.

2218937 0 HAS-A, IS-A terminology in object oriented language

I was just reading through the book and it had the terms, "HAS-A" and "IS-A" in it. Anyone know what they mean specifically? Tried searching in the book, but the book is 600 pages long. Thanks!

24947366 0 Ruby on Rails: How to change the Foriegn Key values on a collection_select drop down?

I have a drop down on my form which is a foreign key to another table:

<div class="field"> <td><%= f.label "#{column_name}" %></td> <td><%= f.collection_select "#{column_name}", Table.all, :id, :message_id %></td> </div> 

"Table" has a column "message_id" which is a foreign_key to a different table "Messages".

The "Messages" table contains all the text/strings in my application.

When I load this code on my page it will give me a drop down list of all records but it will only show foreign key ID numbers pointing to the "Messages" table.

How can I change the foreign key ID numbers in the drop down to switch with message content I have on my Messages table?

28332602 0

The code you've shared seems very close. See below to output the first child <tr> of the table, if an <a> element is found, then stop looping through additional <a> elements. What specific problems are you having with your code?

foreach ($html->find('table') as $name) { foreach ($name->find('a') as $elem) { echo $name->find('tr', 0)->plaintext; // echo first TR element echo $elem->plaintext.'<br>'; // echo A element break 1; // skip to the next table } } 
1383277 0 Using preprocessor directives in BlackBerry JDE plugin for eclipse?

How to use preprocessor directives in BlackBerry JDE plugin for eclipse?

29945137 0 Should I add the sass source map to my git repo?

I had added style.css.map to my .gitignore file thinking that this was some kind of internal file that was not needed for public consumption.

Now I'm seeing that when Chrome (not Firefox) loads my page, it is looking for style.css.map and returning a 404. I'm not explicitly asking it to load that file, but it seems to be getting called automatically.

  1. Why is Chrome looking for that file?
  2. Should I have included the .map file to the repo?

For further context, this is a Wordpress site and I am including the style.scss file in the repo.

41069932 0

I had a similar request from a client. but instead of an "x" to close the pop up it was to make it fade after x number of seconds.

see the see this link: http://ausauraair.com.au/product/ausaura-air/

by adding some jQuery i was able to make the box fade.

jQuery(document).ready(function( $ ) { $('.woocommerce-message').fadeTo(7000,1).fadeOut(2000); }); 

you could possibly use a similar technique but add a "x" button and then an on-click function to make the box close on click.

5077413 0

Try this:

DateTime dt = DateTime.ParseExact(strDate, "MMM dd, yyyy", CultureInfo.InvariantCulture); 
5873725 0 12103872 0

The slaveOk property is now known as ReadPreference (.SECONDARY in this case) in newer Mongo Java driver versions. This can be set at the Mongo/DB/Collection level. Note that when you set ReadPreference at these levels, it applies for all callers (i.e. these objects are shared across threads).

Another approach is to try the ReadPreference.SECONDARY and if it fails, try without it and go to the master. This logic can be isolated to your repository layer, so the service layer doesn't have to deal with it. If you are doing this, you may want to set the ReadPreference at the DBQuery object, which is on a per-use basis.

38287434 0

If you run

getAnywhere("complete") 

where is the package providing that function located? Is that package loaded in your .Rmd file?

183197 0

Just like Perl,

loop1: for (var i in set1) { loop2: for (var j in set2) { loop3: for (var k in set3) { break loop2; // breaks out of loop3 and loop2 } } } 

as defined in EMCA-262 section 12.12. [MDN Docs]

Unlike C, these labels can only be used for continue and break, as Javascript does not have goto (without hacks like this).

36170192 0

You can find the extra braces by making use of stack as below:

public static void main(final String[] args) { Stack<String> stack = new Stack<String>(); File file = new File("InputFile"); int lineCount = 0; try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { lineCount++; for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == '{') { stack.push("{"); } else if (line.charAt(i) == '}') { if (!stack.isEmpty()) { stack.pop(); } else { System.out.println("Extra brace found at line number : " + lineCount); } } } } if (!stack.isEmpty()) { System.out.println(stack.size() + " braces are opend but not closed "); } } catch (Exception e) { e.printStackTrace(); } } 
38113933 0

Plivo Sales Engineer here.

Pavan is correct. You need to specify the Content-Type header as application/json for Parse to make a JSON string of the body:

 headers: { "Content-Type": "application/json" }, 

You also should console.log(httpResponse) (aka the Plivo API response) which will tell if you are doing something wrong (sending the wrong data, not authenticating correctly) or if you do something right. Either way it will show you an api_id which you can use to look in your Plivo account dashboard debug logs and figure out what need to be changed. You can also go directly to the debug logs for a specific api_id by making a url like this: https://manage.plivo.com/logs/debug/api/e58b26e5-3db5-11e6-a069-22000afa135b/ and replacing e58b26e5-3db5-11e6-a069-22000afa135b with the api_id returned by your Parse.Cloud.httpRequest

4187709 0

I've been using <div><jsp:text/></div>

11981535 0

It is very simple

Let me make you understand

first

public MyClass() { } 

is simply a default public constructor

But when you write this

public MyClass() { this(); } 

that means you are applying constructor chaining. Constructor Chaining is simply calling another constructor of the same class. This must be the first statement of the Constructor. But in your scenario you are passing nothing in this(); that means you are again calling the same constructor which will result in infinite loop. your class may have another constructor like this

public MyClass(int a) { } 

then you may have called this

public MyClass(){ this(10); } 

the above statement will make you to jump to the constructor receiving the same arguments that you have passed

Now,

public Myclass(){ super(); } 

signifies that you are calling the constructor of the super class which is inherited by the class MyClass. the same scenario occurs here, you have passed nothing in the super(); which will call the default constructor of the Super class.

38354587 0 IONIC2: Content Appearing Pushed To The Right

I am having a problem on my Ionic2 application when deployed to an android 4.2.2 device, all the content appears heavily padded to the right as shown in the image attachment.

enter image description here

Your help will be greatly appreciated.

3614420 0 I need an easy way to extract data from a few thousand emails (apple mail)

I have about 2000 emails from a web contest my company did. All the emails are arranged in the following fashion:

You have received a new contest submission. Here are the details: Name: Bob Jones Email: bobjones@internet.com Location: Springfield, MA Age: 83 Mailinglist: true 

All of these emails are saved in apple mail, is there any way I can extract this data into a text file, excel sheet, or something else more useable?

6153541 0

I found the problem/solution!

The problem is that in my Controller_Website I had this in my action_before():

// Create a new DM_Nav object to hold our page info // Make this page info available to all views as well $this->page_info = new DM_Nav; View::bind_global('page_info', $this->page_info); 

The problem is the bind_global – which is actually working as it's supposed to by letting you change the value of this variable after the fact... (A very neat feature indeed.)

The workaround/solution was to force the template to use only the original page_info by detecting if it was an initial/main request. So at the very end of the action_before() method of Controller_Website where it says:

// Only if auto_render is still TRUE (Default) if ($this->auto_render === TRUE AND $this->request->is_initial()) { 

I added this line to the end of that if statement:

 $this->template->page_info = $this->page_info; } 

This line is redundant on initial/main requests, but it means that any additional sub-requests can still have access to their own page_info values without affecting the values used in the template. It appears, then, that if you assign a property to a view and then attempt to bind_global() the same property with new values, it doesn't overwrite it and uses the original values instead... (Which is why this solution works.) Interesting.

40495193 0 Passing Datomic console options via file

Someone noticed that on one of our Datomic transactor boxes, our process running the Datomic console is exposing database credentials.

Here is what our we get back when running ps aux | grep datomic (linebreaks added for readability):

[ian@testtransactor ~]$ ps aux | grep datomic datomic 18372 0.8 55.7 6898068 4495820 ? Sl Nov01 31:20 java -server -cp lib/*:datomic-transactor-pro-0.9.5394.jar:samples/clj:bin:resources -Xmx4g -Xms4g -Ddatomic.printConnectionInfo=false -Doracle.net.tns_admin=/usr/lib/oracle/11.2/client64/network/admin -Dgraphite.host=graphite -Dgraphite.port=2003 -Dgraphite.prefix=datomic.testransactor clojure.main --main datomic.launcher /opt/datomic-pro-0.9.5394/config/transactor.properties root 18821 0.2 10.2 3503992 826664 ? Sl May20 504:04 java -server -Xmx1g -Doracle.net.tns_admin=/usr/lib/oracle/11.2/client64/network/admin -cp lib/console/*:lib/*:datomic-transactor-pro-0.9.5327.jar:samples/clj:bin:resources clojure.main -i bin/bridge.clj --main datomic.console -p 3035 dev datomic:sql://?jdbc:oracle:thin:USERNAME/PASSWORD@DB_SID 

Our security team would prefer that the password be passed to the console process via a properties file, like we do with the transactor. Unfortunately, just mirroring it with clojure.main -i bin/bridge.clj --main datomic.console /opt/datomic-pro-0.9.5394/config/console.properties doesn't work. Does anyone have suggestions on how to set this up?

22144512 0

There are some different matters in your question. First of all:

1: I don't really understand what you do in your query, but the limit clause must be at the end of a query, so you could try

select * from A join B on A.id = B.id limit 10 

And this should work. More info on:

https://dev.mysql.com/doc/refman/5.0/en/select.html

2: Join vs. IN clause: the IN clause should always perform worse than the join. Imagine something like:

select * from A where A.id in (select id from B) 

This will do a full scan on B table (select id from B subquery) and then another full scan on A to try match the results.

However,

select * from A join B on A.id = B.id 

should do a hash join between both tables, and if you have planned it right, id will be an index column, so it should be quite faster (and do no full scans on neither of them)

13245470 1 Python: What is zip doing in this list comprehension

I am trying to understand this:

a = "hello" b = "world" [chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)] 

I understand the XOR part but I don't get what zip is doing.

3673509 0

Some CSS :

table td, table td * { vertical-align: top; } 
26091260 0

you have to add pull-left to the h1 too.. to have both of them floated..

also add a .cleafix class to the page-header div

<div class="container"> <div class="page-header clearfix"> <h1 class="pull-left"> <img src="logo.png"> Page title </h1> <div class="panel panel-primary pull-right"> ...content... </div> </div> ... </div> 
2233408 0

The "redundant include guard", as you call it, speeds up compilation.

Without the redundant guard, the compiler will iterate the entire foo.h file, looking for some code that might be outside the #ifndef block. If it's a long file, and this is done many places, the compiler might waste a lot of time. But with the redundant guard, it can skip the entire #include statement and not even reopen that file.

Of course, you'd have to experiment and see the actual amount of time wasted by the compiler iterating through foo.h and not actually compiling anything; and perhaps modern compilers actually look for this pattern and automatically know not to bother opening the file at all, I don't know.

(Begin edit by 280Z28)

The following header structure is recognized by at least GCC and MSVC. Using this pattern negates virtually all benefits you could gain with guards in the including files. Note that comments are ignored when the compiler examines the structure.

// GCC will recognize this structure and not reopen the file #ifndef SOMEHEADER_H_INCLUDED #define SOMEHEADER_H_INCLUDED // Visual C++ uses #pragma once to mark headers that shouldn't be reopened #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif // header text goes here. #endif 

(End edit)

5668801 0 Entity framework code-first null foreign key

I have a User < Country model. A user belongs to a country, but may not belong to any (null foreign key).

How do I set this up? When I try to insert a user with a null country, it tells me that it cannot be null.

The model is as follows:

 public class User{ public int CountryId { get; set; } public Country Country { get; set; } } public class Country{ public List<User> Users {get; set;} public int CountryId {get; set;} } 

Error: A foreign key value cannot be inserted because a corresponding primary key value does not exist. [ Foreign key constraint name = Country_Users ]"}

33369903 0

What version of Opentaps are you running ? did you clone from the master git repository ?

are you trying to compile the code in the ide? I suggest you run ./ant inside the project and don't use the ide to compile

4619893 0 Form submission in rails 3

I decided to start a little project in rails 3 and I am a little bit stuck on a form... Where can I specified the f.submit action should go to a special controller / action ?

The code in the form is:

<%= form_for @user, :url => { :action => "login" } do |f| %> <div class="field"> <%= f.text_field :email %><br /> <%= f.text_field :password %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> 

User is defined as @user = User.new in "index" method of "home_controller".

but I have the error:

No route matches {:controller=>"home", :action=>"login"} 

as soon as I run http://0.0.0.0:3000

I am very sorry for this newbee question but I cannot find the routing details (I worked a little bit with rails a couple of years ago but...)

Thanks, Luc

26211646 0 Include Bootstrap form css alone

I have site created already which is not bootstrap, and now i need to implement the bootstrapValidator for the validation purpose, if i include bootstrap css then my site style also changing,

Is there any way to include bootstrap form styles alone in html, apart from cut copy in bootstrap css file?

24274017 0

This is the solution, I didn't change anything in the original code and script:

<div id="content"> <div id="tab1">@{ Html.RenderAction("TabbedIndex", "Stuff", new { claimed = false }); }</div> <div id="tab2">@{ Html.RenderAction("TabbedIndex", "Stuff", new { claimed = true }); }</div> </div> 
5255938 0

as someone who spent time looking for such a solution for my company's product--I can tell you that you are not going to find one. It does not exist. Sorry, dude. :(

38048090 0

It's a bug in iex. I've tracked down and fixed it: https://github.com/elixir-lang/elixir/pull/4895

34014365 0 Mybatis how to dynamic create table sql in xml

Before,I use

<select id="queryUser" parameterType="userInfo"> select * from uc_login_${tableSuffix} </select> userInfo:{ private String tableSuffix; } 

and I create userInfo with tableSuffix like

new DateTime().getYear() + "_" + new DateTime().getMonthOfYear(); 

and now I select from uc_login_nowYear_nowMonth(uc_login_2015_12). Now,I don't want create tabkeSuffix by myself,I want Mybatis help me to dynamic create sql in xml. How can I do that?

5092644 0

In the end I canned the joined DataTable idea and just read the data straight into a List of my objects with a DataReader. So this whole question is now pretty redundant for me. Hopefully someone else will find it useful.

12711873 0 Excel VBA Dynamic Ranges/Index selections

I'm trying to create a talent calculator for myself, and the entire first sheet calls to a Data sheet that does all the background work. On the excel sheet itself, everything calls to INDEX(TableName,Row,Column) because it's much easy to keep track of and I find I often have to move data around while working on it so handling Names is easier than handling cell references.

However, I also use VBA on this sheet, and I'm rather new to it. Instead of, for example, using Range("C1"), if C1 was part of table TableOne, would there be a way to reference it like in the Excel formulas such as INDEX(TableOne,1)?

26522897 0

Usually using lxml and xpath is a common approach in Python.

As you want to use minidom explicitly, you can use the following method to get all HTML elements of a particular tag.

matches = dom.getElementsByTagName("foo") for e in matches: print(e.firstChild.nodeValue) 
840421 0

You can check if its a digit:

char c; scanf( "%c", &c ); if( isdigit(c) ) printf( "You entered the digit %c\n", c ); 
11020766 0

I really liked Phaxmohdem solution, so I added a bit more to it. I hope others continue to improve this. =)

<NotepadPlus> <UserLang name="X12" ext=""> <Settings> <Global caseIgnored="no" /> <TreatAsSymbol comment="no" commentLine="no" /> <Prefix words1="no" words2="no" words3="no" words4="no" /> </Settings> <KeywordLists> <Keywords name="Delimiters">000000</Keywords> <Keywords name="Folder+"></Keywords> <Keywords name="Folder-"></Keywords> <Keywords name="Operators">* : ^ ~ +</Keywords> <Keywords name="Comment"></Keywords> <Keywords name="Words1">ISA IEA GS GE ST SE</Keywords> <Keywords name="Words2">AAA ACT ADX AK1 AK2 AK3 AK4 AK5 AK6 AK7 AK8 AK9 AMT AT1 AT2 AT3 AT4 AT5 AT6 AT7 AT8 AT9 AT8 AT9 B2 B2A BEG BGN BHT BPR CAS CL1 CLM CLP CN1 COB CR1 CR2 CL3 CL4 CR5 CR6 CRC CTX CUR DMG DN1 DN2 DSB DTM DTP EB EC ENT EQ FRM G61 G62 HCP HCR HD HI HL HLH HSD ICM IDC III IK3 IK4 IK5 INS IT1 K1 K2 K3 L3 L11 LIN LQ LUI LX MEA MIA MOA MPI MSG N1 N2 N3 N4 NM1 NTE NX OI PAT PER PLA PLB PO1 PRV PS1 PWK QTY RDM REF RMR S5 SAC SBR SLN STC SV1 SV2 SV3 SV4 SV5 SVC SVD TA1 TOO TRN TS2 TS3 UM</Keywords> <Keywords name="Words3">LS LE</Keywords> <Keywords name="Words4">00 000 0007 001 0010 0019 002 0022 003 004 00401 004010 004010X061 004010X061A1 004010X091 004010X091A1 004010X092 004010X092A1 004010X093 004010X093A1 004010X094 004010X094A1 004010X095 004010X095A1 004010X096 004010X096A1 004010X098 004010X098A1 005 00501 005010 005010X212 005010X217 005010X218 005010X220 005010X220A1 005010X221 005010X221A1 005010X222 005010X222A1 005010X223 005010X223A1 005010X223A2 005010X224 005010X224A1 005010X224A2 005010X230 005010X231 005010X279 005010X279A1 006 007 0078 008 009 01 010 011 012 013 014 015 016 017 018 019 02 020 021 022 023 024 025 026 027 028 029 03 030 031 032 035 036 04 05 050 06 07 08 09 090 091 096 097 0B 0F 0K 102 119 139 150 151 152 18 193 194 196 198 1A 1B 1C 1D 1E 1G 1H 1I 1J 1K 1L 1O 1P 1Q 1R 1S 1T 1U 1V 1W 1X 1Y 1Z 200 232 233 270 271 276 277 278 286 290 291 292 295 296 297 2A 2B 2C 2D 2E 2F 2I 2J 2K 2L 2P 2Q 2S 2U 2Z 30 300 301 303 304 307 31 314 318 330 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 356 357 36 360 361 374 382 383 385 386 388 393 394 3A 3C 3D 3E 3F 3G 3H 3I 3J 3K 3L 3M 3N 3O 3P 3Q 3R 3S 3T 3U 3V 3W 3X 3Y 3Z 40 405 41 417 431 434 435 438 439 441 442 444 446 45 452 453 454 455 456 458 46 461 463 471 472 473 474 480 481 484 492 4A 4B 4C 4D 4E 4F 4G 4H 4I 4J 4K 4L 4M 4N 4O 4P 4Q 4R 4S 4U 4V 4W 4X 4Y 4Z 539 540 543 573 580 581 582 598 5A 5B 5C 5D 5E 5F 5G 5H 5I 5J 5K 5L 5M 5N 5O 5P 5Q 5R 5S 5T 5U 5V 5W 5X 5Y 5Z 607 636 695 6A 6B 6C 6D 6E 6F 6G 6H 6I 6J 6K 6L 6M 6N 6O 6P 6Q 6R 6S 6U 6V 6W 6X 6Y 70 71 72 738 739 74 77 771 7C 82 820 831 834 835 837 85 850 866 87 8H 8U 8W 938 997 999 9A 9B 9C 9D 9E 9F 9H 9J 9K 9V 9X A0 A1 A172 A2 A3 A4 A5 A6 A7 A8 A9 AA AAE AAG AAH AAJ AB ABB ABC ABF ABJ ABK ABN AC ACH AD ADD ADM AE AF AG AH AI AJ AK AL ALC ALG ALS AM AN AO AP APC APR AQ AR AS AT AU AV AX AY AZ B1 B2 B3 B4 B6 B680 B7 B9 BA BB BBQ BBR BC BD BE BF BG BH BI BJ BK BL BLT BM BN BO BOP BP BPD BQ BR BS BT BTD BU BV BW BX BY BZ C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CAD CB CC CCP CD CE CER CF CG CH CHD CHK CI CJ CK CL CLI CLM01 CM CN CNJ CO CON CP CQ CR CS CT CV CW CX CY CZ D2 D3 D8 D9 D940 DA DB DCP DD DEN DEP DG DGN DH DI DJ DK DM DME DN DO DP DQ DR DS DT DX DY E1 E1D E2 E2D E3 E3D E5D E6D E7 E7D E8 E8D E9 E9D EA EAF EBA ECH ED EI EJ EL EM EMP EN ENT01 EO EP EPO ER ES ESP ET EV EW EX EXS EY F1 F2 F3 F4 F5 F6 F8 FA FAC FAM FB FC FD FE FF FH FI FJ FK FL FM FO FS FT FWT FX FY G0 G1 G2 G3 G4 G5 G740 G8 G9 GB GD GF GH GI GJ GK GM GN GO GP GR GW GT GY H1 H6 HC HE HF HH HJ HLT HM HMO HN HO HP HPI HR HS HT I10 I11 I12 I13 I3 I4 I5 I6 I7 I8 I9 IA IAT IC ID IE IF IG IH II IJ IK IL IN IND IP IR IS IV J1 J3 J6 JD JP KG KH KW L1 L2 L3 L4 L5 L6 LA LB LC LD LI LM LOI LR LT LU LTC LTD M1 M2 M3 M4 M5 M6 M7 M8 MA MB MC MD ME MED MH MI MJ ML MM MN MO MOD MP MR MRC MS MSC MT N5 N6 N7 N8 NA ND NE NF NH NI NM109 NL NN NON NQ NR NS NT NTR NU OA OB OC OD ODT OE OF OG OL ON OP OR OT OU OX OZ P0 P1 P2 P3 P4 P5 P6 P7 PA PB PC PD PDG PE PI PID PL PN PO POS PP PPO PQ PR PRA PRP PS PT PU PV PW PXC PY PZ Q4 QA QB QC QD QE QH QK QL QM QN QO QQ QR QS QV QY R1 R2 R3 R4 RA RB RC RD8 RE REC RET RF RGA RHB RLH RM RN RNH RP RR RT RU RW RX S1 S2 S3 S4 S5 S6 S7 S8 S9 SA SB SC SD SEP SET SFM SG SJ SK SL SP SPC SPO SPT SS STD SU SV SWT SX SY SZ T1 T10 T11 T12 T2 T3 T4 T5 T6 T7 T8 T9 TC TD TE TF TJ TL TM TN TNJ TO TPO TQ TR TRN02 TS TT TTP TU TV TWO TZ UC UH UI UK UN UP UPI UR UT V1 V5 VA VER VIS VN VO VS VV VY W1 WA WC WK WO WP WR WU WW X12 X3 X4 X5 X9 XM XN XP XT XV XX XX1 XX2 XZ Y2 Y4 YR YT YY Z6 ZB ZH ZK ZL ZM ZN ZO ZV ZX ZZ</Keywords> </KeywordLists> <Styles> <WordsStyle name="DEFAULT" styleID="11" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="FOLDEROPEN" styleID="12" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="FOLDERCLOSE" styleID="13" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="KEYWORD1" styleID="5" fgColor="0000FF" bgColor="FFFFFF" fontName="" fontStyle="1" /> <WordsStyle name="KEYWORD2" styleID="6" fgColor="800000" bgColor="FFFFFF" fontName="" fontStyle="1" /> <WordsStyle name="KEYWORD3" styleID="7" fgColor="00FF00" bgColor="FFFFFF" fontName="" fontStyle="1" /> <WordsStyle name="KEYWORD4" styleID="8" fgColor="8000FF" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="COMMENT" styleID="1" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="COMMENT LINE" styleID="2" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="NUMBER" styleID="4" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="OPERATOR" styleID="10" fgColor="FF00FF" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="DELIMINER1" styleID="14" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="DELIMINER2" styleID="15" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> <WordsStyle name="DELIMINER3" styleID="16" fgColor="000000" bgColor="FFFFFF" fontName="" fontStyle="0" /> </Styles> </UserLang> </NotepadPlus> 
971828 0

There is also garbage collection to consider - if you are using new() a lot, then that will create lots of objects on the heap that will have to be garbage collected, but Clear() won't create any new heap objects (although this is only really an issue if you're doing this thousands of times)

13026080 0

If you want to AUTOMATICALLY redirect from www.google.com to www.google.com#something you can use firefox's redirector addon.
Whenever you load www.google.com, the addon will automatically change the URL in the location bar to www.google.com#something (or whatever you specify.)

Alternately, you could use firefox addon, called greasemonkey, to write the 1 line script given by Jacob. That will also serve the purpose.

Off course, both these solutions are specific to firefox.

31940324 0 vb.net to pull data from Excel Data GridView

I have 78 excel columns and I have 5 datagridviews.

How do I make connection?

18114495 0 Imagemagick position and size of a sub-image

Problem description:

In imagemagick, it is very easy to diff two images using compare, which produces an image with the same size as the two images being diff'd, with the diff data. I would like to use the diff data and crop that part from the original image, while maintaining the image size by filling the rest of the space with alpha.

The approach I am taking:

I am now trying to figure the bounding box of the diff, without luck. For example, below is the script I am using to produce the diff image, see below. Now, I need to find the bounding box of the red color part of the image. The bounding box is demonstrated below, too. Note that the numbers in the image are arbitrary and not the actual values I am seeking.

compare -density 300 -metric AE -fuzz 10% ${image} ${otherImage} -compose src ${OUTPUT_DIR}/diff${i}-${j}.png 

enter image description here enter image description here

37239427 0 Delete Method's return value in Excel VBA

According to Microsoft Developer Network, both Range.Delete and Worksheet.Delete method will return a value. However, by using the MsgBox function I can only view the return value for the Worksheet.Delete method but have no luck with the Range.Delete method. The code I used is MsgBox Worksheets("Sheet1").Delete

Here are the two articles from MSDN for your information: https://msdn.microsoft.com/en-us/library/office/ff837404.aspx https://msdn.microsoft.com/en-us/library/office/ff834641.aspx

9514715 0

It might be possible, try setting the window background color to clear, as well as the view controller's view background color.

I say it might be possible because I've seen my home screen while using some apps, for example, the Facebook app sometimes shows it during a transition (it might be a bug on either Facebook or the OS).

Anyway, I'm pretty sure that kind of app would be rejected from the App Store, so be advised.

21366036 0 Correctly serializing objects in java

can anyone help me to spot the mistake? I am trying to pass certain information (min/max/avg ages) from file people.txt (which consists of 200 lines like 'Christel ; MacKay ; 4"2' ; 38'), to another file, by serializing. Here's the first class, where I process some info about these people:

import java.io.Serializable; @SuppressWarnings("serial") public class Person implements Serializable { private String firstname; private String lastname; private int age; public Person (String PersonFN, String PersonLN, int PersonA) { firstname = PersonFN; lastname = PersonLN; age = PersonA; } public String toString() { return "Name: "+firstname+" "+lastname+" Age: "+age; } public int getAge() { return age; } } 

And another one, which does all the job:

import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.*; public class Collection { int min; int max; int total; private static ArrayList<Person> people; public Collection() { people = new ArrayList<Person>(); min = 100; max = 1; total = 0; } BufferedReader fr = null; BufferedWriter fw = null; public void readFromFile() throws IOException { fr = new BufferedReader (new FileReader("people.txt")); String line = null; StringTokenizer st; while (fr.ready()) { line = fr.readLine(); st = new StringTokenizer(line); String name = st.nextToken(";"); String surname = st.nextToken(";").toUpperCase(); String height = st.nextToken(";"); int age = Integer.parseInt(st.nextToken(";").trim()); Person p = new Person (name, surname, age); p.toString(); people.add(p); //for the 2nd part if(age < min) min = age; if (age > max) max = age; total = total + age; } } public int minAge() { int minA = 100; for (int i = 0; i < people.size(); i++) { Person p = people.get(i); int age = p.getAge(); if (age < minA) { minA = age; } } System.out.print(minA+"; "); return minA; } public int maxAge() { int maxA = 1; for (int i = 0; i < people.size(); i++) { Person p = people.get(i); int age = p.getAge(); if (age > maxA) { maxA = age; } } System.out.print(maxA+"; "); return maxA; } public float avgAge() { int sum = 0; for (int i = 0; i < people.size(); i++) { Person p = people.get(i); int age = p.getAge(); sum = sum + age; } float avgA = sum / people.size(); System.out.print(avgA); return avgA; } public int fastMinAge() { //System.out.print("Minimum age: " + min); return min; } public int fastMaxAge() { return max; } public float fastAvgAge() { return total / people.size(); } public void writeToFile(String filename) throws IOException { StringBuffer val = new StringBuffer ("Minimum age: "); val.append(fastMinAge()); val.append("\n Maximum age: "); val.append(fastMaxAge()); val.append("\n Average age: "); val.append(fastAvgAge()); BufferedWriter out = new BufferedWriter(new FileWriter(filename)); String outText = val.toString(); out.write(outText); out.close(); } public static void main(String[] args) throws IOException, ClassNotFoundException { Collection c = new Collection(); c.readFromFile(); for(Person d: people) { System.out.println(d); } c.minAge(); c.maxAge(); c.avgAge(); c.fastMinAge(); c.fastMaxAge(); c.fastAvgAge(); c.writeToFile("RESULTS.txt"); String filename = "people.txt"; //FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename)); os.writeObject(c); os.close(); String filename1 = "results1.txt"; FileInputStream fis = new FileInputStream(filename1); ObjectInputStream ois = new ObjectInputStream(fis); Collection p = (Collection) ois.readObject(); ois.close(); } } 

When I run the code, it creates the RESULTS.txt file and adds the correct information there. I'm sure there's something wrong with this exact part of code:

 String filename = "people.txt"; //FileOutputStream fos = new FileOutputStream(filename); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(filename)); os.writeObject(c); os.close(); String filename1 = "results1.txt"; FileInputStream fis = new FileInputStream(filename1); ObjectInputStream ois = new ObjectInputStream(fis); Collection p = (Collection) ois.readObject(); ois.close(); 

By the way, my people.txt file changes into "¬ķ {sr java.io.NotSerializableException(Vx ē†5 xr java.io.ObjectStreamExceptiondĆäk¨9ūß xr java.io.IOExceptionl€sde%š« xr java.lang.ExceptionŠż>;Ä xr java.lang.ThrowableÕĘ5'9wøĖ L causet Ljava/lang/Throwable;L detailMessaget Ljava/lang/String;[ stackTracet [Ljava/lang/StackTraceElement;L suppressedExceptionst Ljava/util/List;xpq ~ t SD3lab1.Collectionur [Ljava.lang.StackTraceElement;F*<<ż"9 xp sr java.lang.StackTraceElementa Å&6Ż… I lineNumberL declaringClassq ~ L fileNameq ~ L methodNameq ~ xp˙˙˙˙t java.io.ObjectOutputStreampt writeObject0sq ~ ˙˙˙˙q ~ pt writeObjectsq ~ ©q ~ t Collection.javat mainsr &java.util.Collections$UnmodifiableListü%1µģˇ L listq ~ xr ,java.util.Collections$UnmodifiableCollectionB €Ė^÷ L ct Ljava/util/Collection;xpsr java.util.ArrayListxŅ™Ēa¯ I sizexp w xq ~ x", and I get these errors on the console:

Exception in thread "main" java.io.NotSerializableException: SD3lab1.Collection at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at SD3lab1.Collection.main(Collection.java:169) 

MANY THANKS FOR ANY HELP

5724765 0

You can check for the license for the first time, then cache it. The next time when your app runs, read the license from the cache, and also start a Thread that gets the license from your server. If the license that you got from the server is now invalid. You can pop up a dialog box to tell the user that the license is invalid, remove the cached license, and quit the app.

38156646 0 Using @RequestParam for multipartfile is a right way?

I'm developing a spring mvc application and I want to handle multipart request in my controller. In the request I'm passing MultiPartFile also, currently I'm using @RequestParam to get the file paramaeter, the method look like,

@RequestMapping(method = RequestMethod.POST) public def save( @ModelAttribute @Valid Product product, @RequestParam(value = "image", required = false) MultipartFile file) { ..... } 

Above code works well in my service and the file is getting on the server side. Now somewhere I seen that in case of file need to use @RequestPart annotation instead of @RequestParam. Is there anything wrong to use @RequestParam for file ? Or it may cause any kind of error in future?

4225379 0

You can do like this (note that I have moved some of your generic parameters and constraints around).

public class MyType { public void doStuff(int i){} } public abstract class ABase<T>where T : class, new() { public abstract T method(int arg); } public class AChild : ABase<MyType> { override public MyType method(int arg) { MyType e = new MyType(); e.doStuff(arg); // no more error here return e; } } 
2579588 0 Incorrect emacs indentation in a C++ class with DLL export specification

I often write classes with a DLL export/import specification, but this seems to confuse emacs' syntax parser. I end up with something like:

class myDllSpec Foo { public: Foo( void ); }; 

Notice that the "public:" access spec is indented incorrectly, as well as everything that follows it.

When I ask emacs to describe the syntax at the beginning of the line containing public, I get a return of:

((label 352)) 

If I remove the myDllSpec, the indentation is correct, and emacs tells me that the syntax there is:

((inclass 352) (access-label 352)) 

Which seems correct and reasonable. So I conclude that the syntax parser is not able to handle the DLL export spec, and that this is what's causing my indentation trouble.

Unfortunately, I don't know how to teach the parser about my labels. Seems that this is pretty common practice, so I'm hoping there's a way around it.

23893046 0 How to add timestamp to the existing mysql table

I am updatng my application from standard php into laravel and i am creating two new field in each of my table which is created_at and updated_at.

The problem is both field has being set as null for the existing data. How to make a query to set the created_at and updated_at to the current date time??

32405642 0

I need to see the full query, but at a guess it is going to be:

LEFT JOIN adcfvc ON adcfvc.advert_id = $table.id 

Where $table is the tablename of the first table.

34273628 0

You have to tell the server that your body is in a JSON format by adding the right request header:

... request.HTTPBody = [newNewString dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPMethod = @"POST"; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; ... 
5625589 0 Javac erroring out when compiling Servlet libraries

I am using ubuntu and I have set my paths to be the following:

JAVA_HOME=/usr/local/jdk1.6.0_24 export CLASSPATH=/usr/local/tomcat/lib export JAVA_HOME 

I thought that would put the servlet libraries in the compile path, but I am still getting compile errors like this:

package javax.servlet does not exist [javac] import javax.servlet.ServletException; 

Any ideas how to fix this or what I am doing wrong? The general Java libraries seem to be working fine.

6356792 0

I thought I'd answer this one since it has a few votes, although based on Christina's other questions I don't think this will be a usable answer for her since a 50,000-word language model almost certainly won't have an acceptable word error rate or recognition speed (or most likely even function for long) with in-app recognition systems for iOS that use this format of language model currently, due to hardware constraints. I figured it was worth documenting it because I think it may be helpful to others who are using a platform where keeping a vocabulary this size in memory is more of a viable thing, and maybe it will be a possibility for future device models as well.

There is no web-based tool I'm aware of like the Sphinx Knowledge Base Tool that will munge a 50,000-word plaintext corpus and return an ARPA language model. But, you can obtain an already-complete 64,000-word DMP language model (which can be used with Sphinx at the command line or in other platform implementations in the same way as an ARPA .lm file) with the following steps:

  1. Download this language model from the CMU speech site:

http://sourceforge.net/projects/cmusphinx/files/Acoustic%20and%20Language%20Models/US%20English%20HUB4%20Language%20Model/HUB4_trigram_lm.zip

In that folder is a file called language_model.arpaformat.DMP which will be your language model.

  1. Download this file from the CMU speech site, which will become your pronunciation dictionary:

https://cmusphinx.svn.sourceforge.net/svnroot/cmusphinx/trunk/pocketsphinx/model/lm/en_US/cmu07a.dic

Convert the contents of cmu07a.dic to all uppercase letters.

If you want, you could also trim down the pronunciation dictionary by removing any words from it which aren't found in the corpus language_model.vocabulary (this would be a regex problem). These files are intended for use with one of the Sphinx English-language acoustic models.

If the desire to use a 50,000-word English language model is driven by the idea of doing some kind of generalized large vocabulary speech recognition and not by the need to use a very specific 50,000 words (for instance, something specialized like a medical dictionary or 50,000-entry contact list), this approach should give those results if the hardware can handle it. There are probably going to be some Sphinx or Pocketsphinx settings that will need to be changed which will optimize searches through this size of model.

34835581 0 Buy Google search result data?

Wanted to use GoogleAPI to search the Internet and return the results in JSON.
Google API allows this to search within a specific website, but I could not find this to the entire web. Is this possible? Thanks

32230557 0 Create new row based on column value SQL Server

I have data like this

DECLARE @Employee TABLE (EmployeeName NVARCHAR(50), EmployeeAddress NVARCHAR(50), WorkedLocations NVARCHAR(50), IdNumbers NVARCHAR(50), UpdatedOn Date ) Insert into @Employee Values ('Alex',' Alex address','Cisco','12345',GETDATE()), ('John','John Address','Microsoft','23456',GETDATE()), ('Bob','Bob Address','CiscoMicrosoft','78903,89067',GETDATE()), ('Bill','Bill Address','Microsoft','54652',GETDATE()) select * from @Employee 

In 3rd row based on the 3rd column value a row has to be created and 4th row value should be split and assigned to respective 3rd column. Please see below required output

DECLARE @Employee TABLE ( EmployeeName NVARCHAR(50) , EmployeeAddress NVARCHAR(50) , WorkedLocations NVARCHAR(50) , IdNumbers NVARCHAR(50) ,UpdatedOn Date) Insert into @Employee Values ('Alex',' Alex address','Cisco','12345',GETDATE()), ('John','John Address','Microsoft','23456',GETDATE()), ('Bob','Bob Address','Cisco','78903',GETDATE()), ('Bob','Bob Address','Microsoft','89067',GETDATE()), ('Bill','Bill Address','Microsoft','54652',GETDATE()) select * from @Employee 

Thanks in advance!

31613403 0

I was seing this same issue today, and I didn't have any code changes. Twitter just suddenly stopped authorizing and told me it couldn't get request token.

I just had to restart my emulator and it started working again.

35776087 0

You need to modify web.xml to use the special role ** as indicated here: Authorization section for Jetty Authentication:

access granted to any user who is authenticated, regardless of roles. This is indicated by the special value of "**" for the <role-name> of a <auth-constraint> in the <security-constraint>

So, this is what my security-constraint looks like:

<security-constraint> <web-resource-collection> <web-resource-name>Secured Solr Admin User Interface</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>**</role-name> </auth-constraint> </security-constraint> 
21756702 0 WCF service Endpoint X509 certificate Identity

I have service on one machine which I would like to access from another machine. So I need a help with setting the identity of the endpoints because i am getting

The identity check failed for the outgoing message. The expected identity is 'identity(http://schemas.xmlsoap.org/ws/2005/05/identity/right/possessproperty:http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint)' (http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint%29%27) for the 'net.tcp:...' target endpoint. 

My service is configured to use certificate for transport security and validation mode is set to ChainTrust.

What type of identity should I set on the client of this service since I am accessing the service using the ip address of the machine hosting it and not the dns name? More precisely what EndpointIdentity setting should I set to the EndpointAddress when I am setting the service host and what should I use on the client when I am setting the EndpointAddress?

On both client and the service machine the issuer of the certificates used to secure the transport is in the trusted authorities.

23987241 0 I'm trying to sort an NSMutableArray of objects by a field of type double

the code I'm currently trying doesn't give any errors but after it runs nothing is sorted. This is my first time in objective-c so I'm hoping there's something obvious here that I'm missing.

NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distanceOfPlace" ascending:true] ; [surroundingRestaurants sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 
10165928 0

Yes, set the proxy_max_temp_file_size to zero, or some other reasonably small value. Another option (which might be a better choice) is to set the proxy_temp_path to faster storage so that nginx can do a slightly better job of insulating the application from buggy or malicious hosts.

14460134 0

One way is to wait until the infinite loop shows up, then use jstack -l <pid> to get a stack dump, and analyze that.

With a modicum of luck, this should suggest some lines of further inquiry.

28945990 0 MVC 4: Create HTML textboxes dynamically with JQUERY and PartialViewResult. How to fill the model if the code is added dynamically?

I am creating form input fields with JQUERY like

$('#students').live('change', function () { var value = $(this).val(); if (value) { $.ajax({ type: "GET", timeout: 10000, url: "@Url.Action(MVC.Company.ManageWorkReport.GetStudent())", data: { studentId: value }, cache: false, success: function (data) { if (data) { $("#students tbody").html(data); } }, error: function (xhr, status, error) { alert(xhr.responseText); } }); } return false; }); 

HTML code to insert data is

@using (Html.BeginDefaultForm(MVC.Company.ManageWorkReport.Create())) { <table class="table table-striped table-bordered bootstrap-datatable datatable" id="students"> <thead> <tr> <th>Ime in Priimek</th> <th>Vrsta</th> <th>Začetek dela</th> <th>Konec dela</th> <th>Enota</th> <th>Cena za enoto</th> <th>Količina</th> <th>Neto znesek</th> <th>Bruto znesek</th> <th></th> </tr> </thead> <tbody> <tr> <td colspan="11">Podatek še ne obstaja</td> </tr> </tbody> </table> @Html.SimpleSubmitAndCancelButton(Translations.Global.SAVE, Translations.Global.CANCEL) } 

and C#

[HttpGet] public virtual PartialViewResult GetStudent(int studentId) { StudentsWorksReportsFormModel studentsWorksReportsFormModel = new StudentsWorksReportsFormModel(); ..... var view = PartialView("StudentWorkReportResult", studentsWorksReportsFormModel); return view; 

}

Problem is that when I enter data in form and click SUBMIT button model is always empty. Why model is empty if I fill page with JQUERY and later enter data in text fields? How to fill the model also that I can insert data in DB.

20837913 0

The approach will not succeed, as you can search, but you cannot sort by a multivalued field. This pointed out in Sorting with Multivalued Field in Solr and written in Solr's Wiki

Sorting can be done on the "score" of the document, or on any multiValued="false" indexed="true" field provided that field is either non-tokenized (ie: has no Analyzer) or uses an Analyzer that only produces a single Term (ie: uses the KeywordTokenizer)

Update

About the alternatives, as you point out that you need to find similar documents for one given ID, why not create a second core with a schema like

<fields> <field name="doc_id" type="int" indexed="true" stored="true" /> <field name="similar_to_id" type="int" indexed="true" stored="true" /> <field name="similarity" type="string" indexed="true" stored="true" /> </fields> <types> <fieldType name="int" class="solr.TrieIntField"/> <fieldType name="string" class="solr.StrField" /> </types> 

Then you could do a second query, after performing the actual search

q=similar_to_id=42&sort=similarity

16130137 0

Notes :

  1. Query optimization and indexing the search traget tables
  2. datagrids are complex objects and get time in updating and filling its ordinary( spcially when have more column )
  3. your System hardware (Ram , CPU ,VGA, ... ) that must be considered
  4. i think best approach is sort your query result and paging your result by Last code accessed and use this :

    void NextPage()
    {
    Qr="select Top N from tbl where Code>LastCode order by Code asc";
    //reading data
    FirstCode=Drr["Code"];//for first record result
    LastCode=Drr["Code"];//for last record result
    }
    void PreviousPage()
    {
    Qr="select Top N from tbl where Code < FirstCode order by Code asc";

    //reading data

    FirstCode=Drr["Code"];//for first record result
    LastCode=Drr["Code"];//for last record result
    }

Hope this Help

23503635 0

This statement, for instance,

String studAnswers[][] = answerArray[rowIndex][1].replace(" ", "S"); 

gives the compilation error

Type mismatch: cannot convert from String to String[][] 

because

answerArray[rowIndex][1].replace(" ", "S"); returns a String.

You are trying to assign it to a String array.

Also, you cannot use equals on primitives (int, char...). You need to use == for comparison.

4982879 0

Here's another way. Of course this is just for int but the code could easily be altered for other datatypes.

AOMatrix.h:

#import <Cocoa/Cocoa.h> @interface AOMatrix : NSObject { @private int* matrix_; uint columnCount_; uint rowCount_; } - (id)initWithRows:(uint)rowCount Columns:(uint)columnCount; - (uint)rowCount; - (uint)columnCount; - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex; - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex; @end 

AOMatrix.m

#import "AOMatrix.h" #define INITIAL_MATRIX_VALUE 0 #define DEFAULT_ROW_COUNT 4 #define DEFAULT_COLUMN_COUNT 4 /**************************************************************************** * BIG NOTE: * Access values in the matrix_ by matrix_[rowIndex*columnCount+columnIndex] ****************************************************************************/ @implementation AOMatrix - (id)init { return [self initWithRows:DEFAULT_ROW_COUNT Columns:DEFAULT_COLUMN_COUNT]; } - (id)initWithRows:(uint)initRowCount Columns:(uint)initColumnCount { self = [super init]; if(self) { rowCount_ = initRowCount; columnCount_ = initColumnCount; matrix_ = malloc(sizeof(int)*rowCount_*columnCount_); uint i; for(i = 0; i < rowCount_*columnCount_; ++i) { matrix_[i] = INITIAL_MATRIX_VALUE; } // NSLog(@"matrix_ is %ux%u", rowCount_, columnCount_); // NSLog(@"matrix_[0] is at %p", &(matrix_[0])); // NSLog(@"matrix_[%u] is at %p", i-1, &(matrix_[i-1])); } return self; } - (void)dealloc { free(matrix_); [super dealloc]; } - (uint)rowCount { return rowCount_; } - (uint)columnCount { return columnCount_; } - (int)valueAtRow:(uint)rowIndex Column:(uint)columnIndex { // NSLog(@"matrix_[%u](%u,%u) is at %p with value %d", rowIndex*columnCount_+columnIndex, rowIndex, columnIndex, &(matrix_[rowIndex*columnCount_+columnIndex]), matrix_[rowIndex*columnCount+columnIndex]); return matrix_[rowIndex*columnCount_+columnIndex]; } - (void)setValue:(int)value atRow:(uint)rowIndex Column:(uint)columnIndex { matrix_[rowIndex*columnCount_+columnIndex] = value; } @end 
15692210 0 What's the difference between 301 and 302 in HTTP for Search engine

I read this question and know What's the difference between 301 and 302 in HTTP but my question is What's the difference between 301 and 302 in HTTP for Search engine?

17532229 1 What does "Cannot have more than on screen object" error mean?

I'm working on a timer template for use in my games that I create. This is the code I have for a timer module (haven't put it into a class yet)

import time import math import pygame from livewires import games, color timer = 0 games.init(screen_width = 640, screen_height = 480, fps = 50) gamefont = pygame.font.Font(None, 30) timertext = gamefont.render('Timer: ' +str(timer), 1, [255,0,0]) screen.blit(timertext, [scoreXpos,20]) 

Eventually, I'm going to have a live timer which is why I use the the render and blit methods, but for now, I just have a static variable called timer set equal to 0. When I run this program however, I get an error that says "Cannot have more than on screen object." I'm really confused because I don't think I've ever seen this error before, and definitely don't know what it means, or how to fix it. If someone could help me understand what's happening, I would very much appreciate it. Also, the reason I've imported games and color from livewires, is to use it for another purpose later on in the code.

4309378 0 Association Extensions no longer working in Rails 2.3.10

I have an app that we just upgrade from 2.1.0 to 2.3.10. After the upgrade, an Association Extension that previously worked causes a failure. Here is the code on the model for the extension:

Class Classroom has_many :registrations has_many :students, :through => :registrations, :uniq => true do def in_group(a_group) if a_driver scoped(:conditions => ['registrations.group_id = ?', a_group]) else in_no_group end end def in_no_group scoped(:conditions => 'registrations.group_id is null') end end end 

This is a simplified model of my actual issue, but basically I used to be able to do

classroom.students.in_group(honor_students) 

This no longer works, with the following output:

classroom.students.in_group(honor_students) ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'registrations.group_id' in 'where clause': SELECT * FROM `students` WHERE (registrations.group_id = 1234) 

When I just grab the list of students, the SQL has all the expected join syntax there thats missing from the above version:

SELECT DISTINCT `students`.* FROM `students` INNER JOIN `registrations` ON `students`.id = `registrations`.student_id WHERE ((`registrations`.classroom_id = 9876)) 

Why is the association extension missing all the join SQL?

18094751 0

Use e.Cancel = true; to cancel back navigation.

Please correct me if I'm wrong. Your code is looking messed up. I think you last page/back page is mainpage.xaml and in OK you are again navigating to this page. If this is the case then there is no need of navigating again you can use below code.

protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e) { MessageBoxResult res = MessageBox.Show("Are you sure that you want to exit?", "", MessageBoxButton.OKCancel); if (res != MessageBoxResult.OK) { e.Cancel = true; //when pressed cancel don't go back } } 
31244421 0

You have the following errors:

  1. You cannot nest anything like form elements inside <p> tag. Replace it with a <div> tag.
  2. You haven't closed the <input />.

Use this snippet:

<li> <div> <label for="request" id="officallabel">Purpose</label> <input type = "radio" name = "approvalbuttons" id = "approved" value = "Approved" /> <label for = "approved">Approved</label> <input type = "radio" name = "approvalbuttons" id = "denied" checked = "checked" value = "denied" /> <label for = "denied">Denied</label> </div> </li>

34394842 0

I guess you mean the category tree, And this should give you category tree. you can see the various filters being applied. (You can always do according to your need.)

<?php $rootCatId = Mage::app()->getStore()->getRootCategoryId(); $catlistHtml = getTreeCategories($rootCatId, false); echo $catlistHtml; function getTreeCategories($parentId, $isChild){ $allCats = Mage::getModel('catalog/category')->getCollection() ->addAttributeToSelect('*') ->addAttributeToFilter('is_active','1') ->addAttributeToFilter('include_in_menu','1') ->addAttributeToFilter('parent_id',array('eq' => $parentId)) ->addAttributeToSort('position', 'asc'); $class = ($isChild) ? "sub-cat-list" : "cat-list"; $html .= '<ul class="'.$class.'">'; foreach($allCats as $category) { $html .= '<li><span>'.$category->getName()."</span>"; $subcats = $category->getChildren(); if($subcats != ''){ $html .= getTreeCategories($category->getId(), true); } $html .= '</li>'; } $html .= '</ul>'; return $html; } ?> 

EDIT: getting all parent category using an id/current category id..

$id = Mage::registry('current_category'); //or if you are retrieving other way around $category = Mage::getModel('catalog/category')->load($id); $categorynames = array(); foreach ($category->getParentCategories() as $parent) { $categorynames[] = $parent->getName(); } print_r($categorynames); //dumping category names for eg. 
14371345 1 Get field value within Flask-MongoAlchemy Document

I've looked at documentation, and have searched Google extensively, and haven't found a solution to my problem.
This is my readRSS function (note that 'get' is a method of Kenneth Reitz's requests module):

def readRSS(name, loc): linkList = [] linkTitles = list(ElementTree.fromstring(get(loc).content).iter('title')) linkLocs = list(ElementTree.fromstring(get(loc).content).iter('link')) for title, loc in zip(linkTitles, linkLocs): linkList.append((title.text, loc.text)) return {name: linkList} 

This is one of my MongoAlchemy classes:

class Feed(db.Document): feedname = db.StringField(max_length=80) location = db.StringField(max_length=240) lastupdated = datetime.utcnow() def __dict__(self): return readRSS(self.feedname, self.location) 

As you can see, I had to call the readRSS function within a function of the class, so I could pass self, because it's dependent on the fields feedname and location.
I want to know if there's a different way of doing this, so I can save the readRSS return value to a field in the Feed document. I've tried assigning the readRSS function's return value to a variable within the function __dict__ -- that didn't work either.

I have the functionality working in my app, but I want to save the results to the Document to lessen the load on the server (the one I am getting my RSS feed from).

Is there a way of doing what I intend to do or am I going about this all wrong?

11968366 0 cURL loop memory growth

I have this problem with a loop using cURL where memory grows exponentially. In this example script, it starts using approximately 14MB of memory and ends with 28MB, with my original script and repeating to 1.000.000, memory grows to 800MB, which is bad.

PHP 5.4.5
cURL 7.21.0

for ($n = 1; $n <= 1000; $n++){ $apiCall = 'https://api.instagram.com/v1/users/' . $n . '?access_token=5600913.47c8437.358fc525ccb94a5cb33c7d1e246ef772'; $options = Array(CURLOPT_URL => $apiCall, CURLOPT_RETURNTRANSFER => true, CURLOPT_FRESH_CONNECT => true ); $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch); unset($ch); } 
25353469 0 Two issues while trying to update wordpress user meta

I have a form that is submitting data to a php script. Here is some of the code in the script.

foreach ($newuser_values as $key => $value) { echo $key; echo $value; switch ($key) { case "show_name": echo "1"; switch ($value) { case "first": $update_val = $current_user->user_firstname; break; case "first_initial": echo "HI"; $update_val = $current_user->user_firstname . " " . substr($current_user->user_lastname,0,0) . "."; break; case "first_last": $update_val = $current_user->user_firstname . " " . $current_user->user_lastname; break; default: echo "HELLO"; $update_val = $user_identity; } echo $update_val; update_user_meta($user_ID, $show_name, $update_val); echo get_user_meta($user_ID, $show_name); ... } } 

$newuser_values is an array of form info. I get it like this:

$newuser_values = $_POST['edit-profile']; 

I have two issues here. They can both be seen from the beginning of the script output (from echo statements). The script output is:

show_namefirst_intital1HELLOtestuser1Array

Problem 1: As you can see, the script prints a 1 which means that it is entering the case titled "show_name" of the switch on $key. However, it does not enter the case entitled "first_intial" of the switch on $value. Why is this?

Problem 2: Anyway the script enters the default case of the switch on $value and prints HELLO. Then, it prints the $update_val which is the testuser1. However, that value is not getting assigned to the user_meta because it is printing "Array". Why is this?

Thanks in advance. I apologize if these questions are simplistic. I am pretty new to wordpress and web development.

18138512 0

The correct thing to do is to set an execution policy on your machine (a one-time action), at which point you won't need to bypass it every time, and the Jenkins plugin should "just work". Are you unable to?

A reasonable starting setting would be RemoteSigned, which will allow you to execute local scripts fine but would still disallow scripts downloaded from the internet.

From an elevated PowerShell prompt, you would run:

Set-ExecutionPolicy RemoteSigned 

See also: http://technet.microsoft.com/library/hh849812.aspx

UPDATE: excerpt from Help on applying policy and how it's supposed to behave:

If you set the execution policy for the local computer (the default) or the current user, the change is saved in the registry and remains effective until you change it again.

Of course, if your machine is on a Domain, then Group Policy could revert this.

17133620 0 Setting timeout on blocking I/O ops with ServerSocketChannel doesn't work as expected

I'm working on a small group conversation server in Java and I'm currently hacking network code, but it seems like I cannot set right timeout on blocking I/O ops: chances are I've been bitten by some Java weirdness (or, simply, I misinterpret javadoc).

So, this is the pertinent code from ConversationServer class (with all security checks and logging stripped for simplicity):

class ConversationServer { // ... public int setup() throws IOException { ServerSocketChannel server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(port), Settings.MAX_NUMBER_OF_PLAYERS + 1); server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS); int numberOfPlayers; for (numberOfPlayers = 0; numberOfPlayers < Settings.MAX_NUMBER_OF_PLAYERS; ++numberOfPlayers) { SocketChannel clientSocket; try { clientSocket = server.accept(); } catch (SocketTimeoutException timeout) { break; } clients.add(messageStreamFactory.create(clientSocket)); } return numberOfPlayers; } // ... } 

The expected behaviour is to let connect Settings.MAX_NUMBER_OF_PLAYERS clients at most, or terminate setup anyway after Settings.AWAIT_PLAYER_MS milliseconds (currently, 30000L).

What happens, is that if I connect Settings.MAX_NUMBER_OF_PLAYERS clients, everything is fine (exit because of for condition), but if I don't, the SocketTimeoutException I'd expect is never thrown and the server hangs forever.

If I understand right, server.socket().setSoTimeout((int) Settings.AWAIT_PLAYERS_MS); should be sufficient, but it doesn't give the expected behaviour.

So, can anyone spot the error here?

37428778 0

just try with adding this piece of code

<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" /> 

<!-- all normal size screens --> <screen android:screenDensity="ldpi" android:screenSize="normal" /> <screen android:screenDensity="mdpi" android:screenSize="normal" /> <screen android:screenDensity="hdpi" android:screenSize="normal" /> <screen android:screenDensity="xhdpi" android:screenSize="normal" /> 

This code involves everything even tablets refer this to exclude tablets

33217783 0 Optimizing opencl kernel

I am trying to optimize this kernel. The CPU version of this kernel is 4 times faster than the GPU version. I would expect that the GPU version would be faster. It might be that we have a lot of memory accesses and that is why we have a low performance. I am using an Intel HD 2500 and OpenCL 1.2.

The GPU kernel is:

__kernel void mykernel(__global unsigned char *inp1, __global unsigned char *inp2, __global unsigned char *inp3, __global unsigned char *inp4, __global unsigned char *outp1, __global unsigned char *outp2, __global unsigned char *outp3, __global unsigned char *outp4, __global unsigned char *lut, uint size ) { unsigned char x1, x2, x3, x4; unsigned char y1, y2, y3, y4; const int x = get_global_id(0); const int y = get_global_id(1); const int width = get_global_size(0); const uint id = y * width + x; x1 = inp1[id]; x2 = inp2[id]; x3 = inp3[id]; x4 = inp4[id]; y1 = (x1 & 0xff) | (x2>>2 & 0xaa) | (x3>>4 & 0x0d) | (x4>>6 & 0x02); y2 = (x1<<2 & 0xff) | (x2 & 0xaa) | (x3>>2 & 0x0d) | (x4>>4 & 0x02); y3 = (x1<<4 & 0xff) | (x2<<2 & 0xaa) | (x3 & 0x0d) | (x4>>2 & 0x02); y4 = (x1<<6 & 0xff) | (x2<<4 & 0xaa) | (x3<<2 & 0x0d) | (x4 & 0x02); // lookup table y1 = lut[y1]; y2 = lut[y2]; y3 = lut[y3]; y4 = lut[y4]; outp1[id] = (y1 & 0xc0) | ((y2 & 0xc0) >> 2) | ((y3 & 0xc0) >> 4) | ((y4 & 0xc0) >> 6); outp2[id] = ((y1 & 0x30) << 2) | (y2 & 0x30) | ((y3 & 0x30) >> 2) | ((y4 & 0x30) >> 4); outp3[id] = ((y1 & 0x0c) << 4) | ((y2 & 0x0c) << 2) | (y3 & 0x0c) | ((y4 & 0x0c) >> 2); outp4[id] = ((y1 & 0x03) << 6) | ((y2 & 0x03) << 4) | ((y3 & 0x03) << 2) | (y4 & 0x03); } 

I use :

 size_t localWorkSize[1], globalWorkSize[1]; localWorkSize[0] = 1; globalWorkSize[0] = X*Y; // X,Y define a data space of 15 - 20 MB 

LocalWorkSize can vary between 1 - 256.

for LocalWorkSize = 1 I have CPU = 0.067Sec GPU = 0.20Sec for LocalWorkSize = 256 I have CPU = 0.067Sec GPU = 0.34Sec 

Which is really weird. Can you give me some ideas why I get these strange numbers? and do you have any tips on how I can optimize this kernel?

My main looks like this:

int main(int argc, char** argv) { int err,err1,j,i; // error code returned from api calls and other clock_t start, end; // measuring performance variables cl_device_id device_id; // compute device id cl_context context; // compute context cl_command_queue commands; // compute command queue cl_program program_ms_naive; // compute program cl_kernel kernel_ms_naive; // compute kernel // ... dynamically allocate arrays // ... initialize arrays cl_uint dev_cnt = 0; clGetPlatformIDs(0, 0, &dev_cnt); cl_platform_id platform_ids[100]; clGetPlatformIDs(dev_cnt, platform_ids, NULL); // Connect to a compute device err = clGetDeviceIDs(platform_ids[0], CL_DEVICE_TYPE_GPU, 1, &device_id, NULL); // Create a compute context context = clCreateContext(0, 1, &device_id, NULL, NULL, &err); // Create a command queue commands = clCreateCommandQueue(context, device_id, 0, &err); // Create the compute programs from the source file program_ms_naive = clCreateProgramWithSource(context, 1, (const char **) &kernelSource_ms, NULL, &err); // Build the programs executable err = clBuildProgram(program_ms_naive, 0, NULL, NULL, NULL, NULL); // Create the compute kernel in the program we wish to run kernel_ms_naive = clCreateKernel(program_ms_naive, "ms_naive", &err); d_A1 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A1, &err); d_A2 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A2, &err); d_A3 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A3, &err); d_A4 = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, mem_size_cpy/4, h_A4, &err); d_lut = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, 256, h_ltable, &err); d_B1 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); d_B2 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); d_B3 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); d_B4 = clCreateBuffer(context, CL_MEM_WRITE_ONLY, mem_size_cpy/4, NULL, &err); int size = YCOLUMNS*XROWS/4; int size_b = size * 4; err = clSetKernelArg(kernel_ms_naive, 0, sizeof(cl_mem), (void *)&(d_A1)); err |= clSetKernelArg(kernel_ms_naive, 1, sizeof(cl_mem), (void *)&(d_A2)); err |= clSetKernelArg(kernel_ms_naive, 2, sizeof(cl_mem), (void *)&(d_A3)); err |= clSetKernelArg(kernel_ms_naive, 3, sizeof(cl_mem), (void *)&(d_A4)); err |= clSetKernelArg(kernel_ms_naive, 4, sizeof(cl_mem), (void *)&d_B1); err |= clSetKernelArg(kernel_ms_naive, 5, sizeof(cl_mem), (void *)&(d_B2)); err |= clSetKernelArg(kernel_ms_naive, 6, sizeof(cl_mem), (void *)&(d_B3)); err |= clSetKernelArg(kernel_ms_naive, 7, sizeof(cl_mem), (void *)&(d_B4)); err |= clSetKernelArg(kernel_ms_naive, 8, sizeof(cl_mem), (void *)&d_lut); //__global err |= clSetKernelArg(kernel_ms_naive, 9, sizeof(cl_uint), (void *)&size_b); size_t localWorkSize[1], globalWorkSize[1]; localWorkSize[0] = 256; globalWorkSize[0] = XROWS*YCOLUMNS; start = clock(); for (i=0;i< EXECUTION_TIMES;i++) { err1 = clEnqueueNDRangeKernel(commands, kernel_ms_naive, 1, NULL, globalWorkSize, localWorkSize, 0, NULL, NULL); err = clFinish(commands); } end = clock(); return 0; } 
37501223 0 I can not print correctly mysql to xml

I do not know where I went wrong. I want to this.

 <mekan> <Soguk Icecekler> <yemek> <urunismi>Kola</urunismi> <fiyat>2</fiyat> <efiyat>0</efiyat> </yemek> <yemek> <urunismi>Kola</urunismi> <fiyat>2</fiyat> <efiyat>0</efiyat> </yemek> </Soguk Icecekler> <Sicak Icecekler> <yemek> <urunismi>cay</urunismi> <fiyat>2</fiyat> <efiyat>0</efiyat> </yemek> <yemek> <urunismi>kahve</urunismi> <fiyat>2</fiyat> <efiyat>0</efiyat> </yemek> </Sicak Icecekler> </mekan> 

What is my mistake?

$xml = new SimpleXMLElement('<mekan/>'); while($data = mysql_fetch_array($resultID)) { $kategori=$xml->addChild('Kategori'); $kategori->addChild('kategori_adi', $data["kategoriadi"]); $kategori->addChild('urunismi', $data["urunadi"]); $kategori->addChild('fiyat', $data["fiyat"]); $kategori->addChild('efiyat', $data["eskifiyat"]); } Header('Content-type: text/xml'); echo $xml->asXML(); 

XML is read, but I get mistaken result.

24100405 0 How to dynamically configure DataSource in Spring based on application mode?

We have an application which runs both as standalone Spring application and as Webservice in Weblogic. The standalone application creates the database DataSource as show below by reading the properties file.

However for the Webservices part, I'd like to use the DataSource configured in Weblogic via JNDI. I'm not sure how to make that dynamic DataSource switch based on the mode my application runs. Any help here please?

@Configuration @PropertySources(value = {@PropertySource("classpath:app.properties")}) public class DAOConfig { @Autowired Environment env; @Bean(destroyMethod = "close") public DataSource dataSource() { return new DataSources.Builder() .host(env.getProperty("dbhost")) .port(env.getProperty("dbport", Integer.class)) .service(env.getProperty("dbservice")) .user(env.getProperty("dbuser")) .pwd(env.getProperty("dbpwd")) .initialConnectionsInPool(env.getProperty("dbinitialConnectionsInPool", Integer.class)) .maxConnectionsInPool(env.getProperty("dbmaxConnectionsInPool", Integer.class)) .build(); } } 
32739558 0 Media Foundation EVR no video displaying

I've been trying in vain to come up with a no frills example of displaying video using Microsoft's Media Foundation Enhanced Video Renderer (EVR). I'm testing on Windows 7 with Visual Studio 2013.

I'm pretty sure I've got the media types configured correctly as I can export and save the buffer from the IMFSample in my read loop to a bitmap. I can also get the video to render IF I get MF to automatically generate the topology but in this case I need to wire up the source reader and sink writer manually so I can get access to the different parts of the pipeline.

I have used mftrace to see if I can spot anything different between the automatically generated topology and the manually wired up example but nothing obvious jumps out.

The code is below (full sample project at https://github.com/sipsorcery/mediafoundationsamples/tree/master/MFVideoEVR).

Is there a step I've missed to get the IMFSample from the SinkWriter to display on the video window? I've been looking at a few examples that go deeper into the DirectX pipeline but should that be necessary or is the EVR meant to abstract those mechanics aways?

#include <stdio.h> #include <tchar.h> #include <evr.h> #include <mfapi.h> #include <mfplay.h> #include <mfreadwrite.h> #include <mferror.h> #include "..\Common\MFUtility.h" #include <windows.h> #include <windowsx.h> #pragma comment(lib, "mf.lib") #pragma comment(lib, "evr.lib") #pragma comment(lib, "mfplat.lib") #pragma comment(lib, "mfplay.lib") #pragma comment(lib, "mfreadwrite.lib") #pragma comment(lib, "mfuuid.lib") #pragma comment(lib, "Strmiids") #pragma comment(lib, "wmcodecdspuuid.lib") #define CHECK_HR(hr, msg) if (hr != S_OK) { printf(msg); printf("Error: %.2X.\n", hr); goto done; } void InitializeWindow(); // Constants const WCHAR CLASS_NAME[] = L"MFVideoEVR Window Class"; const WCHAR WINDOW_NAME[] = L"MFVideoEVR"; // Globals. HWND _hwnd; using namespace System::Threading::Tasks; int main() { CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); MFStartup(MF_VERSION); IMFMediaSource *videoSource = NULL; UINT32 videoDeviceCount = 0; IMFAttributes *videoConfig = NULL; IMFActivate **videoDevices = NULL; IMFSourceReader *videoReader = NULL; WCHAR *webcamFriendlyName; IMFMediaType *videoSourceOutputType = NULL, *pvideoSourceModType = NULL, *pSrcOutMediaType = NULL; IMFSourceResolver *pSourceResolver = NULL; IUnknown* uSource = NULL; IMFMediaSource *mediaFileSource = NULL; IMFAttributes *pVideoReaderAttributes = NULL; IMFMediaType *pVideoOutType = NULL; MF_OBJECT_TYPE ObjectType = MF_OBJECT_INVALID; IMFMediaSink *pVideoSink = NULL; IMFStreamSink *pStreamSink = NULL; IMFMediaTypeHandler *pMediaTypeHandler = NULL; IMFMediaType *pMediaType = NULL; IMFMediaType *pSinkMediaType = NULL; IMFSinkWriter *pSinkWriter = NULL; IMFVideoRenderer *pVideoRenderer = NULL; IMFVideoPresenter *pVideoPresenter = nullptr; IMFVideoDisplayControl *pVideoDisplayControl = nullptr; IMFGetService *pService = nullptr; IMFActivate* pActive = NULL; MFVideoNormalizedRect nrcDest = { 0.5f, 0.5f, 1.0f, 1.0f }; IMFPresentationTimeSource *pSystemTimeSource = nullptr; IMFMediaType *sinkPreferredType = nullptr; IMFPresentationClock *pClock = NULL; IMFPresentationTimeSource *pTimeSource = NULL; CHECK_HR(MFTRegisterLocalByCLSID( __uuidof(CColorConvertDMO), MFT_CATEGORY_VIDEO_PROCESSOR, L"", MFT_ENUM_FLAG_SYNCMFT, 0, NULL, 0, NULL ), "Error registering colour converter DSP.\n"); Task::Factory->StartNew(gcnew Action(InitializeWindow)); Sleep(1000); if (_hwnd == nullptr) { printf("Failed to initialise video window.\n"); goto done; } // Set up the reader for the file. CHECK_HR(MFCreateSourceResolver(&pSourceResolver), "MFCreateSourceResolver failed.\n"); CHECK_HR(pSourceResolver->CreateObjectFromURL( L"..\\..\\MediaFiles\\big_buck_bunny.mp4", // URL of the source. MF_RESOLUTION_MEDIASOURCE, // Create a source object. NULL, // Optional property store. &ObjectType, // Receives the created object type. &uSource // Receives a pointer to the media source. ), "Failed to create media source resolver for file.\n"); CHECK_HR(uSource->QueryInterface(IID_PPV_ARGS(&mediaFileSource)), "Failed to create media file source.\n"); CHECK_HR(MFCreateAttributes(&pVideoReaderAttributes, 2), "Failed to create attributes object for video reader.\n"); CHECK_HR(pVideoReaderAttributes->SetGUID(MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE, MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID), "Failed to set dev source attribute type for reader config.\n"); CHECK_HR(pVideoReaderAttributes->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, 1), "Failed to set enable video processing attribute type for reader config.\n"); CHECK_HR(MFCreateSourceReaderFromMediaSource(mediaFileSource, pVideoReaderAttributes, &videoReader), "Error creating media source reader.\n"); CHECK_HR(videoReader->GetCurrentMediaType((DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, &videoSourceOutputType), "Error retrieving current media type from first video stream.\n"); Console::WriteLine("Default output media type for source reader:"); Console::WriteLine(GetMediaTypeDescription(videoSourceOutputType)); Console::WriteLine(); // Set the video output type on the source reader. CHECK_HR(MFCreateMediaType(&pvideoSourceModType), "Failed to create video output media type.\n"); CHECK_HR(pvideoSourceModType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video), "Failed to set video output media major type.\n"); CHECK_HR(pvideoSourceModType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32), "Failed to set video sub-type attribute on EVR input media type.\n"); CHECK_HR(pvideoSourceModType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive), "Failed to set interlace mode attribute on EVR input media type.\n"); CHECK_HR(pvideoSourceModType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE), "Failed to set independent samples attribute on EVR input media type.\n"); CHECK_HR(MFSetAttributeRatio(pvideoSourceModType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1), "Failed to set pixel aspect ratio attribute on EVR input media type.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pvideoSourceModType, MF_MT_FRAME_SIZE), "Failed to copy video frame size attribute from input file to output sink.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pvideoSourceModType, MF_MT_FRAME_RATE), "Failed to copy video frame rate attribute from input file to output sink.\n"); CHECK_HR(videoReader->SetCurrentMediaType((DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, NULL, pvideoSourceModType), "Failed to set media type on source reader.\n"); Console::WriteLine("Output media type set on source reader:"); Console::WriteLine(GetMediaTypeDescription(pvideoSourceModType)); Console::WriteLine(); // Create EVR sink . //CHECK_HR(MFCreateVideoRenderer(__uuidof(IMFMediaSink), (void**)&pVideoSink), "Failed to create video sink.\n"); CHECK_HR(MFCreateVideoRendererActivate(_hwnd, &pActive), "Failed to created video rendered activation context.\n"); CHECK_HR(pActive->ActivateObject(IID_IMFMediaSink, (void**)&pVideoSink), "Failed to activate IMFMediaSink interface on video sink.\n"); // Initialize the renderer before doing anything else including querying for other interfaces (https://msdn.microsoft.com/en-us/library/windows/desktop/ms704667(v=vs.85).aspx). CHECK_HR(pVideoSink->QueryInterface(__uuidof(IMFVideoRenderer), (void**)&pVideoRenderer), "Failed to get video Renderer interface from EVR media sink.\n"); CHECK_HR(pVideoRenderer->InitializeRenderer(NULL, NULL), "Failed to initialise the video renderer.\n"); CHECK_HR(pVideoSink->QueryInterface(__uuidof(IMFGetService), (void**)&pService), "Failed to get service interface from EVR media sink.\n"); CHECK_HR(pService->GetService(MR_VIDEO_RENDER_SERVICE, __uuidof(IMFVideoDisplayControl), (void**)&pVideoDisplayControl), "Failed to get video display control interface from service interface.\n"); CHECK_HR(pVideoSink->GetStreamSinkByIndex(0, &pStreamSink), "Failed to get video renderer stream by index.\n"); CHECK_HR(pStreamSink->GetMediaTypeHandler(&pMediaTypeHandler), "Failed to get media type handler.\n"); // Set the video output type on the source reader. CHECK_HR(MFCreateMediaType(&pVideoOutType), "Failed to create video output media type.\n"); CHECK_HR(pVideoOutType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video), "Failed to set video output media major type.\n"); CHECK_HR(pVideoOutType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_RGB32), "Failed to set video sub-type attribute on EVR input media type.\n"); CHECK_HR(pVideoOutType->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive), "Failed to set interlace mode attribute on EVR input media type.\n"); CHECK_HR(pVideoOutType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE), "Failed to set independent samples attribute on EVR input media type.\n"); CHECK_HR(MFSetAttributeRatio(pVideoOutType, MF_MT_PIXEL_ASPECT_RATIO, 1, 1), "Failed to set pixel aspect ratio attribute on EVR input media type.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_FRAME_SIZE), "Failed to copy video frame size attribute from input file to output sink.\n"); CHECK_HR(CopyAttribute(videoSourceOutputType, pVideoOutType, MF_MT_FRAME_RATE), "Failed to copy video frame rate attribute from input file to output sink.\n"); //CHECK_HR(pMediaTypeHandler->GetMediaTypeByIndex(0, &pSinkMediaType), "Failed to get sink media type.\n"); CHECK_HR(pMediaTypeHandler->SetCurrentMediaType(pVideoOutType), "Failed to set current media type.\n"); Console::WriteLine("Input media type set on EVR:"); Console::WriteLine(GetMediaTypeDescription(pVideoOutType)); Console::WriteLine(); CHECK_HR(MFCreatePresentationClock(&pClock), "Failed to create presentation clock.\n"); CHECK_HR(MFCreateSystemTimeSource(&pTimeSource), "Failed to create system time source.\n"); CHECK_HR(pClock->SetTimeSource(pTimeSource), "Failed to set time source.\n"); //CHECK_HR(pClock->Start(0), "Error starting presentation clock.\n"); CHECK_HR(pVideoSink->SetPresentationClock(pClock), "Failed to set presentation clock on video sink.\n"); Console::WriteLine("Press any key to start video sampling..."); Console::ReadLine(); IMFSample *videoSample = NULL; DWORD streamIndex, flags; LONGLONG llTimeStamp; while (true) { CHECK_HR(videoReader->ReadSample( MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, // Flags. &streamIndex, // Receives the actual stream index. &flags, // Receives status flags. &llTimeStamp, // Receives the time stamp. &videoSample // Receives the sample or NULL. ), "Error reading video sample."); if (flags & MF_SOURCE_READERF_ENDOFSTREAM) { printf("End of stream.\n"); break; } if (flags & MF_SOURCE_READERF_STREAMTICK) { printf("Stream tick.\n"); } if (!videoSample) { printf("Null video sample.\n"); } else { printf("Attempting to write sample to stream sink.\n"); CHECK_HR(videoSample->SetSampleTime(llTimeStamp), "Error setting the video sample time.\n"); //CHECK_HR(videoSample->SetSampleDuration(41000000), "Error setting the video sample duration.\n"); CHECK_HR(pStreamSink->ProcessSample(videoSample), "Streamsink process sample failed.\n"); } SafeRelease(&videoSample); } done: printf("finished.\n"); getchar(); return 0; } LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hwnd, uMsg, wParam, lParam); } void InitializeWindow() { WNDCLASS wc = { 0 }; wc.lpfnWndProc = WindowProc; wc.hInstance = GetModuleHandle(NULL); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = CLASS_NAME; if (RegisterClass(&wc)) { _hwnd = CreateWindow( CLASS_NAME, WINDOW_NAME, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, GetModuleHandle(NULL), NULL ); if (_hwnd) { ShowWindow(_hwnd, SW_SHOWDEFAULT); MSG msg = { 0 }; while (true) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { Sleep(1); } } } } } 
15481263 0

The short answer is no, there isn't. You always should write the access specifier in front of your field/method.

public int var1; public char var2; 

Note that private is the default specifier. It is a question of design, but I would always explicitly designate the modifier. (And even if it is just for the consistent indentation!)

Read more on Accessibility Levels (C#) at msdn.

34390276 0

Just do it, like this:

Update TableTest SET COL3 = newdata Where Col1= D11 
9401392 0

You can add panels to a form at runtime the same way the designer does - construct the Panel, and add it to the form (via this.Controls.Add(thePanel);).

The easiest way to see the appropriate code is to add a panel to the form using the designer, then open up the "YourForm.designer.cs" file. The designer just generates the required code for you - but you can see the exact code required to duplicate what the designer would create.

As for the layout, I'd recommend watching the Layout Techniques for Windows Forms Developers video. It may give you some good clues as to the various options available for layout. There is nothing exactly like Java's GridLayout, though there are some open source projects that attempt to duplicate this functionality.

22980802 0

SendMailAsync and all methods that use the Task Parallel Library execute in a threadpool thread, although you can make them use a new thread if you need to. This means that instead of creating a new thread, an available thread is picked from the pool and returned there when the method finishes.

The number of threads in the pool varies with the version of .NET and the OS, the number of cores etc. It can go from 25 threads per core in .NET 4 to hundreds or per core in .NET 4.5 on a server OS.

An additional optimization for IO-bound (disk, network) tasks is that instead of using a thread, an IO completion port is used. Roughly, this is a callback from the IO stack when an IO operation (disk or network) finishes. This way the framework doesn't waste a thread waiting for an IO call to finish.

When you start an asynchronous network operation, .NET make the network call, registers for the callback and releases the threadpool thread. When the call finishes, the framework gets notified and schedules the rest of the asynchronous method (essentially what comes after the await or ContinueWith) on a threadpool thread.

Submitting a 100 asynchronous operations doesn't mean that 100 threads will be used nor that all 100 of them will execute in parallel. Rather, the framework will take into account the number of cores, the load and the number of available threads to execute as many of them as possible, without hurting overall performance. Waiting on the network calls may not even use a thread at all, while processing the messages themselves will execute on threadpool threads

20908161 0 Special character in concatenated sql script causing error

I save stored procedure code as files and then execute them in several different databases. I am trying to concatenate multiple files (100's). Every utility I use seems to create some special characters in the file that cause an error when i execute the script in sql.

Currently, i used

type *.sql > script.sql 

in DOS. I am getting the following error in many places.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ''. 

How can I find this character so I can do a find/replace? Thanks!

36973295 0 Balloon synopsis - jQuery plugin - which file specifically?

I have downloaded what seems to be a handy tool called Balloon Synopsis (homepage: http://schlegel.github.io/balloon/index.html GitHub: https://github.com/balloonLD/balloon-synopsis) and ran the Gruntfile. All there is however is bunch of .js files (/src/js) and I am not sure which one (or several) are the jQuery plugin. Alternatively, have I been misled completely? There is no documentation or how-to whatsoever, so any help or advice would be great :) Thanks!

24777375 0

This is not a cross-domain issue. You are mixing the dynamic proxy and proxyless approaches. $.hubConnection and createHubProxy are from the proxyless API, but .client is available only with dynamic proxies. Check the documentation about both and you will be able to fix it (I don't go further with code because I do not know which approach you really want to use).

34815913 0

You can also do it in pure xaml, just use trigger action:

 <Button> <Button.Triggers> <EventTrigger RoutedEvent="PreviewMouseDown"> <BeginStoryboard Storyboard="{DynamicResource BotRotation}"/> </EventTrigger> </Button.Triggers> </Button> 
5605025 0

The system NAND flash for the emulator has run out of space. Your host system D: is not the issue, but for some reason the system.img file that represents a NAND flash for the emulator is full. You can try creating a new emulator, or doing a factory default reset in the emulator to clean it up. To do this, either issue a Factory Data Reset inside Android under Settings -> Privacy, or start the emulator from the command-line:

android list avd emulator -avd My_Avd_Name -wipe-data 

The first command list all Android Virtual Devices. You need the name for the second command. The emulator should not already be running. A third option would be to delete the disk images located under your Windows profile. Under your profiles, it's .android/avd/My_Avd_Name.avd You should only need to delete userdata-qemu.img and maybe cache.img. You can try deleting other image files if necessarily, but note, sdcard.img won't be re-created automatically. You need to run mksdcard from the command-line.

13156139 0

If you could change your student class properties to match the Xml element names and/or decorate the properties with attributes indicating what XML value goes to what class property, then you could use the .Net to deserialise the XML into a List Students in one line.

Then just persist to the DB as you normally would.

Here's an example

39297430 0

you should use a table as grid

Try this

<table> <tr> <?php $numbers_per_row = 5; $rowi= 0; $numbers_limit = 25; for($b=1; $b<=$numbers_limit ; $b++) { echo '<td><a href="index.php?page='.$b.'">'.$b.'</td>'; if($rowi<=$numbers_per_row) { $rowi++; } else { echo '</tr><tr style="margin-top:10px;">'; /* <-- change it ^ to what you want */ /* Reset counter */ $rowi = 0; } } ?> </table> 
6971446 0 distribution provisioning and code signing issues

I just generated a ad hoc distribution provisioning. I dragged this into xcode and then set my ad hoc build to be iphone distribution. Followed every single step in this tutorial. The issue is that when I follow this instruction to see my list of devices it doesn't even have a ProvisionedDevices key in the embedded.mobileprovison. The key goes something like this:

<key>Entitlements</key> <dict> <key>application-identifier</key> <string>8CH38P5X6X.*</string> <key>get-task-allow</key> <false/> <key>keychain-access-groups</key> <array> <string>8CH38P5X6X.*</string> </array> </dict> <key>ExpirationDate</key> <date>2012-03-17T00:31:45Z</date> <key>Name</key> <string>Fever</string> //this is not my app name, how come it's here <key>TimeToLive</key> <integer>291</integer> <key>UUID</key> <string>101F3A06-B33C-411A-8173-A4CEAFF5E673</string> <key>Version</key> <string>101F3A06-B33C-411A-8173-A4CEAFF5E673</string> <key>Version</key> <integer>1</integer> </dict> </plist> 

The weirdest issue is that it has an app name in the , which is not my app name!! How is this even possible? Something is messed up..

This 8CH38P5X6X is also the App ID of my other app called Fever... how.. how is this possible. I've code signed adhoc using iphone distribution and it clearly says this:

enter image description here

UPDATE:

I removed/clear the provisioning profile that I have for the Fever app, restart xcode, and tried to build the archive again and it works! Anyone ever have issues with multiple provisioning profile on your xcode being mixed up like this?

32798837 0

Why not use a validation:

#app/models/review.rb class Review < ActiveRecord::Base validates :movie_id, uniqueness: { scope: :user_id, message: "You've reviewed this movie!" } end 

This is considering your review model belongs_to :movie


You could also use an ActiveRecord callback:

#app/models/review.rb class Review < ActiveRecord::Base before_create :has_review? belongs_to :user, inverse_of: :reviews belongs_to :movie def has_review? return if Review.exists?(user: user, movie_id: movie_id) end end #app/models/user.rb class User < ActiveRecord::Base has_many :reviews, inverse_of: :user end 

Is there any way to improve the lookup in my has_reviewed? method?

 def has_reviewed? redirect_to album_reviews_path, notice: "You've already written a review for this album." if current_user.reviews.exists?(movie: @movie) end 
21572016 1 List connected Bluetooth LE devices to Windows 8 with python

I want to be able to read out information about connected Bluetooth Low Energy HID devices in Windows 8. My main application uses Qt, but I thought it could be much easier to get help from a Python script. Since Windows 8.1 supports Bluetooth Low Energy natively, I connect my mouse to it and tried using the pywinusb package, but it doesn't seem to be able to read out this wirelessly connected device, only connected HID devices.

How can I read out information about my BLE device with Python?

39388527 0

All answers are creating NEW arrays before projecting the final result : (filter and map creates a new array each) so basically it's creating twice.

Another approach is only to yield expected values :

Using iterator functions

function* foo(g) { for (let i = 0; i < g.length; i++) { if (g[i]['images'] && g[i]["images"].length) yield g[i]['images'][0]["name"]; } } var iterator = foo(data1) ; var result = iterator.next(); while (!result.done) { console.log(result.value) result = iterator.next(); } 

This will not create any additional array and only return the expected values !

However if you must return an array , rather than to do something with the actual values , then use other solutions suggested here.

https://jsfiddle.net/remenyLx/7/

27845377 0 Issues connecting to mySql database on target machine

I'm using hostgator for hosting my website and I have added my IP address as remote access host. And then I connected with mySql workbench and tested the connection and I get the message that all parameters are correct. On hostgator, I added myself as a the admin user granting myself all privileges. Now I want to manipulate the database via a PHP script using PDO but this is the error I'm getting in my browser when I try to run the PHP file:

Connection failed: SQLSTATE[28000] [1045] Access denied for user 'user'@'host' (using password: YES)

On mySQL workbench Users and Privileges tab, I get this:

"The account you are currently using does not have sufficient privileges to make changes to MySQL users and privileges."

I'm not sure whats going wrong here and I'm quiet new to this. Can somebody please help?

edit:

php code below:

<?php ini_set('display_errors',1); error_reporting(E_ALL); //this block tries to connect to the database //if there's an error connecting, the code under catch will //and the program will end $host="host"; $port="3306"; $user="xxx"; $password="xxx"; $dbname="database"; try { $conn = new PDO("mysql:host=$host;dbname=$dbname;", $user, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } //$con->close(); ?> 
20081748 0 Drawing layers with jcanvas: performance optimization

)

I have a small web-application which uses jquery and jcanvas (http://calebevans.me/projects/jcanvas/) to print some shapes onto a canvas.

It's basically a map. The user can zoom into it and drag it around and whenever he does so everything has to be drawn again.

As you may see in the code below I remove and recreate layers pretty often (whenever the user drags the map, zooms or resizes his window). I need the layers to handle hover- and click-events. My question is whether there is a big performance impact of this way to handle events in comparison to other solutions. If this is the case, how could I optimize my performance?

var posX = 0, posY = 0; var zoom = 100; var points = []; //array of up to 1000 points retrieved by ajax function draw(){ $("canvas").removeLayers(); $("canvas").clearCanvas(); var xp, yp, ra; var name; $.each(points, function(index) { xp = (this["x"]-posX)/zoom; yp = (this["y"]-posY)/zoom; ra = 1000/zoom; $("#map").drawArc({ layer:true, fillStyle: "black", x: xp, y: yp, radius: ra, mouseover: function(layer) { $(this).animateLayer(layer, { fillStyle: "#c33", scale: 1.0 },200); }, mouseout: function(layer) { $(this).animateLayer(layer, { fillStyle: "black", scale: 1.0 },200); }, mouseup: function(layer){ context(index,layer.x,layer.y); } }); }); } 

Thank you for your time :-)

3991107 0

You should not be using HTML Entities in XML. Using normal UTF-8 characters should be fine.

The occurrence of Osnabrück means that at some point, most likely, the city name is processed as ISO-8859-1 instead of UTF-8. It is not htmlentities()'s fault. You need to find that point and fix it.

8772833 0

You are just passing that function a string. For it to make any sense of that, it would have to parse the string to split up the key/value pairs. I'm not saying it's the best approach, but if you want to do that, you should use parse_str().

Note that this is not by any means a language feature of PHP, but I am just providing a means to handle what you've shown.

9716871 0

Try this

 return Fluently.Configure().Database(MsSqlConfiguration.MsSql2008 .ConnectionString(@"Data Source=CHRIS-PC\\SQLEXPRESS;Initial Catalog=TestDB;User ID=test")) .Mappings(m => m.AutoMappings.Add(model)) .ExposeConfiguration(BuildSchema) .BuildSessionFactory(); 

or use this let mymodel be a sample model

 Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString(ConfigurationManager.ConnectionStrings["CHRIS-PC\\SQLEXPRESS"].ConnectionString)) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<mymodel>().Add<UsersMap>()) .ExposeConfiguration(cfg => { new SchemaExport(cfg).Execute(false, true, false); // new SchemaUpdate(cfg).Execute(true, true); }).BuildSessionFactory(); 
16583017 0

For formatting options, see this

Dim v1 as Double = Val(txtD.Text) / Val(txtC.Text) * Val(txtF.Text) / Val(txtE.Text) txtA.text = v1.ToString("N2"); 
11855579 0

STL containers in VS Debug are notoriously slow. Game programmers forums are rife with complaints about this. Often people choose alternative implementations. However, from what I've read, you can get a performance boost up front by disabling iterator debugging/checking:

#define _HAS_ITERATOR_DEBUGGING 0 #define _SECURE_SCL 0 

Other things that can affect debug performance are excessive calls to new and delete. Memory pools can help with that. You haven't provided details for PropMsg::add_v_var_repeated() or PropMsg::~PropMsg(), so I can't comment. But I assume there's a vector or other STL container inside that class?

28081273 0 How do I change only background color of ProgressDialog without affecting border in Android?

I used the following code to change the background of Progress Dialog. But the color changes on the outside frame too as below. I want to change only inside the dialog.

<style name="StyledDialog" parent="@android:style/Theme.Panel"> <item name="android:background">#083044</item> </style> 

enter image description here

As per the answer given at this question Change background of ProgressDialog

<style name="StyledDialog" parent="@android:style/Theme.Dialog"> <item name="android:alertDialogStyle">@style/CustomAlertDialogStyle</item> <item name="android:textColorPrimary">#000000</item> </style> <style name="CustomAlertDialogStyle"> <item name="android:bottomBright">@color/background</item> <item name="android:bottomDark">@color/background</item> <item name="android:bottomMedium">@color/background</item> <item name="android:centerBright">@color/background</item> <item name="android:centerDark">@color/background</item> <item name="android:centerMedium">@color/background</item> <item name="android:fullBright">@color/background</item> <item name="android:fullDark">@color/background</item> <item name="android:topBright">@color/background</item> <item name="android:topDark">@color/background</item> </style> 

This code gives background color perfect. But since, dialog color and activity's background color is same. It appears like transparent with no border. I want some border as before.

enter image description here

4010166 0 prevent url tampering in php

This is a test engine application with 5 papers set by me..as 5 php pages

Flow of the application

Login.html

check.php // to check whether credentials r right

if correct then

main.php //user clicks on "take test" in this page which displays him 1 of the 5 papers...

but once i am logged in i can just change the url to the url of the test paper i want..the paper names r 1.php 2.php....

how do i stop this...??

if(!isset($_SESSION['page'])//Tp continue; //Tp else { header('Location:login.php'); exit; } //Tp $_SESSION['page']=$_SERVER['SCRIPT_NAME'];//tp 

is this correct...as i said there are 5 pages....

in eac page i have this code....

i check whether the Session variable is set....if it is set...it means it already has visited the page.....but this code doesnt work...did i use the variable _SESSION['page'] before declaring it???

40054572 0

When you avoid of using the with_message method on the matcher then it uses default message.

To make your test works you should override the matcher's default message:

it { should validate_uniqueness_of(:name).with_message("has already been taken") } 
13240740 0

Microsoft's documentation is of limited use, once you move off Windows. Their discussion of the ODBC APIs is fine -- but anything about Visual Studio or other Windows-specific components should generally be ignored.

iODBC.org can provide some pointers -- especially if you look into the source for iODBC Demo.app and/or iODBC Test.command, which ship with the free and open source iODBC SDK.

You may also benefit from developing and testing with a commercially-supported ODBC driver, such as my employer's offering.

2206099 0

I've found a solution.

I can apply system theme for that single element in the resource, something like this:

<ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/PresentationFramework.Aero;V3.0.0.0;31bf3856ad364e35;component\themes/aero.normalcolor.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> 
28839744 1 Convert XML to string to find length

I am trying to find the length of an XML document and would like to know how to convert an XML document into a string so that I can find its length.

4804176 0

You could use a not exists clause to ensure the combination has not been voted on:

select a.itemId , b.itemId from Items a join Items b on a.ItemId < b.ItemId where not exists ( select * from Vote where userId = 42 and ((betterItemId = a.ItemId and worseItemId = b.ItemId) or (worseItemId = a.ItemId and betterItemId = b.ItemId)) ) order by rand() limit 2 
12284347 0

In the CMSButton you set base.BackColor, but in CMSLabel you set this.BackColor, which has no code in the setter.

19137295 0

Strictly by the standard type-punning expect in narrow circumstances is undefined behavior but in practice many compilers support it for example gcc manual points here for type-punning and under -fstrict-aliasing section is says:

The practice of reading from a different union member than the one most recently written to (called “type-punning”) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type.

I would recommend reading Understanding Strict Aliasing if you plan on using type-punning a lot.

y.b has the value b since all the elements of the union share memory and you initialized y with 100 which in ASCII is b. This is the same reason why the other fields of x change when you modify one including the case of strcpy and depending on your compiler this may be undefined or well defined(in the case of gcc it is defined).

For completeness sake the C++ draft standard section 9.5 Unions paragraph 1 says(emphasis mine):

In a union, at most one of the non-static data members can be active at any time, that is, the value of at most one of the non-static data members can be stored in a union at any time. [ Note: One special guarantee is made in order to simplify the use of unions: If a standard-layout union contains several standard-layout structs that share a common initial sequence (9.2), and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members; see 9.2. —end note ] The size of a union is sufficient to contain the largest of its non-static data members. Each non-static data member is allocated as if it were the sole member of a struct.

29624392 0

What you could do is, use the Coding4Fun Toolkit and use the control to display the current memory use and peak memory while developing your app. So download the Toolkit and add the correct dlls to your project. You can also use NuGet.

Now you can add this to your layout:

<coding4fun:MemoryCounter xmlns:coding4fun="clr-namespace:Coding4Fun.Phone.Controls;assembly=Coding4Fun.Phone.Controls"/> 

Or declare it in C#:

public MainPage() { InitializeComponent(); MemoryCounter counter = new MemoryCounter(); this.ContentPanel.Children.Add(counter); } 

Now you should see two numbers on the top of your screen when you launch it.

enter image description here

You can see the MemoryCounter results only in DEBUG mode!

Otherwise check the DeviceStatus class out, it has some useful things in it:

namespace Microsoft.Phone.Info { public static class DeviceStatus { public static long ApplicationCurrentMemoryUsage { get; } public static long ApplicationPeakMemoryUsage { get; } public static long ApplicationMemoryUsageLimit { get; } public static long DeviceTotalMemory { get; } } } 

To see how to use it check this out!

Hope it helps!

7753989 0

Yes, you have to create the product id for every product you wish to put on the app store. Apple checks each and every purchase made by the user on the basis of the product id you create on iTunes Connect.

18155087 0 intellij Debugger is not able to connect with Remote VM

I am working on a JNLP based application which is hosted on JBOSS server. My IDE is intellij . When I tried to do the remote debug on the port defined for that the on Debug console of intellij this message is written

Connected to the target VM, address: 'camelot-dev.kwcorp.com:8787', transport: 'socket' 

from this message, I thought that I am connected with the Remote VM and I jumped into the workspace for debugging but nothing seems to be working for me. When I clicked on F6 and respective buttons for debugging nothing seems to working (no debug happened). I checked the debug port and it is correct. I am not sure that whether I am doing the correct thing or not.

37712436 0

Your plunkr wasn't working because your script tag was pointing to a not existing app.js in index.html after re-naming script.js to app.js the plunkr is working.

Your JSON mock seems a bit complicated. You can easily add a json file to the plunkr and load it with a $http.get() request.

Please have a look at the demo below and this updated plunkr.

// Code goes here /* var mockDataForThisTest = "json=" + encodeURI( JSON.stringify([ { name: "Dave", email: "dave@gmail.com", option: "Home", number: "1234567890" }, { name: "John", email: "jon@gmail.com", option: "Home", number: "1234567890" } ]));*/ var app = angular.module('angularApp', []); app.controller('MainCtrl', function($scope, $http) { $scope.choices = []; loadChoices(); function loadChoices() { var httpRequest = $http({ method: 'GET', url: 'https://www.mocky.io/v2/5758817a130000f82d896c76' //url: './example.json' //data: mockDataForThisTest }).then(function(response) { //success(function(data, status) { // use then --> newer syntax console.log(response.data); $scope.choices = response.data; }); }; $scope.addNewChoice = function() { var newItemNo = $scope.choices.length + 1; $scope.choices.push({ 'id': 'choice' + newItemNo }); }; $scope.removeChoice = function(index) { //var lastItem = $scope.choices.length - 1; $scope.choices.splice(index, 1); //lastItem); }; });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <div ng-app="angularApp" ng-controller="MainCtrl"> <fieldset data-ng-repeat="choice in choices"> <input type="text" ng-model="choice.name" name="" placeholder="Enter name"> <input type="text" ng-model="choice.email" name="" placeholder="Enter email"> <input type="text" ng-model="choice.number" name="" placeholder="Enter mobile number"> <select ng-model="choice.option"> <option value>Select</option> <option value="Mobile">Mobile</option> <option value="Office">Office</option> <option value="Home">Home</option> </select> <button class="remove" ng-click="removeChoice($index)">-</button> </fieldset> <button class="addfields" ng-click="addNewChoice()">Add fields</button> <div id="choicesDisplay"> {{ choices }} </div> </div>

11566417 0

The problem is that the browser is downloading the image when you first reference it, and not before.

I'd simply have two image elements and hide/show them instead of changing the src attribute of a single element.

32030396 0

The documentation is pretty clear. You cannot use this property on characteristics you publish. The purpose of this value is to enable you to interpret the properties of characteristics that are discovered from other peripherals.

If you want to advise centralised that your value has changed then notify is the appropriate method.

8334450 0

Note: This method is automatically called by JavaScript whenever a Date object needs to be displayed as a string.

So d+'' is the same as d.toString().

4092645 0 Store metadata "CurrentBind" is not valid. Error

In the context of a click-once application that is being debugged locally with exception breaking on "Thrown" turned on in VS2010, I am experiencing the following error:

Deployment Exception: "Store metadata "CurrentBind" is not valid." at System.Deployment.Application.ComponentStore.GetPropertyString(DefinitionAppId appId, String propName) 

when I execute the following line of code:

if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed) 

This exception is being caught and handled by .net code, and the application will not crash after experiencing this error. Unfortunately, this error is followed up by:

InvalidDeploymentException: "Application is not installed" at System.Deployment.Application.ApplicationDeployment..ctor(String fullAppId) 

If I continue to wade through the exceptions, I get another error:

SynchronizationLockException: "Object synchronization method was called from an unsynchronized block of code" at Microsoft.Practices.Unity.SynchronizedLifetimeManager.TryExit() @ ProvidedContainer.RegisterInstance(LoggerFacade); 

and finally:

ConfigurationErrorsException: "This element is not currently associated with any context" at System.Configuration.ConfigurationElement.get_EvaluationContext() 

in the constructor of

[System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class InfrastructureDataServiceClient : System.ServiceModel.ClientBase<Infrastructure.DataServices.IInfrastructureDataService>, Infrastructure.DataServices.IInfrastructureDataService { public InfrastructureDataServiceClient() { } } 

These errors are all handled by the .net framework code and don't ripple into the application, but as long as I have the option to break on exception "Thrown" I continue to go through these errors until I lose patience and choose to break only on unhandled exceptions, at which point the app fully loads.

This has happened to me in the past, and at that time I had to completely re-install visual studio, but it worked fine after that. I'd rather not do that, as it is time consuming and my VS installation is pretty customized. Also, my co-workers are not experiencing the same error, so that tells me that there is something unique about my environment.

I experienced a visual studio hang recently when debugging, and had to kill the devenv process, that might play a role, but it's hard to say because I recently turned on the break on thrown option. I've already tried to delete the suo files, but that had no effect.

I have the following addons installed: Resharper, .Net Reflector, Team Explorer, TFS Power Tools, Theme Manager

5684415 0

(1) The stack is actually only local to expressionParser so I KNOW I can remove the new keyword

correct

(2) Do I HAVE To create a pointer to the queue in this case. If I need to create the pointer, then I should call a delete output in my query function to properly get rid of the queue?

correct. Here, "creating pointer" doesn't mean again using new and copy all contents. Just assign a pointer to the already created queue<string>. Simply delete output; when you are done with it in your query().

(3) vector being returned by query. Should that be left as I have it or should it be a pointer and what's the difference between them?

I would suggest either you pass the vector<Line*> by non-const reference to your query() and use it or return a vector<Line*>* from your function. Because difference is, if the vector is huge and return by value then it might copy all its content (considering the worst case without optimization)

(4) Once I consume that vector (display the information in it) I need it to be removed from memory, however, the pointers contained in the vector are still good and the items being pointed to by them should not be deleted. What's the best approach in this case?

Pass the vector<Line*> into the function by reference. And retain it in scope until you need it. Once you are done with pointer members 'Line*inside it, justdelete` them

(5) What happens to the contents of containers when you call delete on the container? If the container held pointers?

Nothing happens to the pointer members of the container when it's deleted. You have to explicitly call delete on every member. By the way in your case, you can't delete your vector<Line*> because it's an object not a pointer & when you delete output;, you don't have to worry about contents of queue<> because they are not pointers.

(6) Those pointers are deleted won't that affect other areas of my program?

Deleting a valid pointer (i.e. allocated on heap) doesn't affect your program in any way.

8588334 0

The center of a view is expressed in it's superview's coordinate system. So you are centering your image view in the wrong coordinate system. (dynamic view's superview as opposed to dynamic view)

To centre view A within view B, the centre point of view A has to be the centre of the bounds rectangle of view B. You can get this using (from memory!) CGRectGetMidX and CGRectGetMidY.

9625734 0

You are trying to do too much in the main method. You need to break this up into more manageable parts. Write a method boolean isPrime(int n) that returns true if a number is prime, and false otherwise. Then modify the main method to use isPrime.

37425524 0 Problems in building a gradle project on Intellij Idea

I'm having problems when trying to build a proyect on Intellij Idea. There are 2 problems:

So, which is the best way to create a gradle project, or, how can I solve this problems?

Thanks

30769109 0

If using uWSGI, there is a command line option which allows you to say you are providing it with a module path instead of a file path. For standard Apache with mod_wsgi, or with uWSGI defaults, you can create a WSGI script file which imports the WSGI application from your module by its path into the WSGI script file and then refer to that WSGI script file. If using mod_wsgi-express, then it has an option like uWSGI which allows you to say you are providing it with a module path instead.

38539650 0 Google map not load completely and rending error

I have one problem with google map, I used https://ngmap.github.io/#/!places-auto-complete.html.

I split my web app into multiple tabs and turn catch it by ng-if.

Currently in the main tab, I can google map fully loaded, but in others, it fails tab as shown below. The first image is the main tab, it's okay. But the 2nd picture is faulty, somebody please tell me why and how to fix me, please In tab Dashboard, google map is okay, but in tab Manage it does not load completely.

enter image description here

30409981 0 How to allow access to a file for a specific domain and block for other domain in Apache2.conf?

I have blocked the access to a file in apache configuration by editing the .conf file. For now, only localhost can access the files. Is there a way where i can access the files if it requested from a specific domain name or if requested by query string parameters.

Apache.conf -

Order allow,deny Allow from 127.0.0.1

13279307 0

Cast the obj to type of the return.

For example if your expected return type is PdsLongAttrImpl

Then, it would be:

PdsLongAttrImpl pdsObj = (PdsLongAttrImpl)obj; 

//Then perform operation on pdsObj.

NOTE: If obj is not of the type you are casting to, you will end up with ClassCastException.

29589230 0 Why wont my loop within a loop in Javascript work?

This is suppose to store the chosen answer for multiple questions. When I use this code, it only checks the first question and disregards the other questions.

 for(i = 0; i < questions.length-1; i++){ radios = document.getElementsByName(questions[i]); for (var t = 0; length < radios.length; t++) { if (radios[t].checked) { var qResults = JSON.parse(localStorage["qResults"]); num = radios[t].value; checked = num.toString(); var temp = (id[0] + ";" + questions[i] + ";" + checked); alert(temp); qResults.push(temp); localStorage["qResults"] = JSON.stringify(qResults); } } alert("question finished"); } 
13264230 0 What is the difference between named and optional parameters in Dart?

Dart supports both named optional parameters and positional optional parameters. What are the differences between the two?

Also, how can you tell if an optional parameter was actually specified?

25979649 0 dgrid editor with a dijit.form.Select

I have a column in my dgrid that uses a digit.form.Select.

var gl = {}; gl.coverTypeEditorData = [{label: "C", value: "C"}, {label: "F", value: "F"}, {label: "G", value: "G"}, {label: "S", value: "S"}, {label: "P", value: "P"}]; ... ,editor({ 'label': 'Type', 'field': 'TYPE', 'editor': Select, 'editorArgs': { options: gl.coverTypeEditorData } } ) 

The select drop down displays the correct value, but when it closes the value in the cell gets changed to whatever value was last chosen.

Row 1: Change the value to S.
Row 2: Has value C. I select the dd but do not change the value. Display changes to S. Change row event does not fire. The cell has a S displaying but its actual value is C, which will be the selected value if I open the drop down again.

What do I need to add to get the cell to display the correct value?

36282002 0 Handling option groups in Access form- runtime error 2427

I have an option group on a form. I want the form to process code based on which button is selected. The snippet I have for now is:

If Me.Option18.Value = True Then DoCmd.OpenQuery "Logbook Query all available" End If 

Option 18 is the radio button on the form.
On the If line, I get 'run time error 2427: You entered an expression that has no value'

I tried different uses of me.option 18, and get the same error. I also tried replacing 'true' with 1, same result.

Is there a better way to execute code based on an option group selection. or is this simply a syntax error?

19122892 0

If you want to know if an object property exists, regardless of its value, you can use property_exists.

if (property_exists($model, $column) { ... } 
36524426 0

I think that the best way to do it is to overriding the default ExceptionController. Just extend it, and override the findTemplate method. Check from the request's attribute if there's _route or _controller set, and do something with it.

namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController; class ExceptionController extends BaseExceptionController { protected function findTemplate(Request $request, $format, $code, $showException) { $routeName = $request->attributes->get('_route'); // You can inject these routes in the construct of the controller // so that you can manage them from the configuration file instead of hardcode them here $routesAdminSection = ['admin', 'admin_ban', 'admin_list']; // This is a poor implementation with in_array. // You can implement more advanced options using regex // so that if you pass "^admin" you can match all the routes that starts with admin. // If the route name match, then we want use a different template: admin_error_CODE.FORMAT.twig // example: admin_error_404.html.twig if (!$showException && in_array($routeName, $routesAdminSection, true)) { $template = sprintf('@AppBundle/Exception/admin_error_%s.%s.twig', $code, format); if ($this->templateExists($template)) { return $template; } // What you want to do if the template doesn't exist? // Just use a generic HTML template: admin_error.html.twig $request->setRequestFormat('html'); return sprintf('@AppBundle/Exception/admin_error.html.twig'); } // Use the default findTemplate method return parent::findTemplate($request, $format, $code, $showException); } } 

Then configure twig.exception_controller:

# app/config/services.yml services: app.exception_controller: class: AppBundle\Controller\ExceptionController arguments: ['@twig', '%kernel.debug%'] 

# app/config/config.yml twig: exception_controller: app.exception_controller:showAction 

You can then override the template in the same way:

UPDATE

A simpler way to do this is to specify the section of the website inside the defaults collection of your routes. Example:

# app/config/routing.yml home: path: / defaults: _controller: AppBundle:Main:index section: web blog: path: /blog/{page} defaults: _controller: AppBundle:Main:blog section: web dashboard: path: /admin defaults: _controller: AppBundle:Admin:dashboard section: admin stats: path: /admin/stats defaults: _controller: AppBundle:Admin:stats section: admin 

then your controller become something like this:

namespace AppBundle\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Bundle\TwigBundle\Controller\ExceptionController as BaseExceptionController; class ExceptionController extends BaseExceptionController { protected function findTemplate(Request $request, $format, $code, $showException) { $section = $request->attributes->get('section'); $template = sprintf('@AppBundle/Exception/%s_error_%s.%s.twig', $section, $code, format); if ($this->templateExists($template)) { return $template; } return parent::findTemplate($request, $format, $code, $showException); } } 

And configure twig.exception_controller in the same way as described above. Now you just need to define a template for each section, code and format.

11499101 0 Open a text file with vb.net , and if it exists delete that file

I am writing code for a windows application using vb.net. I want to open a text file under c:\. If the file already exists I want to delete that file.

my code ------- Dim file As String = "C:\test.txt" If System.IO.File.Exists(file) Then file.Remove(file) Else System.Diagnostics.Process.Start(file) End If 

I am getting the following error when I try to open that file.

error ----- The system cannot find the file specified 
34577849 1 Getting value of an HiddenField inserting it from template - Flask

I'm a newbie in Python/Flask programmation and I'm having some problems to return the value of my HiddenField inserting it from my template.

This my Form Class:

class DownloadForm(Form): link = HiddenField() download = SubmitField('Download') 

And this is my template "Material" with a table in which I put my materials from DB and where I'm trying to put the value of the HiddenField:

 <tbody> {% for mat in materials %} <tr> <td>{{ mat.author }}</td> <td>{{ mat.title }}</td> <td>{{ mat.subject }}</td> <td>{{ mat.description }}</td> <td>{{ mat.faculty }}</td> <td>{{ mat.professor }}</td> <td> <select class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </td> <form method="POST" enctype="multipart/form-data" action={{url_for('download')}}> {{ formDownload.link(value = '{{mat.link}}')}} <td>{{ formDownload.download }}</td> </form> <td>{{ formDelete.delete }}</td> </tr> {% endfor %} </tbody> </table> 

The problem is in this line of code where I would like to insert the HiddenField value.

{{ formDownload.link(value = '{{mat.link}}')}} 

I want to insert the value here because every SubmitField is linked with a specific row of the table. The variable mat.link contains the url of the material that users want to download but I can't get this value with the function form.request['link'].

Here there's my function download when form is submitted:

@app.route('/download', methods=['GET', 'POST']) def download(): form = DownloadForm(csrf_enabled=False) if form.validate_on_submit(): link = request.form['link'] return redirect(url_for('download', filename=link)) 

I've tried to debug my application and the variable link results equal to "mat.link" as a string . Can someone help me please ? Thanks

31093166 0 Polymer 1.0 Dom-Repeat Bind Array

In my try to update to Polymer 1.0 I got the following problem with Data-Binding:

My Polymer 0.5 Webapp uses a Repeat-Template to generate Checkboxes for some Categories. All checked values are bound to an array (sortedCatsArray) with the category-ids as key. Here is my first attempt to update that part to Polymer 1.0, but it doesn't work...

 <template is="dom-repeat" items="{{sortedCatsArray}}" as="category"> <paper-checkbox for category$="{{category.id}}" checked="{{filterChkboxes[category.id]}}"></paper-checkbox> </template> 

As you may read in the docs, it is no longer possible to bind to Array-Properties with square-brackets (now that way: object.property). May anybody tell me if it's still possible to bind all generated checkbox-values in one array?

Update #1

As you may read in the docs, Array-Binding by index is not supported. So I tried to use that example from the docs for my case and wrote the following code. If I run this code, it seems to work as expected: the first and third checkbox is checked. But I also want the array to be changed if I manual check/uncheck a checkbox. That does not happen, only if I change the array (in the ready-function) the checkbox gets checked...

<dom-module id="my-index"> <link rel="import" type="css" href="/css/index.css"> <template> <template is="dom-repeat" items="{{sortedCatsArray}}" as="category"> <paper-checkbox for category$="{{category.id}}" checked="{{arrayItem(filterChkboxes.*,category.id)}}" on-change="test"></paper-checkbox> </template> </template> </dom-module> <script> Polymer({ is: "my-index", properties: { filterChkboxes: { type: Array, notify: true, observer: "filterChkboxesChanged", value: function(){return[true,false,true,false];} }, sortedCatsArray: { type: Array, value: function(){return[{id: 0}, {id: 1},{id: 2},{id: 3}]}, notify: true }, }, ready: function(){ this.set('filterChkboxes.1',true); }, test: function(){ console.log(this.filterChkboxes); }, observers: [ 'filterChkboxesChanged(filterChkboxes.*)' ], arrayItem: function(array, key){ return this.get(key, array.base); }, filterChkboxesChanged: function(changes){ console.log(changes); }, }); </script> 
31041329 0 Kendo combobox not show the Text corresponding to value from modal

I have a partial view with a combobox. When try to render partial view with modal(contains data from database), it shows only the value field. i want to show the text field of that value field. Help me please.

@(Html.Kendo().ComboBoxFor(m => m.divCode) .DataTextField("Name") .DataValueField("ID") .HtmlAttributes(new { style = "width:160px" }) .SelectedIndex(0) .AutoBind(false) .Placeholder("Select Div Code") .Filter(FilterType.Contains) .DataSource(source => { source.Read(read => { read.Action("GetDivision", "AssetTransaction"); }); }) ) 
36286882 0 need to create one sample app using google app engine

I need to integrate Google app engine to use as back end for iOS app .

I have tried following the Link But I wasnt able to complete it .

Can AnyOne Please guide me the step to convert the Parse database back end to Google App Engine as back end .

Kindly guide the proper way .

Thanks

38872477 0

Then you can't use a form-level setting.

If this is constant (the fields are always locked), simply set all other controls to Locked = True.

If it's dynamic, use a procedure like this:

Private Sub SetEditable(EnableEdit As Boolean) Dim ctl As Control For Each ctl In Me.Controls ' The main editable control types (add more if they occur on your form) If ctl.ControlType = acTextBox Or ctl.ControlType = acComboBox Or _ ctl.ControlType = acCheckBox Or ctl.ControlType = acSubform Then If ctl.Name = "MySpecialDateField" Then ' Always editable ctl.Locked = False Else ctl.Locked = Not EnableEdit ' If you want to provide a visual feedback: ' 0 = Flat (locked), 2 = Sunken (editable) ctl.SpecialEffect = IIf(EnableEdit, 2, 0) End If End If End If Next ctl End Sub 
22534739 0

The panel's update function expects a HTML string instead of a DOM object:

// using a HTML string Ext.getCmp('treeContainer').update("<div class='NodeContent'>" + node.displayText + "</div>"); // using a DOM object Ext.getCmp('treeContainer').update(nodeDiv.outerHTML); 

Note, that using this function will always replace all existing HTML content in the panel.


If you really want to append HTML (i.e. preserve existing HTML content), you need to get a target element to append your HTML/DOM node to.

This could be the panel's default render target element:

var panel = Ext.getCmp('treeContainer'), renderEl = panel.isContainer ? panel.layout.getRenderTarget() : panel.getTargetEl(); // using a DOM node renderEl.appendChild(nodeDiv); // using a HTML string renderEl.insertHtml('beforeEnd', "<div class='NodeContent'>" + node.displayText + "</div>"); 

Or - as this may change depending on your panel's layout - you just create a containg element in your initial html config:

{ xtype: 'panel', id: 'treeContainer', html: '<div class="html-content"></div>' } 

and append your content there:

Ext.getCmp('treeContainer').getEl().down('.html-content').appendChild(nodeDiv); 

In any of the latter two cases, you should update the panel's layout afterwards, as you changed it's content manually:

Ext.getCmp('treeContainer').updateLayout(); 
23576794 0 When pasting into the console, spaces after command are causing issue

I have a simple line of code, with multiple readline commands that works just fine if I type it into the console directly, or paste it in from an existing R document without any excess spaces after the last bracket.

{ v1 <- readline("Choose 1: "); v2 <- readline("Choose 2: "); v3<- readline("Choose 2: ")} 

If I run the above line I will be asked to Choose 1, then Choose 2, then Choose 3. This example is simple, but it is how I like to enter a lot of my data.

But if I inadvertently copy some empty spacing after the line of code when copying from an R document, or the above line is included with other code like so:

X<-c(1,2,3,4,5) { v1 <- readline("Choose 1: "); v2 <- readline("Choose 2: "); v3<- readline("Choose 2: ")} Y<-c(1,2,3,4) 

All three readline commands will be printed at once, so that I can't enter my data in.

I've tried including the readline statements in a function, but I run into the same kind of problem with pasting spaces after the function call, causing the readline statements to all be printed out at once.

fun<-function(){ v1 <- readline("Choose 1: "); v2 <- readline("Choose 2: "); v3<- readline("Choose 2: ") } fun() Y<-c(1,2,3,4) 

The only luck I've had is to use source() to call a function from a separate R document, but I'm trying to avoid using source and keep everything in one R document. Ideally I'd like to be able to run multiple readline (or some other way to be asked to enter data), from a piece of code sandwiched in other code.

3123951 0 SQLite: How to calculate age from birth date

What is the best way to calculate the age in years from a birth date in sqlite3?

10693076 0

It is possible to "Publish" the results of the job. The response from the HTTP request can be written to the file server, and that will have the values of the last run job.

<cfschedule action = "update" task = "TaskName" operation = "HTTPRequest" url = "/index.cfm?action=task" startDate = "#STARTDATE#" startTime = "12:00:00 AM" interval = "Daily" resolveURL = "NO" requestTimeOut = "600" publish = "yes" path = "#PATH#" file = "log_file.log"> 

Then you can verify the log against the database if you wanted. Since it is the response from the page, you can get and store errors and warnings here as well.

6183877 0

Javascript Patterns is a good book to learn object oriented programming and advanced concepts in javascript.

4981227 0

This is on mac, I'm guessing? I'm not very familiar with compiling on mac.

Can you tell us how you're compiling (i.e. what compile flags, etc). And perhaps add an example which is compilable).

Also, can you compile this code using your environment?

#include "CLucene.h" int main(){ lucene::analysis::SimpleAnalyzer *sanalyzer = new lucene::analysis::SimpleAnalyzer(); } 

I compiled the above code with the following command with no problems. (-fPIC because i'm on an 64 bit machine).

g++ test.cpp -lclucene -I/usr/lib -fPIC

38905683 0 JSON DECODE using PHP

I am doing some JSON decodes - I followed this tutorial well explained - How To Parse JSON With PHP

and the PHP code, I used

 <?php $string='{"person":[ { "name":{"first":"John","last":"Adams"}, "age":"40" }, { "name":{"first":"Thomas","last":"Jefferson"}, "age":"35" } ]}'; $json_a=json_decode($string,true); $json_o=json_decode($string); // array method foreach($json_a[person] as $p) { echo ' Name: '.$p[name][first].' '.$p[name][last].' Age: '.$p[age].' '; } // object method foreach($json_o->person as $p) { echo ' <br/> Name: '.$p->name->first.' '.$p->name->last.' Age: '.$p->age.' '; } ?> 

It is working correctly... But my concern I need only details of Thomas' last name and age. I need to handle this to extract only certain features, not all the objects.

38442568 0 Problems with NSTokenView (again) - using objectvalue

In my Swift Application for Mac OS X, I'm using a NSTokenField. I'm using, among others, the delegate methods tokenField(tokenField: NSTokenField, representedObjectForEditingString editingString: String) -> AnyObject and tokenField(tokenField: NSTokenField, displayStringForRepresentedObject representedObject: AnyObject) -> String? to work with represented objects. My represented objects are instances of a custom class.

From the Apple Documentation, I know that objectValue can be used to access the represented objects of a NSTokenView as a NSArray:

To retrieve the objects represented by the tokens in a token field, send the token field an objectValue message. Although this method is declared by NSControl, NSTokenField implements it to return an array of represented objects. If the token field simply contains a series of strings, objectValue returns an array of strings. To set the represented objects of a token field, use the setObjectValue: method, passing in an array of represented objects. If these objects aren’t strings, NSTokenField then queries its delegate for the display strings to use for each token.

However, this doesn't seem to work for me. let tokenArray = self.tokenField.objectValue! as! NSArray does return a NSArray, but it is empty, even though the delegate method required to return a represented object has been called the appropriate amount of times before.

NSTokenView doesn't seem like a particularly strong tool to work with tokenization, but, lacking an alternative, I hope that you guys can help me making my implementation work.

Thanks in advance!

21929870 0 Error 410:gone (codenameone)

So I tried the tutorial Codenameone provided on JSON parsing, but now when i try it out it gives me a 410:gone error.

I did google the error but didn't find anything in combination with java or codenameone and i don't really understand the meaning of this error.

This error is not only in netbeans as i expected but even the on android it gives this error.

Code below is the action performed after clicking the "get twitter"-button:

public void actionPerformed(ActionEvent evt) { ConnectionRequest request = new ConnectionRequest() { @Override protected void readResponse(InputStream input) throws IOException { JSONParser parser = new JSONParser(); System.out.println(parser.parse(new InputStreamReader(input))); } }; request.setUrl("http://search.twitter.com/search.json"); request.setPost(false); request.addArgument("q", "@codenameone"); NetworkManager manager = NetworkManager.getInstance(); manager.start(); manager.addToQueue(request); } }); 
33373890 0

MySQLi is not a driver for PDO. It is a standalone class. PDO has the following drivers:

More information you can find here: http://php.net/manual/de/pdo.drivers.php
You have to remove the i from the dsn: mysql:host=127.0.0.1;dbname=app

13648622 0

You will need to identify what makes that data unique in the table. If it's a customer table, then it's probably the customerid of 13029. However if it's a customer order table, then maybe it's the combination of CustomerId and OrderDate (and maybe not, I have placed two unique orders on the same date). You will know the answer to that based on your table's design.

Armed with that knowledge, you will want to write a query to pull back the keys from the target table SELECT CO.CustomerId, CO.OrderId FROM dbo.CustomerOrder CO If you know the process only transfers data from the current year, add a filter to the above query to restrict the number of rows returned. The reason for this is memory conservation-you want SSIS to run fast, don't bring back extraneous columns or rows it will never need.

Inside your dataflow, add a Lookup Transformation with that query. You don't specify 2005, 2008 or 2012 as your SSIS version and they have different behaviours associated with the Lookup Transformation. Generally speaking, what you are looking to do is identify the unmatched rows. By definition, unmatched means they don't exist in the target database so those are the rows that are new. 2005 assumes every row is going to match or it errors. You will need to click the Configure Error Output... button and select "Redirect Rows". 2008+ has an option under "Specify how to handle rows with no matching entries" and there you'll want "Redirect rows to no match output."

Now take the No match output branch (2008+) or the error output branch (2005) and plumb that into your destination.

What this approach doesn't cover is detecting and handling when the source system reports $56.82 and the target system has $22.38 (updates). If you need to handle that, then you need to look at some change detection system. Look at Andy Leonard's Stairway to Integration Services series of articles to learn about options for detecting and handling changes.

38004053 0
function dividedByArray(data,low,high) { for (i=low; i<=high; i++) { var passed = 0; for(var curr in data) { if(i % data[curr] === 0) { passed++; } } switch(passed) { case data.length : console.log(i + 'all_match'); break; case 0 : console.log(i) break; default: console.log(i + " one_match"); } } } 
29969185 0

Found the solution. The problem was the labelunderscore div that was created in the page. This "confuses" the jquery library as whilst it applying the slide in effect, it has to apply the slide out effect on the same div.

The problem has been sorted by creating the labelunderscore div in the function at runtime and assigning it a unique id based on the id of the hovered element. Code as follows:

// Slide in effect for hover on class=head labels $(".head").hover(function () { //alert($(this).attr('id')) $('#main').append('<div id="labelunderscore_' + $(this).attr("id") + '" class="labelunderscore"></div>'); // Set width to hovering element width: $('#labelunderscore_' + $(this).attr("id")).css("width", $(this).width() + 20); // Set position on labelunderscore to current element left value $('#labelunderscore_' + $(this).attr("id")).css("left", $(this).offset().left); // Check where are we hovering. Left side slide from left right from right if ($(this).offset().left > $(window).width()/2) { // We are on the right side $('#labelunderscore_' + $(this).attr("id")).show('slide', {direction: 'right'}, 200); } else { // Left side $('#labelunderscore_' + $(this).attr("id") ).show('slide', {direction: 'left'}, 200); } }, function () { $('#labelunderscore_' + $(this).attr("id")).hide('slide', {direction: 'left'}, 200); }) 
1680067 0

I would recommend that you create another column in the database for arranging your items instead of using the OrderID - which is, I'm assuming here, may be used as a row identifier/ primary key for your database.

I'll give you a scenario.

Say you have the following items:

And you have added another item:

What if the user deletes Order ID 2 - Banana, and would want Order ID 4- Grapes to replace the deleted item in your list, how are you going to sort it by then? At least if you add another column, then you can preserve the sorting order for your items without touching your Order ID.

On the other hand, if the Order ID is not the primary key for your table and you have a different primary key, then by all means use the Order ID as your sorting column. Make sure that you implement unique index for the sorting column so that it could enhance your db as well as application performance.

To make your sorting a lot easier in .NET, you can use the classes in System.Collections.Specialized Namespace to sort your lists and want it for strongly-typed collections, i.e. Dictionary, OrderedDictionary, etc. because you will be using a key/value pair if you are implementing a sort order column.

Hope this helps!

26231138 0 Error in update ADT in Eclipse and IBM Worklight Studio

After update Android SDK I found this error message in Eclipse:

This Android SDK requires Android Developer Toolkit version 23.0.0 or above. Current version is 22.6.3.v201404151837-1123206. Please update ADT to the latest version.

In Stackoverflow are several very complete answer to this problem like here and here.
But I'm Working with Eclipse Kepler because is a requirement of IBM Worklight Studio.

Have I to update ADT to the latest version?
IBM Worklight still working afterwards?

24406553 0 Automatically send SCORM data to LMS

I have this code so far...

function sendData() { // this work out where I am and construct the 'cmi.core.lesson.location' variable computeTime(); var a = "" + (course.length - 1) + "|"; for (i = 1; i < course.length; i++) { a = a + qbin2hex(course[i].pages).join("") + "|"; if (iLP == 1) { a = a + course[i].duration + "|"; a = a + course[i].timecompleted + "|" } } SetQuizDetails(); a = a + course[0].quiz_score_running + "|0|0|0|0|0|0|"; objAPI.LMSSetValue("cmi.core.lesson_location", "LP_AT7|" + a); bFinishDone = (objAPI.LMSCommit("") == "true"); objAPI.LMSCommit(""); console.log("Data Sent!"); } setTimeout(sendData(), 1000); 

However, it doesn't seem to work as intented. Data should be sent off to the server every 1000ms, but that's not happening. What am I missing here?

As I side note, this is SCORM 1.2.

6673450 0

This is an example of an object literal.

It creates a normal object with two properties.

5411974 0

Check if the proc belongs to a different schema than expexted.

Something like myaccount.MyProc if it is expected to be dbo.MyProc

25664859 0

Do not do that: new FormInt64Control(). Just don't. Only create form controls using addControl.

To answer your question you need access to the C++ source code implementing the control. I do not have that access, nor do you.

12479124 0

No, there aren't any changes in respect to custom action filters. Assuming you have controller/actions decorated with this attribute the OnAuthorization will always be called.

9641029 0

You might be able to implement a DeviceAdminReceiver

From it's description it should be notified of failed password attempts but it's not really clear from the description if that includes lock screen attempts.

If that did work from a service or something you might be able to launch a toast though.


[Edit] Found a better resource

27854464 0 Unable to change label text after presenting the view controller programmatically in swift

I am presenting the a view programmatically in if else statement using this code:

if (Condition) { ..... } else { var vc = self.storyboard?.instantiateViewControllerWithIdentifier("gameover") as UIViewController self.presentViewController(vc, animated: true, completion: nil) finalMsg.text="Thank you" } 

So the view is getting changed but I am not able to change the text of label finalMsg which belongs to the view that I changed programmatically (gameover).

I am getting error "fatal error: unexpectedly found nil while unwrapping an Optional value"

Can someone help me on this?

19797247 0

Have a look at this article: HOW TO: Control Authorization Permissions in an ASP.NET Application

In short you can set folder permissions like this:

<configuration> <location path="images"> <system.web> <authorization> <deny users ="?" /> </authorization> </system.web> </location> </configuration> 
24999421 0

You can find source code in Appendix E of this paper explaining how to proceed for a variety of problems.

The code is reproduced below in case the paper becomes lost to the Internet:

function result = acorPTcg() %Archive table is initialized by uniform random % clear all nVar = 10; nSize = 50; %size nAnts = 2; fopt = 0; %Apriori optimal q=0.1; qk=q*nSize; xi = 0.85; maxiter = 25000; errormin = 1e-04; %Stopping criteria %Paramaeter range Up = 0.5*ones(1,nVar); %range for dp function Lo = 1.5*ones(1,nVar); %Initialize archive table with uniform random and sort the result from %the lowest objective function to largest one. S = zeros(nSize,nVar+1,1); Solution = zeros(nSize,nVar+2,1); for k=1:nSize Srand = zeros(nVar); for j = 1:nAnts for i=1:nVar Srand(j,i) = (Up(i) - Lo(i))* rand(1) + Lo(i); %uniform distribution end ffbest(j)=dp(Srand(j,:)); %dp test function end [fbest kbest] = min(ffbest); S(k,:)=[Srand(kbest,:) fbest]; end %Rank the archive table from the best (the lowest) S = sortrows(S,nVar+1); %Select the best one as the best %Calculate the weight,w %the parameter q determine which solution will be chosen as a guide to %the next solution, if q is small, we prefer the higher rank %qk is the standard deviation % mean = 1, the best on w = zeros(1,nSize); for i=1:nSize w(i) = pdf('Normal',i,1.0,qk); end Solution=S; %end of archive table initialization stag = 0; % Iterative process for iteration = 1: maxiter %phase one is to choose the candidate base one probability %the higher the weight the larger probable to be chosen %value of function of each pheromone p=w/sum(w); ref_point = mean(Solution(:,nVar+1)); for i=1:nSize pw(i) = weight_prob(p(i),0.6); objv(i)= valuefunction(0.8,0.8, 2.25, ref_point-Solution(i, nVar+1)); prospect(i) = pw(i)*objv(i); end [max_prospect ix_prospect]=max(prospect); selection = ix_prospect; %phase two, calculate Gi %first calculate standard deviation delta_sum =zeros(1,nVar); for i=1:nVar for j=1:nSize delta_sum(i) = delta_sum(i) + abs(Solution(j,i)- ... Solution(selection,i)); %selection end delta(i)=xi /(nSize - 1) * delta_sum(i); end % xi has the same as pheromone evaporation rate. Higher xi, the lower % convergence speed of algorithm % do sampling from PDF continuous with mean chosen from phase one and % standard deviation calculated above % standard devation * randn(1,) + mean , randn = random normal generator Stemp = zeros(nAnts,nVar); for k=1:nAnts for i=1:nVar Stemp(k,i) = delta(i) * randn(1) + Solution(selection,i); %selection if Stemp(k,i)> Up(i) Stemp(k,i) = Up(i); elseif Stemp(k,i) < Lo(i); Stemp(k,i) = Lo(i); end end ffeval(k) =dp(Stemp(k,:)); %dp test function end Ssample = [Stemp ffeval']; %put weight zero %insert this solution to archive, all solution from ants Solution_temp = [Solution; Ssample]; %sort the solution Solution_temp = sortrows(Solution_temp,nVar+1); %remove the worst Solution_temp(nSize+1:nSize+nAnts,:)=[]; Solution = Solution_temp; best_par(iteration,:) = Solution(1,1:nVar); best_obj(iteration) = Solution(1,nVar+1); %check stopping criteria if iteration > 1 dis = best_obj(iteration-1) - best_obj(iteration); if dis <=1e-04 stag = stag + 1; else stag = 0; end end ftest = Solution(1,nVar+1); if abs(ftest - fopt) < errormin || stag >=5000 break end end plot(1:iteration,best_obj); clc title (['ACOR6 ','best obj = ', num2str(best_obj(iteration))]); disp('number of function eveluation') result = nAnts*iteration; %%------------------------------------------------------------- function value = valuefunction(alpha, beta, lambda, xinput) value =[]; n = length(xinput); for i=1:n if xinput(1,i) >= 0 value(1,i) = xinput(1,i) ^ alpha; else value(1,i) = -lambda * (-xinput(1,i))^ beta; end end function prob = weight_prob(x, gamma) % weighted the probability % gamma is weighted parameter prob=[]; for i=1:length(x) if x(i) < 1 prob(i) = (x(i)^(gamma))/((x(i)^(gamma) + (1-x(i))^(gamma))^(1/gamma)); %prob(i) = (x(i)^(1/gamma))/((x(i)^(1/gamma) + (1-x(i))^(1/gamma))^(1/gamma)); else prob(i) = 1.0; end end function y = dp(x) % Diagonal plane % n is the number of parameter n = length(x); s = 0; for j = 1: n s = s + x(j); end y = 1/n * s; 
24336551 0 Charts in zend framework2

I am working with zend framework 2 and i want to display charts in some views but it doesn't work!! This is my Action:

public function statvehAction(){ $data = [ 'labels' => ["January","February","March","April","May","June","July"], 'data' => [18,99,30,81,28,55,30] ]; json_encode($data); $viewModel = new ViewModel(array('data' => $data)); return $viewModel; } 

this is my view:

<script src="../../../../jquery.min.js"></script> <script src="../../../../chart.min.js"></script> <script> (function($){ var ctx = document.getElementById("chart").getContext("2d"); $.ajax({ type: "POST", url: "VehiculesController.php", dataType: "json" }) .success(function(data) { var d = { labels: $data.labels, datasets : [ { fillColor: "rgba(220,220,220,0.5)", strokeColor: "rgba(220,220,220,1)", data: data.data }] }; var barChart = new Chart(ctx).Bar(d); }); })(jQuery); </script> 

But when i want to diplay my chart i got a white page whith no error !! Please can you help me to solve this problem.

22814123 0 How to correctly affect multiple css properties in jquery

Below is an example of how I currently would affect two css properties for the same div in jquery:

$('#mydiv').css("width",myvar+"px"); $('#mydiv').css("margin-left",myvar+"px"); 

I don't believe this to be the most efficient method as it requires two lines of code for one div, can somebody please show me a more susinct (tidier) method of writing the same thing?

38263641 0

It may be model update problem try this.

$scope.$apply(); 
900136 0

One way is to just have a copy of your database file (mdf) available for pushing onto a new server. This similiar to what microsoft does with it's Model database. Whenever you create a new database it starts by making a copy of that one.

Your button click could copy the database file to the desired location, rename it as appropriate, then attach it to the running sql server instance. Whenever you need to update the database with a new schema, just copy the mdf to your deployment directory.

17935206 0 How to layout correctly

I just try to create my own layout. I used UITableView for my UIViewController. I have some JSON response from server. This is like detailed publication. Also i calculate my UITableViewCell height because my publication contain mix of images and text. I wrote own layout and recalculate when device in rotation.

for (UIView * sub in contentSubviews) { if([sub isKindOfClass:[PaddingLabel class]]) { PaddingLabel *textPart = (PaddingLabel *)sub; reusableFrame = textPart.frame; reusableFrame.origin.y = partHeight; partHeight += textPart.frame.size.height; [textPart setFrame:reusableFrame]; } else if([sub isKindOfClass:[UIImageView class]]) { UIImageView * imagePart = (UIImageView *)sub; reusableFrame = imagePart.frame; reusableFrame.origin.y = partHeight; reusableFrame.origin.x = screenWidth/2 - imageSize.width/2; reusableFrame.size.width = imageSize.width; reusableFrame.size.height = imageSize.height; [imagePart setFrame:reusableFrame]; partHeight += imagePart.frame.size.height; } } 

But I have some issue. When device change orientation state UIScrollView offset is same as was. I don't know how to change it. Before rotation:

enter image description here

After rotation:

enter image description here

I want to save visible elements in rect. Suggest pls.

7389510 0

I also started to look at the MVC Music Store example.

40953020 0

You don't have an instance of elasticsearch running failing to get to server at localhost:9200 indicates that.

16297052 0 Replace a text with a variable (sed)

How can I do this?

sed -i 's/wiki_host/$host_name/g' /root/bin/sync 

It will replace wiki_host with the text $host_name. But i want to replace it with the content of the variable..

I tried it with

sed -i 's/wiki_host/${host_name}/g' /root/bin/sync 

It doesnt work too..

30050115 0

Use word boundaries:

Pattern p=Pattern.compile("\\b(1[0-9]|[0-9])\\b"); 
14768853 0

If you take a look into the Android.mk file of OpenSSH you'll find the following line:

LOCAL_MODULE_TAGS := optional 

This means that the module will be include into a build if the module name is listed in the appropriate make file (for instance, in a build/target/product/core.mk)

35942849 0

If you want to use just 1 transaction and more then one EJB method call, then 1., use the session facade design pattern. Create a facae bean with CMT (Container Managed Transaction) to call the other beans within its own transaction. 2., Use BMT (Bean Managed Transaction)

18281403 0

Try to use the "new" keyword instead of "override" and remove the "virtual" keyword from methods;)

2512863 0 Have you been in cases where TDD increased development time?

I was reading TDD - How to start really thinking TDD? and I noticed many of the answers indicate that tests + application should take less time than just writing the application. In my experience, this is not true. My problem though is that some 90% of the code I write has a TON of operating system calls. The time spent to actually mock these up takes much longer than just writing the code in the first place. Sometimes 4 or 5 times as long to write the test as to write the actual code.

I'm curious if there are other developers in this kind of a scenario.

34537143 0 SharedPreferences variable always returns false

I am using a Preference Fragments following the step by step guide on Android guide.

I am trying to set some preferences using this fragment, so later on the code I can check the value of each variable to perform actions accordingle.

Mi Preference fragment is working fine. However, when I try to recover the value of a CheckedBoxPreference somewhere else on the code, it always returns false.

This is the preference xml file :

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:persistent="true" > <PreferenceCategory android:title="NOTIFICACIONES" android:key="pref_key_storage_settings"> <CheckBoxPreference android:key="sendMail" android:defaultValue="false" android:persistent="true" android:summary="Send emails to contacts" android:title="E-mail"/> </PreferenceCategory> </PreferenceScreen> 

This is the class I've done to use SharedPReferences

public class Prefs{ private static Prefs myPreference; private SharedPreferences sharedPreferences; private static final String NOMBRE_PREFERENCIAS = "MisPreferencias"; public static Prefs getInstance(Context context) { if (myPreference == null) { myPreference = new Prefs(context); } return myPreference; } private Prefs(Context context) { sharedPreferences = context.getSharedPreferences(NOMBRE_PREFERENCIAS,context.MODE_PRIVATE); } public Boolean getBoolean(String key) { boolean returned = false; if (sharedPreferences!= null) { returned = sharedPreferences.getBoolean(key,false); } return returned; } } 

And this is how I check if the options is selected, so I can send/or not emails to clients

Prefs preferences = Prefs.getInstance(getApplicationContext()); if(preferences.getBoolean("sendMail") { // .... send email } 

As I said, what is strange is that It is persistent on the settings fragment ( if I select the option sendEmmail, it is selected even if I close the app and reopen it. However, when I check the value using my method, it always returns false.

What am I doing wrong?

Thank you

14857267 0 VS regex search: Find Try..Finally with no Catch

I want to use the Regular Expression search in Visual Studio to find all instances of a Try/Finally block without a Catch.

After reading the help file, I started with this which returns a match of Try without matching End Try.

~(End )Try\n 

Then, I wanted to get a match where there was Finally:

~(End )Try\n*Finally\n 

This actually doesn't work.

The full, working Regex, I assume would look something like this:

~(End )(Sub|Function)*~(End )Try\n*~(Catch*\n)*Finally\n*End (Sub|Function) 

That's try trying to say, within a Sub Or Function, return matches that have Try/Finally but no Catch.

Am I in the ballpark for accomplishing this search?

3998271 0

There is no difference in reading standard input from threads except if more than one thread is trying to read it at the same time. Most likely your threads are not all calling functions to read standard input all the time, though.

If you regularly need to read input from the user you might want to have one thread that just reads this input and then sets flags or posts events to other threads based on this input.

If the kill character is the only thing you want or if this is just going to be used for debugging then what you probably want to do is occasionally poll for new data on standard input. You can do this either by setting up standard input as non-blocking and try to read from it occasionally. If reads return 0 characters read then no keys were pressed. This method has some problems, though. I've never used stdio.h functions on a FILE * after having set the underlying file descriptor (an int) to non-blocking, but suspect that they may act odd. You could avoid the use of the stdio functions and use read to avoid this. There is still an issue I read about once where the block/non-block flag could be changed by another process if you forked and exec-ed a new program that had access to a version of that file descriptor. I'm not sure if this is a problem on all systems. Nonblocking mode can be set or cleared with a 'fcntl' call.

But you could use one of the polling functions with a very small (0) timeout to see if there is data ready. The poll system call is probably the simplest, but there is also select. Various operating systems have other polling functions.

#include <poll.h> ... /* return 0 if no data is available on stdin. > 0 if there is data ready < 0 if there is an error */ int poll_stdin(void) { struct pollfd pfd = { .fd = 0, .events = POLLIN }; /* Since we only ask for POLLIN we assume that that was the only thing that * the kernel would have put in pfd.revents */ return = poll(&pfd, 1, 0); } 

You can call this function within one of your threads until and as long as it retuns 0 you just keep on going. When it returns a positive number then you need to read a character from stdin to see what that was. Note that if you are using the stdio functions on stdin elsewhere there could actually be other characters already buffered up in front of the new character. poll tells you that the operating system has something new for you, not what C's stdio has.

If you are regularly reading from standard input in other threads then things just get messy. I'm assuming you aren't doing that (because if you are and it works correctly you probably wouldn't be asking this question).

6659250 0

protobuf.net has to maintain compatibility with the protobuf binary format, which is designed for the Java date/time datatypes. No Kind field in Java -> No Kind support in the protobuf binary format -> Kind not transferred across the network. Or something along those lines.

As it turns out, protobuf.net encodes the Ticks field (only), you'll find the code in BclHelpers.cs.

But feel free to add another field in your protobuf message definition for this value.

9369592 0

Given that a family tree application has more to do with relationships between entities than the entities themselves, modeling this in a relational database would be the better fit.

I release this does not answer your question, but at the end of the day we need to choose the most appropriate tool for the task.

32066748 0

The statement $scope.messages = messageOptions.slice(0, messageOptions.length); create a clone/copy of array and assigning it to $scope.messages

You can also achieve same using

 $scope.messages = messageOptions.slice(); 

Code to demonstrate

var messageOptions = [1, 2]; var messages = messageOptions.slice(0, messageOptions.length); //Update messageOptions[0] = 100; snippet.log("messages: " + JSON.stringify(messages)); snippet.log("messageOptions: " + JSON.stringify(messageOptions));
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

34338418 0

Here's what I would do, making use of a Person class. It may not seem necessary right now given the scope of your project, but if the scope ever grows, using classes and instances will pay off. Plus, this way, you have the names to match the ages you're seeking which is probably going to be necessary at some point anyway.

public static List<Person> GetResults(string[] text) { var results = new List<Person>(); foreach(var line in text) { results.Add(Person.Parse(line)); } return results; } public class Person { public string Name { get; private set; } public int Age { get; private set; } public Person(string name, int age) { Name = name; Age = age; } public static Person Parse(string fromInputLine) { ValidateInput(fromInputLine); var delimPosition = fromInputLine.LastIndexOf(' '); var name = fromInputLine.Substring(0, delimPosition); var age = Convert.ToInt32(fromInputLine.Substring(delimPosition + 1)); return new Person(name, age); } private static void ValidateInput(string toValidate) { if (!System.Text.RegularExpressions.Regex.IsMatch(toValidate, @"^.+\s+\d+$")) throw new ArgumentException(string.Format(@"The provided input ""{0}"" is not valid.", toValidate)); } } 
10090013 0

This is a relly good tutorial about UIScrollView&IPageControl combination. But I my self look for a tutorail for more dynamic designs(like main page of ios applications-i increments-decrements automatically)

4108113 0 php fopen: failed to open stream: HTTP request failed! HTTP/1.0 403

I am receiving an error message in PHP 5 when I try to open a file of a different website. So the line

fopen("http://www.domain.com/somef­ile.php", r) 

returns an error

Warning: fopen(www.domain.com/somefile.php) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in D:\xampp\htdocs\destroyfiles\index.php on line 2

30911184 0 Running use ant in java

Both compilation and JAR file creation is sucessful.

Running java file through ant file is producing error.

<project> <target name="clean"> <delete dir="build"/> </target> <target name="compile"> <mkdir dir="build/classes"/> <javac srcdir="src" destdir="build/classes"/> </target> <target name="jar"> <mkdir dir="build/jar"/> <jar destfile="build/jar/Helloworld" basedir="build/classes"> <manifest> <attribute name="Main-Class" value="Helloworld"/> </manifest> </jar> </target> <target name="run"> <java jar="build/jar/Helloworld" fork="true"/> </target> </project> 

Buildfile: C:\Workspace\anttest\build.xml

run: [java] java.lang.NoClassDefFoundError: Helloworld [java] Caused by: java.lang.ClassNotFoundException: Helloworld [java] at java.net.URLClassLoader$1.run(URLClassLoader.java:202) [java] at java.security.AccessController.doPrivileged(Native Method) [java] at java.net.URLClassLoader.findClass(URLClassLoader.java:190) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:306) [java] at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) [java] at java.lang.ClassLoader.loadClass(ClassLoader.java:247) [java] Could not find the main class: Helloworld. Program will exit. [java] Exception in thread "main" [java] Java Result: 1 

BUILD SUCCESSFUL

4645070 0

This is happening because the user 'sarin' is the actual owner of the database "dbemployee" - as such, they can only have db_owner, and cannot be assigned any further database roles.

Nor do they need to be. If they're the DB owner, they already have permission to do anything they want to within this database.

(To see the owner of the database, open the properties of the database. The Owner is listed on the general tab).

To change the owner of the database, you can use sp_changedbowner or ALTER AUTHORIZATION (the latter being apparently the preferred way for future development, but since this kind of thing tends to be a one off...)

17732610 0

This is just the way it is. first and last are not a complementary pair of operations. last is more closely related to rest and nthcdr. There is also butlast which constructs a new list that omits the last item from the given list.

first versus last is nothing compared to how get and getf have nothing to do with set and setf.

31892188 0

You can overcome this easily by using the ChoiceMode option CHOICE_MODE_MULTIPLE for the ListView as used in the API Demo -

public class List11 extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, GENRES)); final ListView listView = getListView(); listView.setItemsCanFocus(false); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); } private static final String[] GENRES = new String[] { "Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama", "Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller" }; } 

EDIT Alternate for your context- Have an extra boolean object with your HashMap<String, Object> isChecked and initialize it to false when you populate your list.

Set your CheckBox in getView() method as-

check.setChecked(Boolean.parseBoolean(dataMap.get("isChecked")); 

Now in the listener OnCheckedChangeListener() set the value of your dataMap true or false accordingly.

29351130 0

JSON string values should be quoted and so should parameter expansions. You can achieve this by using double quotes around the entire JSON string and escaping the inner double quotes, like this:

curl -i -H "Content-Type: application/json" -X POST -d "{\"mountpoint\":\"$final\"}" http://127.0.0.1:5000/connect 
1784093 0 Get Application Pool Uptime in c#

Is there a way I can determine how long an application pool (in IIS7) has been up (time since started, or last restart) in c#?

7790366 0

If you run your regex snippet in a C# program, I have the solution for you:

Regex regex = new Regex(@"(?<=\{{1}[\s\r\n]*)((?<Attribute>[^}:\n\r\s]+):\s+(?<Value>[^;]*);[\s\r\n]*)*(?=\})"); regex.Replace(input, match => { var replacement = string.Empty; for (var i = 0; i < match.Groups["Attribute"].Captures.Count; i++) { replacement += string.Format(CultureInfo.InvariantCulture, "{0}: {1}\r\n", match.Groups["Attibute"].Captures[i], match.Groups["Value"].Captures[i]); } return replacement; }); 
39913248 0

OpenCV uses by default the now very uncommon BGR (blue, green, red) ordering of the color channels. Normal is RGB.

Why OpenCV Using BGR Colour Space Instead of RGB

This could explain the bad performance of the model.

29143825 0 No SCM URL was provided to perform the release from

I am trying to use maven release plugin and after that automate this using nexus.

Here is my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ozge.net</groupId> <artifactId>com.ozge.net</artifactId> <version>1.1- snapshot</version> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.5.1</version> <configuration> <tagBase>svn://local/exekuce/com.ozge.net</tagBase> </configuration> </plugin> </plugins> </pluginManagement> </build> <scm> <tag>HEAD</tag> <connection>scm:svn:svn://[svnusername]:[svn password]@local/exekuce/com.ozge.net</connection> <developerConnection>scm:svn:svn://[svnusername]:[svn password]@local/exekuce/com.ozge.net</developerConnection> <url>scm:svn:svn://[svnusername]:[svn password]@local/exekuce/com.ozge.net</url> </scm> <distributionManagement> <repository> <id>OzgeRelease</id> <url>http://localhost:8081/nexus/content/repositories/OzgeRelease</url> </repository> </distributionManagement> </project> 

after I ran the command mvn release:perform on command prompt

it says

No SCM URL was provided to perform the release from

I believe I provided.

Anybody here tried to maven-subversion-nexus-hudson for automating builds?

8087446 0

here you are

$("#bxs").on('click', 'li',function() { var exists = false for(var i=0;i<result.length;i++) { var item = result[i]; if(item.id == $(this).prop("id")) { exists = true; break; } } if(exists) { alert("exists"); } else { alert("doesn't exists"); } }); 
22901149 0
if ($contract['Contract']['contract_maandag'] = 1){ if ($contract['Contract']['contract_dinsdag'] = 1){ 

This won't work. You're doing an assignment (=), so it's always true. But you want a comparison (===). It is recommended to do always (except required otherwise) to use strict (===) comparison.

48508 0

I can only once again point to Stroustrup and preach: Don't teach the C subset! It's important, but not for beginners! C++ is complex enough as it is and the standard library classes, especially the STL, is much more important and (at least superficially) easier to understand than the C subset of C++.

Same goes for pointers and heap memory allocation, incidentally. Of course they're important but only after having taught the STL containers.

Another important concept that new students have to get their head around is the concept of different compilation units, the One Definition Rule (because if you don't know it you won't be able to decypher error messages) and headers. This is actually quite a barrier and one that has to be breached early on.

Apart from the language features the most important thing to be taught is how to understand the C++ compiler and how to get help. Getting help (i.e. knowing how to search for the right information) in my experience is the single most important thing that has to be taught about C++.

I've had quite good experiences with this order of teaching in the past.

/EDIT: If you happen to know any German, take a look at http://madrat.net/coding/cpp/skript, part of a very short introduction used in one of my courses.

6675225 0 Advantages of using Passenger + Apache over Webrick

I want to convince my management that using Apache + passenger setup is way to go on production rather than having webrick or mongrel

I have found some points from the net.

It would be great help if you could add your thoughts as that will defiantly help me to present my points. (technical details are welcome)

and It will great if you could send some links if you have any

thanks in advance

cheers

sameera

36609262 0

You have two class attributes on each of your menu items. The second one is being ignored by jQuery.

<a class="list-group-item allnotif" href="#allnotif"><strong>Alle Notificaties</strong></a> 

Working demo

33999562 0

You should use ArrayList rather than Vector. There is no simple way to convert though. One way is

ArrayList<String> list = new ArrayList<String>(); for (char a : x) list.add(String.valueOf(a)); 

Arrays.asList works for arrays of object references, not arrays of primitives like char.

If you are using Java 8, another way is

List<String> list = IntStream.range(0, x.length) .mapToObj(i -> String.valueOf(x[i])) .collect(Collectors.toList()); 
5093338 0

Thinking in high level, this is what I'd do:

Develop a decorator function, with which I'd decorate every event-handling functions.

This decorator functions would take note of thee function called, and its parameters (and possibly returning values) in a unified data-structure - taking care, on this data structure, to mark Widget and Control instances as a special type of object. That is because in other runs these widgets won't be the same instances - ah, you can't even serialize a toolkit widget instances, be it Qt or otherwise.

When the time comes to play a macro, you fill-in the gaps replacing the widget-representating object with the instances of the actually running objects, and simply call the original functions with the remaining parameters.

In toolkits that have an specialized "event" parameter that is passed down to event-handling functions, you will have to take care of serializing and de-serializing this event as well.

I hope this can help. I could come up with some proof of concept code for that (although I am in a mood to use tkinter today - would have to read a lot to come up with a Qt4 example).

15875144 0

use

 $this->m_user->delete($user_id); 

Instead

 $this->m_user->delete_user($user_id); 
9779994 0 I just need someone to help me with a tiny actionscript error

I've made the hourly wages calculator, but there is one problem: I can't get it to calculate anything, so if you were to use this program; you would add your name, hours worked and wages. once you click the button, at the bottom with have your results.

i'm trying to get it to say hi, "the person's name" you have this much... something like that.

can anyone help me?

thanks

here is my code:

button.mouseChildren = false button.addEventListener(MouseEvent.CLICK, onClick); } private function onClick(event:MouseEvent):void { this.results.text = "Hi, " } } } 
9628155 0

What i would do is look at it in an Object Oriented Perspective, which is what Java is all about. When i get stuck on a piece of code then i write it down. Think of what the objective of the code is.

It is all about how your code is structured, structure and true Object Orientation are the most important things in Java. When you stray from Object Oriented Design then you can run into problems that should never have existed.

978043 0

A module in the Python natural language toolkit (nltk) does naïve Bayesian classification: nltk.classify.naivebayes.

Disclaimer: I know crap all about Bayesian classification, naïve or worldly.

20799086 0

I finally chose to use websockets to solve my problem (with Ratchet). Like this, I can invoke my script from my browser passing the arguments I need to the executable file.

PHP in CLI doesn't seem to have any problem with exec() on .exe files.

32746403 0 Groovy script to transform xml to json

I have the following groovy script that transforms an xml into json.

http://stackoverflow.com/a/24647389/2165673

Here is my xml

<?xml version="1.0" encoding="utf-8"?> <Response xmlns=""> <ProgressResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <ErrorMessage>error </ErrorMessage> <IsSuccessful>false</IsSuccessful> </ProgressResult> </ProgressResponse> 

The JSON result i need is

{ "IsSuccessful" : "false", "ErrorMessage" : "Something Happened" } 

but i am getting the following http://www.tiikoni.com/tis/view/?id=b4ce664

I am trying to improve my groovy script but i just started using it and it has a steep learning curve. Can someone help direct me to the right direction?

Thanks!!

20498360 0 Android logcat errors on project

I'm trying to run a project in Android but it crashes upon trying to execute it: I don't really understand the logCat messages I get so I wanted to see if someone could help me out in understanding them.

Here are some of my errors:

FATAL EXCEPTION: MAIN java.lang.RunTimeException: Unable to start activity componentInfo (com.example.logger/com.example.logger.ThirdActivity):java.lang.RuntimeException: your content must have a ListView whose id attribe is 'android.R.id.list'; Caused by: java.lang.RuntimeException: your content must have a ListView whose id attribute is 'android.R.id.list'; at.com.example.logger.ThirdActivity.onCreate (ThirdActivity:java:18) 

Android Manifest

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.logger" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.logger.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.logger.SecondActivity" android:label="@string/title_activity_second" ></activity> <activity android:name="com.example.logger.ThirdActivity" android:label="@string/title_activity_third" > </activity> </application> </manifest> 

End manifest

Main Activity

package com.example.logger; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; public class MainActivity extends Activity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); attachHandlers(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private void attachHandlers() { findViewById(R.id.login).setOnClickListener(this); } @Override public void onClick(View arg0) { if(arg0.getId() == R.id.login) { Intent i = new Intent(this, SecondActivity.class); startActivity(i); } } 

}

End Main Activity

SecondActivity

package com.example.logger; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.widget.ImageView; import android.view.ViewGroup; public class SecondActivity extends Activity { private static final int NUM_PAGES = 10; private ViewPager mpager; private MyPagerAdapter mPagerAdapter; private int [] pics = {R.drawable.android_interfaz_layout_estructura_final, R.drawable.baixa, R.drawable.baixada, R.drawable.greenprogressbar, R.drawable.layout_keyboard, R.drawable.linerlay, R.drawable.merge1, R.drawable.o2zds, R.drawable.regbd, R.drawable.s7qrs}; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); mPagerAdapter = new MyPagerAdapter(null); mpager = (ViewPager) findViewById(R.id.viewer); mpager.setAdapter (mPagerAdapter); } public void showImage (int position, View view) { //View is your view that you returned from instantiateItem //and position is it's position in array you can get the image resource id //using this position and set it to the ImageView } private class MyPagerAdapter extends PagerAdapter { SecondActivity activity; public MyPagerAdapter (SecondActivity activity){ this.activity=activity; } @Override public int getCount() { // TODO Auto-generated method stub return pics.length; } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return false; } @Override public Object instantiateItem(View collection, int position) { ImageView view = new ImageView (SecondActivity.this); view.setImageResource (pics[position]); ((ViewPager) collection).addView(view, 0); return view; } @Override public void setPrimaryItem (ViewGroup container, int position, Object object) { super.setPrimaryItem (container, position, object); activity.showImage(position,(View)object); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.second, menu); return true; } private OnClickListener mPageClickListener = new OnClickListener() { public void onClick (View v) { // TODO Auto-generated method stub //aquí anirà la funció per traslladar la image de la gallery a la pantalla Integer picId = (Integer) v.getTag(); mpager.setVisibility(View.VISIBLE); mpager.setCurrentItem(v.getId()); } @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }; 

}

End Second Activity

Third Activity

package com.example.logger; import android.os.Bundle; import android.app.Activity; import android.app.ListActivity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; public class ThirdActivity extends ListActivity implements OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_third); final ListView listview = (ListView) findViewById(android.R.id.list); String[] values = new String[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_third, android.R.id.list, values); setListAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.third, menu); return true; } public void attachButton() { findViewById(R.id.add).setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub } 

}

End Third Activity

Activity_Main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity" > <Button android:id="@+id/login" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/Login" android:layout_alignParentBottom="true" android:background="@drawable/shapes" android:textColor="@color/text" /> <EditText android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/input_u" android:layout_marginTop="10dp" android:textColor="@color/text" /> <EditText android:id="@+id/password" android:layout_below="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/input_p" android:layout_marginTop="10dp" android:textColor="@color/text" /> </RelativeLayout> 

End Activity_Main.xml

Activity_Second.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".SecondActivity" > <android.support.v4.view.ViewPager android:padding="16dp" android:id="@+id/viewer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_weight="0.70" /> <ImageView android:id="@+id/big_image" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_below="@+id/viewer" android:layout_weight="0.30" /> </RelativeLayout> 

End Activity_Second.xml

**Activity_Third.xml** <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".ThirdActivity" > <Button android:id="@+id/add" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:text="@string/add" /> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_below="@+id/add" android:layout_height="wrap_content" ></ListView> </RelativeLayout> 

End Activity_Third.xml

I'd very grateful if someone could help me figure out what I'm doing wrong on this project.

Yours sincerely,

Mauro.

5198155 0 Not all tiles redrawn after CATiledLayer -setNeedsDisplay

My view has a CATiledLayer. The view controller has custom zooming behavior, so on -scrollViewDidEndZooming every tile needs to be redrawn. But, even though -setNeedsDisplay is being called on the layer after every zoom, not all tiles are being redrawn. This is causing the view to sometimes look wrong after a zoom. (Things that should appear in just 1 tile are appearing in multiple places). It often corrects itself after another zoom.

Here's the relevant code. updatedRects is for testing -- it stores the unique rectangles requested to be drawn by -drawLayer.

CanvasView.h:

@interface CanvasView : UIView @property (nonatomic, retain) NSMutableSet *updatedRects; @end 

CanvasView.m:

@implementation CanvasView @synthesize updatedRects; + (Class)layerClass { return [CATiledLayer class]; } - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context { CGRect rect = CGContextGetClipBoundingBox(context); [updatedRects addObject:[NSValue valueWithCGRect:rect]]; CGContextSaveGState(context); CGContextTranslateCTM(context, rect.origin.x, rect.origin.y); // ...draw into context... CGContextRestoreGState(context); } @end 

MyViewController.m:

@implementation MyViewController - (void)viewDidLoad { [super viewDidLoad]; canvasView.updatedRects = [NSMutableSet set]; } - (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale { canvasView.transform = CGAffineTransformIdentity; canvasView.frame = CGRectMake(0, 0, canvasView.frame.size.width * scale, canvasView.frame.size.height); [self updateCanvas]; } - (void)updateCanvas { NSLog(@"# rects updated: %d", [canvasView.updatedRects count]); [canvasView.updatedRects removeAllObjects]; canvasView.frame = CGRectMake(canvasView.frame.origin.x, canvasView.frame.origin.y, canvasView.frame.size.width, myHeight); CGFloat tileSize = 256; NSLog(@"next # rects updated will be: %f", [canvasView.layer bounds].size.width / tileSize); [canvasView.layer setNeedsDisplay]; } @end 

When testing this, I always scrolled all the way across the view after zooming to make sure every tile was seen. Whenever the view looked wrong, the predicted "next # of rects updated" was greater than the actual "# of rects updated" on the next call to -updateCanvas. What would cause this?

Edit:

Here's a better way to visualize the problem. Each time updateCanvas is called, I've made it change the background color for drawing tiles and record the time it was called -- the color and time are stored in canvasView. On each tile is drawn the tile's rectangle, the tile's index along the x axis, the time (sec.) when the background color was set, and the time (sec.) when the tile was drawn. If everything is working correctly, all tiles should be the same color. Instead, here's what I'm sometimes seeing:

Screenshot of tiles with mismatched colors Screenshot of tiles with mismatched colors

I only seem to see wrong results after zooming out. The problem might be related to the fact that scrollViewDidEndZooming, and therefore updateCanvas, can get called multiple times per zoom-out. (Edit: No-- not called multiple times.)

661733 0

If you are running Time Machine on Leopard (OS X 10.5) then you have a chance that the files are in the backup. By default Time Machine backs up every hour so unless the files were created and deleted between backups then you should have something.

28711174 0 Showing message after customer is redirected to logout page magento

I have a problem here. I want to show a message to the customer after his/her session is out. Let me explain in detail. I have a case, at first the customer is logged in when the customer clicks the "My Account" he/she is redirected to customer login page.Here i want to show the message that "your session is out please log in again".

One method i tried is to check the customer session in indexAction() in AcountController.php but this redirection is not taking place from this indexAction().

I am guessing that this redirection is taking somewhere from the block because "My Account" link is added through the xml file using "addLink" method.But i couldn't figure it out.

Has anyone faced such problem and has solved it. Can anyone provide me with some insights so i can fix it.

20752692 0

HTML

<div id='mydiv'>Lorem<span> ipsum</span> dolor amet</div> 

JS/Jquery

var elm = $('#mydiv'); highlite(elm, 2, 28); //specify the start and end position // if you know the word you can find the index of word using indexOf/lastIndexOf function highlite(element, startpos, endpos) { var rgxp = elm.html().substr(startpos,endpos) var repl = '<span class="myClass">' + rgxp + '</span>'; elm.html(elm.html().replace(rgxp, repl)); } 

Demo

http://jsfiddle.net/raunakkathuria/sD2pX/

22358491 0

HANDLE_MSG macro is defined in Windowsx.h header.

Note: To use message cracker for WM_NOTIFY you must use HANDLE_WM_NOTIFY macro defined in commctrl.h header.

32731041 0

You should create a variable containing the \n:

(bind ?newline " ") 

and then use it in str-cat or sym-car or other places.

(bind ?a (sym-cat ?a ?newline)) 
32560451 0

Maybe what you want is like this :

public void startApp(){ primaryStage.show(); new Thread(new Runnable(){ @Override public void run() { try { Thread.sleep(20000);//2 seconds } catch (InterruptedException e) { e.printStackTrace(); } //do something......... System.out.println("all things done"); } }).run(); } 

You need to implement the method run() of Runnable

13594906 0 Executing an API call in Android

I am trying to make an API call to the address: apps.smilemachine.com/smilefactory/api/v1.0/speedup. I just want to execute the url (above) so that it increments the machine and changes the speed value stored at Smilemachine.com? Nothing special I just need to execute the url as if you were typing it into the address bar in any browser?

Has anyone got any advice for this or code snippets?

My current code just opens the browser, please find below:

increasespeed.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Intent increasespeed = new Intent(null, Uri.parse("http://apps.smilemachine.com/smilefactory/api/v1.0/speedup")); startActivity(increasespeed); } }); 
2935604 0 Qt cross thread call

I have a Qt/C++ application, with the usual GUI thread, and a network thread. The network thread is using an external library, which has its own select() based event loop... so the network thread isn't using Qt's event system.

At the moment, the network thread just emit()s signals when various events occur, such as a successful connection. I think this works okay, as the signals/slots mechanism posts the signals correctly for the GUI thread.

Now, I need for the network thread to be able to call the GUI thread to ask questions. For example, the network thread may require the GUI thread to request put up a dialog, to request a password.

Does anyone know a suitable mechanism for doing this?

My current best idea is to have the network thread wait using a QWaitCondition, after emitting an object (emit passwordRequestedEvent(passwordRequest);. The passwordRequest object would have a handle on the particular QWaitCondition, and so can signal it when a decision has been made..

Is this sort of thing sensible? or is there another option?

6362068 0

This website is answer to my question: http://embed.ly/ :)

15532242 0 error while installing WindowBuilder Pro Update Site - http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7

I faced this error while installing http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7 on eclipse Juno Service Release 1

An error occurred while collecting items to be installed session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.p2.engine.phases.Collect, operand=, action=). Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer_2.6.0.r37x201206111227.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.GWTExt_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.GXT_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.GXT.databinding_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.SmartGWT_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.UiBinder_2.6.0.r37x201206111227.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.UiBinder.wizards_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.doc.user_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/com.google.gdt.eclipse.designer.editor.feature_2.6.0.r37x201206111227.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/com.google.gdt.eclipse.designer.feature_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0.super_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0.webkit_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_0.webkit_win32x64_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_2_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.2_2.webkit_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/com.google.gdt.eclipse.designer.hosted.feature_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.hosted.lib_2.6.0.r37x201206111222.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.launch_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.preferences_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/com.google.gdt.eclipse.designer.wizards_2.6.0.r37x201206111253.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.GroupLayout_1.5.0.r37x201206111330.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.GroupLayout_support.feature_1.5.0.r37x201206111330.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.SWT_AWT_1.5.0.r37x201206111333.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.SWT_AWT_support_1.5.0.r37x201206111333.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.databinding_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.databinding.emf_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.databinding.xwt_1.5.0.r37x201206111323.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.doc.user_1.5.0.r37x201206111236.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.doc.user.feature_1.5.0.r37x201206111236.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.rcp.feature_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.nebula_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.rcp.swing2swt_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.swt_1.5.0.r37x201206111304.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.swt.feature_1.5.0.r37x201206111304.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.swt.layout.grouplayout_1.5.0.r37x201206111330.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.swt.widgets.baseline_1.5.0.r37x201206111317.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/plugins/org.eclipse.wb.xwt_1.5.0.r37x201206111323.jar dl.google.com Unknown Host: http://dl.google.com/eclipse/inst/d2wbpro/latest/3.7/features/org.eclipse.wb.xwt.feature_1.5.0.r37x201206111323.jar dl.google.com 
37482250 0 Dropdown menu isn't working

I'm doing a Menu where it has four dropdown buttons that aren't working. The following image shows how it is supposed to work: "Bijutaria=(perfumes+fios)"
"Inserir=(Perfumes=homem+mulher)+Bijutaria=fios+pulseiras)"

I think the problem is located in my CSS code, but I'm not being able to figure out what the problem is.

ul { margin: 0; padding: 0; list-style: none; width: 150px; } ul li { position: relative; } li ul { position: absolute; left: 120px; top: 0; display: none; } ul li a { display: block; text-decoration: none; color: #E2144A; background: #fff; padding: 5px; border: 1px solid #ccc; } li:hover ul { display: block; }
<ul id="left" class='column'> <li><a href="ver.php">Home</a></li> <li><a href="#">Bijutaria</a></li> <ul> <li><a href="pulseiras.php">Pulseiras</a> </li> <li><a href="fios.php">Fios</a> </li> </ul> <li><a href="#">Perfumes</a> <ul> <li><a href="prfh.php">Homem</a></li> <li><a href="prfm.php">Mulher</a></li> </ul> <li><a href="#">Inserir</a></li> <ul> <li><a href="#">Perfumes</a></li> <ul> <li><a href="insrph.php">Homem</a></li> <li><a href="insrpm.php">Mulher</a></li> </ul> <li><a href="#">Bijutaria</a></li> <ul> <li><a href="insrp.php">Pulseiras</a></li> <li><a href="insrf.php">Fios</a></li> </ul> </ul> </li> </ul>

29019976 0

Where you will have a problem is when find descends into subdirectories, and it tries to exec something like cp ./foo/bar.txt /new/path/./foo/bar.txt and "/new/path" has no subdirectory "foo" -- you might want to:

3917587 0

Have you tried FQL? Using this I was able to get users display pictures on any site I wanted by simply constructing a simple SQL like query.

2228489 0 image thumb list with opacity changes and add class/remove class on click

I got the script from another post on here, but for some reason it isn't working quite correctly on my implementation of it. Everything works fine except for stripping of the "selected" class, therefore the thumbnails all stay highlighted after being clicked. Easiest way is to show in context:

http://www.studioimbrue.com/beta

I changed it around a bit trying to figure out the problem but I couldn't find anything.

663380 0

This is going to sound strange, but does the view/table have a column named "1"?

12896034 0

LESS provides the ability to use previously defined classes as mixins in other contexts. Try this:

.theme-dark { .navbar { .navbar-inverse; } } 
26383784 0 View not refreshing following post in Razor MVC using datatable

As per subject. The view looks like this.

@using System.Globalization @model IEnumerable<TaskEngine.WebUI.Models.TaskViewModel> <script src="../../Scripts/progress-task.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $.ajax({ url: '@Url.Action("Index", "Home")', data: { from: "10/01/2014", to: "10/14/2014" }, dataType: "html", success: function () { alert('Success'); }, error: function (request) { alert(request.responseText); } }); }); </script> <div class="container"> <div class="row"> <div class="span16"> <div id="sitename"> <a href="/" id="logo">xxxxxxxx</a> <span class="name">Workbasket</span> </div> <div class="row"> <div class="span16"> <table class="table table-striped table-condensed" id="task-table"> <thead> <tr> <th class="left">Client</th> <th class="left">Task</th> <th class="left">State</th> <th class="left">Assigned By</th> <th class="left">Assigned To</th> <th class="left">Date Opened</th> <th class="left">Date Due</th> @* <th class="left">Date Closed</th>*@ <th class="left">Outcomes</th> </tr> </thead> <tbody> @foreach (var task in Model) { <tr> <td><span>@task.ClientId</span></td> <td><span class="nowrap">@task.TaskDescription</span></td> <td><span class="nowrap">@task.CurrentState</span></td> <td><span >@task.AssignedBy.Replace("CORPORATE\\", "").Replace(@".", " ")</span></td> <td><span>@task.AssignedTo.Replace("CORPORATE\\", "").Replace(@".", " ")</span></td> <td><span>@task.DateOpened.ToString("dd/MM/yyyy HH:mm")</span></td> <td><span>@task.DateDue.ToString("dd/MM/yyyy HH:mm")</span></td> @* <td><span>@(task.DateClosed.HasValue ? task.DateClosed.Value.ToShortDateString() : " - ")</span></td>*@ <td> <span class="nowrap"> @Html.DropDownList( "Outcomes", new SelectList(task.Outcomes, "Id", "Name"), "---Please Select ---", new Dictionary<string, object> { {"data-case-id", @task.CaseId }, {"data-task-log-id", @task.TaskLogId}, {"data-client-id", @task.ClientId} }) </span> </td> </tr> } </tbody> </table> </div> </div> </div> </div> <div class="modal hide span8" id="complete-task-modal" tabindex="-1" role="dialog" aria-labelledby="complete-task-header" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="complete-task-header">Complete Task</h3> </div> <div class="modal-body"> <div class="row"> <div class="span8"> <div class="alert alert-info"> <label id="CurrentState"></label> <label id="NewState"></label> <label>Generated Tasks</label> <ul id="task-list"> </ul> </div> </div> </div> <form id="form"> <input type="hidden" id="task-log-id" name="taskLogId" /> <input type="hidden" id="case-id" name="caseId" /> <input type="hidden" id="outcome-id" name="triggerId" /> <input type="hidden" id="client-id" name="clientId" /> <div id="popup"> </div> </form> </div> <div class="modal-footer"> <button class="btn" id="close" data-dismiss="modal" aria-hidden="true">Go Back</button> <button class="btn btn-primary" id="confirm-task">Confirm</button> </div> </div> </div> 

This is the controller method.

 public ActionResult Index(DateTime? from, DateTime? to) { var usergroups = GetGroups(HttpContext.User.Identity.Name); var model = _taskLogger.GetTasks(from, to) .Select(task => new TaskViewModel { TaskLogId = task.TaskLogId, CaseId = task.CaseId, ClientId = task.ClientId, TaskDescription = task.Description, AssignedBy = task.AssignedBy, AssignedTo = task.AssignedTo.Trim(), DateOpened = task.DateCreated, DateClosed = task.DateClosed, DateDue = task.DateDue }).ToList() .Where(x => IsAvailableToUser(x.AssignedTo, usergroups)) .OrderBy(x => x.DateDue); foreach (var task in model) { var workflow = _workflowEngine.GetCase(task.CaseId); task.CurrentState = workflow.State.ToNonPascalString(); task.Outcomes = workflow.GetPermittedTriggers().OrderBy(x => x.Name).ToList(); } ModelState.Clear(); return View(model); } 

When the model is returned following the ajax post, the dataset is different, as expected, however, within the datatable in the view it still displays the old data.

Having done some googling on this issue, I've tried clearing the modelstate but that makes no difference and from what I've read, it only seems to affect HTMLHelpers anyway.

I'm not sure if this is an issue with the datatable or just a refresh issue with the view itself. Any input would be appreciated.

1328836 0 How can I include line numbers in a stack trace without a pdb?

We are currently distributing a WinForms app without .pdb files to conserve space on client machines and download bandwidth. When we get stack traces, we are getting method names but not line numbers. Is there any way to get the line numbers without resorting to distributing the .pdb files?

21550489 0

Does it read the file while omitting the format argument?

x=read('g:\Work\WD\Debug\wd.txt',100,4) 

I am suspecting it has something to do with your formatting string.

(5x,a2,3(5x,e12.4)) 

Maybe have a look here to learn more about Fortran format edit descriptors.

29986258 0 How to render QuickBlox VideoStream into opponentVideoView and ownVideoView?

I have to accept video call(QuickBlox) anywhere from the application. for this I have create a singleton class in which I have implemented few Quick Blox delegate method for receiving call. after receiving call i present user to VideoCallController. But I am unable to render VideoStream into opponanenVideoView and myVideoView. Can anyone suggest me where I have to set VideoChat Property either in Singleton or VideoCallController.

self.videoChat.viewToRenderOpponentVideoStream = opponentVideoView; self.videoChat.viewToRenderOwnVideoStream = myVideoView; 
28283134 0

Sounds easy enough. You just need to use jquery selectors to slice and dice to get the li into the correct position.

Take a look at nth-child() selector.

40950774 0

Remedy User Tool macro language is proprietary.

Since Remedy User Tool is not supported anymore, I'd encourage you to use updated technologies, like SOAP or REST (for everything back-end), or AngularJS (for everything front-end)

Another solution would be to use tools created by the Remedy Community, like the one appearing on https://communities.bmc.com/message/437693#437693

31361842 0 Why layoutIfNeeded() allows to perform animation when updating constraints?

I have two states of UIView:

enter image description here enter image description here

I have animation between them using @IBaction for button:

@IBAction func tapped(sender: UIButton) { flag = !flag UIView.animateWithDuration(1.0) { if self.flag { NSLayoutConstraint.activateConstraints([self.myConstraint]) } else { NSLayoutConstraint.deactivateConstraints([self.myConstraint]) } self.view.layoutIfNeeded() //additional line } } 

Animation is working only when I add additional line:

But when I remove that line, then my UIView is updated but without any animation, it happens immediately.

Why this line makes such difference? How is it working?

10864824 0 Organizing my papers in org-mode

I've just started using org-mode, and so far find it quite useful. I have a very large collection of technical papers in a directory tree, and I'd like to go through them and index them through org-mode. What I'd like is to have a way of going through them and look at the unannotated ones, and annotate them one by one. I imagine doing this by first making up a file of links like [[xxx.pdf][not done yet]], and then being presented with the not done ones, glancing at them and deciding how what annotations to put in. In addition I'd like to add tags. What I'd really like is to be able to make up new tags on the fly. Has anyone done anything like this in org-mode?

Victor

24588828 0
request.update("growl"); 

This is the wrong part.

Put an id to your form, then reference it like

i.e

request.update("your_for_mid:growl"); 

Alternatively you could activate the auto-update feature of the growl with the attribute autoUpdate="true" of the growl component, and remove the request.update() method call in your backing bean.

28371485 0 No debug option in VBA runtime error

I am using excel 2013. I do not get any debug option when there is a runtime error. How can I get a debug option during runtime errors?

Edit - I have realized that I have this problem only in the following instance. Normally I am getting the debug option (except for this case). What is especially painful is that it doesn't even tell me which line the error is on.

screenshot of error -

Code is as follows -

Option Explicit Option Base 1 Sub doit() Dim intRowCounter As Long Dim intColCounter As Long Dim parentFormula As String Dim resultantFormulas As String For intRowCounter = 1 To 100 For intColCounter = 1 To 200 'This is the line giving the error parentFormula = Right(parentFormula, Len(parentFormula) - 1) Next intColCounter Next intRowCounter End Sub 

Screenshot of the error http://imgur.com/gC32z74

enter image description here

32392463 0

well, you want to hide the fields in the gridfield detail form? that cannot be done in your pages getCMSFields(), as the grid is responsible for generating the detail form. Two possible solutions:

1) tell the grid to hide that fields with a custom component. I dunno how to do it

2) tell your Rotator class to show the fields ONLY if the related page is a homepage:

public function getCMSFields() { $fields = parent::getCMSFields(); //...other stuff.... $isOnHomePage = ($this->Page() && $this->Page()->ClassName == 'HomePage'); //put in your own classname or conditions if(!$isOnHomePage) { //remove the fields if you're not on the HomePage $fields->removeByName('Body'); //we need to suffix with "ID" when we have a has_one relation! $fields->removeByName('BackGroundImageID'); } return $fields; } 
31238631 0 Refreshing html table using Jquery Java built on Codeigniter

Guys I have a data coming from an outsource table which I'm presenting in table. The original data coming in Json which I'm decoding using PHP function and displaying.

I have been googling for auto refreshing that data and found this Auto refresh table without refreshing page PHP MySQL

I have managed to built what is suggested in the Ticked answers and seems like working for the first time but it doesn't refresh. So when page is loaded

I'm calling this

$(document).ready (function () { var updater = setTimeout (function () { $('div#user_table').load ('get_new_data', 'update=true'); /* location.reload(); */ }, 1000); }); 

Which loads a function named get_new_data from controller file and loads on to

 <div class="container-fluid" id="user_table"> </div> 

Codeigniter controller function is

 public function get_new_data(){ $url = 'https://gocleanlaundry.herokuapp.com/api/users/'; $result = $this->scripts->get_data_api($url); $data_row = $result; $tbl = ''; $tbl .= '<table class="table table-striped table-responsive" id="tableSortableRes"> <thead> <tr> <th>Name</th> <th>Email Address</th> <th>Role</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody>'; foreach($data_row as $row){ $tbl .= '<tr class="gradeX"> <td>' . $row->name . '</td> <td>' . $row->email . '</td> <td>' . $row->role . '</td> <td><p id="' . $row->_id. '_status">'.( $row->alive == true ? 'Active' : 'Banned').' </p></td> <input id="' . $row->_id . 'status_val" value="' . $row->alive . '" type="hidden"> <td class="center"> <a href="#" id="' . $row->_id . '_rec" onclick="UpdateStatus(' . $row->_id . ')" class="btn btn-mini ">' . ($row->alive == '1' ? '<i class="fa fa-thumbs-o-up fa-fw"></i>' : '<i class="fa fa-thumbs-o-down fa-fw"></i>' ) . '</a> </td> </tr> '; } $tbl .= '</tbody> </table>'; echo $tbl; } 

As I said when page loads is showing data so something is working but when I add new data to the database is doesn't automatically show up. I want function to call and refresh the data. Sorry I'm very new to javascript and jQuery so please go easy on me :)

Thank you guys

9816460 0 Loop Design: Counting & Subsequent Code Duplication

Exercise 3-3 in Accelerated C++ has led me to two broader questions about loop design. The exercise's challenge is to read an arbitrary number of words into a vector, then output the number of times a given word appears in that input. I've included my relevant code below:

string currentWord = words[0]; words_sz currentWordCount = 1; // invariant: we have counted i of the current words in the vector for (words_sz i = 1; i < size; ++i) { if (currentWord != words[i]) { cout << currentWord << ": " << currentWordCount << endl; currentWord = words[i]; currentWordCount = 0; } ++currentWordCount; } cout << currentWord << ": " << currentWordCount << endl; 

Note that the output code has to occur again outside the loop to deal with the last word. I realize I could move it to a function and simply call the function twice if I was worried about the complexity of duplicated code.

Question 1: Is this sort of workaround is common? Is there a typical way to refactor the loop to avoid such duplication?

Question 2: While my solution is straightforward, I'm used to counting from zero. Is there a more-acceptable way to write the loop respecting that? Or is this the optimal implementation?

13754000 0

Is there a reason you were using Request.Form? You should use

Guid myGuid = Guid.Parse(GuidToken.Value); 

If you still want to use Request.Form which I would not recommend, the name of the hidden field control has been changed by asp.net so the collection does not contain exactly what you specified because it has some autogenerated naming convention added to it. It now looks like this

Request.Form["ctl00$MainContent$GuidToken"] 

Debug mode

enter image description here

38638442 0

As a workaround, download data per day and define weeks in alignment with your measurements from the other dataset. Now Aggregate the Trends data. In case you are dealing with more than 3 months worth of data, consider to rescale your segments beforehand as described here: http://erikjohansson.blogspot.de/2014/12/creating-daily-search-volume-data-from.html http://erikjohansson.blogspot.de/2014/05/daily-google-trends-data-using-r.html

13914974 0

I recommend you read about CSS a little, here is a good example of centering anything.

http://www.w3.org/Style/Examples/007/center.en.html

36159118 0 Guava EventBus - FIFO or LIFO?

This is a very generic question on EventBus. Does the EventBus exhibit a FIFO or LIFO behavior? I am using the EventBus as a Java event "queuing" mechanism and seeing LIFO behavior when a single publisher publishes events to the EventBus faster than the Subscriber can handle.

34755958 0

The difference is caused by doSomeY yielding a number in the first case vs. yielding a function in the second case when applied to one argument.

Given

doSomeX x = if x==7 then True else False doSomeY x y = x+y+1 

we can infer the types (these aren't the most generic types possible, but they'll do for our purposes):

doSomeX :: Int -> Bool doSomeY :: Int -> Int -> Int 

Remember that -> in type signature associates to the right, so the type of doSomeY is equivalent to

doSomeY :: Int -> (Int -> Int) 

With this in mind, consider the type of (.):

(.) :: (b -> c) -> (a -> b) -> a -> c 

If you define

doSomeXY = doSomeX.doSomeY 

...which is equivalent to (.) doSomeX doSomeY, it means that the first argument to (.) is doSomeX and the second argument is doSomeY. Hence, the type b -> c (the first argument to (.)) must match the type Int -> Bool (the type of doSomeX). So

b ~ Int c ~ Bool 

Hence,

(.) doSomeX :: (a -> Int) -> a -> Bool 

Now, applying this to doSomeY causes a type error. As mentioned above,

doSomeY :: Int -> (Int -> Int) 

So when inferring a type for (.) doSomeX doSomeY the compiler has to unify a -> Int (the first argument of (.) doSomeX) with Int -> (Int -> Int) (the type of doSomeY). a can be unified with Int, but the second half won't work. Hence the compiler barfs.

35189371 0 MVN archetype generate a sub project structure (grunt and package.json)

I'm adding to the adobe aem archetype https://github.com/Adobe-Marketing-Cloud/aem-project-archetype . I'm trying to have the archetype create a directory directory call ui.resources with a Gruntfile and package.json in it. I place those files in a ui.resources directory in src/main/archetype. When I run mvn archetype:generate and point to it, there's a gruntfile placed under ui.resource/{packageName} . What am I missing in the archetype-metadata?

27370203 0

You need be superuser for the Process in Java, see my example: https://github.com/adouggy/MyRecorder

14778756 0

There are several ways to achieve that, see Ant FAQ
One possible solution via macrodef simulates the antcontrib / propertycopy task but doesn't need any external library.

5532679 0

What version of Django are you using?

Can you post the generated HTML code? if the URL works when you copy and paste in the browser, it might be an html issue as well.

Have you looked at this page yet?

http://docs.djangoproject.com/en/dev/howto/static-files/

Update:

Can you post the model for a? is a.picture an image field? If so, then you don't need to put the MEDIA_URL in your img src, since it is already an absolute url and it should include the MEDIA_URL already. try removing that and see if it works.

<img src='{{a.picture.url}}' /> 

For more info see this page.

http://docs.djangoproject.com/en/1.3/ref/models/fields/#django.db.models.FileField.storage

4442587 0 Simple jQuery problem

This one should be easy

I've got this HTML

<table class="PageNumbers"> <tr> <td colspan="3">text3 </td> </tr> <tr> <td colspan="2">text </td> <td>text2 </td> </tr> <tr> <td>moretext </td> <td>moretext2 </td> <td>moretext3 </td> </tr> </table> 

I need to change the colspan of the first rows first column to one

This is what i've got

$('.PageNumbers tr:first td:first').attr('colspan') = '1' 

Doesn't seem to work though

Any ideas?

Thanks

9780858 0 Understanding the MVC design pattern in Cocoa Touch

Usually I just put together an app in any random way, as long as it works, but this means I don't pay any attention to any design patterns. My application currently makes extensive use of global variables (I carry an instance of my AppDelegate in every view controller to access properties I declared in my AppDelegate.h). Although it does what I want it to do, I've read this is not a good design practice.

So I want to start making my code "legit". However, I can't imagine my app right now without global variables. They are so important to the well-being of the app, but this must mean I'm doing something wrong, right? I just can't imagine how else I'd do some things. Take for example this:

enter image description here

You have two view controllers here, a SideViewController and a MainViewController. Using global variables, such as say if the entire application had one shared instance of SideViewController and MainViewController (appDelegate.sideViewController and appDelegate.mainViewController), I can easily communicate between the two view controllers, so that if I press "News Feed" in my SideViewController, I can tell my MainViewController to reload it's view.

I can't imagine, however, how this would be done if these were not global variables? If an event occurs in my SideViewController, how would I notify my MainViewController, in a way that is in accordance with design standards?

35071799 0 Dynamically enumerate keys in libconfig

in libconfig - is it possible to dymanically enumerate keys?

As an example, in this example config file from their repo - if someone invented more days in the hours section, could the code dynamically enumerate them and print them out?

Looking at the docs, I see lots of code to get a specific string, or list out an array, but I can't find an example where it enumerates the keys of a config section.

Edit

Received some downvotes, so thought I'd have another crack at being more specific.

I'd like to use libconfig to track some state in my application, read in the last known state when the app starts, and write it out again when it exits. My app stores things in a tree (of depth 2) - so this could be niceley represented as an associative array in a libconfig compatible file as below. The point is that the list of Ids (1234/4567) can change. I could track them in another array, but if I could just enumerate the 'keys' in the ids array below - that would be neater.

so

ids = { "1234" = [1,2,3] "4567" = [9,10,11,23] } 

e.g (psuedocode)

foreach $key(config_get_keys_under(&configroot)){ config_get_String($key) } 

I can't see anything obvious in the header file.

2663579 0

You probably have an ancient version of xerces on the classpath. Definitely check xerces versions.

32054793 0 Are there other means of obtaining the properties of a target in cmake?

I have created a C++ static library, and in order to make it searchable easily, I create the following cmake files:

lib.cmake

# The installation prefix configured by this project. set(_IMPORT_PREFIX "C:/------/install/win32") # Create imported target boost add_library(lib STATIC IMPORTED) set_target_properties(lib PROPERTIES INTERFACE_COMPILE_DEFINITIONS "lib_define1;lib_define2" INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/../include" ) # Load information for each installed configuration. get_filename_component(_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) file(GLOB CONFIG_FILES "${_DIR}/lib-*.cmake") foreach(f ${CONFIG_FILES}) include(${f}) endforeach() 

lib-debug.cmake

# Import target "boost" for configuration "Debug" set_property(TARGET lib APPEND PROPERTY IMPORTED_CONFIGURATIONS DEBUG) set_target_properties(boost PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_DEBUG "CXX" IMPORTED_LOCATION_DEBUG "${_IMPORT_PREFIX}/Debug/staticlib/lib.lib" ) 

When I want to use this library in an executable, I can simply invoke it by calling find_package command:

find_package(lib REQUIRED) if(lib_FOUND) message("lib has been found") else() message("lib cannot be found") endif(boost_FOUND) 

It works and if I want to know the head file directory of the library, I will have to call it this way:

 get_target_property(lib_dir lib INTERFACE_INCLUDE_DIRECTORIES) 

I was just wondering whether there are other ways of obtaining the properties of an target. In this case I expect some variable like lib_INCLUDE_DIRECTORIES will exist.

39932643 0 Log level Client side

I need to know a strategy to overwrite the log level server side by a unique client session. I mean, I don't want to let all client to write more than needed in order to debug errors only for a specific client. So I'm trying to drive the log level client side instead of server side.

1651061 0

You might want to set these session options in your vimrc. Especially options is annoying when you've changed your vimrc after you've saved the session.

set ssop-=options " do not store global and local values in a session set ssop-=folds " do not store folds 
40768802 0 Reload linechart only

I have this chart element

<canvas class="main-chart" id="line-chart" height="200" width="600"></canvas>

and i have this script to insert the data

<script> function hour(){ return a=["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00", "11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00", "19:00","20:00","21:00","22:00","23:00"]; }; var data_visitors_present=<?php echo json_encode(visitorsPresentDay()[0]);?>; var data_visitors_previous=<?php echo json_encode(visitorPreviousDay()[0]);?>; var lineChartData = { labels : hour(), datasets : [ { label: "My First dataset", fillColor : "rgba(220,220,220,0.2)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(220,220,220,1)", data : data_visitors_previous }, { label: "My Second dataset", fillColor : "rgba(48, 164, 255, 0.2)", strokeColor : "rgba(48, 164, 255, 1)", pointColor : "rgba(48, 164, 255, 1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(48, 164, 255, 1)", data : data_visitors_present } ] } </script>

The final result is this enter image description here

I want every 10 seconds to reload only the chart element; I wrote this without effect..

<script> var chart=document.getElementById('#line-chart'); setInterval(chart){( function hour(){ return a=["00:00","01:00","02:00","03:00","04:00","05:00","06:00","07:00","08:00","09:00","10:00", "11:00","12:00","13:00","14:00","15:00","16:00","17:00","18:00", "19:00","20:00","21:00","22:00","23:00"]; }; var data_visitors_present=<?php echo json_encode(visitorsPresentDay()[0]);?>; var data_visitors_previous=<?php echo json_encode(visitorPreviousDay()[0]);?>; var lineChartData = { labels : hour(), datasets : [ { label: "My First dataset", fillColor : "rgba(220,220,220,0.2)", strokeColor : "rgba(220,220,220,1)", pointColor : "rgba(220,220,220,1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(220,220,220,1)", data : data_visitors_previous }, { label: "My Second dataset", fillColor : "rgba(48, 164, 255, 0.2)", strokeColor : "rgba(48, 164, 255, 1)", pointColor : "rgba(48, 164, 255, 1)", pointStrokeColor : "#fff", pointHighlightFill : "#fff", pointHighlightStroke : "rgba(48, 164, 255, 1)", data : data_visitors_present } ] } }1000); </script>

how i can fix it?

26956433 1 Python - non-English characters don't work in one case

Despite the fact I tried to find a solution to my problem both on english and my native-language sites I was unable to find a solution. I'm querying an online dictionary to get translated words, however non-English characters are displayed as e.g. x86 or x84. However, if I just do print(the_same_non-english_character) the letter is displayed in a proper form. I use Python 3.3.2 and the HTML source of the site I extract the words from has charset=UTF-8 set. Morever, if I use e.g. replace("x86", "non-english_character"), I don't get anything replaced, but replacing of normal characters works.

39113806 0 How to send a value in Database to Google analytics?

I manage web application which is made by Symfony2(PHP). I measure some value in Database (for example, register User per a day) on management screen made by myself.

But I want to compare this value with data on Google analytics. so I want to know how to send a value in database to Google analytics.

14089825 0

I usually select a base color and change the hue in 5-6 step (=changing main color) If I need more colors, I'd change saturation (strength or grayish) or luminosity.

The problem here is that you should avoid two adjacent colors (on your drawing) to be close together in terms of 'distance' of the three values H,S,L.

This is quite easy to implement and gives acceptable results.

e.g. (use the windows color editor)
(S=140, L=160): H=0,40,80,120,160,200
(S=90 , L=180); H=20,60,100,140, 180

Please don't use too many colors. Play with fill patterns as well.

23295562 0
el = document.getElementsByName("invoice_line[0][vat]") el.options[[el.selectedIndex]].attributes["data-id"].value 
37505779 0

I use following code fix:

require 'nokogiri' d = Nokogiri::HTML(%Q(<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> </body> </html> )) d.css('body')[0].add_child(Nokogiri::XML::Comment.new(d, "doc")) puts d.to_s 
40195101 0

To store inside your program multiple instances of the same class you need an object called List (here the MSDN reference and here a fast tutorial). To store the List you have multiple choice: serialize and deserialize using xml, json, protobuf protocol and much more, it's you choice.

8075116 0 Database Login Failed, Mysql, html, and php

I am trying to work on getting better at making HTML forms using PHP and Mysql databases so I decided to make a little mock-up website to do some experiments and things like that.

I decided that the first thing I would need to do was to create a login and register page for users who want to sign on to the website. I had no idea how to do this so I did a little research online and I found some pre-built scripts that would do exactly what I wanted to do. In the end I decided to go with this script: http://www.html-form-guide.com/php-form/php-registration-form.html

On my website (hosted with hostgator using cPanel) I set up a Mysql database called ljbaumer_gifts (website is a gift website) and I added a table with 2 columns. The first one a login column which was set to int with auto increment and 25 characters. The second one is a password one which was set to var_char and 25 characters.

I filled in all of the information on the setup scripts from the website I linked to earlier completely correctly but every single time I try to register I get this error code:

Database Login failed! Please make sure that the DB login credentials provided are correct mysqlerror:Access denied for user 'ljbamer_root'@'my_server_adress' (using password: YES) Database login failed!

I used an account that has complete privileges on my server but it still doesn't work!

31562696 0

It appears that in case of using impersonated async http calls via httpWebRequest

HttpWebResponse webResponse; using (identity.Impersonate()) { var webRequest = (HttpWebRequest)WebRequest.Create(url); webResponse = (HttpWebResponse)(await webRequest.GetResponseAsync()); } 

the setting <legacyImpersonationPolicy enabled="false"/> needs also be set in aspnet.config. Otherwise the HttpWebRequest will send on behalf of app pool user and not impersonated user.

901893 0

Try doing

GridView1.DataSource = users.ToList(); 

or

GridView1.DataSource = users.ToArray(); 

Is possibly that the query isn't executing at all, because of deferred execution.

31651332 0 Google+ Sign In Button not functioning Android Studio

Hi so I am currently integrating a Google Sign In into my app. Lately this has been my only concern that for some reason Android Studio not recognizing the Plus_Login scope (which is necessary for the app to access basic profile info, etc). My current error is this

Error:(40, 17) error: method addScope in class Builder cannot be applied to given types; required: Scope found: String reason: actual argument String cannot be converted to Scope by method invocation conversion 

and here is my onCreate file where the Error is found

EDIT 1 - Added import statement and variable declarations

package com.instigate.aggregator06; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.api.Scope; import com.google.android.gms.plus.Plus; public class SocialNetworkActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener { private static final String TAG = "Social Network Activity"; /* Request code used to invoke sign in user interactions. */ private static final int RC_SIGN_IN = 0; /* Client used to interact with Google APIs. */ private GoogleApiClient mGoogleApiClient; /* A flag indicating that a PendingIntent is in progress and prevents * us from starting further intents. */ private boolean mIntentInProgress; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) .addScope(Scopes.PLUS_LOGIN) // <----- This is where the error is found .addScope(Scopes.PLUS_ME) .build(); findViewById(R.id.sign_in_button).setOnClickListener(this); } 

I have searched a while to find a solution for this error (seeing as the Plus_Login scope should be functioning) yet have found no solution.

EDIT 2 - Errors after solving I found the answer to this. Apparently instead of:

.addScope(Scopes.PLUS_LOGIN) .addScope(Scopes.PLUS_ME) 

we write this

.addScope(new Scope(Scopes.PLUS_LOGIN)) .addScope(new Scope(Scopes.PLUS_ME)) 

which solved my problem.

However, it revealed a new problem:

 findViewById(R.id.sign_in_button).setOnClickListener(this); 

where logcat points out that there is a NullPointerException at that point.

EDIT 3 - Solved NullPointerException I have solved the NullPointer Exception Problem, however my Google+ Sign In Button will still not function.

here is the overall class (continuation of the code snippet mentioned above)

package com.instigate.aggregator06; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.Scopes; import com.google.android.gms.common.api.Scope; import com.google.android.gms.plus.Plus; public class SocialNetworkActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener, View.OnClickListener { private static final String TAG = "Social Network Activity"; /* Request code used to invoke sign in user interactions. */ private static final int RC_SIGN_IN = 0; /* Client used to interact with Google APIs. */ private GoogleApiClient mGoogleApiClient; /* A flag indicating that a PendingIntent is in progress and prevents * us from starting further intents. */ private boolean mIntentInProgress; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_social_network); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) //.addScope(Scopes.PLUS_LOGIN) //.addScope(Scopes.PLUS_ME) .addScope(new Scope(Scopes.PLUS_ME)) .addScope(new Scope(Scopes.PLUS_LOGIN)) .build(); this.findViewById(R.id.sign_in_button).setOnClickListener(this); } protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } protected void onStop() { super.onStop(); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } /* Code in case second one doesn't work @Override public void onConnectionFailed(ConnectionResult connectionResult) { // Could not connect to Google Play Services. The user needs to select an account, // grant permissions or resolve an error in order to sign in. Refer to the javadoc for // ConnectionResult to see possible error codes. Log.d(TAG, "onConnectionFailed:" + connectionResult); if (!mIsResolving && mShouldResolve) { if (connectionResult.hasResolution()) { try { connectionResult.startResolutionForResult(this, RC_SIGN_IN); mIsResolving = true; } catch (IntentSender.SendIntentException e) { Log.e(TAG, "Could not resolve ConnectionResult.", e); mIsResolving = false; mGoogleApiClient.connect(); } } else { // Could not resolve the connection result, show the user an // error dialog. showErrorDialog(connectionResult); } } }*/ public void onConnectionFailed(ConnectionResult result) { if (!mIntentInProgress && result.hasResolution()) { try { mIntentInProgress = true; startIntentSenderForResult(result.getResolution().getIntentSender(), RC_SIGN_IN, null, 0, 0, 0); } catch (IntentSender.SendIntentException e) { // The intent was canceled before it was sent. Return to the default // state and attempt to connect to get an updated ConnectionResult. mIntentInProgress = false; mGoogleApiClient.connect(); } } } public void onConnected(Bundle connectionHint) { // We've resolved any connection errors. mGoogleApiClient can be used to // access Google APIs on behalf of the user. Log.d(TAG, "onConnected:" + connectionHint); Intent j = new Intent(SocialNetworkActivity.this, AccountPageActivity.class); startActivity(j); } protected void onActivityResult(int requestCode, int responseCode, Intent intent) { if (requestCode == RC_SIGN_IN) { mIntentInProgress = false; if (!mGoogleApiClient.isConnecting()) { mGoogleApiClient.connect(); } } } public void onConnectionSuspended(int cause) { mGoogleApiClient.connect(); } @Override public void onClick(View v) { if (v.getId() == R.id.sign_in_button) { //onSignInClicked(); mGoogleApiClient.connect(); } // ... } /* I find this unnecesary private void onSignInClicked() { // User clicked the sign-in button, so begin the sign-in process and automatically // attempt to resolve any errors that occur. //mShouldResolve = true; mGoogleApiClient.connect(); // Show a message to the user that we are signing in. //mStatusTextView.setText(R.string.signing_in); }*/ public void backToMainPage(View view) { Intent j = new Intent(SocialNetworkActivity.this, MainActivity.class); startActivity(j); } } 

and here is my xml for that class file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="com.instigate.aggregator06.SelectSNActivity" android:orientation="vertical" android:id="@+id/SelectSNActivity" android:weightSum="1"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/backbtn2" android:id="@+id/backbtntest" android:layout_gravity="right" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_marginBottom="43dp" android:onClick="backToMainPage"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="@string/selectSocialNetwork" android:id="@+id/selectSocialNetworkHeader" android:textStyle="bold" android:textSize="36sp" android:layout_gravity="center_horizontal" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" /> <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/selectSocialNetworkHeader" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="52dp" /> </RelativeLayout> 

Any help is much appreciated, thank you.

14212199 0

The other answers seem to have missed the source-control history side of things.

From http://forums.perforce.com/index.php?/topic/359-how-many-lines-of-code-have-i-written/

Calculate the answer in multiple steps:

1) Added files:

p4 filelog ... | grep ' add on .* by <username>' p4 print -q foo#1 | wc -l 

2) Changed files:

p4 describe <changelist> | grep "^>" | wc -l 

Combine all the counts together (scripting...), and you'll have a total.

You might also want to get rid of whitespace lines, or lines without alphanumeric chars, with a grep?

Also if you are doing it regularly, it would be more efficient to code the thing in P4Python and do it incrementally - keeping history and looking at only new commits.

35512272 0

It looks like your datanodes are full. Could you please check disk space?

34677900 0

That's because getPerson() returns nothing. You are missing a return keyword.

Correct structure is:

getPerson() { return addressService.get() .then(...) .then(...); } 

Side note: There are also several other typos/minor errors to fix:

class PersonService { getPerson() { return addressService.get().then(({address}) => { // <== Added return at beginning of line return `http://localhost/${address}`; // <== Use ` (backtick), not ', for template strings }).then(url => { // <== Fixed typo return new es6Promise.Promise(function(resolve, reject) { ApiUtils.get(url, {}, {}, { success: resolve, error: reject }); }); }); // <== Fixed typo } } 
8394380 0

If the parent has display:none; then you'll need to show it before trying to slideUp the child. You can do this with the show function.

$(divToSlide).parent().show(); $(divToSlide).slideUp(); 

Per the comment, you could alternatively, you could just set the display property to 'block'

$(divToSlide).parent().css("display", "block"); $(divToSlide).slideUp(); 
37023081 0

The Recycle View supports AutofitRecycleView.

You need to add android:numColumns="auto_fit" in your xml file.

You can refer to this AutofitRecycleViewLink

15723806 0

Basic mechanics for this is very simple. Just toggle a class on list container. In CSS set a set of rules for items that are descendent of that class to change floats or columns or css table properties . Also use that main list class to determine what you want displayed within the items, or how you want them displayed

Once class is removed they go back to block elements and default css

Simple example:

HTML:

<ul id="itemList"> <li> <h3 class="title">Item # 1</h3> <div class="details">Detals # 1</div> </li> </ul> 

CSS:

.grid li{ float:left; width:30%;margin-right:5px} .grid .details{display:none} 

JS:

$('button').click(function(){ var txt=$(this).text(); txt= txt=='Grid view'? 'List view' : 'Grid view'; $(this).text( txt); $('#itemList').toggleClass('grid') }); 

DEMO: http://jsfiddle.net/kzDNe/

15341673 0

DataStax provides a Community Edition AMI for Amazon EC2, detailed instructions here.

9253056 0

Yes. It's possible. Use plpython for example. Use this in trigger.

CREATE OR REPLACE FUNCTION move_file(old_path text, new_path text) RETURNS boolean AS $$ import shutil try: shutil.move(old_path, new_path) return True except: return False $$ LANGUAGE 'plpythonu' VOLATILE; 
24402847 0 non-static variable s cannot be referenced from a static context

I'm trying to write a piece of code that when I check one of the two checkboxes, it will change the message that appears when I then select the button.

import javax.swing.*; import java.awt.*; import java.awt.event.*; public class FirstWindow extends JFrame{ String message; public static void main(String[] args){ //the string to show the message for button 1 message = "goodjob \n"; //all of the main window JFrame frame = new JFrame("heading"); frame.setVisible(true); frame.setSize(600,400); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); //makes seperate panels JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); JPanel panel3 = new JPanel(new GridBagLayout()); //set of buttons JButton button1 = new JButton("Button 1"); JButton button2 = new JButton("Button 2"); //makes an ACTION LISTENER, which tells the button what to do when //it is pressed. button1.addActionListener(new ActionListener(){ //the command to button @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, message); } }); //for panel adds buttons panel1.add(button1); panel1.add(button2); //set of checkboxes JCheckBox checkBox = new JCheckBox("Option1"); JCheckBox checkBox2 = new JCheckBox("Option2"); //adds text if the box is checked if (checkBox.isSelected()) { message += "you picked option 1"; } if (checkBox2.isSelected()) { message += "you picked option 2"; } //for panel2 adds checkboxes panel2.add(checkBox); panel2.add(checkBox2); //makes a new label, text area and field JLabel label = new JLabel("This is a label"); JTextArea textArea = new JTextArea("this is a text area"); JTextField textField = new JTextField("text field"); //makes an invisible grid GridBagConstraints grid = new GridBagConstraints(); grid.insets = new Insets(15, 15, 15, 15); //sets the the coordinates 0,0. adds the label, and sets position grid.gridx = 0; grid.gridy = 0; panel3.add(label, grid); //sets the the coordinates 0,1. adds the textArea, and sets position grid.gridx = 0; grid.gridy = 1; panel3.add(textArea, grid); //sets the the coordinates 0,2. adds the text field, and sets position grid.gridx = 0; grid.gridy = 2; panel3.add(textField, grid); //adds each PANEL to the FRAME and positions it frame.add(panel1, BorderLayout.SOUTH); frame.add(panel3, BorderLayout.CENTER); frame.add(panel2, BorderLayout.NORTH); } } 

The error message I'm receiving is:

"FirstWindow.java:12: error: non-static variable message cannot be referenced from a static context message = "goodjob \n";"

for lines 12, 37, 53, 57. I've tried declaring the String variable in the main but then I will just receive the error:

"FirstWindow.java:38: error: local variables referenced from an inner class must be final or effectively final JOptionPane.showMessageDialog(null, message);"

How to solve this problem?

16481898 0

From here:

When you open catalina.sh / catalina.bat, you can see :

Environment Variable Prequisites JAVA_HOME Must point at your Java Development Kit installation. 

So, set your environment variable JAVA_HOME to point to Java 7. Also make sure JRE_HOME is pointing to the same target, if it is set.

You may not have this same issue, but if you do, it could be helpful to know ; )

37791208 0 Knockout JS - How to initialize a complex object as observable?

I have a ViewModel and have an observable property that will have a complex object after an edit link is clicked. This is a basic example of managing a set of Groups. User can click on the 'edit' link and I want to capture that Group in SelectedGroup property.

But I'm not sure how should I initialize the SelectedGroup and make every peoperty in this object as observable to begin with.

function ManageGroupsViewModel() { var self = this; self.Groups = ko.observableArray(); self.IsLoading = ko.observable(false); self.SelectedGroup = ko.observable(); } 
4431992 0 as3: Error: Implicit coercion of a value of type void to an unrelated type

I'm attempting to set up a Metadata object like so:

public function myFunction(event:MediaFactoryEvent):void { var resource:URLResource = new URLResource("http://mediapm.edgesuite.net/osmf/content/test/logo_animated.flv"); var media:MediaElement = factory.createMediaElement(resource); // Add Metadata for the URLResource var MediaParams:Object = { mfg:"Ford", year:"2008", model:"F150", } media.addMetadata("MediaParams", (new Metadata()).addValue("MediaParams", MediaParams) ); 

When I attempt this, I get:

Implicit coercion of a value of type void to an unrelated type org.osmf.metadata:Metadata. (new Metadata()).addValue("MediaParams", MediaParams) ); I actually need the metadata at a couple of levels of depth there, because the metadata gets passed and another function expects the Metadata that way.

How do I get the Metadata added to my URLResource the way I want? Thanks!

20895184 0 Identical template for many functions

Hello guys (and happy new year!)

I'm writing a (not really) simple project in C++ (my first, coming from plain C). I was wondering if there is a way to simplify the definition for multiple functions having the same template pattern. I think an example would be better to explain the problem.

The context

Let's assume I have a "Set" class which represents a list of numbers, defined as

template <class T> class Set { static_assert(std::is_arithmetic<T>(), "Template argument must be an arithmetic type."); T *_address; ... } 

So if I have an instance (say Set<double>) and an array U array[N], where U is another arithmetic type and N is an integer, I would like to be able to perform some operations such as assigning the values of the array to those of the Set. Thus I create the function template inside the class

template <class U, int N> void assign(U (&s)[N]) { static_assert(std::is_arithmetic<U>(), "Template argument must be an arithmetic type."); errlog(E_BAD_ARRAY_SIZE, N == _size); idx_t i = 0; do { _address[i] = value[i]; } while (++i < size); } 

The problem

As far as my tests went the code above works perfectly fine. However I find it REALLY REALLY ugly to see since I need the static_assert to ensure that only arithmetic types are taken as arguments (parameter U) and I need a way to be sure about the array size (parameter N). Also, I'm not done with the assign function but I need so many other functions such as add, multiply, scalar_product etc. etc.!

The first solution

I was wondering then if there is a prettier way to write this kind of class. After some work I've come up with a preprocessor directive:

#define arithmetic_v(_U_, _N_, _DECL_, ...) \ template <class U, idx_t N> _DECL_ \ { \ static_assert(std::is_arithmetic<U>(),"Rvalue is not an arithmetic type."); \ errlog(E_BAD_ARRAY_SIZE, N == _size); \ __VA_ARGS__ \ } 

thus defining my function as

arithmetic_v(U, N, void assign(U (&value)[N]), idx_t i = 0; do { _address[i] = value[i]; } while (++i < _size); ) 

This is somehow cleaner but still isn't the best since I'm forced to lose the brackets wrapping the function's body (having to include the static_assert INSIDE the function itself for the template parameter U to be in scope).

The question

The solution I've found seems to work pretty well and the code is much more readable than before, but... Can't I use another construct allowing me to build an even cleaner definition of all the functions and still preserving the static_assert piece and the info about the array size? It would be really ugly to repeat the template code once for each function I need...

The thanks

I'm just trying to learn about the language, thus ANY additional information about this argument will be really appreciated. I've searched as much as I could stand but couldn't find anything (maybe I just couldn't think of the appropriate keywords to ask Google in order to find something relevant). Thanks in advance for your help, and happy new year to you all!

Gianluca

26027094 0

Use this:

(?s)<Device(?:(?!<\/Device).)*<Block[^>]+Name="ZG123CZ123".*?<\/Device> 

Demo


Explanation:

38363122 0

Yeah there's a matches pseudo class, but if you're hoping it will save you some typing it still needs vendor prefixes you'd have to duplicate and the support isn't great.

:matches(#header, #footer) button active:hover { color: purple; } :-webkit-any(#header, #footer) button active:hover { color: purple; } :-moz-any(#header, #footer) button active:hover { color: purple; } 

So as you can see it ends up being more verbose than just adding the comma and another selector at the moment.

27665172 0
list_a = list_b = [0 for k in range(10)] 

Because list_a equal to list_b. So if list_b is changed, then list_a will change.

34990373 0

You could use ngModel to do this automatically

<li *ngFor="#hero of heroes"> <input type="text" [(ngModel)]="hero.name"/> </li> 
22297215 0

don't look for bug free query here because you haven' provided enough info and sample data. So start pointing out one be one,

Declare @i varchar='Jan-13' declare @upto int=11 Declare @FromDate date=convert(varchar(12),'1-'+'Jan-13',120) Declare @Todate date =dateadd(month,@upto,@FromDate) select convert(char(6),@FromDate,107) ,@ToDate Declare @StringDate varchar(2000)='' select @StringDate= stuff((select ','+'['+convert(char(6),ODLN.DocDate ,107)DocDate+']' from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between @FromDate and @Todate for xml path('')),1,1,'') --@StringDate will have value like [Jan-13],[Dec-12] and so on Declare @qry varchar(max)='' set @qry='select CardName,'+@StringDate+' from (select CardName,CardCode ,DLN1.Quantity,convert(char(6),ODLN.DocDate ,107)DocDate from ODLN inner join DLN1 on odln.DocEntry = ODLN.DocEntry where ODLN.DocDate between between '+@FromDate+' and '+@Todate+')tbl pivot( max(Quantity) for DocDate in('+@StringDate+'))pvt' exec @qry 
32282831 1 Unable to log Flask exceptions with SMTP handler

I am attempting to get an email sent to me any time an error occurs in my Flask application. The email is not being sent despite the handler being registered. I used smtplib to verify that my SMTP login details are correct. The error is displayed in Werkzeug's debugger, but no emails are sent. How do I log exceptions that occur in my app?

import logging from logging.handlers import SMTPHandler from flask import Flask app = Flask(__name__) app.debug = True app.config['PROPAGATE_EXCEPTIONS'] = True if app.debug: logging.basicConfig(level=logging.INFO) # all of the $ names have actual values handler = SMTPHandler( mailhost = 'smtp.mailgun.org', fromaddr = 'Application Bug Reporter <$mailgun_email_here>', toaddrs = ['$personal_email_here'], subject = 'Test Application Logging Email', credentials = ('$mailgun_email_here', '$mailgun_password_here') ) handler.setLevel(logging.ERROR) app.logger.addHandler(handler) @app.route('/') def index(): raise Exception('Hello, World!') # should trigger an email app.run() 
32090894 0 Maven - Debug - Can not find symbol

During using mvn install or mvn compile i got error that maven can not find symbol with different methods and variables in mozilla rhino classes. I made exclusions everywhere where it is possible and said to use 7r5 build for rhino. Also i decompiled jar and got sure that mentioned classes and methods in maven were in that classes. I had pom deps and i couldnt exclude all 3d libraries. So in classpath i saw also path to rhino 6r5 library. I thought that problem was there. So i also decompiled that jar but i saw that methods in the error were also there. My question is how i can debug maven and see what library or class it is using for compiling class. All mozilla rhino libraries which are set in classpath have that methods. PS: I wanted to mention that mvn eclipse:eclipse works fine and i have no errors in eclipse.

[ERROR] ...path_to_class...:[264,65] cannot find symbol [ERROR] symbol: method getLength() [ERROR] location: class org.mozilla.javascript.NativeArray [ERROR] ...path_to_class...:[288,18] cannot find symbol [ERROR] symbol: method getWrapFactory() [ERROR] location: variable cx of type org.mozilla.javascript.Context [ERROR] ...path_to_class...:[322,49] cannot find symbol [ERROR] symbol: method getLength() [ERROR] location: variable array of type org.mozilla.javascript.NativeArray 
38124350 0 Does Setting Session in Model is bad practice?

I do some database transaction and the set $new_user = TRUE like this

Model Code:

$data_insert = array ( 'username' => $username_post, 'password'=>$username_post, ); $this->db->insert('Tenant', $data_insert); $new_tenant_id = $this->db->insert_id(); //CREATE TABLE FOR THAT DISTRIBUTOR $this->dbforge->add_field( array( 'id' => array( 'type' => 'INT', 'constraint' => 10, 'unsigned' => TRUE, 'auto_increment' => TRUE ), 'site_key' => array( 'type' => 'VARCHAR', 'constraint' => '100', ), 'display_name' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), 'ext' => array( 'type' => 'VARCHAR', 'constraint' => '50', 'null' => TRUE ), 'auth_user' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), 'password' => array( 'type' => 'VARCHAR', 'constraint' => '128', 'null' => TRUE, ), 'base_ini_id' => array( 'type' => 'VARCHAR', 'constraint' => '50', 'null' => TRUE ), 'md_user' => array( 'type' => 'VARCHAR', 'constraint' => '128', 'null' => TRUE ), 'uc_user' => array( 'type' => 'VARCHAR', 'constraint' => '50', 'null' => TRUE ), 'uc_password' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), 'comments' => array( 'type' => 'VARCHAR', 'constraint' => '200', 'null' => TRUE ), 'custom_ini_filename' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), 'email' => array( 'type' => 'VARCHAR', 'constraint' => '100', 'null' => TRUE ), )); $this->dbforge->add_key('id', TRUE); if (!$this->db->table_exists('table_name')) { $this->dbforge->create_table($usertable); } //TABLE CREATED NOW ADD SOME DATA $insert_data = array ( 'site_key' =>$site_post, 'tenant_id'=>$new_tenant_id ); //TENANT CREATED AND THE SITE BY HIM IS ADDED TO DATABASE $query = $this->db->insert('MLCSites',$insert_data); $new_user = TRUE; 

Now if i have the user in database then $validate is set to TRUE if not i check if $new_user == TRUE then I set loggedin = TRUE in my session like this:

if(!empty($validate)) { if ($validate == TRUE) { // Log in user $data = array( 'site' => $site->site_post, 'id' =>$tenant_id, 'username'=>$username_post, 'user_table'=>$usertable, 'nec_distributor'=>TRUE, 'loggedin' => TRUE, ); $this->session->set_userdata($data); return TRUE; } elseif ($new_user == TRUE) { // Log in user $data = array( 'site' => $site->site_post, 'id' =>$new_tenant_id, 'username'=>$username_post, 'user_table'=>$usertable, 'nec_distributor'=>TRUE, 'loggedin' => TRUE, ); $this->session->set_userdata($data); return TRUE; } return FALSE; } 

Now in my controller i Check like this:

$dashboard ='customer/dashboard'; $rules = $this->distributor_m->rules; $this->form_validation->set_rules($rules); if ($this->distributor_m->login() == TRUE) { var_dump($this->session->all_userdata()); $this->distributor_m->loggedin() == FALSE || redirect($dashboard); redirect($dashboard); } else { $this->session->set_flashdata('error', 'That email/password combination does not exist'); //redirect('secure/login', 'refresh'); } 

But when i submit username and key, all the database transaction are done as per the code successfully. But there is nothing in my session, if I resend the form information then i see the SESSION data. So where I am going wrong?

26407526 0

No answer yet has explained why NASM reports

Mach-O 64-bit format does not support 32-bit absolute addresses 

The reason NASM won't do this is explained in Agner Fog's Optimizing Assembly manual in section 3.3 Addressing modes under the subsection titled 32-bit absolute addressing in 64 bit mode he writes

32-bit absolute addresses cannot be used in Mac OS X, where addresses are above 2^32 by default.

This is not a problem on Linux or Windows. In fact I already showed this works at static-linkage-with-glibc-without-calling-main. That hello world code uses 32-bit absolute addressing with elf64 and runs fine.

@HristoIliev suggested using rip relative addressing but did not explain that 32-bit absolute addressing in Linux would work as well. In fact if you change lea rdi, [rel msg] to lea rdi, [msg] it assembles and runs fine with nasm -efl64 but fails with nasm -macho64

Like this:

section .data msg db 'This is a test', 10, 0 ; something stupid here section .text global _main extern _printf _main: push rbp mov rbp, rsp xor al, al lea rdi, [msg] call _printf mov rsp, rbp pop rbp ret 

You can check that this is an absolute 32-bit address and not rip relative with objdump. However, it's important to point out that the preferred method is still rip relative addressing. Agner in the same manual writes:

There is absolutely no reason to use absolute addresses for simple memory operands. Rip- relative addresses make instructions shorter, they eliminate the need for relocation at load time, and they are safe to use in all systems.

So when would use use 32-bit absolute addresses in 64-bit mode? Static arrays is a good candidate. See the following subsection Addressing static arrays in 64 bit mode. The simple case would be e.g:

mov eax, [A+rcx*4] 

where A is the absolute 32-bit address of the static array. This works fine with Linux but once again you can't do this with Mac OS X because the image base is larger than 2^32 by default. To to this on Mac OS X see example 3.11c and 3.11d in Agner's manual. In example 3.11c you could do

mov eax, [(imagerel A) + rbx + rcx*4] 

Where you use the extern reference from Mach O __mh_execute_header to get the image base. In example 3.11c you use rip relative addressing and load the address like this

lea rbx, [rel A]; rel tells nasm to do [rip + A] mov eax, [rbx + 4*rcx] ; A[i] 
1315826 0 Sharing objects between C# and C++ code

Is it possible to share references to C# objects between C# and C++ code without massive complexity? Or is this generally considered a bad idea?

16525056 0 remove multiple line using str_replace

I want to remove this multi line with str_replace

<div><i>Hello</i><br/> <!-- Begin: Hello.text --> <script src="http://site.com/hello.php?id=12345" type="text/javascript"> </script> <!-- End: Hello.text --></div> 

12345 = random number

37551018 0 how to check longitude latitude database sql server

i have longitude and latitude in geofence table how to check longitude and latitude in database level. if car longitude latitude are in Zone, update geofance column zones = 'car in zone area'

CREATE TRIGGER Tr_CheckGeoFance ON CheckGeoFance AFTER INSERT AS BEGIN Update tblgeofencing Set CarZone ='Car In Zone Area' END GO ShapesString ={"shapes":[{"type":"rectangle","color":"#1E90FF","bounds":{"northEast":{"lat":"32.379961464357315","lon":"70.99365234375"},"southWest":{"lat":"31.840232667909362","lon":"70.2685546875"}}}]} 

enter image description here

enter image description here

36487261 0

Instead of TStringGrid use TGrid with TColumn columns. Then use the OnGetValue event to fetch values for display in the grid. This is closest to the VCLs TDrawGrid.

procedure TForm1.Grid1GetValue(Sender: TObject; const Col, Row: Integer; var Value: TValue); begin Value := inttostr(col)+', '+inttostr(row); end; 

Sample result of grid with 10 mio rows:

enter image description here

14716668 0 quicker WiFi scan rate to obtain rssi changes android

I am trying to increase the wifi scan rate but with the method wifi.startscan and getting the info of the list result returned, i dont see that the rssi change each 2 seconds. My question is if it is possible to get a low rate scan of the rssi and if it is possible how could i do it.

20710003 0

You can use GridBagLayout in netBeans . this layout is stable way for complex form and panel .

tutorial for Netbeans

3519222 0
>gawk -F"/" "{ split($5,a,\".\"); print a[1]}" 1.t PRX01 PRX02 PRX03 PRX04 
25004136 0

I got this after more trial and error: '/table/tbody/tr[preceding-sibling::tr[th/text()="First header"] = preceding-sibling::tr[th][1]]' Which translates to English: get all rows preceded by the "First header" row where that row is also the first preceding row that contains a header.

36072122 0

According to documentation for CanvasRenderingContext2D.drawImage() function:

ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

sx, sy, sWidth, sHeight are parameters of the sub-rectangle of the source image
In your case: parameters sx, sy, sWidth, sHeight should coincide with parameters dx, dy, dWidth, dHeight (in most simple case)
Change your imageObj.onload handler as shown below:

... imageObj.onload = function() { context.drawImage(imageObj, x, y, width, height, x, y, width, height); callback(canvas.toDataURL()) }; ... 
15720869 0 Connect to database in android

I used the login code to login through simple android application , I've created mydatabase also created the whole java classes needed and the xml files, the result always gives me "Invalid username or password" even though the username and the password are correct as inserted in the DB ,, the app runs with no errors

this is the MainActivity java class:

package com.logintest.fh; import java.io.IOException; public class MainActivity extends Activity { /** Called when the activity is first created. */ Button login; String name="",pass=""; EditText username,password; TextView tv; byte[] data; HttpPost httppost; StringBuffer buffer; HttpResponse response; HttpClient httpclient; InputStream inputStream; SharedPreferences app_preferences ; List<NameValuePair> nameValuePairs; CheckBox check; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); app_preferences = PreferenceManager.getDefaultSharedPreferences(this); username = (EditText) findViewById(R.id.username); password = (EditText) findViewById(R.id.password); login = (Button) findViewById(R.id.login); check = (CheckBox) findViewById(R.id.check); String Str_user = app_preferences.getString("username","0" ); String Str_pass = app_preferences.getString("password", "0"); String Str_check = app_preferences.getString("checked", "no"); if(Str_check.equals("yes")) { username.setText(Str_user); password.setText(Str_pass); check.setChecked(true); } login.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { name = username.getText().toString(); pass = password.getText().toString(); String Str_check2 = app_preferences.getString("checked", "no"); if(Str_check2.equals("yes")) { SharedPreferences.Editor editor = app_preferences.edit(); editor.putString("username", name); editor.putString("password", pass); editor.commit(); } if(name.equals("") || pass.equals("")) { Toast.makeText(MainActivity.this, "Blank Field..Please Enter", Toast.LENGTH_LONG).show(); } else { try { httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://10.0.0.1/my_folder_inside_htdocs/check.php"); // Add your data nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("username", name.trim())); nameValuePairs.add(new BasicNameValuePair("password", pass.trim())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request response=httpclient.execute(httppost); ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String response = httpclient.execute(httppost, responseHandler); System.out.println("Response : " + response); if(response.equalsIgnoreCase("User Found")){ runOnUiThread(new Runnable() { public void run() { Toast.makeText(MainActivity.this,"Login Successfull", Toast.LENGTH_SHORT).show(); } }); //startActivity(new Intent(MainActivity.this, UserPage.class)); Move_to_next(); }else{ Toast.makeText(MainActivity.this, "Invalid Username or password", Toast.LENGTH_LONG).show(); } } catch (Exception e) { Toast.makeText(MainActivity.this, "error"+e.toString(), Toast.LENGTH_LONG).show(); } } } }); check.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on clicks, depending on whether it's now checked SharedPreferences.Editor editor = app_preferences.edit(); if (((CheckBox) v).isChecked()) { editor.putString("checked", "yes"); editor.commit(); } else { editor.putString("checked", "no"); editor.commit(); } } }); } public void Move_to_next() { startActivity(new Intent(MainActivity.this, UserPage.class)); } } 

the UserPage an empty page I want the user to go to after logging in

this is my php file :

try { $db = new PDO("mysql:host=$hostname_localhost;dbname=mydatabase", $username_localhost, $password_localhost); echo "Connected to database"; // check for connection $username = $_POST['myusername']; $password = $_POST['mypassword']; $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $sql = "select * from mydatabase.tbl_user where username = '".$username."' AND password = '".$password. "'"; $result = $db->query($sql); foreach ($result as $row) { echo "<br/> success"; } $db = null; // close the database connection } catch(PDOException $e) { echo $e->getMessage(); } ?> 

any ideas of what the problem might be ?

18988050 0

If the form is posting a field with a parameter of name, a 404 will result.

30678371 0

You can try this:judge the parameter wether is a file, then according to the type of parameter execute the operation respectively

30322733 0

try this, if Z axis is your forward direction:

for(var i=0;i<10;i++) { gun.transform.position += gun.transform.forward; yield return 0; } for(var i=0;i<10;i++) { gun.transform.position -= gun.transform.forward; yield return 0; } 

this will move the gun in the forward direction of the gun

if you turn, the forward direction is not (0,0,1)

you can also use this if X axis is your forward direction:

for(var i=0;i<10;i++) { gun.transform.position += gun.transform.right; yield return 0; } for(var i=0;i<10;i++) { gun.transform.position -= gun.transform.right; yield return 0; } 
930920 0

If you are able to use LINQ,

 void Main() { Dictionary d1 = new Dictionary<int, string>(); Dictionary d2 = new Dictionary<int, string>(); d1.Add(1, "1"); d1.Add(2, "2"); d1.Add(3, "3"); d2.Add(2, "2"); d2.Add(1, "1"); d2.Add(3, "3"); Console.WriteLine(d1.Keys.Except(d2.Keys).ToArray().Length); }  

This prints 0 to the console. Except tries to find the difference between two lists in the above example.

You can compare this with 0 to find if there is any difference.

EDIT: You could add the check for comparing the length of 2 dictionaries before doing this.
i.e. You can use Except, only if the length differs.

4518512 0 16410142 0

If you're using the standard Android binding, whose Javadoc is at http://developer.android.com/reference/android/database/sqlite/package-summary.html, then you can find the right code to call by looking at the Javadoc for an overload of execSQL. See http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#execSQL(java.lang.String,%20java.lang.Object[]).

Now, the Javadoc says that execSQL is not to be used for SELECT/INSERT/UPDATE/DELETE. Instead, there are three insertXXX methods, each of which takes additional data in a ContentValues object. So, you construct that object, which looks like a Map, with the new row's data.

17195288 0 remove "+" or "0" from a telephone number string

i need in php a regular expression to remove from a string of telephone numbers the + or the 0 at the beginning of a number

i have this function to remove every not-number characters

ereg_replace("[^0-9]", "", $sPhoneNumber) 

but i need something better, all these examples should be...

$sPhoneNumber = "+3999999999999" $sPhoneNumber = "003999999999999" $sPhoneNumber = "3999999999999" $sPhoneNumber = "39 99999999999" $sPhoneNumber = "+ 39 999 99999999" $sPhoneNumber = "0039 99999999999" 

... like this

$sPhoneNumber = "3999999999999" 

any suggestions, thank you very much!

16218085 0

Here, check this out! This is what you need!

This tut explains everything you need -> Slide Elements in Different Directions

8307372 0 Diagnostics not available in Insights

I have a couple of apps on Facebook. I would like to be able to see how many wallposts per user I am allowed to make. I know I can see this on insights (http://www.facebook.com/insights) by opening an app and clicking on "diagnostics" in the left column under "App insights".

However: for a couple of my apps there is no "diagnostics" link under "App insights". There is only a button that says "Open graph".

I have no idea what the difference is between the apps that have and don't have the "diagnostics" button. Can anyone give me some insight (har har) on this?

16822317 0 getText between tags with Selenium

I'm trying to parse the following XML file so that I can get some attributes. One thing I need to do is verify that the content between tags is not empty. To do this, I though I would be able to use the getText method provided for web elements.

The XML file:

<results> <result index="1"> <track> <creator>Cool</creator> <album>Amazing</album> <title>Awesome and Fun</title> </track> </result> </results> 

My code for parsing through and getting what I want is as follows (keep in mind there is more than one result):

boolean result = false; driver.get(url); List<WebElement> result_list = driver.findElements(By.xpath(".//result")); if (result_list.size() == num_results) { try { for (int i = 0; i < result_list.size(); i++) { WebElement track = result_list.get(i).findElement(By.xpath(".//track")); WebElement creator = track.findElement(By.xpath(".//creator")); System.out.println(creator.getText()); track.findElement(By.xpath(".//album")); track.findElement(By.xpath(".//title")); } result = true; } catch (Exception e) { result = false; } } return result; 

The problem is that the System.out.println call returns an empty string when there is clearly text between the creator tags. Any help would be greatly appreciated!

18342913 0

Make sure your zoom is at 100%. Also in Internet Options > security you need to make sure that 'Enable protected mode' is selected on all 4 zones.

32863649 0 How to add an action to notifications in Swift 2 iOS 9

I'm trying to get a button in my notifications send with PHP Apns http://immobiliare.github.io/ApnsPHP/html/

Following this documentation from Apple: https://developer.apple.com/library/ios/documentation/General/Conceptual/WatchKitProgrammingGuide/BasicSupport.html#//apple_ref/doc/uid/TP40014969-CH18-SW5

But the buttons never show..

My code:

 var categories = NSMutableSet() var acceptAction = UIMutableUserNotificationAction() acceptAction.title = NSLocalizedString("Accept", comment: "Accept") acceptAction.identifier = "accept" acceptAction.activationMode = UIUserNotificationActivationMode.Background acceptAction.authenticationRequired = false var declineAction = UIMutableUserNotificationAction() declineAction.title = NSLocalizedString("Decline", comment: "Decline") declineAction.identifier = "decline" declineAction.activationMode = UIUserNotificationActivationMode.Background declineAction.authenticationRequired = false var inviteCategory = UIMutableUserNotificationCategory() inviteCategory.setActions([acceptAction, declineAction], forContext: UIUserNotificationActionContext.Default) inviteCategory.identifier = "cat1" categories.addObject(inviteCategory) let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: (NSSet(array: [categories])) as? Set<UIUserNotificationCategory>) UIApplication.sharedApplication().registerUserNotificationSettings(settings) UIApplication.sharedApplication().registerForRemoteNotifications() 

My APNS code:

$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, 'dict_prod.pem'); $push->setProviderCertificatePassphrase('XXXXXXX'); $push->setRootCertificationAuthority('entrust_root_certification_authority.pem'); $push->connect(); $message = new ApnsPHP_Message("THE TOKEN"); $message->setText("Test"); $message->setSound('default'); $message->setExpiry(30); $message->setCategory('cat1'); $push->add($message); $push->send(); $push->disconnect(); $aErrorQueue = $push->getErrors(); if (!empty($aErrorQueue)) { var_dump($aErrorQueue); } 
16229840 0 android - required layout_attribute is missing
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" > <gradient android:layout_width="match_parent" android:angle="270" android:centerColor="#4ccbff" android:endColor="#24b2eb" android:startColor="#24b2eb" /> <corners android:radius="5dp" /> </shape> 

The above code shows " required layout_height attribute is missing" on the line no 4

&

"required layout_height and layout_width attribute is missing" on the line no 11.

98081 0

I've used pMock in the past, and didn't mind it, it had pretty decent docs too. However, Foord's Mock as mentioned above is also nice.

21023322 0

try adding

div.myClass{ position: absolute; bottom:0; width:100%; } 

to the div.

Example with the div positioned only on td bottom.

JSFiddle

10818756 0

Your selectors are incorrect, you're using the hash to indicate and id. Also you're prefixing your classes with an element notation that is not correct.

This

if($('#tr').hasClass('tr_group')) 

should be:

if($('tr').hasClass('group')) 
25618368 0

The "Micro" version of Cloud Foundry is not available for Cloud Foundry V2 users onward. Check those options to run Cloud Foundry V2 locally: http://docs.cloudfoundry.org/deploying/run-local.html

This currently includes bosh-lite and cf_nise_installer.

24510945 0

Save is meant to insert one document. Update can be used over several documents that match the criteria in the first parameter.

Under certain circumstances (specifying a unique id as the criteria, upsert:true, and not using multi: true) both can serve the same purpose.

9400307 0

Browser configuration settings are available in online documenation, I suggest adding as a "Trusted Site"

28559864 0 Comparing values of two promises

I wish to achieve the following:

var textPromise1 = element(by.id('id1')).getText(); var textPromise2 = element(by.id('id2')).getText(); if(textPromise1.SOMELOGIC == textPromise2.SOMELOGIC ) console.log('These are equal') 

I know the promise is resolved using .then(). However, I want to know if there exists some way with which above can be achieved!

Thanks,

10692147 0 Error while installing caldecott

I am getting this error while running this command on windows prompt> gem insatll caldecott. I have downloaded the development kit but the error is still the same.

Please update your PATH to include build tools or download the DevKit from 'http://rubyinstaller.org/downloads' and follow the instructions at 'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'

6300010 0

All of your questions can be solved very easy if you use a DFS for each relationship and then use your function calculate() again if you want it more detailed.

6487736 0

Try:

$('.btn-reply').click(function(){ $(this).parents('.roar').siblings('.newreply').toggleClass('show'); return false; }); 

However, I agree with Francisc that a better approach would be to modify the HTML and assign a unique id to each message set. That way you can grab the .newreply to show based on a shared unique id which would be agnostic regarding the positioning of the HTML layout.

E.g.

<div class="roar" rel="msg0">...</div> ... <button class="btn-reply" rel="msg0"></button> ... <div class="newreply" rel="msg0">...</div> ... 

Then your jQuery becomes:

$('.btn-reply').click(function(){ var id = $(this).attr('rel'); var selector = '.newreply[rel=' + id + ']'; $(selector).toggleClass('show'); return false; }); 
23782945 0

Thanx cs 1088,

I basically used casting a List to an array List as you correctly proposed and I finally after much mucking about realised I needed to use this structure below to cast the IList back to a BIC after retrieving the array from the Schema.

userCheckedbuiltInCategory = retrievedData.Cast().ToList();

16059073 1 How to change file_extension internally in Blender 2.65

I am writing a python script for Blender and I am quite new. I want to change output file format in render option internally. For example, context.scene.render.file_extension = "PNG" . But it is a read-only variable so I get an error. Is there a way to change it in code?

I am using Blender-2.65.

36256047 0

Your codeResult() method throws Exception

public int coderesult (String urlstring) throws Exception { 

Therefore, you must either catch it specifically catch(Exception ex) , or declare that your throw it from your method.

When catching exceptions, you either catch a specific exception type, or a more generic parent exception type. You could combine all catches into one catch, because all built in java exceptions extend from Exception

catch(Exception ex){ ex.printStackTrace(); } 
28818282 0

You can make regular expression groups by using ( and ) and reference then in replace using $N, which will access N-th group.

So in your case, you can do this regex: ([^: ]+:[^:]+:([^:]+):[^:]+:[^:]+)(:[^: ]+) replace: \1<\2>\3 or on some implementation $1<$2>$3

You can try it yourself here: https://www.regex101.com/r/hY8pY9/1

32955667 0

I think I have an answer for you. In this you do not have to flip the y-axis, and I can get the names in the x-axis, but I still use a hierarchy. I'm not sure it's more efficient, but here goes.

First, I created a Hierarchy defined as:

CREATE NESTED HIERARCHY [New hierarchy (2)] [yearsOfExp] AS [yearsOfExp], [name] AS [name] 

This allowed me to order the category axis by years of experience.

Secondly, I created a calculated column defined as:

Sum([yearsOfExp]]) over (AllNext([yearsOfExp]])) 

I then created a line chart. The hierarchy is the x axis and the calculated column is the y axis. When setting the x axis, be sure to "reverse scale". enter image description here

I hope this does what you're looking for. Good luck. Any questions, just ask.

38428541 0 How to erase rows in a data frame R

I have a data frame that look like this:

Quality Data Name 1 667 green 3 647 white 1 626 Blue 2 345 yellow 1 550 Blue 5 730 green 

i want a code that goes through a for loop and takes the one less the 600 and greater than 700 and delete the row && all the ones with the same name and saves the ones that were deleted in another data frame
example

 for i in nrow(df){ if (df$Data[i]<=600 || df$Data[i]>=700){ Subset_by_name=subset(df,df$Name==df$Name[i]) (saves bad samples) (delete from data) Subset_by_name=data.frame(Subset_by_name) bad_sample=rbind(Subset_by_name) (saves all the bad data in a data frame) } } 

result
bad_sample

Quality Data Name 1 667 green 1 626 Blue 2 345 yellow 1 550 Blue 5 730 green 

data

Quality Data Name 3 647 white 

help please????

20856099 0 Meteor Js , Store images to mongoDB

I want to store an image browsed by a file input to database. I am browing the image using redactor plugin using this code

$('.editor').redactor({ imageUpload:"/uploads" }); 

Using this when i select or browse an image i am directly sending that image to server using meteor HTTP-methods

HTTP.methods({ '/uploads': function(data) { console.log(data) Meteor.call("uploadImage",data) return JSON.stringify({'Hello':"hello"}); } }); 

Here when i am doing console.log data I am getting the 64bit binary code for the image. Now i want to save this data to the mongodb database.
I am using meteor-collection 2 for defining fields and their types. But i couldn't get which data type i have to use to store image to the mongo db.
I am trying to use mongodb gridfs to store the image. Tell me how can i store image in mongodb ? Thanx

30157519 0

Use $user->profile() ->save(new UserProfile($params));

37706079 0 Prevent HTML Removing Successive spaces

I have an issue in a JSP page where I have to display a generated message onscreen based on a string. It all works fine until one of the account numbers contains two spaces.

So, I have this HTML:

 <logic:notEqual name="migrationsMessage" value=""> <div style="color:Red;font-weight:bold"> <bean:write name="solasDetailsForm" property="migrationsMessage"/> </div> </logic:notEqual> 

When the field migrationsMessage contains this:

<input type="hidden" name="migrationsMessage" value="A 123456W has migrated to A 123456."> 

The output on the screen is this:

“A 123456W has migrated to A 123456.” 

The second space after the first A is removed. I tried to alter the style to be this but it didn't help:

 <logic:notEqual name="migrationsMessage" value=""> <div style="color:Red;font-weight:bold;white-space:pre"> <bean:write name="solasDetailsForm" property="migrationsMessage"/> </div> </logic:notEqual> 

Any ideas what is going wrong?

8018632 0

It is not possible to reliably get sorted results without explicitly using ORDER BY.

Sources:

The Beatles versus the Stones

Without ORDER BY, there is no default sort order

40370122 0 Best way to index a SQL table to find best matching string

Let's say I have a SQL table with an int PK column and an nvarchar(max). In the the nvarchar(max) column, I have a bunch of table entries that are all like this:

SOME_PEOPLE_LIKE_APPLES SOME_PEOPLE_LIKE_APPLES_ON_TUESDAY SOME_PEOPLE_LIKE_APPLES_ON_THE_MOON SOME_PEOPLE_LIKE_APPLES_ON_THE_MOON_CAFE SOME_PEOPLE_LIKE_APPLES_ON_THE_RIVER . . . SOME_ANTS_HATE_SYRUP SOME_ANTS_HATE_SYRUP_WITH_STRAWBERRIES 

There's millions of these rows - Then let's say my goal is to find the row with the most overlap for an input searchTerm - So in this case, if I input SOME PEOPLE_LIKE_APPLES_ON_THE_MOON_MOUNTAIN, the returned entry would be the third entry from the table above, SOME_PEOPLE_LIKE_APPLES_ON_THE_MOON

I have a SPROC that does this very naively, it goes through the entire table as follows:

SELECT DISTINCT phrase, len(phrase) l, [id] FROM X WHERE searchTerm LIKE phrase + '%' -- phrase is the row entry being searched against -- searchTerm is the phrase we're searching for 

I then ORDER BY length and pick the TOP only

Would there be a way to speed this up, perhaps by doing some indexing?

If this is confusing, think of it as tableRowEntry + wildcard = searchTerm

I'm on MSSQL 2008 if that makes any difference

29924627 0

You could look into Application.registerActivityLifecycleCallbacks() &c.

7313818 0

As mentioned in the comments by HK1, here's what can be done (although it's workaround):

Use a continuous form instead of the datasheet.

29392005 0 Generate a unique number that is formed from 2 numbers and vice versa?

I am not sure if this is possible but,

I have 2 numbers, a 32-bit int x and a 64-bit long y.

Given that 'y' is ALWAYS unique.

Given these numbers, I want to generate a unique identifier which is a 32-bit int. I should also be able to construct the individual numbers back from the unique identifier. Is this possible? I apologize if this is the wrong forum to ask, but this is related to C# programming on a project i am working on.

Basically, 'x' refers to a categoryID and 'y' refers to a unique 'categoryItemId' in my database, a single category can have a million of catalogItems.

Thanks!

20207798 0

Your using WriteString to display a string. WriteString uses edx to hold the address of the string to print.

You call DisplayPrompt and move the address of vHexPrompt into edx, then you call DisplayString and in that function, you call WriteString. edx still contains the address of vHexPrompt which is why you are getting a double prompt.

Until you write more code to utilize DisplayString, either comment out the call to writestring in that function, or just add xor edx, edx right before your call to WriteString in DisplayString

17387295 0

You don't need to use Regex, you can just use .length to search for the longest string.

i.e.

function longestWord(string) { var str = string.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").split(" "); longest = str[0].length; longestWord = str[0]; for (var i = 1; i < str.length; i++) { if (longest < str[i].length) { longest = str[i].length; longestWord= str[i]; } } return longestWord; } 

EDIT: You do have to use some Regex...

4382442 0

(Before the longer discussion: it looks like you're typing myButton one line 2, and eventButton on line 3. Make sure these match!)

You're correct in thinking that you're creating a new instance of mainViewController. To get at the one you want, You'll either need to pass a reference to mainViewController into the new view controller when you create it, writing a method like:

@synthesize mainViewController; -(void) initWithMainVC:(MainViewController *)mainVC { if ((self = [super init])) { self.mainViewController = mainVC; } return self; } 

to override init, or, if you've got a reference to mainViewController in your App Delegate, you can get it using:

MainViewController *mainVC = [(YourAppDelegate *)[[UIApplication sharedApplication] delegate] mainViewController]; 

Either way you choose, you'll want to read up on object oriented programming and pointers in objective C. When you call alloc, you're manufacturing a new copy of that class. All copies sit in different chunks of memory, so any new one you make (as in your code above) is actually a totally different entity, like two Priuses, or something like that.

A pointer is like a nametag that identifies, or points the way, to that block of memory. In my init code example above, we're attaching a new nametag to a mainViewController instance with the same guts. Same thing with the second line -- we make a new pointer (see the star?) tell it it's going to be pointing to a MainViewController instance, and slap that nametag, or pointer, on to an instance.

(The second one is a little more complicated, as you're plucking mainViewController from an object called a singleton, or an object that you can get at from anywhere... read more about those and the App Delegate at this post from Cocoa with Love.)

Anyway, I get nervous expounding on this stuff on Stack! Check out Apple's Objective C reference for some more of the basics. The sample code on the iOS Dev Center is really, really good to check out. Download a project that looks nice, or, better yet, just create a project from an Xcode template, and go try to figure out how it's stitched together. Good luck!

10514710 0

If you want anything starting with page1 to be rewritten, this will work:

 RewriteRule ^page1.* http://www.example.com/newpage.htm [R=301,L] 

If you want only page1 and page1.htm to be rewritten, but not e.g. page1whatever, this should work:

 RewriteRule ^page1(.htm)? http://www.example.com/newpage.htm [R=301,L] 
12911179 0

You must specify the following property

sonar.host.url=http://localhost:9100 

, if you want Sonar batch to connect to the correct URL.

You can set it either as a property in your Ant script or a JVM parameter.

4666017 0

You can access faster to local vars, also you can shorten the variable name "window" (and even "document") with something like:

(function(w, d)(){ // use w and d var })(window, document) 
32518542 0 How to set up dc.js x axis for dates

I have a CSV file with 2 columns, in the first I have got some dates, in the second there are some values.

How do I initialize the x axis to show dates?

21929808 0

c_str is a method on a string, so you need to call it like cell.c_str() to tell the compiler is a method, not a class member

34587113 0

My opinion is that you can remove the george_holiday_passengers and add the type,age,gender columns to the george_holiday_users as looking to it; its only a extended data of the holiday_users table and build query with your new database tables.

$query = $this->db->select('u.*, p.package_name, p.description') ->from('george_holiday_users u') ->join('george_packges p', 'u.package_id = p.id', 'left') ->get(); return $query->result(); 

anyway, you can achieved the result using this query.

$query = $this->db->select('u.*, hp.type, hp.name AS passengers_name, hp.age, hp.gender, p.package_name, p.description') ->from('george_holiday_users u') ->join('george_holiday_passengers hp', 'hp.user_id = u.id', 'left') ->join('george_packges p', 'u.package_id = p.id', 'left') ->get(); return $query->result(); 

you should be careful about the column names because on your database there are a lot of columns with the same names, It might affect your query when your using joins, etc.

Hope that helps.

23446458 0

Do you really use command dir in your batch file or another command, a command which itself is enclosed in double quotes because of a space in path or has a parameter in double quotes?

If the output of a command should be processed within the loop and the command itself must be specified in double quotes or at least one of its parameters, the following syntax using back quotes is required:

for /f "usebackq delims=" %%a in (`"command to run" "command parameter"`) do echo %%a 

An example:

for /f "usebackq delims=" %%a in (`dir "%CommonProgramFiles%"`) do echo %%a 

%CommonProgramFiles% references the value of environment variable CommonProgramFiles which is a directory path containing usually spaces. Therefore it is necessary to enclose the parameter of command dir in double quotes which requires the usage of usebackq and back quotes after the opening and before the closing round bracket.

Further I suggest to look on value of environment variable PATH. There are applications which add their program files directory to PATH during installation, but not by appending the directory to end of the list of directories, but by inserting them at beginning. That is of course a bad behavior of the installer of those applications.

If you call in your batch file standard Windows commands not located in cmd.exe, but in Windows system directory which is usually the first directory in PATH, like the command find, and the installed application by chance has also an executable with same name in the program files directory of the application, the batch file might not work on this computer because of running the wrong command.

It is safer to use instead of just find in a batch file %SystemRoot%\system32\find.exe to avoid problems caused by bad written installer scripts of applications modifying the PATH list on wrong end.

16002801 0 Find if any element is present in System.Array or not and if exists remove from the original

I have three System.Array where I store basically phone numbers with 10 characters. The definition is this:

private static System.Array objRowAValues; private static System.Array objRowBValues; private static System.Array objRowCValues; 

I do this because I read a huge Excel file with many cells (around 1 000 000) and process with List<string> is a bit slow. Later in my code I change the System.Array to a List<string> mainly because I fill a ListBox elements. These are the definition for the List

private List<string> bd = new List<string>(); private List<string> bl = new List<string>(); private List<string> cm = new List<string>(); 

I want to check if any values in objRowAValues exists in objRowBValues or in objRowCValues and if exists then remove the existent value, how can I do this? I'm newbiew with C# and this is my first steps.

EDIT: here is the code (relevant parts only) of what I'm doing:

private List<string> bd = new List<string>(); private static System.Array objRowAValues; private List<string> bl = new List<string>(); private static System.Array objRowBValues; private List<string> cm = new List<string>(); private static System.Array objRowCValues; private List<string> pl = new List<string>(); private static Microsoft.Office.Interop.Excel.Application appExcel; Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; Excel.Range rngARowLast, rngBRowLast, rngCRowLast; long lastACell, lastBCell, lastCCell, fullRow; // this is the main method I use to load all three Excel files and fill System.Array and then convert to List<string> private void btnCargarExcel_Click(object sender, EventArgs e) { if (this.openFileDialog1.ShowDialog() == DialogResult.OK) { if (System.IO.File.Exists(openFileDialog1.FileName)) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Thread.Sleep(10000); filePath.Text = openFileDialog1.FileName.ToString(); xlApp = new Microsoft.Office.Interop.Excel.Application(); xlWorkBook = xlApp.Workbooks.Open(openFileDialog1.FileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Excel.Worksheet) xlWorkBook.Worksheets.get_Item(1); fullRow = xlWorkSheet.Rows.Count; lastACell = xlWorkSheet.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row; rngARowLast = xlWorkSheet.get_Range("A1", "A" + lastACell); objRowAValues = (System.Array) rngARowLast.Cells.Value; foreach (object elem in objRowAValues) { bd.Add(cleanString(elem.ToString(), 10)); } nrosProcesados.Text = bd.Count().ToString(); listBox1.DataSource = bd; xlWorkBook.Close(true, null, null); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; executiontime.Text = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds/10).ToString(); } else { MessageBox.Show("No se pudo abrir el fichero!"); System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel); appExcel = null; System.Windows.Forms.Application.Exit(); } } } // This is the method where I clean the existent values from bd (the List where I should remove existent values on bl and existent values on cm private void btnClean_Click(object sender, EventArgs e) { pl = bd; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Thread.Sleep(10000); pl.RemoveAll(element => bl.Contains((element))); pl.RemoveAll(element => cm.Contains((element))); textBox2.Text = pl.Count.ToString(); listBox4.DataSource = pl; stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; textBox6.Text = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10).ToString(); } 
29205252 0 Android: java.lang.StringIndexOutOfBoundsException: on copy to clipboard selected text on long press event

In my app I would like to give copy to clipboard selected text functionality on long press event.foo is a text view foo = (TextView) findViewById(R.id.single_string);. I am using the below code to implement this functionality.

 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); activateToolbar(); text = parseSourceCode(text); foo = (TextView) findViewById(R.id.single_string); foo.setTextSize(mRatio + 14); foo.setText(Html.fromHtml(text,imgGetter, null)); foo.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { String stringYouExtracted = foo.getText().toString(); int startIndex = foo.getSelectionStart(); int endIndex = foo.getSelectionEnd(); stringYouExtracted = stringYouExtracted.substring(startIndex, endIndex); if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(stringYouExtracted); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", stringYouExtracted); clipboard.setPrimaryClip(clip); } // TODO Auto-generated method stub return false; } }); 

I am able to set the text but my code is getting crashed when I press long on the screen to copy the selected text. Error I am getting is :

java.lang.StringIndexOutOfBoundsException: length=3704; regionStart=-1; regionLength=0 at java.lang.String.startEndAndLength(String.java:504) at java.lang.String.substring(String.java:1333) at java.lang.String.subSequence(String.java:1671) – 
21501160 0

addGestureRecognizer is a method on UIView, not UIViewController.

Try

 [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(isTapped:)]]; 
35397885 0

I encountered this issue as you did. I got an error that's something like "couldn't find package Emacs-24.4". This inspired me to install Emacs-24.4 on my Ubuntu, instead of older version 24.3 which is the newest I can get from apt-get. (A convincing fact is that the newer version 24.5 provided by Homebrew works well with Purcell's package on my Mac.)

Under Emacs 24.4, slime proved to run well with Purcell's .emacs.d/. But it really costs me a lot of time to install Emacs-24.4 on my Ubuntu. First, I had to solve the problems of dependencies. Using aptitude, I get rid of the problem which apt-get failed to solve:

sudo apt-get install aptitude sudo aptitude install build-essential sudo aptitude build-dep emacs24 

When the dependency issue pops out, aptitude will give you some suggestions including downgrading your current packages. I chose solutions of downgrade without leaving over any unsolved dependency problem (select 'no' until you find an acceptable one). During reinstalling build packages, Ubuntu iso cdrom may be required.

Then install Emacs 24.4:

wget http://open-source-box.org/emacs/emacs-24.4.tar.xz tar xvf emacs-24.4.tar.xz cd emacs-24.4 ./configure --prefix=$HOME/.local LDFLAGS=-L$HOME/.local/lib --without-pop --without-kerberos --without-mmdf --without-sound --without-wide-int --without-xpm --without-jpeg --without-tiff --without-gif --without-png --without-rsvg --without-xml2 --without-imagemagick --without-xft --without-libotf --without-m17n-flt --without-xaw3d --without-xim --without-ns --without-gpm --without-dbus --without-gconf --without-gsettings --without-selinux --without-gnutls --without-x make && make install 

References:

https://gist.github.com/tnarihi/6054dfa7b4ad2564819b

http://linuxg.net/how-to-install-emacs-24-4-on-ubuntu-14-10-ubuntu-14-04-and-derivative-systems/

26217398 0 Cannot get div element by id to display gif in internet explorer

I am trying to make a .gif image display in a loading window to alert my user that loading is underway, quite simple. I was doing it using only css and background property like this:

/background: url(ajax-loader.gif) no-repeat center #fff;/

but my .gif was not loading in internet explorer. So I've made a research and found this and, based on J.Davies's solution, I have implemented this instead in my js file:

function ShowProgress() { if (!spinnerVisible) { $('div#layer').fadeIn("fast"); $('div#spinner').fadeIn("fast"); spinnerVisible = true; var pb = $('#spinner'); pb.innerHTML = '<img src="./ajax-loader.gif" width=200 height=40/>'; pb.style.display = ""; } } 

My problem is that it works still in chrome, but I get a crash in internet explorer saying that it pb is undefined. Is there a specificity on how to work with jquery and internet explorer? For information, here's my display:

<div id="body"> @RenderSection("featured", false) <section class="content-wrapper main-content clear-fix"> <section> @Html.Partial("MessageDisplay") </section> <div id="layer"></div> <div id="spinner"> Loading, please wait... </div> @RenderBody() </section> </div> 

And the css saying that spinner and layer div are hidden:

div#spinner { display: none; width: 300px; height: 300px; position: fixed; top: 40%; left: 45%; /*background: url(ajax-loader.gif) no-repeat center #fff;*/ text-align: center; padding: 10px; font: normal 16px Tahoma, Geneva, sans-serif; border: 1px solid #666; margin-left: -50px; margin-top: -50px; z-index: 2; overflow: auto; } div#layer { display: none; width: 100%; height: 100%; position: fixed; top: 0; left: 0; background-color: #a4a3a3; background-color: rgba(164, 163, 163, 0.5); z-index: 1; overflow: auto; -moz-opacity: 0.5 } 
12810133 0 link static library in c++ visual studio

can someone please help me to understand the process.

in c++ visual studio 2010

i have a visual studio solution (lets call it mysol)

i have a project built as a static library (let's call it staticprj) staticprj needs to use a library from outside (lets call it ext.lib)

in the body of the source code of staticprj i include outside library header file with # include extlib.h and make calls to some of its functions (let call them extfunctions()) i also include the the path to the header files location of the ext.lib.

the staticprj compiles okay without errors

the mysol also has another project which is a dynamic library (dynprj) and which depends on the staticprj.

also in the source files of the dynprj uses functions from outside library.

i have included #include extlib.h in the source code of dynprj. i have included the path of the header files i have attached extlib.h directly to the dynprj i have also added ext.lib to the linker input (along with the path where the ext.lib resides).

i still get a lnk2001 error stating that extfunctions() where not found.

the whole structure (the mysol solution) compiles okay if i do not use ext.lib at all.

my question is how does the linking process works and what can i do to correct this linking error.

(note that without the presence of ext.lib my linking of the staticprj and dynprj is fine. my compilation works okay and my code works. i only get the linking error when i try to link another ext.lib to staticprj and dynprj and use functions from ext.lib)

thanks in advance.

15570462 0

I don't know about that other editor, but for Vim syntax highlighting, this is definitely not possible. Why?

If you just want similar colors in Eclipse, you can certainly re-create your Vim colorscheme in another editor. The output of :highlight gives you all defined groups and their color values.

11933191 0

Please, try this query (also on SQL Fiddle):

SELECT p.id, p.user_id, m.username, m.privacy, searcher.username "Searcher", p.status_msg FROM posts p JOIN members m ON m.id = p.user_id LEFT JOIN following f ON p.user_id = f.user_id JOIN members searcher ON searcher.username = 'userA' WHERE (m.privacy = 0 OR (m.privacy = 1 AND f.follower_id = searcher.id) OR m.id = searcher.id) AND p.status_msg LIKE '%New%' ORDER BY p.id LIMIT 5; 

I removed username field from posts table, as it is redundant. Also, I named tables and columns slightly different, so query might need cosmetic changes for your schema.

The first line in the WHERE clause is the one that you're looking for, it selects posts in the following order:

  1. First posts from members without privacy;
  2. Then posts from members that are followed by the current searcher;
  3. Finally, posts of the member himself.

EDIT:

This query is using original identifiers:

SELECT p.id, p.`userID`, m.username, m.privacy, searcher.username "Searcher", p.`statusMsg` FROM posts p JOIN `myMembers` m ON m.id = p.`userID` LEFT JOIN following f ON p.`userID` = f.user_id JOIN `myMembers` searcher ON searcher.username = 'userD' WHERE (m.privacy = 0 OR f.follower_id = searcher.id OR m.id = searcher.id) AND p.`statusMsg` LIKE '%New%' ORDER BY p.id LIMIT 5; 

EDIT 2:

To avoid duplicates in case there're several followers for the user from the posts table, join and filtering conditions should be changed the following way (on SQL Fiddle):

SELECT p.id, p.user_id, m.username, m.privacy, searcher.username "Searcher", p.status_msg FROM posts p JOIN members m ON m.id = p.user_id JOIN members searcher ON searcher.username = 'userC' LEFT JOIN following f ON p.user_id = f.user_id AND follower_id = searcher.id WHERE (m.privacy = 0 OR (m.privacy = 1 AND f.id IS NOT NULL) OR m.id = searcher.id) ORDER BY p.id LIMIT 5; 
27549500 0

I think msmq's answer is valid, but you should be a little careful about using the main info.plist this way. Doing that suggests that all your versions of info.plist are almost identical, except for a couple of differences. That's a recipe for divergence, and then hard-to-debug issues when you want to add a new URI handler or background mode or any of the other things that might modify info.plist.

Instead, I recommend you take the keys that vary out of the main info.plist. Create another plist (say "Config.plist") to store them. Add a Run Script build phase to copy the correct one over. See the Build Settings Reference for a list of variables you can substitute. An example script might be:

cp ${SOURCE_ROOT}/Resources/Config-${CONFIGURATION}.plist ${UNLOCALIZED_RESOURCES_FOLDER_PATH}/Config.plist 

Then you can read the file using something like this (based on Read in the Property List):

NSString *baseURL; NSString *path = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"]; NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; NSString *errorDesc = nil; NSDictionary *dict = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListImmutable format:NULL errorDescription:&errorDesc]; if (dict != nil) { baseUrl = dict[@"baseURL"]; } else { NSAssert(@"Could not read plist: %@", errorDesc); // FIXME: Return error } 

There are other solutions of course. I personally generally use the preprocessor for this kind of problem. In my build configuration, I would set GCC_PREPROCESSOR_DEFINITIONS to include BaseURL=... for each build configuration and then in some header I would have:

#ifndef BaseURL #define BaseURL @"http://default.example.com" #endif 

The plist way is probably clearer and easier if you have several things to set, especially if they're long or complicated (and definitely if they would need quoting). The preprocessor solution takes less code to process and has fewer failure modes (since the strings are embedded in the binary at compile time rather than read at runtime). But both are good solutions.

20617512 0

You are trying to connect to a local instance of RabbitMQ.

BROKER_URL = 'amqp://guest:guest@localhost:5672/'

in your settings.py). If you are working currently on development, you could avoid setting up Rabbit and all the mess around it, and just use a development-version of a Message Queue with the Django Database.

Do this by replacing your previous configuration with

BROKER_URL = 'django://' and add this app:

INSTALLED_APPS += ('kombu.transport.django', )

Finally, launch the worker with

./manage.py celery worker --loglevel=info

Source: http://docs.celeryproject.org/en/latest/getting-started/brokers/django.html

10737118 0

The easiest way to go about it is to offload it to separate process using ztask.

from django_ztask.decorators import task @task() def delayed_save(obj): obj.save() ... your_object.something = "something" delayed_save.async(your_object) 
14476479 0 Using mail() to send an attachment AND text/html in an email in PHP4

To make life difficult, the client I'm working for is using a really large yet old system which runs on PHP4.0 and they're not wanting any additional libraries added.

I'm trying to send out an email through PHP with both an attachment and accompanying text/html content but I'm unable to send both in one email.

This sends the attachment:

$headers = "Content-Type: text/csv;\r\n name=\"result.csv\"\r\n Content-Transfer-Encoding: base64\r\n Content-Disposition: attachment\r\n boundary=\"PHP-mixed-".$random_hash."\""; $output = $attachment; mail($emailTo, $emailSubject, $output, $headers); 

This sends text/html:

$headers = "Content-Type: text/html; charset='iso-8859-1'\r\n"; $output = $emailBody; // $emailBody contains the HTML code. 

This sends an attachment containing the text/html along with the attachment contents:

$headers = "Content-Type: text/html; charset='iso-8859-1'\r\n".$emailBody."\r\n"; $headers = "Content-Type: text/csv;\r\n name=\"result.csv\"\r\n Content-Transfer-Encoding: base64\r\n Content-Disposition: attachment\r\n boundary=\"PHP-mixed-".$random_hash."\""; $output = $attachment; 

What I need to know is how can I send an email with text/html in the email body and also add an attachment to it. I'm sure I'm missing something really simple here!

Thanks in advance.

37484024 0

Here is your code converted to PDO.

// Make sure the email address is available: $q = $dbc->query("SELECT user_id FROM users WHERE email=?"); $q->execute(array($e)); $r = $q->fetchColumn(); if (!$r) { // Available. // Create the activation code: $a = md5(uniqid(rand(), true)); 

Three things has been corrected

  1. You have to always use a placeholder tp represent a variable in the query.
  2. To get a single value from the result, fetchColumn have to be used instead of fetchAll
  3. No need for the manual reporting, as PDO can report its errors automatically, if confugired properly, as described in this tutorial I wrote
28096069 0
Def recadd(lis): If lis[0] + lis[1] - lis[2]] = lis[3]: return lis Else: recadd(lis[3] + lis[0:2]) recadd(lis[0] + lis[3] + lis[1:2]) recadd(lis[0:1] + lis[3]. + lis[2]) 

Quick and dirty hack on my mobile, could be elegantly expanded for k numbers, untested but it should work.

Edit: realized this won't work if there is no solution.infinite recursion...

23916553 0

try this

def bookList() = { val res = resource.getAssets.open("demo.png") val image = Drawable.createFromStream(res, "demo.png") val map = Map[String, Drawable]() for (i <- 1 to 100) { map += (s"test book$i" -> image) } map } 
6471481 0

This may be useful:
http://gcc.gnu.org/onlinedocs/gcc-4.1.1/cpp/Search-Path.html#Search-Path

27315459 0 My application does not save data to the database

I have tried to create a C# application that saves data to an existing local SQL database. I created a local database called AccountDatabase.mdf which has a table called AccountTable in it. I first started with an empty table. I then used the code below to get the application to save the input data to the database.

private void FPAccountNotExist_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { //Make forgot password page invisible and create new account page visible ForgotPassword.Visible = false; CreateNewAccount.Visible = true; //Set text content of labels on create new account page CreateNewAccountTitle.Text = "Create New Account"; CNAConfirmLabel.Text = "Confirm Password"; CNAEmailLabel.Text = "Email"; CNAInstruction.Text = "Please fill in the following details."; CNAOpenAccount.Text = "Submit new account"; CNAPasswordLabel.Text = "Password"; CNAUsernameLabel.Text = "Username"; OpenManual.Text = "Start with Manual"; CNAConfirmTextBox.UseSystemPasswordChar = true; CNAPasswordTextBox.UseSystemPasswordChar = true; 

}

private void CNAOpenAccount_Click(object sender, EventArgs e) { AccountVariables.ConfirmedPassword = CNAConfirmTextBox.Text; AccountVariables.Email = CNAEmailTextBox.Text; AccountVariables.Password = CNAPasswordTextBox.Text; AccountVariables.Username = CNAUsernameTextBox.Text; //GeneralVariables.ManualOption = OpenManual.Checked; var CreateNewAccountStrings = new List<string> { AccountVariables.ConfirmedPassword, AccountVariables.Password, AccountVariables.Email, AccountVariables.Username }; if (CreateNewAccountStrings.Contains("")) { MessageBox.Show("All textboxes should be filled"); } else { if ((AccountVariables.ConfirmedPassword == AccountVariables.Password) && (AccountVariables.Password.Length >= 8)) { accountTableTableAdapter.Fill(accountDatabaseDataSet.AccountTable); AccountVariables.defaultAccountRow = AccountVariables.defaultAccountRow + 1; AccountVariables.newAccountTableRow = accountDatabaseDataSet.AccountTable.NewAccountTableRow(); AccountVariables.newAccountTableRow.UserId = AccountVariables.defaultAccountRow; AccountVariables.newAccountTableRow.Username = AccountVariables.Username; AccountVariables.newAccountTableRow.Email = AccountVariables.Email; AccountVariables.newAccountTableRow.Password = AccountVariables.Password; accountDatabaseDataSet.AccountTable.AddAccountTableRow(AccountVariables.newAccountTableRow); accountTableTableAdapter.Update(accountDatabaseDataSet.AccountTable); accountDatabaseDataSet.AccountTable.AcceptChanges(); AccountVariables.AccountDatabaseConnection.Close(); } } } 

However, when I closed the program after running the application, I looked in the database and saw that the rows had not been saved, even after I have saved it. Please can you help me solve this problem.

13341544 0

I would first try to optimze your query. Is it slow in SSMS? Do you use proper indices? Do you need all columns. Most important: do you need all 50000 rows to be displayed?

50000 records are not many records, but it's unusual to show all in a web application since that means you have to generate the HTML for all records and display it in the client's browser(maybe even using ViewState). So i would suggest to use database paging(f.e. via ROW_NUMBER function) to partition your resultset and query only the data you want to show(f.e. 100 rows per page in a GridView).

Efficiently Paging Through Large Amounts of Data

39130085 0
Object json = mapper.readValue(input, Object.class); String indented = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json); 
13966814 0

You can merge all of your string in one string by StringBuilder and apply it to the TextView.

I've implemented my own TextView with scrolling by wrapping textview (and maybe some other views)

private Runnable scrollRight = new Runnable() { @Override public void run() { // can control scrolling speed in on tick topScroll.smoothScrollBy(1, 0); } }; 

and in new Thread I invoke:

while (!interruptScroll){ try{ Thread.sleep(50); // control ticking speed } catch (InterruptedException e){ e.printStackTrace(); } topScroll.post(scrollRight); } 

and by manually scrolling the scrollView i interrupt the scrolling (such an automatic scrolling while not interrupted by user).

29392238 0

Using HtmlAgilityPack (HAP) and XPath function name() didn't work for me, but replacing name() with local-name() did the trick :

//*/@*[starts-with(local-name(), 'on')] 

However, both SelectSingleNode() and SelectNodes() only able to return HtmlNode(s). When the XPath expression selects an attribute instead of node, the attribute's owner node would be returned. So in the end you still need to get the attribute through some options besides XPath, for example :

HtmlDocument doc; ...... var link = doc.DocumentNode .SelectSingleNode("//*/@*[starts-with(local-name(), 'on')]"); var onclick = link.Attributes .First(o => o.Name.StartsWith("on")); 
23678485 0 Adding parameters to URL in ZF2


I am trying to construct url which looks like this:

 abc.com/folder?user_id=1&category=v 

Followed the suggestion given in this link:

How can you add query parameters in the ZF2 url view helper

Initially, it throws up this error

 Query route deprecated as of ZF 2.1.4; use the "query" option of the HTTP router\'s assembling method instead 

Following suggestion, I used similar to

 $name = 'index/article'; $params = ['article_id' => $articleId]; $options = [ 'query' => ['param' => 'value'], ]; $this->url($name, $params, $options); 

Now, I am getting syntax error saying,

 Parse error: syntax error, unexpected '[' in /var/www/test/module/Dashboard/view/dashboard/dashboard/product.phtml on line 3 

My module.config.php is configured like this:

 'browse_test_case' => array( 'type' => 'Literal', 'options' => array( 'route' => '/browse-case[/:productId]', 'defaults' => array( 'controller' => 'Test\Controller\Browse', 'action' => 'browse-test-case', ), ), 'may_terminate' => true, 'child_routes' => array( 'query' => array( 'type' => 'Query', ), ), ), 

Any Idea, please help!

119732 0 How to initialize Hibernate entities fetched by a remote method call?

When calling a remote service (e.g. over RMI) to load a list of entities from a database using Hibernate, how do you manage it to initialize all the fields and references the client needs?

Example: The client calls a remote method to load all customers. With each customer the client wants the reference to the customer's list of bought articles to be initialized.

I can imagine the following solutions:

  1. Write a remote method for each special query, which initializes the required fields (e.g. Hibernate.initialize()) and returns the domain objects to the client.

  2. Like 1. but create DTOs

  3. Split the query up into multiple queries, e.g. one for the customers, a second for the customers' articles, and let the client manage the results

  4. The remote method takes a DetachedCriteria, which is created by the client and executed by the server

  5. Develop a custom "Preload-Pattern", i.e. a way for the client to specify explicitly which properties to preload.

9353661 0 Storing ABRecordRef in Core Data

I would like to store a ABRecordRef in a 'Client' entity in core data.

I have read in apples documentation that ABRecordRef is a primitive C data type. As far as I am aware, you can only insert objects in core data. With this in mind, what is the best way to store it in core data?

I thought about converting it into a NSNumber for storage, but dont know how to convert it back to ABRecordRef for use.

I also thought I could just put it in a NSArray/NSSet/NSDictionary on its own just acting as a wrapper but didnt know if this was silly/inefficient/would even work.

Thoughts appreciated.

Many thanks

22052735 0 Trace a curve with two colors?

is there a way to have a curve with two colors, well i have many curves in my plot. But I like to add a specific characteristic, i want the curve 1 to be simple line in[a,b] interval, and dotted line in interval [b,c].

an example of my graph:

plot exp(-x**2 / 2), sin(x)

can we make sin(x) plotted in dotted line from[0,5]

thanks in advance.

31312465 0 How to avoid duplicate insert of ToolbarItem in Xamarin.forms?
protected override void OnAppearing(){ ToolbarItem itemStudy = new ToolbarItem { Name = "Study", Order = ToolbarItemOrder.Primary, Command = new Command (() => Navigation.PushAsync (studyPage)) }; if (ToolbarItems.Count > 0) { ToolbarItems.RemoveAt(0); } ToolbarItems.Add (itemStudy); } 

This is my Code snipped on Xamarin.forms for adding Toolbaritem. Anyhow I don't think this is an elegant way and looking for better solution. Can anyone help? Thanks.

34020483 0 Where is PFFile saved?

I save UIImage as PFFile:

let imageFile = PFFile(data: imageData) imageFile?.saveInBackgroundWithBlock({}) 

This file is not referenced with any PFObject, so what happens to him?

  1. This file is saved on my reserved storage (20GB)?

  2. Is there any tool for clean non-referenced files?

  3. If I assign some PFFile to object and replace it by other PFFile after that, first object will be deleted?

13503068 0

I think what you will see is just differences in coding practice.

If all child classes have the same exact init() method, there is no reason to even have the method declared within the child classes.

In some cases, however I have seen developers do exactly what you have shown. In a lot of cases this may because the eventual intent may be to somehow augment the parent method behavior in a way specific to the class. In other cases, I have seen some collection of children classes override the functionality, so the developer puts a method like this in all child classes just so the intent (execute parent method as is for this child class) is clear to other developers.

15086294 0

You can also do it like tihs:

public static function generateCode($length = 6) { $az = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $azr = rand(0, 51); $azs = substr($az, $azr, 10); $stamp = hash('sha256', time()); $mt = hash('sha256', mt_rand(5, 20)); $alpha = hash('sha256', $azs); $hash = str_shuffle($stamp . $mt . $alpha); $code = ucfirst(substr($hash, $azr, $length)); return $code; } 
8972776 0

Yes - you or have to introduce date_of_entry field or some other vector field like IDENTITY. For example if column Id is your INT IDENTITY, then your query will look like this:

 ;WITH cte AS (SELECT ROW_NUMBER() OVER (PARTITION BY person_id, date_work, hours ORDER BY ( SELECT Id DESC)) RN FROM work_hours) DELETE FROM cte WHERE RN > 1 

Of course it is valid if nobody changes the values in IDENTITY column

And if your conditions suits - then you may want to use column Hours as your vector field within grouping range of person_id, date_work

And even better way is to have an UNIQUE INDEX over columns person_id, date_work, hours, then there will no any ability to add duplicates.

2192006 0 Failed to Map Path '/doc'. server.map path

If I run the site using the internal Visual Studio web server, I get the failed to map path error.

35561493 0

There's a few ways to clean this up in Ruby that I'll demonstrate here:

puts 'Hello mate what is thy first name?' name1 = gets.chomp # Inline string interpolation using #{...} inside double quotes puts "Your name is #{name1} eh? What is thy middle name?" name2 = gets.chomp # Interpolating a single string argument using the String#% method puts 'What is your last name then %s?' % name1 name3 = gets.chomp # Interpolating with an expression that includes code puts "Oh! So your full name is #{ [ name1, name2, name3 ].join(' ') }?" puts 'That is lovey!' # Combining the strings and taking their aggregate length puts 'Did you know there are %d letters in your full name?' % [ (name1 + name2 + name3).length ] # Using collect and inject to convert to length, then sum. puts 'Did you know there are %d letters in your full name?' % [ [ name1, name2, name3 ].collect(&:length).inject(:+) ] 

The String#% method is a variant of sprintf that's very convenient for this sort of formatting. It gives you a lot of control over presentation.

That last one might look a bit mind-bending but one of the powerful features of Ruby is being able to string together a series of simple transformations into something that does a lot of work.

That part would look even more concise if you used an array to store the name instead of three independent variables:

name = [ ] name << gets.chomp name << gets.chomp name << gets.chomp # Name components are name[0], name[1], and name[2] # Using collect -> inject name.collect(&:length).inject(:+) # Using join -> length name.join.length 

It's generally a good idea to organize things in structures that lend themselves to easy manipulation, exchange with other methods, and are easy to persist and restore, such as from a database or a file.

2773791 0

I finally got the solution. The problem was with the field's verbose name - it was str instead of unicode. Moving to unicode helped.

Thanks :-)

39429247 0

you can use the all method.

Book.all 

This will return all of the books on record.

25918441 0 Creating links relative to localhost

I'm trying to create a custom menu in drupal 7 by coding it in a custom code block, but I'm running into the issue that the links I create aren't lined up to the way my local site is setup. Is there php code or a drupal setting of some sort that can create a link relative to the local machine setup?

To give more context: My friend and I are working on creating a drupal site and have individually setup our local files differently (we are sharing the database which is on a remote server). When browsing to the site, his URL shows up: localhost/content/page. Whereas how I have it setup is: localhost/sitename/content/page.

When I create an internal link in the nav menu, I have to create it using a relative path /content/page, otherwise the link wont work on my coworkers localhost. This, in turn, makes it so that the link doesn't work on my locahost.

Is there a way I can create these links relative to the localhost so that it works on both machines? When creating a navigation menu using my Drupal theme this is not an issue, but since the link list I'm creating is custom coded, I can't seem to figure out how to mimic this same functionality.

Any ideas? Thanks!

5588023 0 ASP.NET MVC - How to re-run jQuery tabs script after getJSON call?

I have some data wrapped in 3 divs, each div represents a 'tab', and a jQuery script to create the tab effect. The 3 tabs include hours of operation, contact info, location info.

Pretty standard, nothing special. When the page loads, the following script is run, creating the 'tab' effect.

 $(document).ready(function () { tabs({ block: "#branch" }); }); 

I have a drop down list that triggers a call to an action that returns a JsonResult, and the following code to handle the change:

 $("#branches").change(function () { $("#branches option:selected").each(function () { $.getJSON("/Branch/JsonBranch/" + $(this)[0].value, null, function (data) { $("#branchinfo").html(data); }); }); }); 

The action is a variation on the post ASP.NET MVC - Combine Json result with ViewResult

The action code isn't relevant. The problem is that, since I'm not reloading the whole page, the 'tab' script is never run again. So, once the html code is replaced, ALL the data shows, the tabs are not created.

Is there a way to run the tab script again after just reloading that one portion of the page? I tried adding the call to tabs() in the .change() function call, but that didn't work.

Any help would be appreciated! Thanks!

22077268 0

The above code will only run once only which will add information to head only once. If you want to add more information in case of second run then add code for else condition. Example:-

if ( head == NULL ) { // code to insert data in case of first run }else{ // code to insert data for second run and so..... } 
32280035 0 Prevent IE caching AngularJS/Restangular

In IE, when I make an update to or destroy an item in a list, the action is successful, but the updated list/data is not returned from the server, thus the list is not being updated in the view.

I've tried the following to no avail:

angular.module('casemanagerApp') .config(function($stateProvider, $urlRouterProvider, RestangularProvider) { if (!RestangularProvider.setDefaultHeaders) { RestangularProvider.setDefaultHeaders({}); } RestangularProvider.setDefaultHeaders({'If-Modified-Since': 'Mon, 26 Jul 1997 05:00:00 GMT'}); RestangularProvider.setDefaultHeaders({'Cache-Control': 'no-cache'}); RestangularProvider.setDefaultHeaders({'Pragma': 'no-cache'}); $stateProvider ... }); 

Can anyone point me in the right direction for a solution to this?

37733893 0 Squash git commits from topic branch

I have a topic branch (macaroni), and I have submitted a pull request. I had to make a change after feedback. It was requested that I squash the two commits into a single commit. This is what I have done:

git status On branch macaroni git log commit def feedback fixes commit abc fix cheddar flavor git rebase -i origin/master .. go through screen where I pick commit to squash .. .. go through screen where I update commit message .. git log commit abc fix cheddar flavor, squashing done! 

at this point I believe I have to push my topic branch using the -force flag, because I have changed history:

git push -f 

I am using the second answer from this question:

Preferred Github workflow for updating a pull request after code review

with subtitle "Optional - Cleaning commit history". The author mentions at the end that you should be using topic branches, not sure if I should have changed any of the commands since I'm already on a topic branch.

I am also concerned with accidentally force-pushing something onto the master branch with the above since I'm using -f, but since I'm on the topic branch, only that branch should be affected, right?

Thanks

38084853 0 how to show a window only one time?

I want display a window only one time. When the user click on this button:

private void Notification_Click(object sender, RoutedEventArgs e) { NotificationSettings notifications = new NotificationSettings(); notifications.ShowDialog(); } 

this will create a new window, I want that if there is already a window opened the user can't open a new one. There is an option in xaml for tell to compiler this? I remember the vb.net with windows form that allow to set the option to show only one windows at time.

Thanks.

10302647 0

If you want to pass the whole list in a single parameter, use array datatype:

SELECT * FROM word_weight WHERE word = ANY('{a,steeple,the}'); -- or ANY('{a,steeple,the}'::TEXT[]) to make explicit array conversion 
5108964 0 Attached databases in Honeycomb

Has anyone ran into attached database issues with Honeycomb yet? My application uses attached databases (working on 1.5 through 2.3) using the statements:

...

String newDb = "/data/data/com.stuff.app/databases/mydata.db"; db.execSQL("attach database ? as newDb", new String[] {newDb}); String[] columns = MY_COL_NAMES; String orderBy = DEFAULT_SORT_ORDER; Cursor cursor = db.query("newDb.mydata", columns, null, null, null, null, orderBy); 

...

This is working (1.5 through 2.3) regardless of the actual location of the sqlite database file (local or SD Card)...However, in Honeycomb, the db.query statement results in a "I/SqliteDatabaseCpp( 628): sqlite returned: error code = 1, msg = no such table: newDb.mydata ..."

I can manually attach the database from within sqlit3 by issuing the statement:

sqlite3>attach database '/data/data/com.stuff.app/databases/mydata.db' as newDb;

Any help resolving this would be greatly appreciated.

9047001 0

If your receiver must know the concrete type, then you're not using Interfaces properly.

If you're returning a page, there's really no reason for anything to know what kind of page it is. I would add a Render method to the IPage interface so that all the receiver has to do is call Render() and the page will handle the rest.

7167976 0

The collection is a reference type, so other holding code onto that will see the old data.

Two possible solutions:

Instead of data = temp use data.Clear(); data.AddRange(temp) which will change the contents of the data field.

Or better delete the MyCollection property and make class implement IEnumerable. This results in much better encapsulation.

18949117 0

Assuming a dash following a space or vice versa is ok:

^( -?|- ?)?(\d( -?|- ?)?){9,13}$ 

Explanation:

( -?|- ?) - this is equivalent to ( | -|-|- ). Note that there can't be 2 consecutive dashes or spaces here, and this can only appear at the start or directly after a digit, so this prevents 2 consecutive dashes or spaces in the string.

And there clearly must be exactly one digit in (\d( -?|- ?)?), thus the {9,13} enforces 9-13 digits.

Assuming a dash following a space or vice versa is NOT ok:

^[ -]?(\d[ -]?){9,13}$ 

Explanation similar to the above.

Both of the above allows the string to start or end with a digit, dash or space.

37299020 0

Instance types are cached in the browser's local storage. You can explicitly refresh the cache via the 'Refresh all caches' link:enter image description here

If you show the network tab of your browser's console (prior to clicking 'Refresh all caches'), you should see a request to http://localhost:8084/instanceTypes.

If the response contains your instance types, you should be good to go.

15978379 0

This command does two main things: create a mask with that torn-paper effect, apply the mask to the image. It does them, fancily, in one line, by using +clone and the parentheses. It's less confusing to do it as two commmands though:

convert thumbnail.gif \ -alpha extract \ -virtual-pixel black \ -spread 10 \ -blur 0x3 \ -threshold 50% \ -spread 1 \ -blur 0x.7 \ mask.png convert thumbnail.gif mask.png \ -alpha off \ -compose Copy_Opacity \ -composite torn_paper.png 

The first command is fairly complex. But you can find decent explanations of each of the component commands in the ImageMagick docs:

Also, by splitting the command into these two pieces, you can see what the mask looks like on its own. It's basically the inverse of the paper effect. White throughout the middle of the images, fading to black around the "torn edges".

The second command is a lot more straightforward. Copy_Opacity, as described in the ImageMagick docs, is a way of making parts of an image transparent or not. Anything that's black in the mask will be made transparent in the resulting image. In effect, the second command uses the mask to "erase" the edges of the original thumbnail in a stylistically interesting way.

18597835 0 Placing a TextView below two ImageViews and in middle - Android

Please share code to achieve the layout of the screen shown in the below link. The text should be in center of the two images and all these components can be dynamic.

(https://docs.google.com/file/d/0B9n2IhVep_QeNDFKaWFHVERQOVk/edit?usp=sharing)

https://www.dropbox.com/s/2j4bpwdmv0wgesg/Untitled%20Diagram.png

30757002 0

pboedker and ChrisKo answers are both good. A couple of extra warnings are needed.

A scan (or the scan time) can be shorter than your code's execution time. In most PLC's there is a "watchdog" to detect this, and warn you that it is happening. You often need to set this "watchdog" up, and set up a alarm/event handler for it.

Know how your PLC executes I/O. Some (Such as ControlLogix) are Asynchronous, I/O gets read into your controllers memory based on the RPI (request packet interval), and gets written out (same RPI) when you make a change to the I/O point with code. Others (Such as AutomationDirect's Productivity 2000 series) only write the outputs upon a COMPLETE scan of your code. I'm sure you can picture the pro's and cons of each scenario, especially if your controller is not completing your code before restarting a scan.

PLC's that allow you to have different scan rates for different pieces of code give you powerful tools for I/O and program flow management. Slow processes can be scanned slowly, allowing you more PLC time for other things.

9814937 0

Follow this guide: http://weblogs.asp.net/psheriff/archive/2009/12/01/load-resource-dictionaries-at-runtime-in-wpf.aspx

  1. Create various xaml resource files, but make sure the file does not compile and copies into the bin directory instead.
  2. Decorate your xaml controls with DynamicResources.
  3. Load in your resources through code.

Basically, you are looking to "skin" your application. The code that loads in your resource file can take advantage of the TimeOfDay enumeration.

If you want it automated you can even have some static class that has a timer to automatically attempt to change the resource and set the timer on the application startup. :)

40354505 0

You can manually bootstrap angular after receive data from server.

Example on jsfiddle:

var app = angular.module("myApp", []); app.controller("myController", function($scope, servicesConfig) { console.log(servicesConfig); $scope.model = servicesConfig.host; $scope.reset = function() { $scope.model = ''; }; }); angular.element(document).ready(function() { //Simulate AJAX call to server setTimeout(function() { app.constant('servicesConfig', { host: "appdev" }); angular.bootstrap(document, ['myApp']); }, 2000); });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-cloak> <div ng-controller="myController"> <input type="text" ng-model="model" /> {{model}} <button ng-click="reset()">Reset</button> </div> </div>

30815407 0 YARN log aggregation on a per job basis

Can properties such as yarn.log-aggregation-enable and yarn.log-aggregation.retain-seconds applied on a per job basis? I would not like this to be enabled at a cluster-wide scale but only for a few tasks.

5286116 0

If you like to learn by doing then learn by doing it in PDO and bind the parameters. This is the safe and correct way to do it these days.

4193721 0

If you want to implement server side sorting then it does not matter what technology you are using in the front end.

On a conceptual level you can do the following things:

  1. Write a SortingServlet which takes your grid and sorts it according to the request parameters passed to it and renders the output in the form of json(not strictly required but good to have)
  2. Use jQuery to make a Ajax call to this servlet and then format the response when you get it back.
25744475 0

EDIT: Updated with resize event listener. Updated fiddle.

As I understand it, you want the text to be as large as possible while still fitting inside the containing <div>, correct? My solution is to put a <span> around the text, which conforms to the text's normal size. Then calculate the ratios between the container's dimensions and the <span>'s dimensions. Whichever is the smaller ratio (either width or height), use that ratio to enlarge the text.

HTML:

<div class="container"> <span class="text-fitter"> text here </span> </div> 

JS (jQuery):

textfit(); $(window).on('resize', textfit); function textfit() { $('.text-fitter').css('font-size', 'medium'); var w1 = $('.container').width()-10; var w2 = $('.text-fitter').width(); var wRatio = Math.round(w1 / w2 * 10) / 10; var h1 = $('.container').height()-10; var h2 = $('.text-fitter').height(); var hRatio = Math.round(h1 / h2 * 10) / 10; var constraint = Math.min(wRatio, hRatio); $('.text-fitter').css('font-size', constraint + 'em'); } 

Here's a fiddle. Adjust the .container dimensions in the CSS to see it in action.

13793935 0

I'm only marking this as the answer to close the case, what the actual answer was to the problem we will never know. The solution: automatic updates. After much hassles with getting automatic updates to actually go through, my machine is now working well.

4969681 0

in case you want both containers to float besides each other, you can rather use a span instead of a div. That might bring the problem to an end.

33093272 0

It's related with thread not killed after use, not related with logging module, it's solved now, thanks for attention.

23032838 0

If you are looking to just "preload" the images so that you can use them later (in your app/page), then you can use the following HTML 5 code:

<link rel="prefetch" href="http://davidwalsh.name/wp-content/themes/walshbook3/images/sprite.png" /> 

See: Link prefetching is a browser mechanism, which utilizes browser idle time to download or prefetch documents that the user might visit in the near future. A web page provides a set of prefetching hints to the browser, and after the browser is finished loading the page, it begins silently prefetching specified documents and stores them in its cache. When the user visits one of the prefetched documents, it can be served up quickly out of the browser's cache. URL, then description, then title, keywords.. and finally body.

If for gallery, then @Santosh is correct. Or http://code.msdn.microsoft.com/Infinite-Scroll-Like-Bing-bc05262b

32792841 0
self.printfunc = weakref.ref(printfunc)() 

isn't actually using weakrefs to solve your problem; the line is effectively a noop. You create a weakref with weakref.ref(printfunc), but you follow it up with call parens, which converts back from weakref to a strong ref which you store (and the weakref object promptly disappears). Apparently it's not possible to store a weakref to the bound method itself (because the bound method is its own object created each time it's referenced on self, not a cached object whose lifetime is tied to self), so you have to get a bit hacky, unbinding the method so you can take a weakref on the object itself. Python 3.4 introduced WeakMethod to simplify this, but if you can't use that, then you're stuck doing it by hand.

Try changing it to (on Python 2.7, and you must import inspect):

# Must special case printfunc=None, since None is not weakref-able if printfunc is None: # Nothing provided self.printobjref = self.printfuncref = None elif inspect.ismethod(printfunc) and printfunc.im_self is not None: # Handling bound method self.printobjref = weakref.ref(printfunc.im_self) self.printfuncref = weakref.ref(printfunc.im_func) else: self.printobjref = None self.printfuncref = weakref.ref(printfunc) 

and change myprint to:

def myprint(self,text): if self.printfuncref is not None: printfunc = self.printfuncref() if printfunc is None: self.printfuncref = self.printobjref = None # Ref died, so clear it to avoid rechecking later elif self.printobjref is not None: # Bound method not known to have disappeared printobj = self.printobjref() if printobj is not None: print ("ExtenalFUNC:%s" %text) # To call it instead of just saying you have it, do printfunc(printobj, text) return self.printobjref = self.printfuncref = None # Ref died, so clear it to avoid rechecking later else: print ("ExtenalFUNC:%s" %text) # To call it instead of just saying you have it, do printfunc(text) return print ("JustPrint:%s" %text) 

Yeah, it's ugly. You could factor out the ugly if you like (borrowing the implementation of WeakMethod from Python 3.4's source code would make sense, but names would have to change; __self__ is im_self in Py2, __func__ is im_func), but it's unpleasant even so. It's definitely not thread safe if the weakrefs could actually go dark, since the checks and clears of the weakref members aren't protected.

40363768 0 runjags trouble locating JAGS - error "'where' not found" even after setting jagspath

Seems that runjags suddenly (after update to version 2.0.3-2) has trouble finding JAGS binary, issuing an error:

[1] "Error in system(\"where jags\", intern = TRUE) : 'where' not found\n" attr(,"class") [1] "try-error" attr(,"condition") <simpleError in system("where jags", intern = TRUE): 'where' not found 

I fixed this by putting this line to my Rprofile:

.runjags.options <- list(jagspath = "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe") 

This pretty much fixes the problem (although it is not ideal - previous versions of runjags could find the binary automatically).

However, when the Rgui (in Windows XP) is launched by opening an .Rdata file, which is associated to it, it stops working:

> .runjags.options # it was set in the Rprofile $jagspath [1] "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe" > require(runjags) Loading required package: runjags Warning message: package ‘runjags’ was built under R version 3.1.3 > runjags.getOption("jagspath") [1] "Error in system(\"where jags\", intern = TRUE) : 'where' not found\n" attr(,"class") [1] "try-error" attr(,"condition") <simpleError in system("where jags", intern = TRUE): 'where' not found 

Is this a bug? How to fix this?

I am currently calling runjags.options(jagspath = "c:/Program Files/JAGS/JAGS-4.2.0/i386/bin/jags-terminal.exe") in my source after require(runjags), but I would like to avoid this as much as possible!

7470318 0 Setting parameter of layout of android programmatically

I am new to android. I want to know how to set the parameters or attributes to layout x and layout y width and height from the program for any layouts like absolute.

9671918 0 Disable submit if inputs empty jquery

Disclaimer: I know there are quite a few questions out there with this topic and it has been highly addressed, though I need assistance in my particular case.

I am trying to check if the input values are empty on keyup then disable the submit button.

My HTML snippet:

<div class='form'> <form> <div class='field'> <label for="username">Username</label> <input id="username" type="text" /> </div> <div class='field'> <label for="password">Password</label> <input id="password" type="password" /> </div> <div class='actions'> <input type="submit" value="Login" /> </div> </form> </div> 

I have used the example answer from here with some modifications:

(function() { $('.field input').keyup(function() { var empty = false; $('.field input').each(function() { if ($(this).val() == '') { empty = true; } }); if (empty) { $('.actions input').attr('disabled', true); } else { $('.actions input').attr('disabled', false); } }); })() 

Any help would be greatly appreciated!

38587336 0

mysqli_real_escape_string is good, but not always safe as prepared statement.

mysql_real_escape_string() prone to the same kind of issues affecting addslashes().

So use of prepared statement is much better.

26567465 0 GeckoInputElement.Click returns System.NullReferenceException

I am making use of the GeckoWebbrowser control in a C# Windows forms app environment.

I am wanting to call the click event on a button on the browser page, from a code event behind.

When I try an access a specific button I can find it by making use of the GetElementById command, however after assigning this information to the GeckoInputElement to call the click event, there is a null reference exception visible with this.

My code call to get the element looks like this:

GeckoInputElement betbt = new GeckoInputElement(wBrowser.Document.GetElementById("bet-bt").DomObject); 

If I assign it like this I can access the element but still cannot click it with the GeckoElement object:

GeckoElement g1 = (GeckoElement)wBrowser.Document.GetElementById("bet-bt"); 

The HTML for the button looks as follows:

<button data-action="bet" id="bet-bt" class="action">Bet</button> 
36754439 0

Use background-size: cover; or background-size: contain; as per your necessity. That should fix it.

29024997 0

The PowerPivot tab is a COM Add-In. To view the progID of it and other COM Add-Ins use:

Sub ListCOMAddins() Dim lngRow As Long, objCOMAddin As COMAddIn lngRow = 1 With ActiveSheet For Each objCOMAddin In Application.COMAddIns .Cells(lngRow, "A").Value = objCOMAddin.Description .Cells(lngRow, "B").Value = objCOMAddin.Connect .Cells(lngRow, "C").Value = objCOMAddin.progID lngRow = lngRow + 1 Next objCOMAddin End With End Sub` 

In my case the progID of the PowerPivot tab is "Microsoft.AnalysisServices.Modeler.FieldList". So to close the tab use:

Private Sub Workbook_Open() Application.COMAddIns("Microsoft.AnalysisServices.Modeler.FieldList").Connect = False End Sub 
33940429 0

In order to define an ArrayList with CheckBoxes please refer to following example:

List<JCheckBox> chkBoxes = new ArrayList<JCheckBox>(); 

Add your JCheckBox elements to the ArrayList using standard approach, for example:

JCheckBox chkBox1 = new JCheckBox(); chkBoxes.add(chkBox1); 

Interatve over the list and carry out check if selected using JCheckBox method #.isSelected() as follows:

for(JCheckBox chkBox : chkBoxes){ chkBox.isSelected(); // do something with this! } 
13315966 0

There's another angle to this one. If you have SQL Server 2008 already installed, you need to select the upgrade option. If you don't, then in your installation of SQL Server 2008 R2 your "management tools - complete" will be grayed out when you get to the install items choice screen. Hover over it and it will tell you as much. Hope this helps someone.

24004362 0

I think that you can change the new resource to newVisit like this:

App.Router.map () -> @resource 'visits', -> @resource 'visit', { path: '/:visit_id' } @resource 'newVisit', -> @route 'welcome' @route 'directory' @route 'thanks' 

Now you will have a NewVisitRoute where you can create a new Visit model to use in each of the child routes.

And you will be able to make a transition to this routes with the route names: newVisit.welcome, newVisit.directory and newVisit.thanks. You can use this route names in a link-to helper link this:

{{link-to "Welcome", "newVisit.welcome"}} 
15040416 0

I use LaTeX to create the DOM representation.

Here is a minimal working example:

\documentclass{scrreprt} \usepackage{tikz-qtree} \begin{document} \Tree[.table [.thead [.tr [.th [.\textit{Vorname} ] ] [.th [.\textit{Nachname} ] ] ] ] [.tbody [.tr [.td [.\textit{Donald} ] ] [.td [.\textit{Duck} ] ] ] ] ] \end{document} 

Which gives:

enter image description here

8414219 0

Q: How can I have DNS name resolving running while other protocols seem to be down?

A: Your local DNS resolver (bind is another possibility besides ncsd) might be caching the first response. dig will tell you where you are getting the response from:

[mpenning@Bucksnort ~]$ dig cisco.com ; <<>> DiG 9.6-ESV-R4 <<>> +all cisco.com ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 22106 ;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 2, ADDITIONAL: 0 ;; QUESTION SECTION: ;cisco.com. IN A ;; ANSWER SECTION: cisco.com. 86367 IN A 198.133.219.25 ;; AUTHORITY SECTION: cisco.com. 86367 IN NS ns2.cisco.com. cisco.com. 86367 IN NS ns1.cisco.com. ;; Query time: 1 msec <----------------------- 1msec is usually cached ;; SERVER: 127.0.0.1#53(127.0.0.1) <--------------- Answered by localhost ;; WHEN: Wed Dec 7 04:41:21 2011 ;; MSG SIZE rcvd: 79 [mpenning@Bucksnort ~]$ 

If you are getting a very quick (low milliseconds) answer from 127.0.0.1, then it's very likely that you're getting a locally cached answer from a prior query of the same DNS name (and it's quite common for people to use caching DNS resolvers on a ppp connection to reduce connection time, as well as achieving a small load reduction on the ppp link).

If you suspect a cached answer, do a dig on some other DNS name to see whether it can resolve too.

Other diagnostic information

If you find yourself in either of the last situations I described, you need to do some IP and ppp-level debugs before this can be isolated further. As someone mentioned, tcpdump is quite valuable at this point, but it sounds like you don't have it available.

I assume you are not making a TCP connection to the same IP address of your DNS server. There are many possibilities at this point... If you can still resolve random DNS names, but TCP connections are failing, it is possible that the problem you are seeing is on the other side of the ppp connection, that the kernel routing cache (which holds a little TCP state information like MSS) is getting messed up, you have too much packet loss for tcp, or any number of things.

Let's assume your topology is like this:

 10.1.1.2/30 10.1.1.1/30 [ppp0] [pppX] uCLinux----------------------AccessServer---->[To the reset of the network] 

When you initiate your ppp connection, take note of your IP address and the address of your default gateway:

ip link show ppp0 # display the link status of your ppp0 intf (is it up?) ip addr show ppp0 # display the IP address of your ppp0 interface ip route show # display your routing table route -Cevn # display the kernel's routing cache 

Similar results can be found if you don't have the iproute2 package as part of your distro (iproute2 provides the ip utility):

ifconfig ppp0 # display link status and addresses on ppp0 netstat -rn # display routing table route -Cevn # display kernel routing table 

For those with the iproute2 utilities (which is almost everybody these days), ifconfig has been deprecated and replaced by the ip commands; however, if you have an older 2.2 or 2.4-based system you may still need to use ifconfig.

Troubleshooting steps:

  1. When you start having the problem, first check whether you can ping the address of pppX on your access server.

  2. If you can ping the ip address of pppX but you cannot ping your TCP peer's ip address, check your routing table to see whether your default route is still pointing out ppp0

  3. If your default route points through ppp0, check whether you can still ping the ip address of the default route.

  4. If you can ping your default route and you can ping the remote host that you're trying to connect to, check the kernel's routing cache for the IP address of the remote TCP host.... look for anything odd or suspicious

  5. If you can ping the remote TCP host (and you need to do about 200 pings to be sure... tcp is sensitive to significant packet loss & GPRS is notoriously lossy), try making a successful telnet <remote_host> <remote_port>. If both are successful, then it's time to start looking inside your software for clues.

If you still can't untangle what is happening, please include the output of the aforementioned commands when you come back... as well as how you're starting the ppp connection.

4521403 0 How to ad a title on a section of my wordpress blog

I want to ad a title "Instant Independent" to the center "featured" section of my wordpress blog. Directly above where the "fee increase coming soon for lake mohave" story. http://www2.az-independent.com/

How do I do this?

27392016 0 Incorrectly parsed ReturnJSON method

This method

var fListItems = db.FListItems.Include(f => f.FList) .Include(f => f.Item) .GroupBy(g => new { g.Item.Name, g.FList.Title }) .Select(lg => new FListItemsViewModel { Title = lg.Key.Title, ItemStat = new ItemStat { Name = lg.Key.Name, NameCount = lg.Count(), NameSum = lg.Sum(w => w.Score), NameAverage = lg.Average(w => w.Score) } }); 

returns this JSON

[ { Title: "Animals", ItemStat: { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 } }, { Title: "Animals", ItemStat: { Name: "Dog", NameCount: 1, NameSum: 5, NameAverage: 5 } } ] 

but I'd like it to return this JSON:

[ { Title: "Animals", ItemStats: [ { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 }, { Name: "Dog", NameCount: 1, NameSum: 5, NameAverage: 5 } ] } ] 

Can anybody suggest how to do this? Here's the viewmodel:

public class FListItemsViewModel { public string Title { get; set; } public ItemStat ItemStat { get; set; } } public class ItemStat { public string Name { get; set; } public int NameCount { get; set; } public int NameSum { get; set; } public double NameAverage { get; set; } } 

Rather than GroupBy Title and Name in the same clause, could it be better to re-write my query with two seperate GroupBys?

Progress based on Rahul's answer:

[ { Title: "Animals", ItemStat: [ { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 }, { Name: "Cat", NameCount: 2, NameSum: 8, NameAverage: 4 } ] }, { Title: "Animals", ItemStat: [ { Name: "Dog", NameCount: 1, NameSum: 5, NameAverage: 5 } ] } ] 
7172537 0

If you accept to recycle the random numbers, why do you want to wait for the exhaustion of the combinations before recycling?

I would just generate random numbers, without caring if they've been used already.

If you really really want to keep it like you asked, here's how you could do it:

You could improve it by moving the used numbers from one table to another, and use the second table instead of the first one when the first table is empty.

You could also do that in memory, if you have enough of it.

5613804 0

Assuming you've made sure your application doesn't persist anything, all you have left to do is add UIApplicationExitsOnSuspend and set it to true in your application's Info.plist. The moment the user leaves your application, its process will terminate. When the user starts your application again it won't remember anything; it'll just start from the beginning. This includes displaying the launch image.

15455247 0 Smallest number in array and it position

What I am trying to achieve is to find smallest number in array and it initial position. Here's an example what it should do:

temp = new Array(); temp[0] = 43; temp[1] = 3; temp[2] = 23; 

So in the end I should know number 3 and position 1. I also had a look here: Obtain smallest value from array in Javascript? , but this way does not gives me a number position in array. Any tips, or code snippets are appreciated. Thanks.

26963227 0

Your recursive predicate isConnected/2 misses the base case:

isConnected(X,Y) :- graph1(X,Y). 

(assuming we are checking graph1, of course).

Anyway, you cannot use isConnected/2, since Prolog will loop on cyclic graphs.

27267854 0 Rounded Corner images

I've been trying to do perfectly shaped circular images with non-square images. I tried to make it with

[self.photoView.layer setCornerRadius:50.0f]; [self.photoView.layer setMasksToBounds:YES]; 

It becomes something like this:

Not so perfectly rounded

I want to make it full perfect circular.

PhotoView's content mode is setted to Aspect Fill, It's height and width fixed to 80x80 with autolayout. I could not figure it out.

I made circular images with cropping and scaling them, but also want to add a border to it, in this way i need to recreate new uiimage to draw borders in it. It's expensive thing. I want to use photoView's layer to do this.

Any help is appreciated.

11979894 0

You are accessing getResources() without a reference to a Context. Because this is a static method, you can only access other static methods within that class without providing a reference.

Instead, you must pass the Context as an argument:

// the 34th button Button tf = (Button) findViewById(R.id.tFour); tf.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Apply.applyBitmap(v.getContext(), R.drawable.tFour); // Pass your context to the static method } }); 

Then, you must reference it for getResources():

public static void applyBitmap(Context context, int resourceID) { BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inScaled = true; opt.inPurgeable = true; opt.inInputShareable = true; Bitmap brightBitmap = BitmapFactory.decodeResource(context.getResources(), resourceID, opt); // Use the passed context to access resources brightBitmap = Bitmap.createScaledBitmap(brightBitmap, 100, 100, false); MyBitmap = brightBitmap; } 
9489652 0

the warnings are caused by the maven tar archiver. By default, it warns for tar entries with path length > 100 chars. Considering this is an ancient tar format limitation, I changed the default to "gnu" for tycho 0.17.0-SNAPSHOT so you should no longer get these warnings:

https://github.com/eclipse/tycho/commit/5db5cc2b76bdba8526cfc4acb66b3e4674f23f03

38432502 0 PayPal iOS Network Connection Was Lost

I actually posted this question on PayPal Repository GitHub, but no one was answering me.

The PayPal SDK works so fine when using a PayPal Account, but when I try to use Pay with card, I can't connect to the PayPal Server, and there is no debug logs, only this:

2016-07-18 10:00:03.447 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:04.036 UPlant[23489:265771] Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 563160167_Portrait_iPhone-Simple-Pad_Default 2016-07-18 10:00:04.077 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:04.077 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:04.077 UPlant[23489:265771] NSScanner: nil string argument 2016-07-18 10:00:08.415 UPlant[23489:265771] Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 563160167_Portrait_iPhone-Simple-Pad_Default 2016-07-18 10:00:10.070 UPlant[23489:265771] Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 563160167_Portrait_iPhone-Simple-Pad_Default

Additional Information

Mode (Mock/Sandbox/Live): Sandbox

PayPal iOS SDK Version: sandbox, PayPal iOS SDK 2.14.2

iOS Version and Device (iOS 8.x, iOS 9.3 on an iPhone 6s, etc.): iOS 9.3 iPhone 5 Simulator

PayPal-Debug-ID(s) (from any logs): No debug logs

After attempting the PayPal to do the transaction with Card, it pops up an alert saying

The Network Connection Was Lost.

Any idea on this why is this happening and how to solve it?

31597735 0

After playing around with it a bit I came to this conclusion. I changed the HTML a bit because I wanted to use the Bootstrap alert boxes.

public static string MyValidationSummary(this HtmlHelper helper, string validationMessage = "") { string retVal = ""; string errorList = ""; foreach (var key in helper.ViewData.ModelState.Keys) { retVal = ""; foreach (var err in helper.ViewData.ModelState[key].Errors) { retVal += "<div class='alert alert-danger'>"; retVal += "<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"; retVal += "<i class='icon-remove-sign'></i>"; retVal += helper.Encode(err.ErrorMessage); retVal += "</div>"; errorList += retVal; } } return errorList.ToString(); } 
4488211 0

Observe that:

Here's my C# implementation, though it should be trivial to port to Java:

static long SumSubtring(String s) { long sum = 0, mult = 1; for (int i = s.Length; i > 0; i--, mult = mult * 10 + 1) sum += (s[i - 1] - '0') * mult * i; return sum; } 

Note that it is effectively O(n).

32227126 0 CentOs Magento files created as directories?

I noticed a few days ago that a few files that belong to a certain Magento extension were in fact created as directories and not in fact the .png .css and .js files that they were supposed to be. When updating the extension there are errors as the files are unable to overwrite the existing directories. I mainly noticed this due to the icons being missing from the Magento admin panel. Although baffling, no big deal, I deleted the directories (x4) and copied the correct files from the original distribution. Problem solved.

I used find . -type d "." and also the 'empty' option to identify directories which should be files. This fixes the symptom but not the cause. There were around 10 files, mostly images but some .js and .css affected.

I've just run an update of M2e via Magento connect, 'successfully', but having noticed some missing icons/graphics in admin I checked the code and have identified 17 empty directories that should have been image files (.png and .gif).

I guess my questions are how and why is this happening? How can I stop it happening again?

I have a dedicated CentOS server running Apache. Installs are done via Filezilla FTP upload or Magento Connect, it seems most likely that it's Connect causing the problem, both extensions have been updated by Connect at least once in their lifetime.

Hoping someone can enlighten me, though not a huge problem in itself, it is a concern that critical files (rather than images) may be prone to the same problems...Anyone seen this before??

Cheers RobH

3294365 0

The destination anchor for a link in an HTML page may be any element with an id attribute. See Links on the W3C site. Here's a quote from the relevant section:

Destination anchors in HTML documents may be specified either by the A element (naming it with the name attribute), or by any other element (naming with the id attribute).

Markdown treats HTML as HTML (see Inline HTML), so you can create your fragment identifiers from any element you like. If, for example, you want to link to a paragraph, just wrap the paragraph in a paragraph tag, and include an id:

<p id="mylink">Lorem ipsum dolor sit amet...</p> 

Then use your standard Markdown [My link](#mylink) to create a link to fragment anchor. This will help to keep your HTML clean, as there's no need for extra markup.

24453451 0 Autoencoders: Papers and Books regarding algorithms for Training

Which are some of the famous research papers and/or books which concern Autoencoders and the various different training algorithms for Autoencoders? I'm talking about research papers and/or books which lay the foundation for the different training algorithms used to train autoencoders.

34564942 0

Am assuming you know javascript array and few method


Use the window.location.href

var url = 'site.com/seach?a=val0&b=val1'

split the '?'

var someArray = url.split('?');

The someArray looks like this ['site.com/seach', 'a=1000&b=c'] index 0 is the window.location and index 1 is queryString

var queryString = someArray[1];

Go futher a split '&' so u get a key=value

var keyValue = queryString.split('&');

keyVal looks like this ['a=val0', 'b=val1'];

Now lets get keys and values.

var keyArray=[], valArray=[];

Loop through the keyValue array and split '=' the update keyArray and valArray

for(var i = 0; i < keyValue.length; i++){

key = keyValue[i].split('=')[0];

val = keyValue[i].split('=')[1];

keyArray.push(key);

valArray.push(val);

}

Finally we have

keyArray = ['a', 'b'];

valArray = ['val0', 'val1'];

Our full codes looks like this.

var url = 'site.com/seach?a=val0&b=val1';

var someArray = url.split('?');

var queryString = someArray[1];

var keyValue = queryString.split('&');

var keyArray=[], valArray=[];

for(var i = 0; i < keyValue.length; i++){

key = keyValue[i].split('=')[0];

val = keyValue[i].split('=')[1];

keyArray.push(key);

valArray.push(val);

}

DONE!

18217302 0

You might need to change

-lopencv_core244 \ -lopencv_highgui244 \ -lopencv_imgproc244 

to

-lopencv_core244d \ -lopencv_highgui244d \ -lopencv_imgproc244d 
37747592 0

Do not set any IBOutlet of your UIViewController before it is displayed.

The IBOutlet is probably not initialised yet. I would suggest making a string property, setting it when you initialise your UIViewController and setting that text to your UILabel in the viewDidLoad or viewWillAppear method.

Hope this helped!

9449562 0 How to remove Scrollbar in ChromeDriver, how to change http-agent?

I use IWebDriver driver = new ChromeDriver(options) in C#

When I take .GetScreenshot();, often see scrollbar, is there a way to remove it?

2nd question, how to mock/change http_agent in ChromeDriver?

11141718 0

I will take it from the silence that there is no such feature. So here is the macro for it:

Sub StopDebugAndKillProcesses() Dim dbg As EnvDTE80.Debugger2 = DTE.Debugger dbg.Stop() Dim shell_string As String shell_string = "taskkill /F /IM TheProcessToKill.exe" Shell(shell_string) End Sub 

Assign it to a button, put it next to the original "Stop" button and your done.

24771191 0

The local file system is declared to be cross-origin and will taint the canvas. This is a good declaration given that your most sensitive information is probably on a local file system.

Here are some ways to be compliant with CORS security:

27585390 0

It's equivalent to

least = Math.min(least, k); 

or

if (!(least < k)) { least = k } 

See also: the Java documentation on the ternary operator (scroll to the "The Conditional Operators" section).

30244323 0 PHP - Cast type from variable

I was asking myself if it's possible to cast a string to become another type defined before

e.g.

$type = "int"; $foo = "5"; $bar = ($type) $foo; 

and where $bar === 5

319672 0 GetWindowLong vs GetWindowLongPtr in C#

I was using GetWindowLong like this:

[DllImport("user32.dll")] private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex); 

But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible. http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx

The MSDN docs for GetWindowLongPtr say that I should define it like this (in C++):

LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex); 

I used to be using IntPtr as the return type, but what the heck would I use for an equivalent for LONG_PTR? I have also seen GetWindowLong defined as this in C#:

[DllImport("user32.dll")] private static extern long GetWindowLong(IntPtr hWnd, int nIndex); 

What is right, and how can I ensure proper 64bit compatibility?

17641209 0

Your app crashing because the variable maxInt in plus1 is undefined. maxInt's scope is local to onCreate. Also final variables are like constant variables in C. They can only get a value when you initialize them, meaning you can't change their value.

Your maxInt should not be final and should be a global variable:

public class ScoreActivity extends Activity { int maxInt; protected void onCreate(Bundle savedInstanceState) { ... maxInt = Integer.parseInt(max); ... } public void plus1 (View V) { maxInt ++; } ... } 
1641232 0

Python has limited support for private identifiers, through a feature that automatically prepends the class name to any identifiers starting with two underscores. This is transparent to the programmer, for the most part, but the net effect is that any variables named this way can be used as private variables.

See here for more on that.

In general, Python's implementation of object orientation is a bit primitive compared to other languages. But I enjoy this, actually. It's a very conceptually simple implementation and fits well with the dynamic style of the language.

4759726 0 .NET - Multiple libraries with the same namespace - referencing

Today I am faced with a curious challenge...

This challenge involves two .NET libraries that I need to reference from my application. Both of which I have no control over and have the same namespace within them.

So...

I have foo.dll that contains a Widget class that is located on the Blue.Red.Orange namespace.

I have bar.dll that also contains a Widget class that is also located on the Blue.Red.Orange namespace.

Finally I have my application that needs to reference both foo.dll and bar.dll. This is needed as within my application I need to use the Widget class from foo and also the Widget class from bar

So, the question is how can I manage these references so that I can be certain I am using the correct Widget class?

As mentioned, I have no control over the foo or bar libraries, they are what they are and cannot be changed. I do however have full control over my application.

18714240 0

Add a hidden field to your aspx page.

 <asp:HiddenField ID="hfrecordID" runat="server" /> 

And assign the recodId to it in the ItemDataBound event and use it in the aspx page.

 <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server"> <script type="text/javascript"> function ViewCheck(filename) { var targetfile = "Allegati/" + <%= hfrecordID.value %> + filename; var openWnd = radopen(targetfile, "RadWindowDetails"); } </script> protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e) { if (e.Item is GridEditableItem && e.Item.IsInEditMode) { GridEditableItem editedItem = e.Item as GridEditableItem; hfrecordID= editedItem.GetDataKeyValue("TransazioneID").ToString(); } } 
18151503 0

It looks from your code like you're trying to run some php code (tradeformresult.php). Loading it this way isn't going to work as expected-that require_once will be run as the page is being built in PHP, not in the browser.

For sending a form without refreshing the page, you should look into AJAX (http://en.wikipedia.org/wiki/Ajax_(programming))

JQuery has a good AJAX method. Here is a simple example of how to use it:

$.ajax({url:"http://www.someserver.com/api/path", data:{val1:"value",val2:"value"}) .success(function(returnData) { console.log(returnData); }); 

The above will call the given URL with the given data as parameters, then, if successful, will return whatever data the server gave back into the returnData variable.

If you're using AJAX, you don't really even have to use a <form> tag, since you'll be building the query string manually. You can have the function that makes the AJAX call be triggered from the onClick event of a button.

32064508 0

There is a wordpress plugin CC Circle Progress Bar which will work for you. Here is the link: https://wordpress.org/plugins/cc-circle-progress-bar/

32958703 0

You need to create a resources folder in your eclipse project. and then add that folder to your project sources. application.properties file (which contains IP/Port of RTSP server) should be located there.

It should look something like this

20176778 0 Is it good to make function in function using 'return'?

While I was investigating functions, I realised that I can create embedded functions. Firstly, I thought it may be useful for structuring code. But now I suppose it isn't good style of coding. Am I right? Here is an example.

function show () { return function a() { alert('a'); return function b() { alert('b'); } } } 

And I can call alert('b') using this string: show()();

In what situations is better to use this method and in what not?

16930087 0

The error is in this line of code.

if (sqlite3_prepare_v2(contactDB, query_stmt, 1, &statement, NULL) == SQLITE_OK) { 

The 1 is wrong. From the SQLite docs:

int sqlite3_prepare_v2( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const char **pzTail /* OUT: Pointer to unused portion of zSql */ ); If the nByte argument is less than zero, then zSql is read up to the first zero terminator. If nByte is non-negative, then it is the maximum number of bytes read from zSql. 

So you are forcing SQLite to only read the first byte from the statement. Of course this is invalid.

22399218 0

Maybe you could use .promise() for this.

You can add a promise to the upload function. This way you could run functions like upload.done(function(e) { /* do stuff */ });

The $.ajax() in jQuery has its build-in promise. You can check if an ajax call succeeded with xhr.done(function(e) { /* do stuff */ });

11117515 0 JqueryUI slider handle stuck on the div border and handle donot reaches max value

Hi guys I'm a Jquery noob ,I'm using jqueryUI slider but the slider handle always stucks on div border (left side) and after clicking on the slider bar it moves forward but doesn't reaches max limit and stucks in between.

Check the JsFiddle the snapshot is from the browser (where you can see the slider handle) ,I have put all the code on fiddle ,but can't make jsFiddle work.

enter image description here
Slider:
1. Slider handle sticks to the div border.
2. Slider handle doesnt move towards the max value and stucks at some value in between.

31997082 0

You can of course use a regexp, but there are libraries which will do the job quicker and easier. Try using a HTML dom parser, or phquery which is an implementation of jquery lib in php. It's also available for Composer. So if you're familiar with jquery syntax, you can find it very neat.

Get the html you need using this: $html = pq('.modal.ww')->html();

18818456 0 center site content on all devices

This is the site I am referring to: http://heattreatforum.flyten.net/

It was built as a child-site to the twenty-twelve theme.

I can't seem to get the content to center on every screen, and I am seeing a strange wide margin on the right that I just can't seem to locate in my css.

Any help would be much appreciated - thanks for looking!

23659948 0 WCF binding over HTTPS an security at message level

I have a WCF Service over HTTP with the following binding:

<basicHttpBinding> <binding name="RegistreReferenciaBinding"> <security mode="Message"> <message clientCredentialType="Certificate" /> </security> </binding> </basicHttpBinding> 

A third party service is connecting to this Service and now this third party is requiring an HTTPS connection.

The problem is that I need to maintain the security at message level in order to be compatible with the third party Service.

To resume the situation what I need to do is configure the service to be HTTPS compatible, without client certificate while maintaining the security at message level.

What is the configuration needed to get this Service working with the same configuration but over HTTPS?

UPDATE:

I tried to use the following configuration:

<basicHttpBinding> <binding name="RegistreReferenciaBinding"> <security mode="Transport" /> </binding> </basicHttpBinding> 

But with this configuration the third party Service could not connect because there was no security at message level.

From what I viewed in captured messages with Wireshark, the third party Service is using SOAP 1

The error message with this configuration was:

<?xml version="1.0"?> <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Body> <s:Fault> <faultcode>s:MustUnderstand</faultcode> <faultstring xml:lang="es-ES">El destinatario de este mensaje no entendió el encabezado 'Security' del espacio de nombres 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', por lo que el mensaje no se procesó. Este error suele indicar que el remitente del mensaje habilitó un protocolo de comunicación que el destinatario no puede procesar. Asegúrese de que la configuración del enlace del cliente es coherente con el enlace del servicio. </faultstring> </s:Fault> </s:Body> </s:Envelope> 

UPDATE 2

I also tried with the following configuration:

<basicHttpBinding> <binding name="RegistreReferenciaBinding"> <security mode="TransportWithMessageCredentials"> <message clientCredentialType="Certificate" /> </security> </binding> </basicHttpBinding> 

And it failed again.

13617138 0 php validation is incorrect for drop down menu

I have a code below where it displays students details in a drop down menu, and then it does a php validation to see if a student is selected from the drop down menu or not:

$sql = "SELECT StudentUsername, StudentForename, StudentSurname FROM Student ORDER BY StudentUsername"; $sqlstmt = $mysqli->prepare($sql); $sqlstmt->execute(); $sqlstmt->bind_result($dbStudentUsername, $dbStudentForename, $dbStudentSurname); $students = array(); // easier if you don't use generic names for data $studentHTML = ""; $studentHTML .= '<select name="students" id="studentsDrop">'.PHP_EOL; $studentHTML .= '<option value="">Please Select</option>'.PHP_EOL; $outputstudent = ""; while($sqlstmt->fetch()) { $student = $dbStudentUsername; $firstname = $dbStudentForename; $surname = $dbStudentSurname; $studentHTML .= "<option value='" . $student . "'>" . $student . " - " . $firstname . " " . $surname . "</option>" . PHP_EOL; } $studentHTML .= '</select>'; $errormsg = (isset($errormsg)) ? $errormsg : ''; if(isset($_POST['resetpass'])) { //get the form data $studentdrop = (isset($_POST['students'])) ? $_POST['students'] : ''; if($studentdrop = "") { $errormsg = "Student is Selected"; } else{ $errormsg = "You must Select a Student"; } } 

The problem I have though is that even though I have selected a student from the drop down menu, it still displays a message stating that "You Must select a Student".

What is suppose to happen is that if the user has not selected a student or in other words when they have submitted the form and the drop down menu is still on the "Please Select" option, then it displays the message stating that user must select a student, else if the user does select a student from the drop down menu then display the message that a student has been selected.

3207102 0

Make sure you have the exact same service pack levels on the test and production servers. Also make sure you have the same version of all the assemblies of the third party library.

39528057 0

It is usually a bad idea to use a python for loop to iterate over a large pandas.DataFrame or a numpy.ndarray. You should rather use the available build in functions on them as they are optimized and in many cases actually not written in python but in a compiled language. In your case you should use the methods pandas.DataFrame.max and pandas.DataFrame.min that both give you an option skipna to skip nan values in your DataFrame without the need to actually drop them manually. Furthermore, you can choose a axis to minimize along. So you can specifiy axis=1 to get the minimum along columns.

This will add up to something similar as what @EdChum just mentioned in the comments:

data.max(axis=1, skipna=True) - data.min(axis=1, skipna=True) 
31202407 0

Even though not specifically mentioned in the API description, the Google GSA Search Protocol Reference is pretty explicit about this limitation:

The maximum number of results available for a query is 1,000, i.e., the value of the start parameter added to the value of the num parameter cannot exceed 1,000.

However, if all you need is more than 1,000 records (as you indicated) you can structure your query to return a well-defined non-overlapping subset of potential results, then piece together the overall result.

A simple example would segment results by date. For the custom query you posted, appending something like &sort=date:r:20100101:20101231 would return 1,000 results from the year 2010. If you repeat this for 2011, you would have a total of 2,000 results.

19262634 0

This might be something you can try: http://www.krautcomputing.com/blog/2012/03/27/how-to-compile-custom-sass-stylesheets-dynamically-during-runtime/.

I've used this in a Rails 3.2x project and it works fine, but I'm having difficulties getting it working in a different (somewhat modified Rails 4 project).

It's older article about compiling css on the fly using the Sprockets::StaticCompiler class.

7704031 0 jquery sliding menu opening/closing animations issue

I'm testing this on local : http://jsfiddle.net/fYkMk/1/ This is a booking form that opens up on mouse over (booking-mask) and closes when mouse leaves it. It has 4 fields :

the last three fields are sliding menus that open up with a click on the relative icon.

These sliding animations work until The user decide to "mouseover" then "mouseleave" and "mouseover" again over the booking-mask div before the oprning/closing animations are finished yet.

So it happens the lists are broken and I can only see a piece of them.[see image below]

enter image description here

Hope you can help me out with this. Thanks

Luca

9416950 0

I would first fetch the title tag and then process the title further. The other answers contain perfectly valid solutions for this task.

Some further notes:

You will now match everything between <title>a</title>... up to <title>test</title>, including everything in between.

17278865 0 Connection to a web service in Android Virtual Device

I have a web service with a WS-security. I can have access to this web service only with my machine IP address and only if I make the right WS configuration.

So when testing it in Soap-ui, I get responses! and when testing connection in browser of my emulator, I get the wsdl page!

But when implemented in my application, I can not call the web service! I'm making something really wrong and didn't get it!

Is the URL I'm using for calling my web service right? Have I to configure the DNS server in the emulator? What have I to do ?

Here is my SOAP request:

 POST http://172.xxx.xxx.xxx:8080/wbb HTTP/1.1 Accept-Encoding: gzip,deflate Content-Type: text/xml;charset=UTF-8 SOAPAction: "" Content-Length: 1146 Host: 172.xxx.xxx.xxx:8080 Connection: Keep-Alive User-Agent: Apache-HttpClient/4.1.1 (java 1.5) <soapenv:Envelope xmlns:ser="http://www.''''.com/wbb/service" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"> <wsse:UsernameToken wsu:Id="UsernameToken-11"> <wsse:Username>whatever2</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">whatever3</wsse:Password> <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">whatever4</wsse:Nonce> <wsu:Created>whatever5</wsu:Created> </wsse:UsernameToken></wsse:Security></soapenv:Header> <soapenv:Body> <ser:RechargeRequest> <ser:value1>?</ser:value1> <ser:value2>?</ser:value2> <!--Optional:--> <ser:value3>?</ser:value3> </ser:RechargeRequest> 

and my android code:

 protected String doInBackground(String... params) { private static final String SOAP_ACTION = ""; private static final String NAMESPACE"http://www.'''''.com/wbb/ws"; private static final String METHOD_NAME="Recharge"; private static final String URL = "http://172.xxx.xxx.xxx:8080/wbb/wbb.wsdl"; SoapPrimitive response = null; String xml=""; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); PropertyInfo p1 =new PropertyInfo(); p1.name = "value1"; p1.setValue(params[0]); request.addProperty(p1); PropertyInfo p2 =new PropertyInfo(); p2.name = "value2"; p2.setValue(params[1]); request.addProperty(p2); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12); // create header Element[] header = new Element[1]; header[0] = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","Security"); Element usernametoken = new Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "UsernameToken"); usernametoken.setAttribute(null, "Id", "UsernameToken-1"); header[0].addChild(Node.ELEMENT,usernametoken); Element username = new Element().createElement(null, "n0:Username"); username.addChild(Node.IGNORABLE_WHITESPACE,"whatever2"); usernametoken.addChild(Node.ELEMENT,username); Element pass = new Element().createElement(null,"n0:Password"); pass.setAttribute(null, "Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"); pass.addChild(Node.TEXT, "whatever3"); usernametoken.addChild(Node.ELEMENT, pass); Element nonce = new Element().createElement(null, "n0:Nonce"); nonce.setAttribute(null, "EncodingType","http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"); nonce.addChild(Node.TEXT, "whatever3"); usernametoken.addChild(Node.ELEMENT, nonce); Element created = new Element().createElement(null, "n0:Created"); created.addChild(Node.TEXT, "whatever4"); usernametoken.addChild(Node.ELEMENT, created); // add header to envelope envelope.headerOut = header; Log.i("header", "" + envelope.headerOut.toString()); envelope.dotNet = false; envelope.bodyOut = request; envelope.setOutputSoapObject(request); //HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); URL url = null; try { url = new URL(URL); } catch (MalformedURLException e1) { e1.printStackTrace(); } HttpTransportSE androidHttpTransport = null; String host = url.getHost(); int port = url.getPort(); String file = url.getPath(); Log.d("Exception d", "host -> " + host); Log.d("Exception d", "port -> " + port); Log.d("Exception d", "file -> " + file); androidHttpTransport = new KeepAliveHttpsTransportSE(host, port, file, 25000); Log.i("bodyout", "" + envelope.bodyOut.toString()); try { androidHttpTransport.debug = true; androidHttpTransport.call(SOAP_ACTION, envelope); xml = androidHttpTransport.responseDump; response = (SoapPrimitive)envelope.getResponse(); Log.i("myApp", response.toString()); } catch (SoapFault e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); Log.d("Exception Generated", ""+e.getMessage()); } return response; } 

Sorry for my bad english and for the mistakes!

21502773 0

As others have said, you update properties of an immutable object by creating a new object with updated properties. But let me try to illustrate how this might work with some code.

For simplicity, let's say you are modelling a particle system, where each particle moves accordingly to it's velocity.

Your model comprises of a set of particles that are updated and then rendered to the screen each frame.

In C#, your model implementation might look like this:

public class Model { public class Particle { public double X { get; set; } public double Y { get; set; } public double Vx { get; set; } public double Vy { get; set; } } public Model() { this.particles = /* ... initialize a set of particles ... */ } public void Update() { foreach (var p in this.particles) { p.X += p.Vx; p.Y += p.Vy; } } public void Render() { /* ... clear video buffer, init something, etc ... */ foreach (var p in this.particles) { this.RenderParticle(p); } } } 

Pretty straightforward. As you can see, each frame we go over entire set of particles and update coordinates of each one according to it's velocity.

Now, if the particle was immutable, there'd be no way to change it's properties, but as been said, we just create a new one with updated values. But hold on a second, doesn't that mean we'd have to replace the original particle object with an updated one in our set? Yes it does. And doesn't that mean that the set now has to be mutable? Looks like we just transfered the mutability from one place to another...

Well, we could refactor to rebuild the entire set of particles each frame. But then, the property that stores the set would have to be mutable... Hmmm. Do you follow?

It appears that at some point you'll have to lose immutability in order to cause effects, and depending on where that point is, your program will or will not have some (arguably) useful properties.

In our case (we're making a video game), we technically can postpone the mutability all the way until we get to drawing on the screen. It's good that the screen is mutable, otherwise we'd have to create a new display each frame :)

Now, let's see how this could be implemented in F#:

type Particle = { X : double Y : double Vx : double Vy : double } type Model = { Particles : Particle seq } module Game = let update model = let updateParticle p = { p with X = p.X + p.Vx; Y = p.Y + p.Vy } { model with Particles = seq { for p in model.Particles do yield updateParticle p } } let render model = for p in model.Particles do Graphics.drawParticle p 

Note that in order to preserve immutability, we had to make the Update method a function that takes a model object and returns it updated. The Render now also takes the model object as an argument, as we don't keep it in memory anymore because it is immutable.

Hope this helps!

30605081 0

OK the answer to my 2 questions are: Yes and No.

I was missing something and there is nothing wrong with my approach.

What was worrying me was that the instantiate approach might be causing the problem as it isn't the method described in the documentation. It turns out that this was not the problem.

What was the problem was lazy copying and pasting. When I copied the tracking code from the GA website I accidentally also copied the line below. When this was copied into the single line textbox for the variable in the inspector the tracking code showed as expected but there was a hidden line that was also part of the string variable that couldn't be seen.

Slap me.

Hopefully this lesson learned helps another careless idiot avoid the same or similar mistake.

37710071 0 Could someone tell me why this code isn't working?

So I have been stuck with this for a long time now, unable to figure why it isn't working. This is a registration page which, after submitting information, should upload the information (the one I choose, not all the registration options enter the database) into a table (called tbl) inside the database (known as Database2.mdf). This is through Visual Studio 2010. There is also a java phase that checks the information but I don't think that is what is causing the problem so I'll just post the SQL code and the HTML code, along with the names of the table lines.

The SQL bit:

<%@ Page Language="C#" %> <%@ Import Namespace="System.Data.SqlClient" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (Request.Form["sub"] != null) { string fName = Request.Form["FName"]; string lName = Request.Form["LName"]; string uName = Request.Form["UName"]; string Street = Request.Form["Street"]; string City = Request.Form["City"]; string Pass = Request.Form["Password"]; string PassCon = Request.Form["PasswordConf"]; string Email = Request.Form["Email"]; string Comments = Request.Form["Comment"]; int ID = int.Parse(Request.Form["ID"]); string conStr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"; string cmdStr = string.Format("INSERT INTO tbl (FirstName, LastName, UserName, Street, City, Password, PasswordConfirm, Email, Comments, IdentificationNumber) VALUES (N'{0}', N'{1}', N'{2}', N'{3}', N'{4}', N'{5}', N'{6}', N'{7}', N'{8}', {9})", fName, lName, uName, Street, City, Pass, PassCon, Email, Comments, ID); SqlConnection conObj = new SqlConnection(conStr); SqlCommand cmdObj = new SqlCommand(cmdStr, conObj); conObj.Open(); cmdObj.ExecuteNonQuery(); conObj.Close(); } } </script> 

The HTML bit: (CheckForm is the name of the Javassript action that checks if the form matches the requirements, also Registration.aspx is the registration page obviously, and it is not linked to a master page)

<form action="Registration.aspx" method="post" name="ContactForm" onsubmit="return CheckForm()"> First Name: <input type="text" size="65" name="FName" /> <br /> Last Name: <input type="text" size="65" name="LName" /> <br /> Username: <input type="text" size="65" name="UName" /> <br /> Street: <input type="text" size="65" name="Street" /> <br /> City: <input type="text" size="65" name="City" /> <br /> Password: <input type="password" size="65" name="Password" /> <br /> Password Confimration: <input type="password" size="65" name="PasswordConf" /> <br /> E-mail Address: <input type="text" size="65" name="Email" /> <br /> Comments: <input type="text" size="100" name="Comment" /> <br /> Identification Number: <input type="password" size="65" name="ID" /> <br /> Mobile : <input type="text" id="mobile" name="mobile" style="width: 40px;" maxlength="3" /> - <input type="text" name="mobile1" maxlength="7" /> <br /> Gender: Male<input type="radio" name="gender" id="gender_Male" value="Male" checked /> Female<input type="radio" name="gender" id="gender_Female" value="Female" /> <br /> Which countries would you like to recieve political news for?: <br /> <input type='checkbox' name='files[]' id='1' value='1' /> Israel <input type='checkbox' name='files[]' id='2' value='2' /> Russia <input type='checkbox' name='files[]' id='3' value='3' /> Canada <br /> How often do you read the newspaper? <br /> <select id="cardtype" name="sel"> <option value=""></option> <option value="1">Never</option> <option value="2">Everyday</option> <option value="3">Once a week</option> <option value="4">Once a year</option> </select> <br /> What can we help you with? <select type="text" value="" name="Subject"> <option></option> <option>Customer Service</option> <option>Question</option> <option>Comment</option> <option>Consultation</option> <option>Other</option> </select> <br /> <input type="submit" value="Send" name="submit" /> <input type="reset" value="Reset" name="reset" /> </form> 

The table lines are as follows:

I know this is A LOT to sift through but I have been stuck with it for so long and I must get it fixed very quickly, I would VERY much appreciate any help provided! Thanks in advance!

24779469 0 Implement rollback in Nested stored procedure

I am using TRY CATCH block to capture error and do rollback

ALTER PROCEDURE sp_first /* parameters */ BEGIN TRY BEGIN TRANSACTION /* statements */ COMMIT END TRY BEGIN CATCH IF(@@TRANCOUNT>0) ROLLBACK END CATCH 

Will the above approach work if there is another stored procedure sp_inner being called inside sp_first which also performs DML statements INSERT , DELETE , UPDATE etc.

ALTER PROCEDURE sp_first /* parameters */ BEGIN TRY BEGIN TRANSACTION /* statements of sp_first */ -- stored procedure sp_inner also requires rollback if error occurs. EXEC sp_inner @paramaterList COMMIT END TRY BEGIN CATCH IF(@@TRANCOUNT>0) ROLLBACK END CATCH 

How to implement roll back if nested stored procedure is used?

35751448 0 Disabling"Synchronous XMLHttpRequest on the main thread is deprecated"

I'm using Chrome to debug a web page, and while debugging I get frequent warnings and stops with the message "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."

I understand what is causing these, but they are in code over which I have no control. But their existence is making it hard to debug my code, as I have to click past twenty or so of these warnings to reach my code, and sometimes others are thrown during the execution of my code.

My question is: How do I prevent the Chrome debugger from stopping on these warnings?

23276302 0

Assuming your adapter is based off some class, and this class has the methods to set and get the switch value, you should be able to do something like this in your adapter:

public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.some_layout, null); } Switch switch_temp = (Switch) v.findViewById(R.id.item_pers_ajout_op_switch); switch_temp.setChecked(getItem(position).getTousCoches()); return convertView; } public void switchAll(boolean mySwitch) { for (int i=0; i<getCount(); i++) { getItem(i).setTousCoches(mySwitch); } notifyDataSetChanged(); } 
8174516 0

You should use strtod; it checks double overflow/underflow also like:

#include <errno.h> #include <stdio.h> #include <math.h> #include <stdlib.h> double d; char *e,s[100]; fgets(s,100,stdin); if( s[strlen(s)-1]=='\n' ) s[strlen(s)-1]=0; errno=0; d=strtod(s,&e); if( *e || errno==EINVAL || errno==ERANGE ) puts("error"); else printf("d=%f\n",d); 
22043342 0

Any decent JPA docs would tell you that a 1-N bidir relation needs mappedBy on the side with the collection. The error message is pretty clear too

12870896 0 Google Analytics Traffic Sources issue with mobile traffic redirected to m. site

A big chunk of my traffic is mobile. My server identifies this traffic by regex on the user agent and redirects (301) from www.mydomain.com to m.mydomain.com

My site has different sources I want to get insights on (ads, Facebook, referrer sites etc)

In the traffic sources report in Google Analytics I see a big chunk of visits originate from mydomain.com. That chunk size is similar to my mobile traffic, though a little lower.

Does it make sense that the traffic source issue is related to mobile?

If so:

One option I saw was faking a Google campaign by having the server add fake parameters to the query. This way I can use Google Analytics advertising-related reports to track origin.

I'm looking for something more straightforward if possible.

Will HTTP 302 work better?

22061093 0

I write one function which will convert date as per my requirement as given below

var getRequiredDate = function(date) { var monthList = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var day = date.getDate(); var month = date.getMonth(); var year = date.getFullYear(); // Use standard date methods var newdate = monthList[month] + ' ' + day + ", " + year; Ti.API.info("Date :" + newdate); 

};

Hope this helps you.

39908486 0 Django attachment and custom data in response

Could someone please let me know if I can add custom message in HTTP response along with a attachment in Django

Here is my django response with file attachment.

data = key[0] response = HttpResponse(data, content_type='text/plain') response['Content-Disposition'] = 'filename=license.txt' 

I also want to send additional data with response (not part of attachment) like employee id '2343'. Can it be done? Is it a good idea to add data to header ?

thanks in advance!

10669832 0 How to customize the full page of a listpicker?

Possible Duplicate:
ListPicker FullMode Selected Item Color

I've a long list of things loading from a listpicker, mostly "useless".

Is there the possibility to add a button on top of the full page opened when I click the listpicker (so when I click on it I only show the most useful things?

Thanks a lot!

14098246 0

If you are hoping to do a random choice using strings you need to put them in an array and do Array shuffle.

shuffle($array_of_filenames); echo $array_of_filenames[0]; 

More examples: http://php.net/manual/en/function.shuffle.php

38301548 0

I think you did not connect the label with xib or storyboard properly.Kindly again connect the label with xib or storyboard correctly with the following screenshots and coding.

FIRST : I drag and drop the Label from the Object Library I drag and drop the Label from the Object Library

SECOND : CLICK control + mouse on label and drag that label to ViewController.h enter image description here

THIRD : Now BOX shows with default cursor in Name field enter image description here

FOUR : Finally give the Label Name in Name Field of BOX enter image description here

Once I did that Now the View Controller.h

#import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (strong, nonatomic) IBOutlet UILabel *labelStringText; @end 

Then in ViewController.m

#import "ViewController.h" @interface ViewController () @end @implementation ViewController @synthesize labelStringText; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. labelStringText.text = @""; NSString *strLabelText = [NSString stringWithFormat:@"%@",labelStringText.text]; //OR NSString *strLabelText = labelStringText.text; } 

for your simple understanding I set the label.text to string in viewDidLoad.You just set the string where you want.

40689117 0

Seems you set inappropriate maximum nested level in style checks which provided by compiler switch "-gnatyL" and then set up the compiler to treat all warnings and style checks as errors by "-gnatwe" switch.

2473340 0

Why are you making this generic? Just overload the method.

 void bar(A a) { a.Foo(); } void bar(B b) { b.Foo(); } 

Generics are there so that you can make potentially infinite bar() methods.

40157074 0 Multiple docker images run from docker file

I am trying to execute multiple docker images run from single docker file with different ports. Please advise How to execute multiple "docker run" commands from single docker file with different ports.

14085145 0

Tobias Ternstrom at Microsoft has a workaround that works for sql server2005 and higher: Consider the following example using the AdventureWorks microsoft sample database:

 SELECT soh.OrderDate ,( SELECT p.Name + ', ' FROM Production.Product AS p INNER JOIN Sales.SalesOrderDetail AS sod ON p.ProductID = sod.ProductID WHERE sod.SalesOrderID = soh.SalesOrderID FOR XML PATH(''), TYPE ).value('/', 'NVARCHAR(max)') AS ProductsOrdered FROM Sales.SalesOrderHeader AS soh 

See where they discuss the same problem here: string aggregate function, something like SUM for numbers

17070179 0 Deleting a file in Java

I want to delete a file, and sometimes I can, sometimes I don't. I'm doing this:

String filePath = "C:\\Users\\User\\Desktop\\temp.xml"; File f = new File(filePath); if (f.exists()) { if(f.delete()) System.out.println("deleted"); else System.out.println("not deleted"); } 

I think that when I can't delete it is because it is still open somewhere in the Application. But how can I can I close it, if I don't use the FileInputStream or the BufferedReader? Because if I use those classes, I can't see if the file exists. Or can I?

Edit: I just found my error. I was doing this:

XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(new FileOutputStream(filePath)); 

and then, closing just the eventWriter .

And I have to do this:

FileOutputStream fos = new FileOutputStream(filePath); XMLEventWriter eventWriter = outputFactory.createXMLEventWriter(fos); 

and then:

 eventWriter.close(); fos.close(); 
10876559 0
char * bytes = [SomeData bytes]; 
14547761 0

Your code looks correct. The most likely problem is that it's being built incorrectly, but to address this we need to see your Makefile.

At the link below (wouldn't let me post the link so you have to copy/paste it yourself) is a post by someone who had a very similar problem to yours. It turned out that he was not running his compiled object file through the linker, with the result that some essential library was missing which caused the PIC to loop endlessly, trying to execute an invalid opcode (instruction).

efreedom dot com/Question/E-27081/Using-Avr-Gcc-Delay-Ms-Causes-Chip-Freeze

If this doesn't fix it, try posting your Makefile.

Also, there is no reason to call _delay_ms(10) 100 times, you can just call _delay_ms(1000) directly. It will use a lower resolution.

Edit: After seeing your Makefile it looks like your clock speed might be set incorrectly. The CLOCK setting specifies what speed you are running your AVR at, if it's set to something way off (like 8MHz and your PIC is running at 1MHz), the delay loop will take 8 seconds when you expect it to take one - if that's the problem your LED's will appear frozen but if you wait long enough they will actually change. Try removing the -DF_CPU=$(CLOCK) statement and see if it makes a difference.

Apart from that your Makefile has a lot of unused/unnecessary stuff, and since I don't have a working avr-gcc setup at the moment, it's hard to follow, so it will help if you try simplifying the Makefile like the following, and see if it works - it will be close, please comment below if you get any problems!

DEVICE = attiny2313 CLOCK = 8000000 OBJECTS = main.o # Tune the lines below only if you know what you are doing: AVRDUDE = avrdude $(PROGRAMMER) -p $(DEVICE) COMPILE = avr-gcc -Wall -Os -DF_CPU=$(CLOCK) -mmcu=$(DEVICE) # symbolic targets: all: main.hex flash: all $(AVRDUDE) -U flash:w:main.hex:i clean: rm -f main.hex main.elf $(OBJECTS) main.elf: $(OBJECTS) $(COMPILE) -o main.elf $(OBJECTS) main.hex: main.elf rm -f main.hex avr-objcopy -j .text -j .data -O ihex main.elf main.hex avr-size --format=avr --mcu=$(DEVICE) main.elf 
23849929 0 how to make uitextview scroll in iOS Storyboards

I have a uitextview with more text that can fit in the view. I enabled "scrolling enabled" on the textview, however the scrollview does not scroll.

Here is how I populate the textview in viewDidLoad:

 PFQuery *query = [MyObject query]; [query whereKey:@"cycleNumber" equalTo:_cycleNumber]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if([objects count] > 0){ NSString *description = objects[0]; _lessonDescriptionTextView.text = description; } }]; 

How can I make the textview scroll to show all content?

27820074 0

If you change

<xsl:template match="order"> <order job_id="{job_id}" site_code="{site_code}" replace="{replace}"> <xsl:apply-templates/> </order> </xsl:template> 

to

<xsl:template match="order"> <order job_id="{job_id}" site_code="{site_code}" replace="{replace}"> <xsl:apply-templates select="node()[not(self::job_id|self::site_code|self::replace)"/> <xsl:copy-of select="following-sibling::master_version[1]"/> </order> </xsl:template> 

and then add <xsl:template match="master_version"/> you get the nesting, assuming it should be done for the following sibling master_version element and not based on some reference value.

27181986 0
void *multiply() 

The values of struct variables a and b are not initialized within this function you should be passing the scanned values in main() to this function as well as divide()

There is no reason here I see why you are returning void *. Pass parameters by reference or by value.

10358488 0

Template value must be compile-time constant, that is literal, constexpr or static const variable.

26536604 0 Loading state for ApplicationRoute

Using: ember 1.7.0

I have some server-side data that I want to load up in my ember app before any routes are transitioned to. Multiple (but not all) of my other routes / controllers need this data. I was thinking that I could just load up this data in the ApplicationRoute model method. It works fine, but does not display a loading state.

Is it possible to have the ApplicationRoute display a loading state until it's model promise gets resolved.

Here's a jsbin illustrating the problem: http://jsbin.com/soqivo/1/

Thanks for the help!

7237488 0

Value property of NumericUpDown is Decimal - that is perhaps why you are having issues. In your if block, I would consider casting the Value Property of NumericUpDown object into an integer in the true part and use integer value 3 in its else part. There after, I would avoid parsing again and give it to Substring as is.

17839560 0

To answer your question directly:

Configuration > Content Authoring > Configure (the format)

At the bottom under "Filter settings" there should be a list of allowable HTML tags. Just add in

For a better solution:

Create an image field and display that above the text. The advantage is that Drupal will handle the uploading and storing of the image.

or install the following modules.

23868607 0

Please see this example that I made for you: http://jsfiddle.net/972ak/

$('form .close').click(function(event) { Boxy.confirm("Are you sure ?", function() { alert('ok'); }); return false; }); 

Boxy documentation says:

Boxy.confirm(message, callback, options) Displays a modal, non-closeable dialog displaying a message with OK and Cancel buttons. Callback will only be fired if user selects OK.

http://onehackoranother.com/projects/jquery/boxy/

37124233 0

In your __init__ method and in some other places you refer to self.__speed. However, in your accelerate and brake methods you refer to self.speed, which is not the same thing. Make all the references the same and your problem should be resolved.

32004919 1 time.gmtime() causes OverflowError on armhf platform

I have a webserver (CherryPy) running with on a Cubox (armhf platform) and upon starting the wever i get the following error:

[14/Aug/2015:09:33:40] HTTP Traceback (most recent call last): File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 661, in respond self.hooks.run('before_request_body') File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 114, in run raise exc File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 104, in run hook() File "(...)/lib/python3.4/site-packages/cherrypy/_cprequest.py", line 63, in __call__ return self.callback(**self.kwargs) File "(...)/lib/python3.4/site-packages/cherrypy/lib/sessions.py", line 901, in init httponly=httponly) File "(...)/lib/python3.4/site-packages/cherrypy/lib/sessions.py", line 951, in set_response_cookie cookie[name]['expires'] = httputil.HTTPDate(e) File "(...)/lib/python3.4/site-packages/cherrypy/_cpcompat.py", line 278, in HTTPDate return formatdate(timeval, usegmt=True) File "/usr/lib/python3.4/email/utils.py", line 177, in formatdate now = time.gmtime(timeval) OverflowError: timestamp out of range for platform time_t 

I'm not sure whether I understand the problem correctly and I am not sure if it can be fixed by me. As far as I can tell by the Traceback it is caused by CherryPy. This error causes a 500 Internal Server Error and won't load the page.

As asked in the comments I inserted a print. I don't see any thing special. This is the output of starting the server and once trying to load the page:

1439551125.1483066 1439551132.639804 4593151132.6458025 1439551132.723468 1439551132.7210276 1439551132.7268708 1439551132.7359934 1439551132.741787 1439551132.7452564 4593151132.750907 4593151132.762612 4593151132.749376 4593151132.731232 4593151132.754474 4593151132.763546 1439551132.8183882 4593151132.828029 1439551132.8379567 4593151132.856025 1439551132.8734775 1439551132.8554301 1439551132.879614 4593151132.884698 4593151132.890394 1439551132.8971672 4593151132.902081 4593151132.908171 1439551132.931757 4593151132.944052 1439551132.9759347 1439551132.9714596 4593151132.987068 4593151132.985899 1439551132.9926524 1439551133.0088623 4593151133.013047 1439551133.0280995 4593151133.040709 4593151133.029601 1439551133.0500746 4593151133.057341 1439551133.0749385 4593151133.081711 1439551133.1032782 4593151133.115171 1439551133.1194305 1439551133.1354048 4593151133.143136 4593151133.151044 1439551133.1612003 4593151133.16934 1439551133.1827784 4593151133.19687 1439551133.201899 4593151133.209947 1439551133.271833 4593151133.277573 1439551133.3090906 4593151133.312978 1439551133.3408027 4593151133.344741 1439551133.3722978 4593151133.376283 1439551133.4031894 4593151133.407124 1439551133.434834 4593151133.439074 

I am not sure which of these values causes the error. I am guessing it's the one with 4 in front? On a windows machine time.gmtime(4593151133.439074) returns a struct which contains the year 2115.

On the Cubox when starting a python shell and entering time.gmtime(4593151133.439074) I can reproduce the error. But I don't know where these values come from.

EDIT

I have found the file and line in CherryPy that returns me the floating numbers which lead to the year 2115. It is line 949 - 951 in the file session.py:

if timeout: e = time.time() + (timeout * 60) cookie[name]['expires'] = httputil.HTTPDate(e) 

Why I get such a high timeout, I don't know.

28701232 0

In order to query based on two separate Parse classes, where one part of the query is a pointer to another class, the best way to do so is to have an outer query on the class which contains the pointer, and then an inner query that finds whatever supplementary objects you're looking for. In my case, this meant finding businesses that were in the user's location, and then only showing Business Posts near the user's location, where in the "BusinessPost" class, the key "Business" is a pointer to my "Business" class, that contains other information about the business that the UI needed. The query would look as follows:

override func queryForTable() -> PFQuery! { var getPosts = PFQuery(className: self.parseClassName) var getBusinesses = PFQuery(className: "Businesses") if locationUpdated == false { return nil } else { getBusinesses.whereKey("City", equalTo: self.city) getBusinesses.whereKey("State", equalTo: self.state) getPosts.whereKey("Business", matchesQuery: getBusinesses) getPosts.includeKey("Business") self.tableView.hidden = false self.tableView.reloadData() return getPosts } 

Hope this can help others that are looking to accomplish a similar query with Parse and Swift.

24622604 0
$('td:first-child').after('&lt;td&gt;new cell&lt;/td&gt;'); 
9245224 0

What you are looking for is a clearfix so that your elements will load properly. See the linked SO question "Which method of 'clearfix' is best?" for numerous possible clearfixes.

The reason why the footer element places itself next to the main element is because absolutely-positioned elements are removed from the page flow. As a result, later elements treat the absolutely-positioned element as if it was not there in the first place. With a clearfix, this issue is resolved.

23806149 0 Installing Java Cryptography Extension in Debian

I need to install the JCE in my Wheezy machine.

According to the documentation, I should replace the files local_policy.jar and US_export_policy.jar in $java_home/lib/security. However, my system doesn't have these files, and just copying JCE's files there don't work, as my code is failing and looking for the error it seems to be due to the lack of JCE.

 [java] GSSException: Failure unspecified at GSS-API level (Mechanism level: Checksum failed) [java] at sun.security.jgss.krb5.Krb5Context.acceptSecContext(Krb5Context.java:788) [java] at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:342) [java] at sun.security.jgss.GSSContextImpl.acceptSecContext(GSSContextImpl.java:285) [java] at mistic.id.krbAction.run(krbAction.java:44) [java] at mistic.id.krbAction.run(krbAction.java:1) [java] at java.security.AccessController.doPrivileged(Native Method) [java] at javax.security.auth.Subject.doAs(Subject.java:356) [java] at mistic.id.Server.acceptSecurityContext(Server.java:119) [java] at mistic.id.Server.main(Server.java:70) [java] Caused by: KrbException: Checksum failed [java] at sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType.decrypt(Aes256CtsHmacSha1EType.java:102) [java] at sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType.decrypt(Aes256CtsHmacSha1EType.java:94) [java] at sun.security.krb5.EncryptedData.decrypt(EncryptedData.java:177) [java] at sun.security.krb5.KrbApReq.authenticate(KrbApReq.java:278) [java] at sun.security.krb5.KrbApReq.<init>(KrbApReq.java:144) [java] at sun.security.jgss.krb5.InitSecContextToken.<init>(InitSecContextToken.java:108) [java] at sun.security.jgss.krb5.Krb5Context.acceptSecContext(Krb5Context.java:771) [java] ... 8 more [java] Caused by: java.security.GeneralSecurityException: Checksum failed [java] at sun.security.krb5.internal.crypto.dk.AesDkCrypto.decryptCTS(AesDkCrypto.java:451) [java] at sun.security.krb5.internal.crypto.dk.AesDkCrypto.decrypt(AesDkCrypto.java:272) [java] at sun.security.krb5.internal.crypto.Aes256.decrypt(Aes256.java:76) [java] at sun.security.krb5.internal.crypto.Aes256CtsHmacSha1EType.decrypt(Aes256CtsHmacSha1EType.java:100) [java] ... 14 more 

So, how could I successfully install JCE in Debian?

37040467 1 Ignoring zero division error

I'm writing a program that reads integer values from an input file, divides the numbers, then writes percentages to an output file. Some of the values that my program may be zero, and bring up a 0/0 or 4/0 occasion.

From here, I get a Zerodivisionerror, is there a way to ignore this error so that it simply prints 0%??

Thanks.

20989083 0

atomically $ readTVar checking does what you want. The GHCi REPL automatically executes any IO action that you give it.

36179369 0 Detail page of split app without model

In my split app the detail view does not bind any model.

In the component.js I instantiate a named model like this:

// creation and setup of the oData model var oConfig = { metadataUrlParams: {}, json: true, defaultBindingMode : "TwoWay", defaultCountMode : "Inline", useBatch : false } // ### tab-employee ### var oModelEmpl = new sap.ui.model.odata.v2.ODataModel("/sap/opu/odata/sap/EMP_SRV"), oConfig); oModelEmpl.attachMetadataFailed(function() { this.getEventBus().publish("Component", "MetadataFailedEMPL"); }, this); this.setModel(oModelEmpl, "EMPL"); 

The method onSelect in der master-view controller is fired by clicking on an listitem.

onSelect: function(oEvent) { this.showDetail(oEvent.getParameter("listItem") || oEvent.getSource()); } 

This will call the method showDetail

showDetail: function(oItem) { var bReplace = jQuery.device.is.phone ? false : true; this.getRouter().navTo("detail", { from: "master", entity: oItem.getBindingContext('EMPL').getPath().substr(1), }, bReplace); }, 

In the controller of the detail-view I've these two methods for updating the binding. onRouteMatched calls bindView, where I get the error-message TypeError: oView.getModel(...) is undefined.

onRouteMatched: function(oEvent) { var oParameters = oEvent.getParameters(); jQuery.when(this.oInitialLoadFinishedDeferred).then(jQuery.proxy(function() { var oView = this.getView(); if (oParameters.name !== "detail") { return; } var sEntityPath = "/" + oParameters.arguments.entity; this.bindView(sEntityPath); }, this)); }, bindView: function(sEntityPath) { var oView = this.getView(); oView.bindElement(sEntityPath); //Check if the data is already on the client if (!oView.getModel().getData(sEntityPath)) { // Check that the entity specified was found. oView.getElementBinding().attachEventOnce("dataReceived", jQuery.proxy(function() { var oData = oView.getModel().getData(sEntityPath); if (!oData) { this.showEmptyView(); this.fireDetailNotFound(); } else { this.fireDetailChanged(sEntityPath); } }, this)); } else { this.fireDetailChanged(sEntityPath); } }, 

I've tried to implement this split app relative to the template generated by WebIDE. Any idea what is missing?

178891 0

I would avoid using the !important clause and instead just ensure their values appear in a <style> tag following the import of the regular style sheets.

Otherwise, I would do it the same way.

12311391 0

set height as fill_parent, the width as wrap_content

and you fix the aspect ratio with android:adjustViewBounds="true"

28824855 0

containerView and show button are in different viewControllers. So you can't just hide it. The simple way to achieve it is when you select the cell in containerView, present the ParentViewController, and the view in ContainerViewController will dismiss automatically.

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [self.delegate ContainerViewBLETable:self andSelectedDone:[NSString stringWithFormat:@"%ld",indexPath.row]]; ParentViewController *vc = [[self storyboard] instantiateViewControllerWithIdentifier:@"ParentViewController"]; [self presentViewController:vc animated:YES completion:nil]; } 

To show the container, you can just dismiss the ParentViewController that presenting. 1.

- (IBAction)btnAction:(id)sender { [self.presentingViewController dismissModalViewControllerAnimated:YES]; } 

Or 2. Set up segue to dismiss viewController and use prepareForSegue for delegate to communicate with other viewController.

Also REMOVE vc.view.hidden = YES in delegate you had implemented

 -(void) ContainerViewBLETable:(ContainerViewBLETable *)vc andSelectedDone:(NSString *)selectedStr. 
24762104 0 Prevent recursive function locking the browser

I have a recursive function which is locking my browser while running.

While this function is running all my jquery commands are locked waiting for the function end.

What should I do to make this function asynchronous?

This function runs on document.ready

function SearchTrip() { $.post("/extensions/searchtrip", { from: $("#from").val(), to: $("#to").val(), ddate: $("#ddate").val() }, function (mReturn) { if (mReturn.fTotalAmount != '0,00') { var sAirline = ''; if (mReturn.Airline) sAirline = ' pela ' + mReturn.Airline; $("#buscandoPassagens").hide(); } else if (SearchTripAmount < 5) { SearchTripAmount++; setTimeout(function () { SearchTrip(); }, 500); } else { $("#pNaoEncontrada").show(); } }, "json"); } 
7788299 0

I agree with the other commenters that this question needs more information about the initial conditions of your problem before it can be properly answered. However, a scenario that causes your code to fail comes to mind immediately.

Suppose that plist is a circularly linked list with three elements: A <-> B <-> C <-> A, and plist points to A.

When your code runs, it will: deallocate A, advance to B, deallocate B, advance to C, deallocate C and then advance to the freed memory that was A. Now your code blows up. (or runs forever)

Since it is a doubly linked list, you should use your previous links to null out your next links before deallocating. And for good measure, null out your prev links as well.

temp_nlist = n_list->next; temp_nlist->prev = NULL; if (n_list->prev != NULL) n_list->prev->next = NULL; free(n_list); n_list = temp_nlist; 
15538241 0 combining cells in table

how do i embed a youtube video to a table. i want the left and right columns to be 2 rows high and the middle column to have 2 cells, i want the video in the bottom cell, and the text in the top but i cant figure out how to move it there

<div class="cbody"> <table class="ctable"> <tr> <td rowspan="2" style="width:105px"><img class="cimg1" src="meh.png" alt=" " width="100px" height="500px"></td> <td><p class="ctxt"> my text here </p></td> <td rowspan="2" style="width:105px"><img class="cimg2" src="meh.png" alt=" " width="100px" height="500px"></td> </tr> <tr> <iframe width="420" height="315" src="http://www.youtube.com/embed/xI_6oLPC-S0" frameborder="0" allowfullscreen></iframe> </tr> </table> </div> 

and the css...

.cbody { width:800px; margin-left: auto; margin-right: auto; border-style:solid; border-width:3px; } .cimg1 { padding-left:5px; padding-top:5px; padding-bottom:5px; float:left; } .cimg2 { padding-left:5px; padding-top:5px; padding-bottom:5px; float:right; } .ctxt { margin-left:5px; margin-right:5px; text-align:center; } .ctable { width:800px; margin-left:auto; margin-right: auto; border-style:solid; border-width:2px; } 
19477217 0 Calling a Java method using javascript from within a JPanel

I have a Java application which displays results on a JPanel. The results are displayed using HTML by using a JLabel.

Now I want to let the user interact with the local application by allowing local methods to be called when the user clicks on a link in that HTML document.

Is this possible?

1551407 0 How to represent AppDomain in ASP.NET?

Recently i attentened an interview.I have been asked to explain the "Application Domain" and the special purpose about the introduction of "application domain".

I explained :

AppDomain is a runtime representation of a logical process withing a physical process (win32) managed by CLR.

Special purpose :

Keeps high level application isolation ;fall down of one AppDomain never interrupt othe AppDomain.

But still the interviewer expects lots from me ? what are the additional points could i add further?

Thanks.

40659955 0

What happened to?:

public interface AsyncResponse<T> { void processFinish(T output); } 

Even if it's not overloading, it seems simple In my eyes.

14040996 0

No. Theres a similar question here: Why should you remove unnecessary C# using directives?

Check it out, it's very well answered.

13975467 0

Change your code as:

String strcategory = getIntent().getExtras().getString("categoriaId"); 

because you are passing String from onListItemClick to sondaggioActivity Activity and trying to receive as Int

NOTE :

Second and important point is id is long and you are trying to parsing it to Int which is also not valid . see this post: How can I convert a long to int in Java?

Solution is just send id as long from onListItemClick as

 myIntent.putExtra("categoriaId",id); 

and receive it as in sondaggioActivity Activity :

long category = getIntent().getExtras().getLong("categoriaId"); 
16050081 0 PostgresSQL combining tables

I am a little confused about merging one table into another. My two tables looks like so:

Table A Table B id | name | likes | email | username id | name | email | username 1 | joe | 3 | null | null 1 | ben | a@co.co | user Result: Table A id | name | likes | email | username 1 | joe | 3 | null | null 2 | ben | null | a@co.co | user 

My issue is that I do not want to overwrite the properties that are in the Table A. Is this a simple UNION?

40861784 0

Slight modification to @maxim-lanin's answer. You can use it like this, fluently.

\Mail::send('email.view', ['user' => $user], function ($message) use ($user) { $message->to($user->email, $user->name) ->subject('your message') ->getSwiftMessage() ->getHeaders() ->addTextHeader('x-mailgun-native-send', 'true'); }); 
6915150 0 Error when using getter/setter methods on Sprite

I'm trying to make a class that extends the Sprite, have some private properties attached to it and be able to read and write those properties using getters and setters. Simple... but the compiler throw this error "Access of possibly undefined property speed through a reference with static type flash.display:Sprite." It works if I set my class to extend the MovieClip object. Could someone explain me the logic behind this? why I can't use getter and setters with a Sprite?

Here is a sample code:

package { import flash.display.Sprite; public class Vehicle extends Sprite{ private var _speed:uint = 3; public function get speed():uint { return _speed; } public function set speed(value:uint):void { _speed = value; } public function Vehicle() { super(); } } } 
34697812 0

With Automatic Uploads checked ON, it is uploading files automatically even before I'm done making all changes to the PHP files and before I even click SAVE button and resulting in INCOMPLETE script files. It is also uploading files in other tab pages. Looks like there is no precise control on uploads in PhpStorm.

39116778 0 how to convert S3ObjectInputStream to PushbackInputStream

I am uploading an excel(xls) file to s3 and then another application should download that file from s3 and parse using Apache POI reader. The reader accepts inputstream type as the input but for proper parsing of the excel it expects PushbackInputStream. The inputstream i get from the file downloaded from s3 is of type S3ObjectInputStream. How do i convert S3ObjectInputStream to PushbackInputStream?

I tried directly passing the S3ObjectInputStream (since this is an inputStream) to PushbackInputStream, but it resulted in the following exception :

org.springframework.batch.item.ItemStreamException: Failed to initialize the reader at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.open(AbstractItemCountingItemStreamItemReader.java:147) at org.springframework.batch.item.support.CompositeItemStream.open(CompositeItemStream.java:96) ..... ..... Caused by: java.lang.IllegalStateException: InputStream MUST either support mark/reset, or be wrapped as a PushbackInputStream at org.springframework.batch.item.excel.poi.PoiItemReader.openExcelFile(PoiItemReader.java:82) ..... 

I tried casting S3ObjectInputStream to PushbackInputStream, but it resulted in classcastexception.

java.lang.ClassCastException: com.amazonaws.services.s3.model.S3ObjectInputStream cannot be cast to java.io.PushbackInputStream 

Anyone knows the solution for this

40348524 0

Repeat 10 times:

  1. I will never use a symlink to solve a missing library problem due to a different soname
  2. I will never use a symlink to solve a missing library problem due to a different soname
  3. I will never use a symlink to solve a missing library problem due to a different soname
  4. I will never use a symlink to solve a missing library problem due to a different soname
  5. I will never use a symlink to solve a missing library problem due to a different soname
  6. I will never use a symlink to solve a missing library problem due to a different soname
  7. I will never use a symlink to solve a missing library problem due to a different soname
  8. I will never use a symlink to solve a missing library problem due to a different soname
  9. I will never use a symlink to solve a missing library problem due to a different soname
  10. I will never use a symlink to solve a missing library problem due to a different soname

Never ever solve that kind of problems via symlinking. If your system does not provide the exact soname required by a library or an executable, you'll need to recompile that library or executable. There is a reason why libraries have the soname version number in their file names, and a mismatching soname will result in a not found for the dynamic linker/loader. You're just breaking that process and your entire system by inserting a broken soname for a library.

So, first thing to do: get rid of the symlink you introduced. Go in /usr/lib/x86_64-linux-gnu/ and remove it. Do it now.


Then, how to recompile the plugin so that it works on Ubuntu?

(Or, actually, anywhere. Even Windows or Mac. Just adapt the instructions)

Step by step:

  1. Install the mysql development packages. On Ubuntu it should be the libmysqlclient-dev package, but double check in case the name changed on your particular Ubuntu edition. Go on https://packages.ubuntu.com and use the file-based search to look for mysql.h.
  2. Run the maintanance tool from the installer, and ask it to also install the Qt source components. You'll find the tool in your Qt installation directory.
  3. Go under INSTALL_DIR/Src/5.7/qtbase/src/plugins/sqldrivers/mysql (adjust INSTALL_DIR and 5.7 to your actual case).
  4. Run the right qmake. The right one is the one coming from the same installation of Qt, and whose version matches the sources. In your case it's likely to be in INSTALL_DIR/5.7/gcc_64/bin/qmake.
  5. Run make. If it fails to compile due to some library not found, install the required packages on your system. The Ubuntu package search linked above may be useful.
  6. Once make runs successfully, it will create a brand new libqsqlmysql.so. It should automatically overwrite the one in INSTALL_DIR/5.7/gcc_64/plugins/sqldrivers. If for any reason it's not automatically overwritten, move it manually there.

Done! Enjoy your MySQL database connection.

3474206 0

Hope I understood it right. Basically you want a mapping from primitive class types to their wrapper methods.

A static utility method implemented in some Utility class would be an elegant solution, because you would use the conversion like this:

Class<?> wrapper = convertToWrapper(int.class); 

Alternatively, declare and populate a static map:

public final static Map<Class<?>, Class<?>> map = new HashMap<Class<?>, Class<?>>(); static { map.put(boolean.class, Boolean.class); map.put(byte.class, Byte.class); map.put(short.class, Short.class); map.put(char.class, Character.class); map.put(int.class, Integer.class); map.put(long.class, Long.class); map.put(float.class, Float.class); map.put(double.class, Double.class); } private Class<?> clazz = map.get(int.class); // usage 
39910041 0 How to Route without reloading the whole page?

I am Using react-route, and i am facing some trouble with routing.

The whole page is reloading , causing all the data that i have already fetched and stored in the reducer to load every time.

Here is my Route file :

var CustomRoute = React.createClass({ render:function(){ return <Router history={browserHistory}> <Route path="/" component={Layout}> <IndexRedirect to="/landing" /> <Route path="landing" component={Landing} /> <Route path="login" component={Login} /> <Route path="form" component={Form} /> <Route path="*" component={NoMatch} /> </Route> </Router> }, }); 

Before routing i already store data by calling action in my main.jsx

/** @jsx React.DOM */ 'use strict' var ReactDOM = require('react-dom') var React = require('react') var Index = require('./components/index') var createStore = require("redux").createStore var applyMiddleware = require("redux").applyMiddleware var Provider = require("react-redux").Provider var thunkMiddleware = require("redux-thunk").default var reducer = require("./reducers") var injectTapEventPlugin =require('react-tap-event-plugin'); injectTapEventPlugin() var createStoreWithMiddleware=applyMiddleware(thunkMiddleware)(createStore); var store=createStoreWithMiddleware(reducer); store.dispatch(actions.load_contacts()) //////////// <<<<<< this is what i call to store data already ReactDOM.render( <Provider store={store}><Index/></Provider> , document.getElementById('content')) 

The issue is i have to route to another page if sucess login :

this.props.dispatch(actions.login(this.state.login,this.state.password,(err)=>{ this.setState({err:err}) if (!err){ window.location = "/form" } })); 

The window.location does the trick but it reloads everything which is very inefficient. In manual route i use <Link\> that routes without reloading, however for automated i am not sure how to do it.

Any Suggestion will be much appreciated.

40233293 0

The error, if you say callbacks are not being called, might just be the sign that you may not have connected first. I imagine you have implemented the callbacks and they are not being called?

In any case, to "handle" the error situation, you may want to check if the GoogleApiClient is connected.. like this:

if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback( new ResultCallback<Status>() { @Override public void onResult(Status status) { ApplicationPreferences.get().clearAll(); Intent intent = getIntent(); finish(); startActivity(intent); } }); } else{ Log.w("SomeTag", "It looks like GoogleApiClient is not connected"); } 

But I do think you need to check if there are any errors (for instance does onConnectionFailed(ConnectionResult result) get called instead? What error do you see?

Hope this helps.

23265815 0 ASP.NET MVC: Accessing binded model in controller without using a form AND Ajax

I have the following scenario:

@model IEnumerable<UI.Models.Customer> @grid.GetHtml( columns: grid.Columns( grid.Column( format: @<text> @Html.ActionLink("Edit", "EditAct", ???) </text> ), grid.Column( format: @<text> @Html.TextBox("Name", (string)item.Name) </text> ) ) ) 

model is just a List consisting of 3 Customer's (Customer is a dummy class with only 2 properties, i.e. ID and Name)

Now, i want to be able to capture in the controller action "EditAct "the Customer, which the user want's to edit. Those were the things, that i desperately tried without success:


1) I tried to fill in ??? with a

new {customer: item} 

and to capture it in controller this way:

public ActionResult SampleFormParams(Customer customer) {...} 

This approach does not work, because HTML anchor links uses GET and we can't send an object with GET.


2) It tried to fill in ??? with a

new {customer: jsSerializer.Serialize(item)} 

and to capture it in controller this way:

public ActionResult SampleFormParams(String customer) { //deserialize(customer) } 

This also does not work, because "item" is not a Customer object, but it is a WebGridRow object.


3) It tried to fill in ??? with a

new {customer: item.ID} 

and to capture it in controller this way:

public ActionResult SampleFormParams(int id) { ... } 

I wanted to know if it would be possible to access the whole IEnumerable model, so that i can find the specified customer in the model using the given id ?


So the question is, is there any way, that i can access model directly just with an anchor i.e. ActionLink
- without using a form> AND without using Ajax ?

I also checked the Custom Model Binder, but it is also based on a form>.

40341014 0

The list is showing inside a Bottom Sheet. It can be slide up from the bottom of the screen to reveal more content. Bottom Sheets are now supported in v23.2 of the support design library and onwards. There are two types of bottom sheets supported: persistent and modal. Persistent bottom sheets show in-app content, while modal sheets expose menus or simple dialogs.

There are lots of tutorials available. Here are some of them: https://guides.codepath.com/android/Handling-Scrolls-with-CoordinatorLayout#bottom-sheets

https://code.tutsplus.com/articles/how-to-use-bottom-sheets-with-the-design-support-library--cms-26031

27377491 0 Set number of cells depending on array size

I'm a beginner and I want to change the number of cells in a collection view depending on whether the user would like to add more cells or not. I tried doing the same thing i did for table views but that doesn't seem to work. no matter what I change the size of the decks array to i only seem to be getting one cell on the screen.

Here is my code :

class FlashViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet var collectionView: UICollectionView! var decks = [5] override func viewDidLoad() { super.viewDidLoad() // Move on ... let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 75, left: 20, bottom: 10, right: 20) layout.itemSize = CGSize(width: 150, height: 200) collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) self.collectionView.dataSource = self self.collectionView.delegate = self collectionView.registerClass(DeckCollectionViewCell.self, forCellWithReuseIdentifier: "DeckCollectionViewCell") collectionView.backgroundColor = UIColor.whiteColor() self.view.addSubview(collectionView!) } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.decks.count } 
21113348 0 Android alertdialog not showing when I think it should

I'm developing an android app which I want to check if there's internet connection, if it's not the case display a warning message, and when there's internet connection again load a certain url.

It can be said that both displaying the message and checking there's internet connection work... but no separately.

I mean I have the following code:

 if (!checkConnectivity()) { browser.stopLoading(); LayoutInflater layoutinflater = LayoutInflater.from(app); final View textEntryView; textEntryView = layoutinflater.inflate(R.layout.exitdialog, null); new AlertDialog.Builder(app) .setView(textEntryView) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Exit") .setNegativeButton("CANCEL", null) .show(); while (!checkConnectivity()) { } browser.loadUrl(url); } 

If I don't use from while (!checkConnectivity()) to browser.loadUrl(url); then AlertDialog shows properly.

If I don't use from LayoutInflater layoutinflater = LayoutInflater.from(app); to .show(); then the app loads the web page correctly on browser.

But if I use the whole code it looks like it enters the while (!checkConnectivity()) loop before it does the show as what happens when internet connection is restabilished is that the alert dialog is shown briefly and the the web page is loaded.

I find this pretty weird, as I'm not using, as far as I know, threads that could cause that one could be executed before other one, and this is not the case this thing doesn't fulfill one of the most basic things in programming, I mean if an instruction is before another one, the one that's before should be plenty executed logically (except for threads).

Hope someone has an idea about this and can help me.

12054987 0 Devise/OmniAuth - LinkedIn: Email is blank in callback

I'm using Devise 2.1.2 with multiple OmniAuth providers. My devise.rb file contains this line:

config.omniauth :linkedin, API_KEY, SECRET_KEY, :scope => 'r_emailaddress', :fields => ["email-address"] 

It is currently stripped down to just email-address since that is the only thing acting strange. Taking a look inside request.env['omniauth.auth'].info, the email key is blank.

How come? I don't want to bypass validation, I wan't to use the email address from the users LinkedIn account.

36608393 0

scanf doesn't try to do a full pattern match of the format string. %s input format simply reads everything up to the next whitespace (or EOF). After that, it looks for a ;, and since it doesn't find that it doesn't parse any of the other inputs.

If you want to stop at some other character, use [^char]

scanf("[^;];%[^=]=%s", id, banner, cp); 
30664773 0 Why ClassName.class.getFields() returns only public fields?

I have one class A

public class A { String host = "localhost"; public String port = "8078"; protected String preFix = "www."; private String postFix = "/uploads"; } 

I am getting field details of class A using below code

public static void main(String[] args) { Field[] fields = A.class.getFields(); System.out.println("fields are:" + Arrays.toString(fields)); } 

The output is

fields are:[public java.lang.String org.test.A.port] 

I understand getFields() method returns only those fields which are declared with public access specifier.

But why Java implemented getFields() like this?

What is the main intention of Java Team for this kind of implementation?

8073396 0

When the file is uploaded it is stored in the tmp folder, to perform any action on it you need to use the tmp path which can be accessed using $_FILES['fotoname']['tmp_name'] , I think thats what you are looking for.

37910532 0

You can take the iterator from the List of OrdemItem here:

private List<OrderItem> items = new ArrayList<OrderItem>(); 

and do:

public Iterator<OrderItem> iterator() { return items.iterator(); } 

instead of doing

public Iterator<OrderItem> iterator() { return this.iterator(); //How to do this part?? } 
40956784 0

I would use:

if [ $YARN -eq 1 ]; then npm install -g yarn && echo "yarn installed" fi 

My bash reports 1 if program is not installed and i am not sure if value 1 will pass the -z test

10050677 0

You can enable the re-pinning button by clicking the "Stop Debugging" button.

30422729 0 Performance difference between member function and global function in release version

I have implemented two functions to perform the cross product of two Vectors (not std::vector), one is a member function and another is a global one, here is the key codes(additional parts are ommitted)

//for member function template <typename Scalar> SquareMatrix<Scalar,3> Vector<Scalar,3>::outerProduct(const Vector<Scalar,3> &vec3) const { SquareMatrix<Scalar,3> result; for(unsigned int i = 0; i < 3; ++i) for(unsigned int j = 0; j < 3; ++j) result(i,j) = (*this)[i]*vec3[j]; return result; } //for global function: Dim = 3 template<typename Scalar, int Dim> void outerProduct(const Vector<Scalar, Dim> & v1 , const Vector<Scalar, Dim> & v2, SquareMatrix<Scalar, Dim> & m) { for (unsigned int i=0; i<Dim; i++) for (unsigned int j=0; j<Dim; j++) { m(i,j) = v1[i]*v2[j]; } } 

They are almost the same except that one is a member function having a return value and another is a global function where the values calculated are straightforwardly assigned to a square matrix, thus requiring no return value.
Actually, I was meant to replace the member one by the global one to improve the performance, since the first one involes copy operations. The strange thing, however, is that the time cost by the global function is almost two times longer than the member one. Furthermore, I find that the execution of

m(i,j) = v1[i]*v2[j]; // in global function 

requires much more time than that of

result(i,j) = (*this)[i]*vec3[j]; // in member function 

So the question is, how does this performance difference between member and global function arise?

Anyone can tell the reasons?
Hope I have presented my question clearly, and sorry to my poor english!

//----------------------------------------------------------------------------------------
More information added:
The following is the codes I use to test the performance:

 //the codes below is in a loop Vector<double, 3> vec1; Vector<double, 3> vec2; Timer timer; timer.startTimer(); for (unsigned int i=0; i<100000; i++) { SquareMatrix<double,3> m = vec1.outerProduct(vec2); } timer.stopTimer(); std::cout<<"time cost for member function: "<< timer.getElapsedTime()<<std::endl; timer.startTimer(); SquareMatrix<double,3> m; for (unsigned int i=0; i<100000; i++) { outerProduct(vec1, vec2, m); } timer.stopTimer(); std::cout<<"time cost for global function: "<< timer.getElapsedTime()<<std::endl; std::system("pause"); 

and the result captured:
enter image description here

You can see that the member funtion is almost twice faster than the global one.

Additionally, my project is built upon a 64bit windows system, and the codes are in fact used to generate the static lib files based on the Scons construction tools, along with vs2010 project files produced.

I have to remind that the strange performance difference only occurs in a release version, while in a debug build type, the global function is almost five times faster than the member one.(about 0.10s vs 0.02s)

26994885 0

I think you can't do this only in css. I think some JQuery will help.

$('#mytable tr:visible').each(function( index ){ //Your code to add ODD and even class }) 
13676790 0

It seems that Visual Studio 2012 doesn't like non-default fonts. Probably a bug in VS2012. Press the use Default fonts to solve the problem, so far that's the only solution I know.

36784597 0

Assuming you already have a database connection called db set up, to get a list of the column names, you can use the following code:

do { let tableInfo = Array(try db.prepare("PRAGMA table_info(table_name)")) for line in tableInfo { print(line[1]!, terminator: " ") } print() } catch _ { } 

where table_name is replaced with the literal string of your table's name.

You can also add

print(tableInfo) 

to see more pragma info about your table.

Credits

Thanks to this answer for clues of how to do this.

4993372 0

You should not embed firstName and lastName in the primary key. userId should be your primary key, and you should add a unique constraint on [firstName, lastName]. BTW, putting these additional fields in the primary key only guarantees that [idUser, firstName, lastName] is unique, but you might still have two users with different idUsers, but with the same [firstName, lastName].

Now to answer the original question, I don't see where the problem is :

UserId userId = new UserId("theId", "theFirstName", "theLastName"); User user = (User) session.load(User.class, userId); 
3272072 0

As explained in this answer, you need to add a TargetFrameworkVersion by manually editing the .vcxproj file.

I have VS2008 installed on that machine but I think I also selected to include the VC90 compilers when I installed 2010.

However, it appears it is not supported by design, according to this Microsoft response: targeting the 3.5 framework with the Visual C++ 2010 compiler is not supported. The Visual C++ 2010 compiler only supports targeting the 4.0 framework.

1070569 0

The answer is: don't do it.

Have the calling application either pass you whatever you need to know in the call, or perhaps in your constructor. The called component should not require knowledge of the caller.

18254011 0

The first expands to the second, so there is no technical difference. Nowadays, the first is the recommended one, while the second is the underlying implementation.

13248261 0 How to make inapp purchase using MKStoreKit 4.x receipt secure from being modified?

I have been storing inapp purchase receipt string in nsuserdefaults or a custom plist .This string used to determine the version of the app as full or limited.But how to make it secure.If any person modify this string by modifying the plist the app will change to full version rite.Then i came to know about keychains,but i am not able to understand how it works..is it a separate place where the string is saved or is it encrypting the string and saving it in plist..If anybody knows how to save inapp receipts from mkstorekit using keychains please share it here.. and also the keychains concept

39987143 0

Final Update: I was able to fix this by using psqlodbc_09_03_0400. For whatever reason, other versions kept throwing error.

38548372 0 Reformatting a csv file, script is confused by ' %." '

I'm using bash on cygwin.

I have to take a .csv file that is a subset of a much larger set of settings and shuffle the new csv settings (same keys, different values) into the 1000-plus-line original, making a new .json file.

I have put together a script to automate this. The first step in the process is to "clean up" the csv file by extracting lines that start with "mme " and "sms ". Everything else is to pass through cleanly to the "clean" .csv file.

This routine is as follows:

# clean up the settings, throwing out mme and sms entries cat extract.csv | while read -r LINE; do if [[ $LINE == "mme "* ]] then printf "$LINE\n" >> mme_settings.csv elif [[ $LINE == "sms "* ]] then printf "$LINE\n" >> sms_settings.csv else printf "$LINE\n" >> extract_clean.csv fi done 

My problem is that this thing stubs its toe on the following string at the end of one entry: 100%." When it's done with the line, it simply elides the %." and the new-line marker following it, and smears the two lines together:

... 100next.entry.keyname... 

I would love to reach in and simply manually delimit the % sign, but it's not a realistic option for my use case. Clearly I'm missing something. My suspicion is that I am in some wise abusing cat or read in the first line.

If there is some place I should have looked to find the answer before bugging you all, by all means point me in that direction and I'll sod off.

29217158 0 how to list all directories for group has access to in unix/linux

Is there a way to list all directories for group has access to in unix/linux. Or a way to list all groups along with directories for which the group has access.

22636707 0

No, it's not possible. But you can add your feature request on JetBrains tracker: http://youtrack.jetbrains.com/issues/WI#newissue=yes

34643822 0 Accessing Metacritic API and/or Scraping

Does anybody know where documentation for the Metacritic api is/if it still works. There used to be a Metacritic API at https://market.mashape.com/byroredux/metacritic-v2#get-user-details which disappeared today.

Otherwise I'm trying to scrape the site myself but keeping getting a blocked by a 429 Slow down. I got data like 3 times this hour and haven't been able to get anymore in the last 20 minutes which is making testing difficult and application possibly useless. Please let me know if there's anything else I can be doing to scape I don't know about.

32780669 0

From developer.android.com:

Subclasses should override this method and verify that the given fragment is a valid type to be attached to this activity. The default implementation returns true for apps built for android:targetSdkVersion older than KITKAT. For later versions, it will throw an exception.

Basically on TargetSDK <= KITKAT, you should make sure the fragment name isValidFragment passes is a correct one.

22009597 0

Some background info...

If you come from the webforms and code-behind world is common to you that an HTML element calls a script in the code, but actually what asp.net webforms does is an http call to the script on the server. If you had an updatepanel, asp.net webforms would have done the same call via ajax.

That's the reason why in asp.net webforms the elements have the preceding asp: on their branded html tags. That way asp.net can convert their branded elements to real HTML elements.

The answer

The only way to execute the code of an action from an HTML element on-click event in asp.net MVC is by calling the URL that gets to that method. Either via ajax or by a request from the browser, an http request needs to be done.

With javascript you can listen when an element's on-click event is fired and then do some logic. If you're using jquery you can use the $.ajax() or $.get() methods to make a call to your action URL.

5308595 0 SQL query (can include pl/sql bits) based on conditional count

Premise: We've got a table with 5 fields. 2 fields are always unique.

What would be a good way to fulfill this:

if (count_of_result == 3) { add up the 3 rows from the same table. unique values get added up & the non-unique values are assumed to be same for all the 3 rows. the query result should show 1 row, with the values added up. } else {

display all the results of the query as usual.

}

Thank you.

15897174 0

This thread seems to describe the solution:

object Test { def apply( int : Int ) = new Test( int ) } class Test @deprecated( "Don't construct directly - use companion constructor", "09/04/13" ) ( int : Int ) { override def toString() = "Test: %d".format( int ) } 

Can't try it right now though.

28931183 0

Further messing around yielded the answer: xargs instead of a subshell:

echo \'foo bar\' \'baz quux\' | xargs /usr/bin/defaults write com.apple.systemuiserver menuExtras -array 
35168470 0 Windows Virtual Machine getting connection refused to port 9090 webpack dev server

I have a Meteor + Webpack application I'm working on, but I can't get a Windows VM (Win10, IE11, from modern.ie running inside VirtualBox) to access the Webpack dev server assets on port 9090, while the Meteor assets on the same host but on port 3000 work fine for whatever reason. The app is running and being accessed at {host}:3000 but this one bundled JS file is on on the same host at port 9090 and the VM is unable to fetch it.

14158048 0

According to the TODO file on CPAN, this capability is not currently supported, but the developers see it as a valuable addition:

The cover script mentions promising options: -add_uncoverable_point and -delete_uncoverable_point.

36285195 0 After using importRange to get Hyperlinked cells, how do you get the value of the URL?

I was trying to help someone solve a problem the other day and I came across an interesting issue I couldn't solve.

Imagine two sheets. One containing HYPERLINKS created by HYPERLINK function in Google Sheets, such as this sheet. Source Sheet

Then you have another sheet that uses importRange to import these URL's, like this sheet. import Sheet

The URLs import correctly, with correct link and link text. But no matter what I tried, in the import sheet, I couldn't extract the link value.

I tried to do this via formulas and via scripting. I'm guessing the URL must be some sort of object but I cannot seem to read or split it. Whatever efforts I've tried have always returned the link text, EG Google, Yahoo and not the URL itself.

22001333 0

If you just want to enable/disable input:

$("#your_input").attr('disabled','disabled'); // disable $("#your_input").removeAttr('disabled');//enable 

Example:

http://jsfiddle.net/juvian/R95qu

36711688 0

You second thread is not appending content to the file, which was written by first thread. Instead it is overwriting content written by first thread.

So you are getting output only from second thread.

Change your code

from

 FileWriter f = new FileWriter("C:\\Users\\Desktop\\sample.txt"); 

to

 FileWriter f = new FileWriter("C:\\Users\\Desktop\\sample.txt",true); 

Refer to java documentation page on FileWriter

public FileWriter(File file, boolean append) throws IOException 

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

20174142 0 keytool error :Alias ​​ does not exist

I get an error when I write this command in the console

C:\Program Files\Java\jdk1.7.0_21\bin> keytool-list-alias-andoiddebugkey keystore C:\Users\AbuHamza\android\debug.keystore-storepass android-keypass androi. d 

error

keytool error: java.lang.Exception: Alias ​​<andoiddebugkey> does not exist 
4423417 0 C++, function that loads text ignores last few lines with only some of the .txt files

I'm following theForger's Win API tutorial to load text files into an edit control. Sometimes the entire file is loaded correctly and sometimes the last part of it is left out, where 'part' is in one case 2 and a half lines and in another 10 lines o_O Here's how the files look:

(I'm a new user so it's not letting me post more than one hyperlink, so here's the gallery where the screenshots are: http://nancy.imgur.com/all/ and I'm referring to the order in which they appear in the gallery)

2.5 lines left out: second (reading stops at the cursor after the 'F')

10 lines left out: fourth (also stops at the cursor after the f)

Read completely: first and third

I tried using fstreams instead, and the same stuff was left out (I also couldn't get the new line characters to show in the edit control =( ). Any idea what could be wrong?

I couldn't link to theForger's tutorial so here's the function:

BOOL LoadTextFileToEdit(HWND hEdit, LPCTSTR pszFileName) { HANDLE hFile; BOOL bSuccess = FALSE; hFile = CreateFile(pszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); if(hFile != INVALID_HANDLE_VALUE) { DWORD dwFileSize; dwFileSize = GetFileSize(hFile, NULL); if(dwFileSize != 0xFFFFFFFF) { LPSTR pszFileText; pszFileText = GlobalAlloc(GPTR, dwFileSize + 1); if(pszFileText != NULL) { DWORD dwRead; if(ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL)) { pszFileText[dwFileSize] = 0; // Add null terminator if(SetWindowText(hEdit, pszFileText)) bSuccess = TRUE; // It worked! } GlobalFree(pszFileText); } } CloseHandle(hFile); } return bSuccess; } 
2844661 0

Checkout the newest revision of the restored backup into a working copy. do an svn export of and old working copy and simply copy all files/folders onto the previously checkout working copy. Than do an svn add if needed and commit. This should summ all changes.

9025780 0

Getting co-ordinates for a polygon would require GIS files and a GIS software like MapInfo to read.

My advice would be visit this site;

http://bbs.keyhole.com/ubb/ubbthreads.php?ubb=showthreaded&Number=332073

Download the KML file which has the district boundaries of UK counties and then use it in either google earth or fusion tables.

Finding out what your using these for may help get a better answer...

10255619 0

I think you're looking for System.Collections.Generic.Queue instead of System.Collections.Queue.

Change

open System.Collections 

to

open System.Collections.Generic 
28699427 0 Printing the value of an R variable in Latex

I am writing .Rnw file in RStudio. At one point, I store (but do not print) the value of the number of rows (nR) of a data frame (df), using the following command:

<<results = hide, echo=FALSE>>= nR = nrow(sbGeneal) nC = ncol(sbGeneal) @ 

Late, in the .Rnw file, I would like to use the nR variable and print it. An equivalent syntax in .Rmd (markdown) would be:

`r nrow(sbGeneal)` 

Is there such a possibility in Latex? Thanks!

21699836 0

Yet another solution:

<lable>Set1</lable> <input type="checkbox" name="set_199[]" value="Apple" /> <input type="checkbox" name="set_199[]" value="Mango" /> <input type="checkbox" name="set_199[]" value="Grape" /> <input type="button" value="check" class="js-submit"> 

Js:

$(".js-submit").on("click", function(){ var a = $("input[type='checkbox']:checked"); var values = {}; a.each(function(){ var value = $(this).val(); var name = $(this).attr("name"); if(!values[name]) values[name] = []; values[name].push(value) }); console.log(values) }); 

Demo

33965928 0

The button elements are not sibling elements.

You need to select the parent element's sibling elements.

Working Example Here

$(document).on('click', '.btn-group button', function (e) { $(this).addClass('active').parent().siblings().find('button').removeClass('active'); }); 

However, the proper way to do this is to use the attribute data-toggle="buttons".

In doing so, you don't need to write any custom JS. For more information, see this old answer of mine explaining how it works.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <div class="btn-group btn-group-justified" data-toggle="buttons" role="group" aria-label="..."> <label class="btn btn-default"> <input type="radio" name="options" />Low Cost/Effeciency </label> <label class="btn btn-default"> <input type="radio" name="options" />Average </label> <label class="btn btn-default"> <input type="radio" name="options" />High Cost/Effeciency </label> </div>

13524314 0 Sorting listview in javascript

I have listview with Title, image and date. I want to sort that list on the basis of date field and then display in html5 page. I used jquery and html5 on this.

$j('#task_summary_list').empty(); if (response.totalSize > 0) { $j.each(response.records, function(i, record) { var imgName; switch (record.Priority) { case "High": imgName = "images/prio_high24.png"; break; case "Low": imgName = "images/prio_low24.png"; break; default: imgName = "images/prio_normal24.png"; } // create new list entry for record to the listview $j('<li></li>') .attr('id', record.Id) .hide() .append( '<a href="#">' + '<img src="' + imgName + '" alt="High" class="ui-li-icon">' + '<h1>' + record.Subject + '</h1>' + '<p>' + '<strong>' + record.ActivityDate + '</strong>' + '</p>' + '</a>') .click(function(e) { e.preventDefault(); console.log("Under onSuccessTasks " + record.Id); showTaskDetails(record); }) .appendTo('#task_summary_list') .show(); }); } else { $j('<li class="norecord">No records to display</li>').appendTo('#task_summary_list'); } $j('#task_summary_list').listview('refresh'); $j.mobile.hidePageLoadingMsg(); 

Any help is appreciated. Thanks in avance.

30296654 0 OnClientClick not working in IE11

The onClientClick event is not getting fired in IE11 browser, however the same piece of code is working perfectly fine in IE8,9 and 10 browsers. Is there any extra piece of code that i need to add in there.

 <table width="100%"> <tr> <td align="center"> <asp:Button runat="server" ID="btnFTCancel" Text="Cancel" OnClientClick="return confirmCancel();" OnClick="btnUpdate_Click" ClientIDMode="Static"/> </td> <td align="center"> <asp:Button runat="server" ID="btnApprove" Text="Approve" Enabled="false" OnClientClick="return confirmApprove();" OnClick="btnUpdate_Click"/> </td> </tr> </table> <script type="text/javascript"> function confirmCancel() { var returnvalue; $("#btnFTCancel").css("cursor", "text"); returnvalue = confirm('Transactions generated for this request ID will be cancelled. Do you wish to continue ?'); return returnvalue; } function confirmApprove() { var returnvalue; returnvalue = confirm('Transactions generated for this request ID will be sent to FCS. Do you wish to continue ?'); return returnvalue; } function setBtnCursor() { $("input[type='submit']").css('cursor', 'pointer'); $("input[type='submit'][disabled='disabled']").css('cursor', 'default'); } </script> 

TIA,

Amit

9081449 0

According to here:

Operators on the same line have equal precedence. When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

So yes.

1808882 0

Not too sure if this will help, but perhaps try getting the the modules first and then the types from there.

Assembly a = Assembly.Load(brockenAssembly); Module[] mList = a.GetModules(); for (int i = 0; i < mList.length; i++) { Module m = a.GetModules()[i]; Type[] tList = m.GetTypes(); } 

Hope fully you could get the list of types available in one of the modules.

16967562 0

Yould could just popup a dialog with the progress in there but if you do not want to block the user from using the map then another alternative would be to overlay another layout on top of the map fragment and put the progress bar in that layout

17161110 0 How to turn on table name autocomplete feature in Toad?

I'm using Toad version 11.0.0.116. I'm not getting default tablename options when I start typing table. How to turn the autocomplete feature on??

13292537 0

Assuming you have any View instance in your activity, you can use View.postDelayed() to post runnable with a given delay. In this runnable you can call Activity.finish(). You should also use View.removeCallbacks() to remove your callback in onDestroy(), to avoid your callback being called after user already navigated back from your activity.

Using AsyncTask just to count some time is just an overkill (unless you want to use AsyncTask to actually do some useful, background work). The Looper and Handler classes provide everything you need to execute any code on UI thread after a given delay. The View methods mentioned above are just convenience methods exposing the Handler functionality.

36149764 0

The upload_to argument can be a function, as described in the documentation:

def group_based_upload_to(instance, filename): return "image/group/{}/{}".format(instance.group.id, filename) class Group_Photo(models.Model): group = models.ForeignKey(Group) photo = models.ImageField(upload_to=group_based_upload_to) 

The function takes two arguments - instance of the model to which the file is being attached and the original name of the file. It has to return a relative path under witch the file will be saved. It will be appended to the path defined in the MEDIA_ROOT setting.

The example above uses directories based on group's numeric id. You can obviously use other fields, for example to use the slug (if it has one) just replace instance.group.id with instance.group.slug.

3304314 0

You should also measure the length of the stick in the first part of the for loop, otherwise you'll be measuring it with every iteration. And you can also make the k bit even more compact:

for (var i = k = 0, j = mystick.length; i < j; i++) { if (mystick[i] == 'huge') { k++; } } 
39233034 0

Well, I dont have a direct approach. But this hack should help you get what you want..

// Start the Browser As Process to start in Private mode Process browserProcess = new Process(); browserProcess.StartInfo.FileName = "iexplore.exe"; browserProcess.StartInfo.Arguments = "-private"; browserProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; // Start browser browserProcess.Start(); // Get Process (Browser) Handle Int64 browserHandle = browserProcess.Handle.ToInt64(); // Create a new Browser Instance & Assign the browser created as process using the window Handle BrowserWindow browserFormHandle = new BrowserWindow(); browserFormHandle.SearchProperties.Add(BrowserWindow.PropertyNames.WindowHandle, browserFormHandle.ToString()); browserFormHandle.NavigateToUrl(new Uri("http://www.google.com")); 
37114802 0

You need to set the value of $scope.objectData[key] to an object before you can add more keys to it.

$scope.objectData[key] = {}; $scope.objectData[key]['digits'] = 'foo'; 
29356529 0

If you don't need it to undock and float then you can use a HeaderedContentControl.

When you want to add the close button you can template the header presenter to include a button.

18965510 0

The way to do this is in the controller for the news_article in def show you write redirect_to @news_article.attach.url

in news_article paperclip store url in attach (I call it this in model) and the .url helper is what makes the browser go there :)

5223322 0 Domain Name with unicode Pitfalls

According to yahoo and stackoverflow.com they advise having a static content site that you don't assign cookies to. http://developer.yahoo.com/performance/rules.html#cookie_free http://sstatic.net

Based of the desire for a static only domain name I though it would be cool to have the domain name made up of unicode characters. From what I understand pitfalls of unicode characters include: difficulty to type and automatic punycode conversation due to the paypal.com innocent.

For example if I wanted to link my stylesheet.

<link rel=stylesheet href=☺.com/s.css> .... <script src=☺.com/s.js></script> 

Considering I only plan to link to static content, are there are issues or pitfalls?

Do all browsers natively support unicode -> punycode conversation? It has been unclear to me if internet explorer less than 7 supports punycode. Also would IE display a notice if you are simply linking to server content in unicode format.

Bonus: Also is there any place to find a list of legal url unicode url characters? Supposedly some characters aren't permitted?! Or would a url containing non permitted characters simply be translated to punycode immediately therefore not effecting my situation?

40751775 0

Not sure how this should be done in query syntax, but here is the method syntax version:

this.Data = data .Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries) .Select(table => table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries) .Select(row => row.Split(';')) .ToArray()) .ToArray(); 

In query synax :

this.Data = ( from table in data.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries) select ( from row in table.Split(new[] { "^^" }, StringSplitOptions.RemoveEmptyEntries) select row.Split(';') ).ToArray() ).ToArray(); 
5817142 0

Exactly, UML class diagrams are just a notation that you could (and should) differently depending on the sofware development phase you are in. You can start with only classes, attributes and associations, then refine the diagram to add types information for the attributes, then navigation, class methods, qualifiers for associations ... until you get a complete class diagram ready for the implementation phase

Note that you could even iterate to the point in which you remove associations and replace them by attributes of complex types to have a class diagram even more similar to the final implementation. It's up to you how to use class diagrams in each phase.

40989587 0

If you use a val, you're not allowed to assign it a new value, so in your code example above, if you switch the third line with

val fa2 = fa.:+(ra) 

then fa can be a val.

33589252 0

I see only two good choices:

  1. make that site a webproxy
  2. use unlimitedStorage permission and store the urls in WebSQL database (it's also the fastest). Despite the general concern that it may be deprecated in Chrome after W3C stopped developing the specification in favor of IndexedDB I don't think it'll happen any time soon because all the other available storage options are either [much] slower or less functional.
16320287 0

Use is_page to detect your front-end login and registration pages:

<?php if ( ! is_user_logged_in() && ! ( is_page( 'register' ) || is_page( 'login' ) ) ) { echo '<div>Some stuff here</div>'; // your code } ?> 
32933716 0

NPE is because of the below reason

try { desktop.browse(uri); } catch(IOException ioe) { System.out.println("The system cannot find the " + uri + " file specified"); //ioe.printStackTrace(); } 

you are initializing desktop in DesktopDemo constructor but onLaunchBrowser() is a static method so desktop object is not instantiated!

5645072 0

Hope U R USING PHP

choose your own separator like

$glue=®(alt 0174) CONCAT_WS($glue,str1,$str2) 
27037271 0

One quick solution is to change your html structure and move sidebar as first child of div wih id #tekst:

body { background: #98c8d7; width: 1000px; margin: auto; font-family: "Trebuchet ms", Verdana, sans-serif; } #header { background: #fff url(banner.jpg) no-repeat; margin: 10px 0 10px 0; padding: 8em 2em 1em 2em; text-align: center; border-radius: 15px; opacity: 0.8; border: 1px dotted #000 } /*Dette formaterer menuen */ ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; } li { float: left; } a:link, a:visited { display: block; width: 312.5px; font-weight: bold; color: #000; background-color: #51a7c2; text-align: center; padding: 4px; text-decoration: none; text-transform: uppercase; border: 1px solid #91cfca; opacity: 0.8; } a:hover, a:active { background-color: #98c8d7; } #content { background: #b4cdd9; color: #000; padding: 1em 1em 1em 1em; top right bottom left } #tekst { background: #98c8d7; color: #000; opacity: 0.8; margin: 5px 0 5px 0; padding: 0.5em 1em 1em 1em; text-align: left; } #sidebar { background: #b4cdd9; color: #000; width: 320px; position: relative; float: right; margin: 5px 0 5px 0; padding: 0.5em 1em 1em 1em; text-align: left; border-style: outset; border-width: 3px; border-color: black; } a { color: #0060B6; text-decoration: none; } a:hover { color: #00A0C6; text-decoration: none; cursor: pointer; }
<body> <!-- Denne div indeholder dit content, altså din brødtekst --> <div id="content"> <!--Header. Indeholder banner --> <div id="header"></div> <!-- Menu --> <ul> <li><a href="forside.html">Forside</a> </li> <li><a href="priser.html">Priser</a> </li> <li><a href="kontakt.html">Kontakt</a> </li> </ul> <!-- Her kommer din brødtekst så --> <div id="tekst"> <div id="sidebar"> <!-- move it here --> <h3>Leon Laksø</h3> <p>Så-og-så-mange år i tjeneste, certificeret bla bla, alt muligt andet shit her. Måske et billede hvor du ser venlig ud?</p> <p>Mail link kunne være her?</p> </div> <h1>Overskrift 1</h1> <p>Her kan du skrive, hvad du tilbuder, hvorfor, hvorledes, til hvem og anden info</p> <!-- Overskrift to. Der er flere former for overskrifter. H1 betegner en bestemt slags, H2 en mindre slags osv. Du kan godt bruge H1 flere gange --> <h2>Underoverskrift 1</h2> <p>Her kan du måske skrive lidt om dig selv og dine kvalifikationer?</p> </div> </div> </body>

26020180 0

OK, I'm not going to try a fix your code. I'm just going to create constraints that I would use to achieve your layout. I'll put the thought process in comments.

First get a nice vertical layout going...

// I'm just using standard padding to make it easier to read. // Also, I'd avoid the variable padding stuff. Just set it to a fixed value. // i.e. ==padding not (>=0, <=padding). That's confusing to read and ambiguous. @"V:|-[titleLabel]-[ratingBubbleView]-[descriptionLabel]-|" 

Then go through layer by layer adding horizontal constraints...

// constraint the trailing edge too. You never know if you'll get a stupidly // long title. You want to stop it colliding with the end of the screen. // use >= here. The label will try to take it's intrinsic content size // i.e. the smallest size to fit the text. Until it can't and then it will // break it's content size to keep your >= constraint. @"|-[titleLabel]->=20-|" // when adding this you need the option "NSLayoutFormatAlignAllBottom". @"|-[ratingBubbleView]-[dateLabel]->=20-|" @"|-[descriptionLabel]-|" 

Try not to "over constrain" your view. In your code you are constraining the same views with multiple constraints (like descriptionLabel to the bottom of the superview).

Once they're defined they don't need to be defined again.

Again, with the padding. Just use padding rather than >=padding. Does >=20 mean 20, 21.5, or 320? The inequality is ambiguous when laying out.

Also, In my constraints I have used the layout option to constrain the vertical axis of the date label to the rating view. i.e. "Stay in line vertically with the rating view". Instead of constraining against the title label and stuff... This means I only need to define the position of that line of UI once.

2846831 0

An alternative to filtering would be to maintain the list of selected users. In setSelected(true) you could add a user to the list and use setSelected(false) to remove it.

class User { List<User> selectedUsers = new ArrayList<User>(0); void setSelected(boolean isSelected) { if ( isSelected) { selectedUsers.add(user.getId()); } else { int idx = selectedUsers.indexOf( this ); if ( idx >= 0 ) selectedUsers.remove( idx ); } } } 

This aproach requires an implemented equals method. BTW your snippet adds the userId (Int?) to the list of type User.

18205592 0

When you do writeObject, the objevt you write needs to be Serializable. Try to change the signature of your copy-method to

public static Object copy(Serializable oldObj) 

The error message will be clearer.

2894704 0

The DataContext on your usercontrol isn't set. Specify a Name for it (I usually call mine "ThisControl") and modify the TextBox's binding to Text="{Binding ElementName=ThisControl, Path=TitleValue, Mode=TwoWay}". You can also set the DataContext explicitly, but I believe this is the preferred way.

It seems like the default DataContext should be "this", but by default, it's nothing.

[edit] You may also want to add , UpdateSourceTrigger=PropertyChanged to your binding, as by default TextBoxes' Text binding only updates when focus is lost.

16890317 0 How to make UIViewController's view inherit from another UIView?

I have one UIViewController without NIB file. Now i have one my customized UIView. I want to make UIViewController's view inherit from my customized UIView, is it possible ? I know that if I have XIB file than I can make Custom Class from there but without XIB can it be done? enter image description here

Thanks in Advance

2038527 0
int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; free(memory); } 

This will crash. You're setting the pointer to memory location 10 and then asking the system to release the memory. It's extremely unlikely that you previously allocated some memory that happeneds to start at 0x10, even in the crazy world of virutal address spaces. Furthermore, IF malloc failed, no memory has been allocated, so you do not need to free it.

int* memory = NULL; memory = malloc(sizeof(int)); if (memory != NULL) { memory=10; } free(memory); 

This is also a bug. If malloc fails, then you are setting the pointer to 10 and freeing that memory. (as before.) If malloc succeeds, then you're immediately freeing the memory, which means it was pointless to allocate it! Now, I imagine this is just example code simplified to get the point across, and that this isn't present in your real program? :)

16783675 0 Running Continumm Standalone

I have downloaded apache continuum.

After that i unpacked and i typed continuun console.

It´s started fine... but when i put localhost:8080/continuum in the browser the console show this error: What´s happend?

jvm 1 | org.apache.jasper.JasperException: PWC6345: There is an error in invo king javac. A full JDK (not just JRE) is required jvm 1 | at org.apache.jasper.compiler.DefaultErrorHandler.jspError(Defau ltErrorHandler.java:92) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDisp atcher.java:378) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDisp atcher.java:119) jvm 1 | at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199J avaCompiler.java:208) jvm 1 | at org.apache.jasper.compiler.Compiler.generateClass(Compiler.ja va:384) jvm 1 | at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453 ) jvm 1 | at org.apache.jasper.JspCompilationContext.compile(JspCompilatio nContext.java:625) jvm 1 | at org.apache.jasper.servlet.JspServletWrapper.service(JspServle tWrapper.java:374) jvm 1 | at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServle t.java:492) jvm 1 | at org.apache.jasper.servlet.JspServlet.service(JspServlet.java: 378) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:455) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:577) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:2 76) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:1 03) jvm 1 | at org.eclipse.jetty.servlet.DefaultServlet.doGet(DefaultServlet .java:566) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:735) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1336) jvm 1 | at org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter.d oFilter(StrutsExecuteFilter.java:85) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent (SiteMeshFilter.java:129) jvm 1 | at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(Site MeshFilter.java:77) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter.d oFilter(StrutsPrepareFilter.java:82) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.springframework.web.filter.CharacterEncodingFilter.doFilt erInternal(CharacterEncodingFilter.java:96) jvm 1 | at org.springframework.web.filter.OncePerRequestFilter.doFilter( OncePerRequestFilter.java:76) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter (ServletHandler.java:1307) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:453) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:559) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandlerCollection.han dle(ContextHandlerCollection.java:255) jvm 1 | at org.eclipse.jetty.server.handler.HandlerCollection.handle(Han dlerCollection.java:154) jvm 1 | at org.eclipse.jetty.server.handler.HandlerWrapper.handle(Handle rWrapper.java:116) jvm 1 | at org.eclipse.jetty.server.Server.handle(Server.java:365) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest (AbstractHttpConnection.java:485) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.headerComplet e(AbstractHttpConnection.java:926) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandle r.headerComplete(AbstractHttpConnection.java:988) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:6 35) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.j ava:235) jvm 1 | at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttp Connection.java:82) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectC hannelEndPoint.java:627) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectCh annelEndPoint.java:51) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedT hreadPool.java:608) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedTh readPool.java:543) jvm 1 | at java.lang.Thread.run(Unknown Source) jvm 1 | 2013-05-27 23:52:11.265:WARN:oejs.ErrorPageErrorHandler:EXCEPTION jvm 1 | org.apache.jasper.JasperException: PWC6345: There is an error in invo king javac. A full JDK (not just JRE) is required jvm 1 | at org.apache.jasper.compiler.DefaultErrorHandler.jspError(Defau ltErrorHandler.java:92) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDisp atcher.java:378) jvm 1 | at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDisp atcher.java:119) jvm 1 | at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199J avaCompiler.java:208) jvm 1 | at org.apache.jasper.compiler.Compiler.generateClass(Compiler.ja va:384) jvm 1 | at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453 ) jvm 1 | at org.apache.jasper.JspCompilationContext.compile(JspCompilatio nContext.java:625) jvm 1 | at org.apache.jasper.servlet.JspServletWrapper.service(JspServle tWrapper.java:374) jvm 1 | at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServle t.java:492) jvm 1 | at org.apache.jasper.servlet.JspServlet.service(JspServlet.java: 378) jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848) jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder. java:648) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:455) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:577) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:2 76) jvm 1 | at org.eclipse.jetty.server.Dispatcher.error(Dispatcher.java:112 ) jvm 1 | at org.eclipse.jetty.servlet.ErrorPageErrorHandler.handle(ErrorP ageErrorHandler.java:136) jvm 1 | at org.eclipse.jetty.server.Response.sendError(Response.java:348 ) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHand ler.java:538) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:137) jvm 1 | at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHan dler.java:559) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doHandle(Sess ionHandler.java:231) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(Cont extHandler.java:1072) jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandl er.java:382) jvm 1 | at org.eclipse.jetty.server.session.SessionHandler.doScope(Sessi onHandler.java:193) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doScope(Conte xtHandler.java:1006) jvm 1 | at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedH andler.java:135) jvm 1 | at org.eclipse.jetty.server.handler.ContextHandlerCollection.han dle(ContextHandlerCollection.java:255) jvm 1 | at org.eclipse.jetty.server.handler.HandlerCollection.handle(Han dlerCollection.java:154) jvm 1 | at org.eclipse.jetty.server.handler.HandlerWrapper.handle(Handle rWrapper.java:116) jvm 1 | at org.eclipse.jetty.server.Server.handle(Server.java:365) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest (AbstractHttpConnection.java:485) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection.headerComplet e(AbstractHttpConnection.java:926) jvm 1 | at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandle r.headerComplete(AbstractHttpConnection.java:988) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:6 35) jvm 1 | at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.j ava:235) jvm 1 | at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttp Connection.java:82) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectC hannelEndPoint.java:627) jvm 1 | at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectCh annelEndPoint.java:51) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedT hreadPool.java:608) jvm 1 | at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedTh readPool.java:543) jvm 1 | at java.lang.Thread.run(Unknown Source) 
9043173 0 MIniMagick::Image.write() saves files with varying permissions

I am writing a little photo gallery with Rails 3.0.11 and MiniMagick.

def JadeImage.rescale path,new_path,max_height=150 image = MiniMagick::Image.open(path) image.adaptive_resize(self.resize(image[:height],max_height))if image[:height] > max_height image.write(new_path) end 

I am using this to save two resized images from the same photo. One of the files gets saved with 644 permissions and all is right in the world. The other always get saved as 600 and as such can't be displayed in the webpage.

For now, after saving them, I run a little utility to set everything in that directory as 644 so it works now.

Is there any reason why this would occur?

40918033 0

I ended up using a BindingTargetVisitor which covers the use cases that I need.

Note that this solution works for our specific use case but might be too limited for your use case, depending on the type of bindings and injections that you use.

public class InjectionPointExtractor extends DefaultBindingTargetVisitor<Object, InjectionPoint> { private final Predicate<TypeLiteral<?>> filter; public InjectionPointExtractor(Predicate<TypeLiteral<?>> filter) { this.filter = filter; } @Override public InjectionPoint visit(UntargettedBinding<?> untargettedBinding) { return getInjectionPointForKey(untargettedBinding.getKey()); } @Override public InjectionPoint visit(LinkedKeyBinding<?> linkedKeyBinding) { return getInjectionPointForKey(linkedKeyBinding.getLinkedKey()); } @Override public InjectionPoint visit(ProviderKeyBinding<?> providerKeyBinding) { return getInjectionPointForKey(providerKeyBinding.getProviderKey()); } private InjectionPoint getInjectionPointForKey(Key<?> key) { if (filter.test(key.getTypeLiteral())) { return InjectionPoint.forConstructorOf(key.getTypeLiteral()); } return null; } } 

We use the filter to filter only on classes defined in our packages. This gets the job done in a nice and clean fashion.

If you don't use @Inject constructors but instead use Guice to set fields directly, you could use TypeListener

1879594 0 How should I start to learn JavaScript, jQuery, etc.? My programming knowledge is zero

I'm from a design background. My programming knowledge is zero. After learning XHTML and CSS I want to learn and get good command on JavaScript, jQuery, etc. How should I start?

This will be my first attempt to programming. I can use and edit readymade available jQuery/JavaScript scripts, but I can't make my own and can't do high level editing in readymade scripts.

Is there any other post on Stack Overflow, any link of start-up tutorial, or any book for my needs?

Edit 1:

This book will work best for me, "DOM Scripting: Web Design with JavaScript and the Document Object Model".

alt text

Edit 2:

Will my design background and knowledge of XHTML CSS help me to learn JavaScript quickly?

and is this correct? If I learn only jQuery then I will not be able to work with other JavaScript framework like MooTools, Prototype, etc. But if I learn core JavaScript then I would be able to work with all JavaScript frameworks and anything in JavaScript.

9919278 0 SQL multiple replace

I want to read the company table and take out all possible suffixes from the name. Here's what I have so far:

declare @badStrings table (item varchar(50)) INSERT INTO @badStrings(item) SELECT 'company' UNION ALL SELECT 'co.' UNION ALL SELECT 'incorporated' UNION ALL SELECT 'inc.' UNION ALL SELECT 'llc' UNION ALL SELECT 'llp' UNION ALL SELECT 'ltd' select id, (companyname = Replace(name, item, '') FROM @badStrings) from companies where name != '' 
36775266 0

to handle ALL worksheet, place this in ThisWorkbook code pane

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) If Not Intersect(Target, Sh.Columns(13)) Is Nothing Then MsgBox "Help Help" End If End Sub 

or

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range) If Target.Column = 13 Then MsgBox "Help Help" End If End Sub 

Otherwise place the following in the code pane of the Sheet(s) you want to "handle" only

Private Sub Worksheet_Change(ByVal Target As Range) If Target.Column = 13 Then MsgBox "Help Help" End If End Sub 
9569438 0

This is an example of code that works for me. It performs these operations:

  1. It splits the string based on whitespace, and each element is stored on an array of strings;
  2. It checks the size of each element of the array;
  3. If the size is == 4 (the number of characters of the postal code), then it checks (with a pattern) if the current element is a number;
  4. If the current element is a number, then this element and the next element (the city) is stored on an ArrayList.

    import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.*; public class split{ private List<String> newline = new ArrayList<String>(); public split(){ String myString = "Graaf Karel De Goedelaan 1 8500 Kortrijk"; String array[] = myString.split("\\s+"); for(int z = 0;z<arr.length;z++){ int sizestr = array[z].length(); if(sizestr==4){/* if the generic string has 4 characters */ String expression = "[0-9]*"; CharSequence inputStr = array[z]; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(inputStr); if(matcher.matches()){/* then if the string has 4 numbers, we have the postal code" */ newline.add(array[z]); /* now we add the postal code and the next element to an array list" */ newline.add(array[z+1]); } } } Iterator<String> itr = newline.iterator(); while (itr.hasNext()) { String element = itr.next(); System.out.println(element); /* prints "8500" and "Kortrijk" */ } } public static void main(String args[]){ split s = new split(); } } 

For further info about the check of the string, take a look to this page, and, for the ArrayList Iterator, see this.

I hope this can help to solve your problem.

26775709 0 Fastest way to join multiple MVC projects into a single one

We have about 4 different MVC projects, in separate Solutions, with their own Controllers, Models and Views.

We need to join all these projects into a single Project (Solution). The new project will have an entry point (Home Page), from which you can go to any of the existing projects.

We will navigate from one project to another (one section to another - after integration) using simple navigation links.

Is Areas a good solution for this approach?

I read this post but i don't understand what the solution from there is.

26038374 0

You can make change in below css

.content { margin-top:50px;//added position:absolute;//changed clear: both; width:100px; height:50px; background:#D52100; } .click_menu{ width:100px; height:50px; float:left; color:#191919; text-align:center; position: absolute;// added z-index: 100;//added } 

Demo

38934847 0

The line of code num1, num2 = num2, (num1 + num2) is assigning two variables at once. num1 gets the old value of num2, while num2 gets the new value (num1 + num2).

Having multiple assignments on a single line of code allows you to do both operations without needing to use a temporary variable. For example, this won't work:

num1 = num2 num2 = (num1 + num2) 

because num1 has been overwritten with a new value before the addition step, so num2 will be assigned the wrong value. The one-line version is equivalent to:

temp = (num1 + num2) num1 = num2 num2 = temp 

For reference, this is called parallel assignment or sometimes multiple assignment.

17099774 0

Try this:

 String strEvents = new JSONArray(apiResponse).getJSONObject(0).toString(); String strVenues= new JSONArray(apiResponse).getJSONObject(1).toString(); jsonArray = new JSONObject(strEvents).getJSONArray("fql_result_set"); jsonVenues = new JSONObject(strVenues).getJSONArray("fql_result_set"); 
4159189 0 Rails Bundler on windows refuses to install hpricot (even on manual gem install get Error: no such file to load -- hpricot)

Upgraded to rails 3, and using Bundler for gems, in a mixed platform development group. I am on Windows. When I run Bundle Install it completes succesfully but will not install hpricot. The hpricot line is:

gem "hpricot", "0.8.3", :platform => :mswin 

also tried

gem "hpricot", :platform => :mswin 

Both complete fine but when I try to do a "bundle show hpricot" I get:

Could not find gem 'hpricot' in the current bundle. 

If I do a run a rails console and try "require 'hpricot'" I get:

LoadError: no such file to load -- hpricot 

I have manually installed hpricot as well, and still get the above error. This worked fine before moving to rails 3.

28226538 0

Try setting your text to "My name is John" outside of the button click, perhaps in a Form.Init handler, then removing txtOutPut.Text = "My name is John" from btnClickMe_Click1

What's happening here is the button click is changing the text first to "My name is John", then changing it to "and this is my first VB program" and the change happens too quickly for it to be visible.

36968760 0

As mentioned by Turnip there is -webkit filter for that. However it is more convenient to use SVG:

<svg> <pattern id="mypattern" patternUnits="userSpaceOnUse" width="750" height="800"> <image width="750" height="800" xlink:href="https://placekitten.com/g/100/100"></image> </pattern> <text x="0" y="80" class="fa fa-5x" style="fill:url(#mypattern);">&#xf0f4;</text> </svg> 

You just need to include icon character in SVG

Demo fiddle

37612974 0

I've spent two days fighting with it. Adding "*" namespace to xPath solved the issue for me (my input file did not have any).

return <label>{fn:doc(fn:concat($collection, '/', $child))//*:testResult/text()}</label> 
2107911 0 Safe class imports from JAR Files

Consider a scenario that a java program imports the classes from jar files. If the same class resides in two or more jar files there could be a problem.

  1. In such scenarios what is the class that imported by the program? Is it the class with the older timestamp??

  2. What are the practices we can follow to avoid such complications.

Edit : This is an example. I have 2 jar files my1.jar and my2.jar. Both the files contain com.mycompany.CrazyWriter

18630530 0

You can use ValueProvider.GetValue("HasEditPermission").RawValue to access the value.

Controller:

public class BController : Controller { public ActionResult Index() { ViewBag.HasEditPermission = Boolean.Parse( ValueProvider.GetValue("HasEditPermission").RawValue.ToString()); return PartialView(); } } 

View:

... @if (ViewBag.HasEditPermission) { // some html rendering } ... 

Update:

Request.Params gets a combined collection of QueryString, Form, Cookies, and ServerVariables items not RouteValues.

In

@Html.Action("Index", "BController", new { HasEditPermission = true }) 

HasEditPermission is a RouteValue.

you can also try something like this

ViewContext.RouteData.Values["HasEditPermission"] 

in your View and subsequent child action views as well..

39643679 0
var orders = JSON.parse($('#orderData')); console.log(orders[0].value); 
8984472 0

Indeed, it's possible. I suggest you to use a @property/@synthesize object on the receiver UIViewController (the one with the UIWebView) that it's initialized/filled from the calling viewController with the search string that you want to use.

3092562 0

A couple of ways:

In your web.config on the customErrors mode set the redirectMode to ResponseRewrite - this removes the 302 redirect from the server to the error page - this also has the happy coincidence that uses can easily see what the original page they requested was, and can retry with an F5 if that's likely to resolve the issue.

If you are hooking into the ApplicationError event, make sure that rather than redirecting to your error pages you use Server.Transfer instead.

I have the following in one of my web.configs:

<customErrors mode="On" defaultRedirect="ErrorHandler.aspx" redirectMode="ResponseRewrite"> 

Then in my ErrorHandler page I check for the last error from the server, and configure those:

 var serverError = Server.GetLastError(); var error = serverError as HttpException; int errorCode; string errorMessage; if (null != error) { errorCode = error.GetHttpCode(); errorMessage = error.GetHtmlErrorMessage(); } else { errorCode = 404; errorMessage = "Page not found"; } Response.StatusCode = errorCode; Response.StatusDescription = errorMessage; 

Obviously you may want to do additional processing - for example before I do all this I'm comparing the original request with my Redirects database to check for moved content/vanity urls, and only falling back to this if I couldn't find a suitable redirect.

22708706 0 Time taken to reconnect to a BLE peripheral after restored by State Restoration

Has anyone used State Restoration to reconnect to a peripheral? if so do you have any feel for the how long it took to reconnect?

It's abit of a difficult question, as it is not easy to tell when to start timing from.

It should be when the iDevice gets in range of its peripheral for which the connection request has been issued.

7061264 0 Access a flash object from jQuery

I am using swfobject 2 to dynamically embed my flash... let's call my object "swfContent"

I have tried to use $('swfContent') and $("#swfContent") to access my swf object, but no luck.

Thanks!

9369161 0

The Visual Studio Visualizer's architecture requires all Visualizers to be Modal windows, so the answer is No. Your best bet is to copy/paste the text into a diff tool.

36704302 0

The error 0000052D is a system error code. Specifically, it means:

ERROR_PASSWORD_RESTRICTION

1325 (0x52D)

Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain.

The problem would seem to be that the account you're enabling has a password-policy applied to it, whereby enabling it that password-policy would not be met.

I would first figure out what the password policy is for the account, then set the password to something that meets that policy criteria before flipping the bit to enable it.

If, however, you really want the user to be able to login with no password then the password should be set to null. But I'm not sure under what circumstances that would be desirable.

9729428 0

I think you're on the right track. Instead of grouping FlightTimes by FlightType, try building FlightTimeResults and grouping those by FlightType instead:

var results = from ft in schedules.FlightTimes group new FlightTimeResult { FlightTimeData = ft, FlagRedeye = ft.DepartureTime.Hour >= 0 && ft.DepartureTime.Hour < 6 } by ft.FlightType.ToString() into groupedFlights select groupedFlights; 
25581405 0

I'm not quite sure whether I have completely understood what the problem here is! But you can simply use a Dictionary to hold string values of each 45-degree slice and check it against the word user drags.

Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1, "Eraser"); dict.Add(2, "Glue"); dict.Add(3, "Pen"); dict.Add(4, "Scissors"); dict.Add(5, "Stapler"); dict.Add(6, "Sharpener"); dict.Add(7, "Ruler"); dict.Add(8, "Pencil"); 

And change your code to:

double degree = rng.Next(360, 720); double resultAngle = degree - 360; int num = (int)Math.Ceiling(resultAngle / 45); 

Then, the name of the element the pointer is currently pointing at would be:

string currentElem = dict[num]; 
13061209 0 Stopping a CSS animation but letting its current iteration finish

I have the following HTML:

<div class="rotate"></div>​ 

And the following CSS:

@-webkit-keyframes rotate { to { -webkit-transform: rotate(360deg); } } .rotate { width: 100px; height: 100px; background: red; -webkit-animation-name: rotate; -webkit-animation-duration: 5s; -webkit-animation-iteration-count: infinite; -webkit-animation-timing-function: linear; }​ 

I want to know if there is a way (using JavaScript) to stop the animation but let it finish its current iteration (preferably by changing one or a few CSS properties). I have tried setting -webkit-animation-name to have a blank value but that causes the element to jump back to its original position in a jarring fashion. I have also tried setting -webkit-animation-iteration-count to 1 but that does the same thing.

267110 0

When you specify the DestinationFolder for the Copy task, it takes all items from the SourceFiles collection and copies them to the DestinationFolder. This is expected, as there is no way for the Copy task to figure out what part of each item's path needs to be replaced with the DestinationFolder in order to keep the tree structure. For example, if your SourceDir collection is defined like this:

<ItemGroup> <SourceDir Include="$(Source)\**\*" /> <SourceDir Include="E:\ExternalDependencies\**\*" /> <SourceDir Include="\\sharedlibraries\gdiplus\*.h" /> </ItemGroup> 

What would you expect the destination folder tree look like?

To preserve the tree, you need to do identity transformation and generate one destination item for each item in the SourceFiles collection. Here's an example:

<Copy SourceFiles="@(Compile)" DestinationFiles="@(Compile->'$(DropPath)%(Identity)')" /> 

The Copy task will take the each item in the SourceFiles collection, and will transform its path by replacing the part before the ** in the source item specification with $(DropPath).

One could argue that the DestinationFolder property should have been written as a shortcut to the following transformation:

<Copy SourceFiles="@(Compile)" DestinationFiles="@(Compile->'$(DestinationFolder)%(Identity)')" /> 

Alas, that would prevent the deep copy to flat folder scenario that you are trying to avoid, but other people might using in their build process.

3500096 0 Lost transaction with JPA unique constraint?

I have a field with an unique constraint:

@Column(unique=true) private String uriTitle; 

When I try to save two entities with the same value, I get an exception - but another exception than I exected:

java.lang.IllegalStateException: <|Exception Description: No transaction is currently active at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.rollback(EntityTransactionImpl.java:122) at com.example.persistence.TransactionFilter.doFilter(TransactionFilter.java:35) 

The questionable filter method looks like this:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { EntityManager entityManager = ThreadLocalEntityManager.get(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { chain.doFilter(request, response); transaction.commit(); } catch (Throwable t) { transaction.rollback(); // line 35, mentioned in the exception throw new RuntimeException(t); } finally { entityManager.close(); ThreadLocalEntityManager.reset(); } } 

... and the ThreadLocalEntityManager like this:

public class ThreadLocalEntityManager { private static EntityManagerFactory entityManagerFactory = null; private static final ThreadLocal<EntityManager> entityManager = new ThreadLocal<EntityManager>() { @Override protected EntityManager initialValue() { return entityManagerFactory.createEntityManager(); } }; private ThreadLocalEntityManager() {} public static synchronized void init(String persistenceUnit) { requireNotNull(persistenceUnit); requireState(entityManagerFactory == null, "'init' can be called only " + "once."); entityManagerFactory = Persistence.createEntityManagerFactory(persistenceUnit); } public static EntityManager get() { requireState(entityManagerFactory != null, "Call 'init' before calling " + "'get'"); return entityManager.get(); } public static void reset() { entityManager.remove(); } } 

I wrapped the call to save with try ...catch to handle the unique constraint violation, but that doesn't work:

try { ThreadLocalEntityManager.get().persist(article); // article is constrained } catch(Throwable t) { t.printStackTrace(); } 

Any idea why there is no transaction? What is the correct way to handle a unique constraint violation?

36343298 0 semantic-ui search following link when pressing 'enter'

I want to allow users to navigate the search tool only with the keyboard which means that they navigate search results with arrows and, when they press 'enter', it follows the item's link.

How could this be done ?

Here is an example from the docs, with a GitHub search box

9378795 0

You can work with fancybox Ajax or Iframe and load your HTML page into box.

9100372 0 Javascript: obj.fn() vs x=obj.fn;x()

Take a look at this snippet:

var obj = { fn: function () {return this;} }; var x = obj.fn; obj.fn(); // returns obj x(); // returns window (in the browser) 

I'm curious why obj.fn() is different from x=obj.fn; x(). Is there a special case for attribute lookup directly followed by a function call within a single expression - or there is some more complex magic going on under the hood (like with descriptor protocol in Python) ?

3725123 0

You cannot programatically fill in login information, that is against the Facebook terms and conditions. You can, however, authenticate as an application as opposed to a user. Use the following method:

Make a GET request to: https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=CLIENT_ID&client_secret=CLIENT_SECRET Facebook returns: access_token=SOME_TOKEN Use this token as your access token and it should allow you to access the group. I have tested this with my application and can confirm it works. You request the wall information via the request: https://graph.facebook.com/GROUP_ID/feed?access_token=SOME_TOKEN 

This will not pop up any login screens as you are not required to be logged in to view a public group. Ensure your privacy settings are public for the group as well.

34589096 0 Instagram Media Endpoint Paging

I'm currently looking at reading out posts and related json data from a given number of Instagram users using the following URL:

https://www.instagram.com//media/

This will only bring back the latest 20 posts. I have done some hunting around and I am unable to see how to form the url to bring back the next 20 results. I've seen some places that have suggested using max_timestamp, but I can't see how to make this work.

For various reasons I do not wish to use the standard Instagram API.

15831268 0

There is a "cacheDirectory" in your "data/package_name" directory.

If you want to store something in that cache memory,

File cacheDir = new File(this.getCacheDir(), "temp"); if (!cacheDir.exists()) cacheDir.mkdir(); 

where this is context.

18177680 0

try this

Dim HttpReq As HttpWebRequest = DirectCast(WebRequest.Create("http://...."), HttpWebRequest) Using HttpResponse As HttpWebResponse = DirectCast(HttpReq.GetResponse(), HttpWebResponse) Using Reader As New BinaryReader(HttpResponse.GetResponseStream()) Dim RdByte As Byte() = Reader.ReadBytes(1 * 1024 * 1024 * 10) Using FStream As New FileStream("FileName.extension", FileMode.Create) FStream.Write(RdByte, 0, RdByte.Length) End Using End Using End Using 
8334422 0

I would personally use an interface as suggested, but in case you didn't have access to who is calling you (such as third party .dll) then you can accept an argument of type object:

 /// <summary> /// Draw any type of object if the objec type is supported. /// Circles, Squares, etc. /// </summary> /// <param name="objectToDraw"></param> public void Draw(object objectToDraw) { // get the type of object string type = objectToDraw.GetType().ToString(); switch(type) { case "Circle": // cast the objectToDraw as a Circle Circle circle = objectToDraw as Circle; // if the cast was successful if (circle != null) { // draw the circle circle.Draw(); } // required break; case "Square": // cast the object as a square Square square = objectToDraw as Square; // if the square exists if (square != null) { // draw the square square.Draw(); } // required break; default: // raise an error throw new Exception("Object Type Not Supported in Draw method"); } } 
4005032 0

If you're augmenting rows that already exist you'll want to use an UPDATE statement.

22092822 0

There is no official release of OpenCV for system without OS. OpenCV library is available for Windows, linux, mac, Android and Ios operating system.

Here you can find a link which explain the challenges of having OpenCV running on microcontrollers

39467508 0

try this solution:

 quest.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { JButton b = (JButton)e.getSource(); for(Component c : yourPanel.getComponents()){ if(c instanceof JButton && !c.equals(b)){ c.setEnabled(false); } } } }); 
21394141 0 Database table structure for storing SSO information for FB or Google+

I have a web application that I would like to add single sign on capability using user's Facebook or Google+/Google App account.

I have a USERS table that stores users login information. All users are required to have a record in this table no matter if they signed up using FB or Google+.

I am trying to figure out the information that I need to store in the database in order to link USERS table records to FB or Google information.

Facebook documentation states:

the app should store the token in a database along with the user_id to identify it.

So should I create a table called SSO_LOOKUP with following columns:

7695751 0

Note that @ is already a 1-char infix operator to concat lists.

25349880 0 GetJsonObject from a for looped JsonArray show syntax error
 JsonObject jObj = JsonObject.Parse(json); JsonArray jArr = jObj.GetNamedArray("records"); for (int i = 0; i < jArr.Count; i++) { JsonObject innerObj = jArr.GetObjectAt(i); mData[i] = new Data(innerObj .GetNamedString("countryName"), innerObj .GetNamedString("countryId"), innerObj.GetNamedString("callPrefix"), innerObj .GetNamedString("isoCode")); } 

Visual studio show syntax error: the best overloaded method for jArr.GetObjectAt(uint) has an invalid argument

25614224 1 How to print a variable from a derived class?

I know there are similar questions on this topics but none of them seem to apply to my case Why would the following code print None and not True? Thanks

class A(object): flag = None @classmethod def set_flag(cls): cls.flag = True class B(A): @classmethod def print_super_flag(cls): print cls.__bases__[0].flag # This prints None print super(B, cls).flag # This also if __name__ == "__main__": b = B() b.set_flag() b.print_super_flag() 
19984966 0

No - there are separate endpoints for web services.

Look in ADFS under Services / Endpoints. Note that not all are enabled by default.

I blogged about this - ADFS : WCF web service

23362695 0 Trouble about assign char pointer in C

I have a simple C program about assign char pointer and malloc like this

#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char str[] = "0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789"; char* str1 = malloc(sizeof(char*)); strcpy(str1, str); printf("%s\n\n", str1); char* str2 = malloc(sizeof(char*)); str2 = str1; printf("%s\n", str2); return 0; } 

And the result is:

0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 01! 

So why the str2 just gets 25 characters from str1? And where is the "!" (in the end of str2) come from?

Could you help me? Thanks!

7650906 0

Option 1:

class Example { public: Example( std::string str, const std::complex<float>& v ): m_str( std::move(str) ), m_v( v ) { } /* other methods */ private: std::string m_str; std::complex<float> m_v; }; 

This has pretty good performance and is easy to code. The one place it falls a little short of the optimum is when you bind an lvalue to str. In this case you execute both a copy construction and a move construction. The optimum is only a copy construction. Note though that a move construction for a std::string should be very fast. So I would start with this.

However if you really need to pull the last cycles out of this for performance you can do:

Option 2:

class Example { public: Example( const std::string& str, const std::complex<float>& v ): m_str( str ), m_v( v ) { } Example( std::string&& str, const std::complex<float>& v ): m_str( std::move(str) ), m_v( v ) { } /* other methods */ private: std::string m_str; std::complex<float> m_v; }; 

The main disadvantage of this option is having to overload/replicate the constructor logic. Indeed this formula will become unrealistic if you have more than one or two parameters that you need to overload between const& and &&.

10292660 0 Getting Windows 8 Live ID: GetPrincipalNameAsync() returns empty string

I'm trying to use the method

Windows.System.UserProfile.UserInformation.GetPrincipalNameAsync() 

to get Windows Live ID, but it returns an empty string, anyone knows why?

Thanks a lot.

38896485 0

I guess the problem is that CD V:\ is not enough. If you are on C:\ CD V:\ won't move the scope to V:. To achieve this you have to add the /d switch to the CD command:

... cd /d V:\ ... 
30187285 0

Values of background-size property should be like Xpx Ypx. Try change Your last line to this:

t.getBody().style.backgroundSize = newWidth+"px "+newHeight+"px"; 
18876763 0 Android Calendar RRULE - Events not being created in the calendar

I would appreciate any possible help from people that have already experienced the same problem.

https://groups.google.com/forum/#!searchin/android-developers/rrule/android-developers/4di2k6c49XY/EiS5FRqcwxoJ

Thanks.

EDIT: Problem found: https://code.google.com/p/android/issues/detail?id=60589

13016625 0

Assuming your xml code is saved to "test.xml":

from xml.dom.minidom import parse dom1 = parse("test.xml") for node in dom1.getElementsByTagName('t'): print node.childNodes[0].nodeValue 

This should print the inner values of all tags "".

34390723 0

From the documentation for dispatchKeyEvent:

Return true if the KeyboardFocusManager should take no further action with regard to the KeyEvent; false otherwise

Also you can directly consume the event in your dispatchKeyEvent implementation when no further processing of the event is required.

e.consume(); 

Suggestion of @MadProgrammer is also important. Using of global event processing possibilities is the last choice.

30962416 0

If you don't want to use RestClient::Resource, you can include basic auth in a request like this:

RestClient::Request.execute method: :get, url: url, user: 'username', password: 'secret'

The trick is not to use the RestClient.get (or .post, .put etc.) methods since all options you pass in there are used as headers.

I just did a quick writeup on this over here: https://www.krautcomputing.com/blog/2015/06/21/how-to-use-basic-authentication-with-the-ruby-rest-client-gem/

11361072 0 input not submitting data to mysql

I'm making a very simple groups(like vb forum groups). I've coded all of it, after getting some errors and fixing it now it's showing the page without errors.

The problem now is the data ISN'T being inserted to mysql. When putting the input into forms and then pressing create it goes to "?update=update" and echo's the success message, but doesn't submit to mysql.

Code:

<? if(!$update) { ?> <form action="make_group.php?update=update" method="post"> Group name: <br /> <input name="title" type="text" size="30" /> <br /> Group picture: <br /> <input name="picture" type="text" size="30" /> <br /> Group desc: <br /> <textarea name="desc" cols=30 rows=10 wrap=physical></textarea> <br /> <input type="submit" value="Create" /> <? } elseif($update==update) { $username = $_SESSION[usr_name]; $action = "made a group"; $title = clean($_POST[title]); $desc = clean($_POST[desc]); $pictures = clean($_POST[pictures]); $updateemail = mysql_query("insert into usr_groups(username, title, desc, picture) values('$username', '$title', '$desc', '$picture')"); $result = @mysql_query($qry2); echo("Your group has been created"); } ?> 

Above page code

<? session_start(); include("config.php"); $ip = $_SERVER['REMOTE_ADDR']; $sqlcontent = mysql_query("select * from usr_config"); $content = mysql_fetch_array($sqlcontent); if(!isset($_SESSION[usr_name]) || empty($_SESSION[usr_name]) || !isset($_SESSION[usr_level]) || empty($_SESSION[usr_level])) { session_destroy(); session_unset(); die(' <tr> <td><meta http-equiv="REFRESH" content="0;url=/index.php"></HEAD></td> </tr> <tr> <td></td> </tr> </table> </div> </body>'); } include("func.php"); $update = clean($_GET[update]); $getprof = mysql_query("select * from usr_users where username = '$_SESSION[usr_name]'"); $prof = mysql_fetch_array($getprof); ?> 
12528564 0 friend function returning reference to private data member

I have two questions about the following code.

class cls{ int vi; public: cls(int v=37) { vi=v; } friend int& f(cls); }; int& f(cls c) { return c.vi; } int main(){ const cls d(15); f(d)=8; cout<<f(d); return 0; } 
  1. Why does it compile, since f(d) = 8 attemps to modify a const object?
  2. Why does it still print 15, even after removing the const attribute?
6369681 0

Initially load part of data in your list view. You have to use concept of Handler. onclick event you have to send message to handler inside handler you have to write the logic to load your full data and call notifydataSetChanged method

have a look on the sample code below. Initially user is able to see some part of list. If user cvlicks on any list item then list user is able to see the whole list view. It is similar to as that you are expecting.

Sample Code

import java.util.ArrayList; import android.app.ListActivity; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MyListView extends ListActivity { ArrayList<String> pens = new ArrayList<String>(); ArrayAdapter arrayAdapter = null; private static final byte UPDATE_LIST = 100; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); pens.add("MONT Blanc"); pens.add("Gucci"); pens.add("Parker"); arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, pens); setListAdapter(arrayAdapter); getListView().setTextFilterEnabled(true); ListView lv = getListView(); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub System.out.println("..Item is clicked.."); Message msg = new Message(); msg.what = UPDATE_LIST; updateListHandler.sendMessage(msg); } }); // System.out.println("....g1..."+PhoneNumberUtils.isGlobalPhoneNumber("+912012185234")); // System.out.println("....g2..."+PhoneNumberUtils.isGlobalPhoneNumber("120121852f4")); } @Override public void onConfigurationChanged(Configuration newConfig) { // TODO Auto-generated method stub super.onConfigurationChanged(newConfig); System.out.println("...11configuration is changed..."); } void addMoreDataToList() { pens.add("item1"); pens.add("item2"); pens.add("item3"); } protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); Object o = this.getListAdapter().getItem(position); String pen = o.toString(); Toast.makeText(this, id + "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show(); } private Handler updateListHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_LIST: addMoreDataToList(); arrayAdapter.notifyDataSetChanged(); break; } ; }; }; } 

Thanks Deepak

18350059 0

A web proxy is not normally defined by just a port, but is usually a full host name. Charles is very likely installed on localhost. Therefore the following adjustment may work for you:

@agent ||= Mechanize.new do |agent| agent.set_proxy("localhost", 8888) end 
410752 0

See Inversion of Control and Dependency Injection with Castle Windsor Container - Part II at DotNetSlackers. It shows how to pass an array of the same service interface to an object.

2150387 0

Probably both elements are linked by a ID..

6229054 0 Unable to load webview in tab view

I have no idea why my webview is unable to load in my tabhost/tabwidget. For the tabhost/tabwidget, I am using the tutorial that was provided by Android Developer. Also, in my logcat, the warning seems to be at the tab1Activity.java, pointing the warning to "wv.loadDataWithBaseURL("http://lovetherings.livejournal.com/961.html", myString, "text/html", "UTF-8", "about:blank"); "

Below are my codes. Can anyone help me? Thanks so much in advance! :D

Here is my main.xml

 <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" > <WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </FrameLayout> </LinearLayout> 

My main activity

public class HelloTabWidgetMain extends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Resources res = getResources(); // Resource object to get Drawables TabHost tabHost = getTabHost(); // The activity TabHost TabHost.TabSpec spec; // Resusable TabSpec for each tab Intent intent; // Reusable Intent for each tab // Create an Intent to launch an Activity for the tab (to be reused) intent = new Intent().setClass(this, ArtistsActivity.class); // Initialize a TabSpec for each tab and add it to the TabHost spec = tabHost.newTabSpec("tab1").setIndicator("tab1", res.getDrawable(R.drawable.ic_tab_tab1)) .setContent(intent); tabHost.addTab(spec); // Do the same for the other tabs intent = new Intent().setClass(this, tab2Activity.class); spec = tabHost.newTabSpec("tab2").setIndicator("tab2", res.getDrawable(R.drawable.ic_tab_tab2)) .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, tab3Activity.class); spec = tabHost.newTabSpec("tab3").setIndicator("tab3", res.getDrawable(R.drawable.ic_tab_tab3)) .setContent(intent); tabHost.addTab(spec); tabHost.setCurrentTab(0); } 

}

And my tab activity (where I would want my webview contents to be displayed)

public class tab1Activity extends Activity{ WebView wv; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { URL url = new URL("http://lovetherings.livejournal.com/961.html"); // Make the connection URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader( new InputStreamReader(conn.getInputStream())); // Read the contents line by line (assume it is text), // storing it all into one string String content =""; String line = reader.readLine(); while (line != null) { content += line + "\n"; line = reader.readLine(); } reader.close(); String myString = content.substring(content.indexOf("<newcollection>")); int start = myString.indexOf("<newcollection>"); if (start < 0) { Log.d(this.toString(), "collection start tag not found"); } else { int end = myString.indexOf("</newcollection>", start) + 8; if (end < 0) { Log.d(this.toString(), "collection end tag not found"); } else { myString = "<html><body>" + myString.substring(start, end) + "</body></html>"; } WebView wv = (WebView)findViewById(R.id.webview); wv.loadDataWithBaseURL("http://lovetherings.livejournal.com/961.html", myString, "text/html", "UTF-8", "about:blank"); } } catch (Exception ex) { ex.printStackTrace(); // Display the string in txt_content //TextView txtContent = (TextView)findViewById(R.id.txt_content); //txtContent.setText(myString); } } 

}

Please help me! Thanks in advance!

21102386 0 What is the term for a "stack" of sub-pages that displays on one page?

I'm building a Wordpress site and am looking for a plugin for managing a very specific kind of content / design scheme. Unfortunately, I do not know what this is called, and am looking for pointers on terminology so I can ease my search.

Imagine a very long page (as tall as 7 screens, for instance).

This is divided into 7 sub-pages, each the size of one screen, stacked one on top of the other.

Each sub-page has its own background and content.

The viewer can scroll from top to bottom of the "parent" page, and get 7 distinct background / content groupings for 7 different products.

What is this kind of content called? "Frames", isn't right, and "divs" is too general. I would appreciate any guidance on this that can be provided. Thanks!

I don't have any live demos of this sort of content, but will post them as I find them.

4440306 0

First try updating your statistics.

Then, look into your indexing, and make sure you have only what you need. Additional indexes can most definitely slow down inserts.

Then, try rebuilding the indexes.

Without knowing the schema, query, or amount of data, it is hard to say more than that.

25039982 0

This is implementation defined as per the draft C99 standard section 6.3.2.3 Pointers which says:

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

gcc documents there implementation here:

The result of converting a pointer to an integer or vice versa (C90 6.3.4, C99 and C11 6.3.2.3).

Alternatively you could use uinitptr_t assuming stdint.h is available which is an unsigned integer that can hold a pointer value:

#include <stdint.h> #include <inttypes.h> uintptr_t ip = &i ; printf("0x%016" PRIxPTR "\n", ip ) ; 
4176241 0 I call Alert.Show in a function and want to get the result from there (Flex, ActionScript)

I'm using the Alert.show in a function and I want to get the user answer from there. So how can I achieve this. The problem is the function that call Alert.show will return a true or false value depend the user answer. but It seem that in Alert.show it only allow to pass in a CloseHandler for this. that is a new function. and since that I can get the user answer from where it is call to return the user answer.

Really thanks for help Yuan

6119230 0 You need 10,000 digits of e on a windows box

Let's say you have a bare-bones Windows XP machine, nothing added. This means no compilers, no MS Office, etc. Oh, and no network connection.

You want 10,000 digits of e (e is the base of the natural logarithm). You have one hour. How could you do it?

Disclaimer: There are probably multiple "good" answers, but I have one particular idea in mind.

25907377 0 error in spring-security.xml for constructor arg error

i m using spring security for my login page.in this in the database user password is stored using sha-password encoder.now i want to use the same in my spring-security.xml.i tried this

<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> <constructor-arg value="256"/> </beans:bean> <authentication-manager> <authentication-provider> <password-encoder ref="passwordEncoder"/> <jdbc-user-service data-source-ref="dataSource" users-by-username-query= "select email,password, 'true' as enabled from user_login where email=? limit 1" authorities-by-username-query= "select email, role from user_roles where email =? " /> </authentication-provider> </authentication-manager> </beans:beans> 

i m getting error at

cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'constructor-arg'. - Security namespace does not support decoration of element [constructor-arg] - Configuration problem: Security namespace does not support decoration of element. 

anyone help me for this,please.

19253826 0

I found the solution. If load following HTML in UIWebView in iOS 7 (not Safari), the onblur event doesn't work:

<html> <head> <meta name='viewport' content='initial-scale=1.0,maximum-scale=10.0'/> </head> <body> <table style='height:80%'><tr><td> <select onblur="alert('blur')" > <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> </td></tr></table> </body> </html> 

The important components: viewport, table with some height defined, select inside this table. If remove table OR remove height style OR remove viewport, then onblur works.

I can't explain this effect, but I just remove table height style and it works. Maybe it helps somebody.

16496963 0

HKL9 (string) is greater than HKL15, beacause they are compared as strings. One way to deal with your problem is to define a column function that returns only the numeric part of the invoice number.

If all your invoice numbers start with HKL, then you can use:

SELECT MAX(CAST(SUBSTRING(invoice_number, 4, length(invoice_number)-3) AS UNSIGNED)) FROM table 

It takes the invoice_number excluding the 3 first characters, converts to int, and selects max from it.

24092656 0

You can either use, but $('title') will fail in IE8

document.title="new title"; 

or

$('title').html('new title'); 

or

$(document).attr('title','new title'); 
34736811 0

You can use the LIKE ability of mysql:

SELECT * FROM company WHERE country LIKE '%$country%'; 
16013020 0 How use Video.js player via Flash fallback without CDN swf file

IE8 or older automatically uses flash fallback player but the player is hosted in CDN.

I want to use hosted video-js.swf file in my server instead of CDN contents. Because CDN swf file is not secured.

The Video.js version is 3.2, that is currently you can download from http://videojs.com/.

I tried this code but it does not work.

Can someone help me with the solution?

Thanks!

9359946 0 Call user defined function on click in jQuery

I have made a jQuery function and want to call it on click event. My code is like below:

<script type="text/javascript"> (function($){ $.fn.my_function = function(options){ return this.each(function(){ alert("Hello"); }); }; })(jQuery); $(document).ready(function(){ $('#submit_buttom').my_function(); }); </script> 

Please help.

Thanks

15148571 0

You need to open the applications screen, in it to scroll right until you get to the widgets section. from there pull the widget that you want and add it to the desired desktop.

8043579 0 How to strip path while archiving with TAR

I have a file that contain list of files I want to archive with tar. Let's call it mylist.txt

It contains:

/path1/path2/file1.txt /path1/path2/file3.txt ... /path1/path2/file10.txt 

What I want to do is to archive this file into a tarball but excluding /path1/path2/. Currently by doing this:

tar -cvf allfiles.tar -T mylist.txt 

preserves the path after unarchiving.

I tried this but won't work too:

tar -cvf -C /path1/path2 allfiles.tar -T mylist.txt 

It archives all the files in /path1/path2 even those which are not in mylist.txt

Is there a way to do it?

38588513 0 Best practice to deploy wso2 esb policies

I have setup an ESB cluster using jdbc connections to ms sql databases for local and remotely mounted config and gov registries. 1x mgt and 2xworker

Our .car file contains some ws-security policy artifacts which go to config. When I deploy to mgt it deploys OK. I have SVN dep sync setup to the cluster and when it picks up the .car it starts to deploy on the worker but fails when loading the policy files into conf. It is trying to duplicate the policy in the shared conf and fails - of course that is right but; how should I deploy these 'shared' artifacts when a .car file is distributed by svn? I need to be able to control the deploy properly. The only way I can see is via the dev studio which is terrible for our change management practice.

Thanks for you help.

2998841 0

Use the application identifier in the .config file to differentiate between your applications. It's in the Membership Provider section. applicationName="MyApplication"

4846718 0 asp.net 3.5 referencing project with assembly reference throws signing/strong name error in Unit Test

I have a reference to a MySQL.Data 5.2.3 assembly in a data layer, great. I currently I have small console app inteh same solution referencing JUST THIS data layer which connects just fine. I then created a unit test project (also in the same solution) and reference that same data layer project, and from that I get:

Test method LTTests.WrapperTest.LoginTest threw exception: System.IO.FileLoadException: Could not load file or assembly 'MySql.Data, Version=5.2.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. Strong name signature could not be verified. The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045).

So I'm trying to understand...I can do this for a console exe and it works but not a unit test? This makes me nervous to build on something apparently flawed, but I'm at a loss for what to do next. I'm lost, I've been re-adding various things looking for what the deal is and I have no clue.

The exception is from the data layer and not from the test (per the stack) so it's like the test is calling the layer's method (duh) and the data layer is puking but not for the console?

Thanks.

35030093 0

Is it crucial for it to have to equal -3.40282306e+38 for your algorithm to work? If nor try an inequality instead of equals. Equlaity works on floating point numbers if they are perfect integers such as 0,for numbers like youre using an inequality maybe the answer. Wont something like

(-3.40282306e+38-smallnumber) fix your problem?-You have to set small number to somthing in the context of your problem which I dont know what it is.

22829563 0

1. Can we get all field names of a collection with their data types?

mongodb collections are schema-less, which means each document (row in relation database) can have different fields. When you find a document from a collection, you could get its fields names and data types.

2. Can we generate a random value of that data type in mongo shell?

3. how to set the values dynamically to store random data.

mongo shell use JavaScript, you may write a js script and run it with mongo the_js_file.js. So you could generate a random value in the js script.

It's useful to have a look at the mongo JavaScript API documentation and the mongo shell JavaScript Method Reference.

Other script language such as Python can also do that. mongodb has their APIs too.

11568153 0

The useful difference between

data Point = Point Float Float data Radius = Radius Float data Shape = Circle Point Radius 

and
data LengthQty = Radius Float | Length Float | Width Float

is the way Haskell's type system handles them. Haskell has a powerful type system, which makes sure that a function is passed data that it can handle. The reason you'd write a definition like LengthQuantity is if you had a function which could take either a Radius, Length, or Width, which your function can't do.

If you did have a function which could take a Radius, Length, or Width, I'd write your types like this:

data Point = Point Float Float data Radius = Radius Float data Shape = Circle Point Radius data LengthQty = R Radius | L Length | W Width 

This way, functions that can only take a Radius benefit from that more specific type checking.

16917797 0 how do i implement a basic timestamp in pull to refresh

I have implemented a pull to refresh and now trying to add a timestamp showing "Last updated: "time""(4:50/tuesday etc). I have implemented a method for the same:

public void setLastUpdated(CharSequence lastUpdated) { if (!TextUtils.isEmpty(lastUpdated)) { eikonLastUpdated.setVisibility(View.VISIBLE); eikonLastUpdated.setText(lastUpdated); } else { eikonLastUpdated.setVisibility(View.GONE); } } 

Does anyone know how I can add the same to an XML, and how do I go about it, do I also have to add the same to java by calling settext method? example:

textView.setText("Last updated:"); 

How do I call the setlastupdated method for the same?

7161624 0 Converting a variadic macro to a variadic template function?

Given a variadic macro of the form:

#define MY_CALL_RETURN_F(FType, FId, ...) \ if(/*prelude omitted*/) { \ FType f = (FType)GetFuncFomId(FId); \ if(f) { \ return f(__VA_ARGS__); \ } else { \ throw invalid_function_id(FId); \ } \ } \ /**/ 

-- how can this be rewritten to a variadic function template?

template<typename FType, typename ...Args> /*return type?*/ tmpl_call_return_f(MyFunId const& FId, /*what goes here?*/) { ... FType f = (FType)GetFuncFomId(FId); return f(/*what goes here?*/); ... } 

Update: I'm specifically interested in how to declare the reference type for the Args: && or const& or what?

Update: Note that FType is supposed to be a "plain" function pointer.

36067236 0

did you try this

{% load games_tags %} 

at the top instead of pygmentize?

11765378 0
Iterator<Integer> it=ar1.iterator(); Iterator<Integer> it2=ar2.iterator(); while(it.hasNext()&&it2.hasNext()) { result.add(new Integer(it.next().intValue()*it2.next().intValue())); } 

will also work efficiently for any list.

630955 0 How to implement dispose pattern with close method correctly (CA1063)

The Framework Design Guidelines (2nd Ed., page 327) say:

CONSIDER providing method Close(), in addition to the Dispose(), if close is standard terminology in the area.

When doing so, it is important that you make the Close implementation identical to Dispose and consider implementing IDisposable.Dispose method explicitly.

So, following the provided example, I've got this class:

public class SomeClass : IDisposable { private SomeDisposable someInnerDisposable; public void Open() { this.someInnerDisposable = new SomeDisposable(); } void IDisposable.Dispose() { this.Close(); } public void Close() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.someInnerDisposable.Dispose(); this.someInnerDisposable = null; } } } 

FxCop doesn't seem to like that:

CA1816 : Microsoft.Usage : 'SomeClass.Close()' calls 'GC.SuppressFinalize(object)', a method that is typically only called within an implementation of 'IDisposable.Dispose'. Refer to the IDisposable pattern for more information.

CA1816 : Microsoft.Usage : Change 'SomeClass.IDisposable.Dispose()' to call 'GC.SuppressFinalize(object)'. This will prevent unnecessary finalization of the object once it has been disposed and it has fallen out of scope.

CA1063 : Microsoft.Design : Modify 'SomeClass.IDisposable.Dispose()' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance ('this' or 'Me' in Visual Basic), and then returns.

CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.

-or-

I tried

[SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly", Justification = "Framework Design Guidelines say it's ok.")] void IDisposable.Dispose() { this.Close(); } 

but FxCop 1.36 still reports them.

EDIT: Changing it around as suggested eliminates all but this warning:

CA1063 : Microsoft.Design : Rename 'SomeClass.IDisposable.Dispose()' to 'Dispose' and ensure that it is declared as public and sealed.

EDIT 2: CODE_ANALYSIS was indeed missing. Thanks.

3112665 0

What about just using typedefs?

typedef V& I; typedef const V& CI; 

Edit:

No. See comments :)

22119836 0 How to Implement a Class/Database Listener?

I am using the Parse.com database service for a PhoneGap app we are creating. We have users that can mark themselves (First User) "Available" for their friends (Second User), and I need a way to listen for that toggle in availability on the second user's side, so their friends list can update without having the refresh the page.

With Parse, your interaction with the database is monitored by # API calls and Burst Limit (Number of API calls per second) so I need to only call the database for the change in status when it is actually changed, I can't keep a setInterval on otherwise it will make the burst limit too small for other user, or it will cause to many API calls for no reason if the status isn't changing.

How can I got about this?

39015432 0 run Spark-Submit on YARN but Imbalance (only 1 node is working)

i try to run Spark Apps on YARN-CLUSTER (2 Nodes) but it seems those 2 nodes are imbalance because only 1 node is working but another one is not.

My Script :

spark-submit --class org.apache.spark.examples.SparkPi --master yarn-cluster --deploy-mode cluster --num-executors 2 --driver-memory 1G --executor-memory 1G --executor-cores 2 spark-examples-1.6.1-hadoop2.6.0.jar 1000 

I see one of my node is working but another is not, so this is imbalance :

enter image description here Note : in the left is namenode, and datanode is on the right...

Any Idea ?

20764999 0

As it turns out, there is a way to do this, but it's not pretty. It involves using the WinForms version of MessageBox and passing an undocumented option as the last property.

var result = System.Windows.Forms.MessageBox.Show("Are you sure you want to exit this app?", "Exit", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button2, (System.Windows.Forms.MessageBoxOptions)8192 /*MB_TASKMODAL*/); 

Source: http://social.msdn.microsoft.com/Forums/vstudio/en-US/8d1bd4a2-455e-4e3f-8c88-7ed49aeabc09/messagebox-is-not-applicationmodal?forum=wpf

Hopefully this is helpful to somebody else in the future!

40907417 0 Why is infinity printed as "8" in the Windows 10 console?

I was testing what was returned from division including zeroes i.e. 0/1, 1/0 and 0/0. For this I used something similar to the following:

Console.WriteLine(1d / 0d); 

However this code prints 8 not Infinity or some other string constant like PositiveInfinity.

For completeness all of the following print 8:

Console.WriteLine(1d / 0d); double value = 1d / 0d; Console.WriteLine(value); Console.WriteLine(Double.PositiveInfinity); 

And Console.WriteLine(Double.NegativeInfinity); prints -8.

Why does this infinity print 8?


For those of you who seem to think this is an infinity symbol not an eight the following program:

Console.WriteLine(1d / 0d); double value = 1d / 0d; Console.WriteLine(value); Console.WriteLine(Double.PositiveInfinity); Console.WriteLine(8); 

Outputs:

Inifinity output

10294436 0

This code:

for(NSString *jidAct in occupantsArray){ if([jidAct isEqualToString:jid]){ [occupantsArray removeObjectAtIndex:i]; } i++; } 

is probably causing your problems. You shouldn't be removing elements while enumerating the array. The way you avoid this is by using an NSMutableIndexSet:

NSMutableIndexSet *indexes = [NSMutableIndexSet set]; // assuming NSInteger i; for(NSString *jidAct in occupantsArray){ if([jidAct isEqualToString:jid]){ [indexes addIndex:i]; } i++; } [occupantsArray removeObjectsAtIndexes:indexes]; 
29617983 0

Here's how I'd approach this:

combiner <- function(n, ...) { ## Capture the unevaluated calls and symbols passed via ... ll <- as.list(substitute(list(...)))[-1] ## Process each one in turn lapply(ll, FUN = function(X) { ## Turn any symbols/names into calls if(is.name(X)) X <- as.call(list(X)) ## Add/replace an argument named n X$n <- n ## Evaluate the fixed up call eval(X) }) } combiner(6, fun1(), fun2, rnorm(), fun4(y=8)) # [[1]] # [1] 3 8 9 7 4 7 # # [[2]] # [1] "Z" "M" "U" "A" "Z" "U" # # [[3]] # [1] 0.6100340 -1.0323017 -0.6895327 1.2534378 -0.3513120 0.3116020 # # [[4]] # [1] 112.31979 91.96595 79.11932 108.30020 107.16828 89.46137 
32262515 0

Yes:

Application.EnableEvents = False 

Then when you are done with the procedure:

Application.EnableEvents = True 
32651039 0

If the client name section of the URL is after the access-guid/ and before the next /:

http://www.disabledgo.com/access-guide/the-university-of-manchester/176-waterloo-place-2 |----------------------------| 

you need to use a negated character class to only match university before the regex reaches that rightmost / boundary.

As per the Reference:

You can extract pages by Page URL, Page Title, or Screen Name. Identify each one with a regex capture group (Analytics uses the first capture group for each expression)

Thus, you can use

/access-guide/([^/]*(universit(y|ies)|colleges?)) ^^^^^ 

See demo.

The regex matches

12796448 0

Position parameter of the getView() method gives the position of the newly created View (i.e the list item), it wont give the clicked item position.

Use listView.onClickListener in the Activity instead of Adater.

34080123 0

You can make Django go back to the Poll instance by overriding the response_change method on the full Choice admin:

from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect class ChoiceAdmin(admin.ModelAdmin): ''' To be called from the Poll choice inline. It will send control back to the Poll change form, not the Choice change list. ''' fields = [...] def response_change(self, request, choice): if not '_continue' in request.POST: return HttpResponseRedirect(reverse("admin:appname_poll_change", args=(choice.poll.id,))) else: return super(ChoiceAdmin, self).response_change(request, choice) 

To address the second part of your question: I think you'll have to register a second, unmodified, admin on the model. You can do that using a proxy model. See Multiple ModelAdmins/views for same model in Django admin

34755100 0 How to parse BigInt from the num crate?

I am trying to use BigInt. My code is like this:

extern crate num; use num::bigint::BigInt; ... println!("{}", from_str::<BigInt>("1")); //this is line 91 in the code 

In my Cargo.toml file I have the following:

[dependencies] num = "0.1.30" 

What I did seem to match what was said in this document, also this document and also an answer here on Stack Overflow.

However I got the following error:

Compiling example v0.1.0 (file:///C:/src/rust/example) src\main.rs:91:20: 91:38 error: unresolved name `from_str` [E0425] src\main.rs:91 println!("{}", from_str::<BigInt>("1")); 
14601824 0

While your pictures are fairly large and you should try to reduce the number and size, you can make gains through packaging the .png into pvr.ccz files. There are multiple different programs available to do this. I like to use Texture Packer which is available here: http://www.codeandweb.com/texturepacker

20111762 0 Mysql date_add 1 year

Can someone help me figure out why adding 1 year doesn't work for me?

I have 6 other conditions (1 day, 1 week, 2 month, etc). The only one NOT working is the year.

Anyone see why? In case it matters, this is Perl.

elsif ($data{length} == "6month") { $store = qq(INSERT INTO main (creator_name,email2,relationship,reason,email1,name1,creator_email,email3,name2,name3,creator_url,victim_url,length_of_stay,release_date) VALUES("$data{creatorname}","$data{email2}","$data{relationship}","$data{reason}","$data{email1}","$data{person1}","$data{creatoremail}","$data{email3}","$data{person2}","$data{person3}", "$creatorURL", "$victimURL","$data{length}", DATE_ADD(NOW(), INTERVAL 6 MONTH)) ); } elsif($data{length} == "1year") { $store = qq(INSERT INTO main (creator_name,email2,relationship,reason,email1,name1,creator_email,email3,name2,name3,creator_url,victim_url,length_of_stay,release_date) VALUES("$data{creatorname}","$data{email2}","$data{relationship}","$data{reason}","$data{email1}","$data{person1}","$data{creatoremail}","$data{email3}","$data{person2}","$data{person3}", "$creatorURL", "$victimURL","$data{length}", DATE_ADD(NOW(), INTERVAL 1 YEAR)) ); } my $sth = $dbh->prepare($store); $sth->execute() or die $dbh->errstr; 
1154732 0 many domains = much memory usage?

I would like to know if for example, I have about 80 domains on my projects, does it means that the 80 domains will be loaded into memory when I run the project or it will be loaded when I need that domain ...

It seems if I have many domains in one project, I have to disable auto compile and increase the perm gen space.

is there any solutions to load just when I need to acces those domain ? not all domain will be used ... sometimes it just small domain that almost never touched by users incase something happens (ie special cases)

I'm using grails 1.1.1 at the moment and have to disable the auto compile for domain or else it will stuck and depleted memory / memory gen space

13831968 0

You can use the http put method to handle the file upload. In this method the data is directly streamed to the PHP script and you can handle it using file functions:

<?php $f = fopen('php://input','r'); while(!feof($f)){ $chunk = fread($f,CHUNK_SIZE); [Handle the uploading file here] } fclose($f); ?> 

(Replace CHUNK_SIZE with your value)

13841315 0

For valid xHTML it should have the alt attribute.

Something like this would work:

$xml = new SimpleXMLElement($doc); // $doc is the html document. foreach ($xml->xpath('//img') as $img_tag) { if (isset($img_tag->attributes()->alt)) { unset($img_tag->attributes()->alt); } } $new_doc = $xml->asXML(); 
13799947 1 Python Filling Up Disk

I need to setup some test conditions to simulate a filled up disk. I created the following to simply write garbage to the disk:

#!/usr/bin/python import os import sys import mmap def freespace(p): """ Returns the number of free bytes on the drive that ``p`` is on """ s = os.statvfs(p) return s.f_bsize * s.f_bavail if __name__ == '__main__': drive_path = sys.argv[1] output_path = sys.argv[2] output_file = open(output_path, 'w') while freespace(drive_path) > 0: output_file.write("!") print freespace(drive_path) output_file.flush() output_file.close() 

As far as I can tell by looking at the return value from freespace, the write method does not write the file to until it is closed, thereby making the while condition invalid.

Is there a way I can write the data directly to the file? Or another solution perhaps?

31752059 0

The main issue you seem to be encountering is that the proxy example you're using requires a POST to update the destination URL you're trying to browse through the proxy. That's why you're not getting any content from the target page, and the error message

<div id="error">Hotlinking directly to proxied pages is not permitted.</div> 

I don't know how your code looks like, but it seems like you could use the HttpWebRequest POST Method

WebRequest request = (HttpWebRequest)WebRequest.Create("http://www.glype-proxy.info/includes/process.php?action=update"); var postData = "url="+"http://www.example.com"; postData += "&allowCookies=on"; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); 

You're going to need to find or host a proxy that returns the HTML of the page, such as http://www.glype-proxy.info/. Even so, in order for a proxy to function correctly, it must change the link to the page's resources to it's own "proxied" path.

http://www.glype-proxy.info/browse.php?u=https%3A%2F%2Fwww.example.com%2F&b=4&f=norefer 

In the URL above, if you want the path to the original resources, you'll have to find all the resources that have been redirected and unencode the path passed in as the u= parameter to this specific proxy. Also, you may wish to ignore additional elements injected by the proxy , in this case the <div id="include"> element.


I believe the proxy you're using works the same way as the "Glype" proxy I used in this example, but I do not have access to it at the time of posting. Also, if you want to use use other proxies, you may want to note that many proxies display the result in an iFrame (probably for XSS prevention, navigation, or skinning).

Note: Generally, using another service outside of a built-in API is a bad practice, since services often get a GUI update or some other change that could break your script. Also, those services could experiences interruptions or just be taken down.

36406243 0 Spring-boot app not rendering war file in Tomcat 8

I know by default Spring-Boot uses Tomcat 7. Therefore I have declared it in my POM file:

<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> <tomcat.version>8.0.33</tomcat.version> </properties> 

I confirm that that is the Tomcat version I am using. Tomcat

I placed the War file in the webapps folder, it naturally unwrapped it but the path localhost:8080/personalsite gives me a 404.

enter image description here

If I run java -jar personalsite it works fine. Now I am wondering what to do next or where to look.

My log file only outputs the following:

04-Apr-2016 10:16:47.834 INFO [http-nio-8080-exec-8] org.apache.catalina.core.ApplicationContext.log Spring WebApplicationInitializers detected on classpath: [org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration$JerseyWebApplicationInitializer@35a7f52a] 

pom.xml

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.personalsite</groupId> <artifactId>personalsite</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>PersonalSite</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.8</java.version> <tomcat.version>8.0.33</tomcat.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> 
3668746 0 How do I move old content down in the search engine rankings?

There is some precedent for search-engine-ranking-related questions on StackOverflow, so please don't close this question. It's programming-related to the extent that HTML META tags can be called "programming".

Here's the problem:

We make FogBugz, the software project planning and bug tracking suite.

Either we did a great job with our old documentation or a crummy job with our new documentation, but for most of the popular searches on FogBugz terms, documentation for our old versions comes up.

Here's an example. For context, our current FogBugz version is FogBugz 7. The top two results for that search are for FogBugz 5, which is positively ancient.

As best I can tell, there are several options for getting these results out of the top slots, but each has problems:

I just want these old documentation versions to stop competing with our current versions, without being completely unavailable.

9129513 0

Try this:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111" /> <Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111 222 333" /> <Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111 222 333 444 555 666" /> <Button android:layout_width="100dip" android:layout_height="70dip" android:layout_gravity="center" android:text="111" /> </LinearLayout> </LinearLayout> 
33104604 0

You just need to add a "Add Row" button at the end and push a new value to your List1 like this in your controller. See an update to your fiddle here.

$scope.addRow = function(){ var len = $scope.List1.length; $scope.List1.push('product'+(len+1)); } 

And right after your table, add a button that calls the above function:

 </table> <button ng-click="addRow()">Add a row</button> 
8862508 1 iFrame within wxpython?

Hi i am wondering if there is a widget or someway to put an iFrame in a program with wxpython. An iFrame with the same capabilities as the HTML one, (ability to see other websites).

Thanks.

29542878 0 Excel VBA fill 100 x 100 martix based on value in a column

I would love to fill a spreadsheet with 100 columns and 100 rows. I used the analysis toolpack to create a column of 10,000 numbers from a distribution (using the discrete distribution options 1 variable, 10,000 numbers and the two columns below as values).

I want the columns to simulate 100 trials of 100 years using the column as the reproduction rates. The column created simulates the reproduction rates for each cell within the 100 x 100 matrix. I would like the initial row value for all columns to be 31.

For the first column, I would like the (2,1) to multiple 31 by the first value in the reproduction column. For (3,1) I would like the to multiple (2,1) by the second value in the reproduction column. I would like this to continue for all 100 cells in the first column. I would then like it to start over on the next column starting with (2,1) being 31 multiplied by the 101 value in the reproductive column.

Private Sub Code() Dim i As Long Dim j As Long Dim iCol Dim ws As Worksheet 'Set this to the source sheet (where your trial counts are) Set ws = ActiveWorkbook.Sheets(4) For i = 2 To 100 iCol = ws.Cells(i, 1) For j = 1 To 100 Cells(1, i).Value = 34 For k = 1 To iCol Cells(j + 1, i + 1).Value = Cells(j, i).Value * k Next k Next j Next i End Sub 

Here is the distribution that I would like the random numbers to be generated from. If there is a way to use the analysis tool within the VBA to allow so the numbers are generated there instead of externally, that would be great!

Value, Probability -0.15,0 -0.125,0 -0.1,0.05 -0.075,0 -0.05,0.05 -0.025,0 0,0 0.025,0.05 0.05,0 0.075,0 0.1,0.15 0.125,0.15 0.15,0.3 0.175,0.05 0.2,0.15 0.225,0.05 0.25,0 

Any help or advice is greatly appreciated!

Thank you!!

34976274 0

You have to create the table before Model from migration file check Documentation Creating tables section, then the model will use the plural name of the class as the table name.

NOTE : You have to set up your database configuration firstly and create database manually check Database: Getting Started section.

Hope this helps.

14617635 0 php thumbnail organizer

Ok, i have this code and is working perfectly, but i need the order of the images to be by the date the image was created, can someone give me a hand?

$images=array(); $dir = @opendir('.') or die("Unable to open $path"); $i=0; while($file = readdir($dir)) { if(is_dir($file)) continue; else if($file != '.' && $file != '..' && $file != 'index.php') { $images[$i]=$file; $i++; } } sort($images); for($i=0; $i<sizeof($images); $i++) { echo "<a href=".chr(34).$path.$images[$i].chr(34)."><img style='border:1px solid #666666; width:200px; margin: 10px;' src='".$images[$i]."'/></a>"; } closedir($dir); 
38942937 0

df["dataset_code"] is a Series, not a DataFrame. Since you want to append one DataFrame to another, you need to change the Series object to a DataFrame object.

>>> type(df) <class 'pandas.core.frame.DataFrame'> >>> type(df['dataset_code']) <class 'pandas.core.series.Series'> 

To make the conversion, do this:

df = df["dataset_code"].to_frame() 
27532359 0 Spring-Boot : Referencing another Spring Boot Project

I created two spring boot projects, one is with JPA and the other with Web. I initially combined both of them into one project and everything works perfectly.

I now want to separate the JPA portion from the Web. So I added the JPA project as a dependency of the Web. But spring-boot is unable to detect the beans on JPA.

Is there any examples on how to implement this?

I am getting the exception when I tried to autowire the beans from the JPA project.

 BeanCreationException: Could not autowire field: 
39906977 0

OGNL allows execution of methods, but the static access is disabled by default, so you cannot use static method in expressions. However, you can teach OGNL which classes needs to access the static methods.

OGNL developer guide: Method Accessors

Method calls are another area where OGNL needs to do lookups for methods based on dynamic information. The MethodAccessor interface provides a hook into how OGNL calls a method. When a static or instance method is requested the implementor of this interface is called to actually execute the method.

public interface MethodAccessor { Object callStaticMethod( Map context, Class targetClass, String methodName, List args ) throws MethodFailedException; Object callMethod( Map context, Object target, String methodName, List args ) throws MethodFailedException; } 

You can set a method accessor on a class-by-class basis using OgnlRuntime.setMethodAccessor(). The is a default method accessor for Object (which simply finds an appropriate method based on method name and argument types and uses reflection to call the method).


You can code something

public class StringUtil extends StringUtils implements MethodAccessor { //implement above methods } 

Action class

public static final String MESSAGE = "hello.message"; /** * Field for Message property. */ private String message; /** * Return Message property. * * @return Message property */ public String getMessage() { return message; } private StringUtil stringUtil = new StringUtil(); public StringUtil getStringUtil() { return stringUtil; } public String execute() throws Exception { setMessage(getText(MESSAGE)); OgnlRuntime.setMethodAccessor(StringUtil.class, stringUtil); return SUCCESS; } 

In JSP

<s:if test="!stringUtil.isEmpty(message)"> <h2><s:property value="message"/></h2> </s:if> 

17287528 0

Try this:

> d <- as.Date("01-01-2013", "%d-%m-%Y") + 0:7 # first 8 days of 2013 > d [1] "2013-01-01" "2013-01-02" "2013-01-03" "2013-01-04" "2013-01-05" [6] "2013-01-06" "2013-01-07" "2013-01-08" > > ufmt <- function(x) as.numeric(format(as.Date(x), "%U")) > ufmt(d) - ufmt(cut(d, "year")) + 1 [1] 1 1 1 1 1 2 2 2 

Note: The first Sunday in the year is defined as the start of week 1 by %U which means that if the year does not start on Sunday then we must add 1 to the week so that the first week is week 1 rather than week 0. ufmt(cut(d, "year")) equals one if d's year starts on Sunday and zero otherwise so the formula above reduces to ufmt(d) if d's year starts on Sunday and ufmt(d)+1 if not.

UPDATE: corrections so Jan starts at week 1 even if year starts on a Sunday, e.g. 2006.

14660230 0

I've spend many hours on that subject, one (working) thing I've found is this: https://github.com/jgallen23/OWAParser

My problem was, after testing many times with my company's Exchange server they've locked my account. And even thought it works, after changing something small in the server configuration it will stop working, and that wasn't an option for me.

Hope this helps you! :-)

16314092 0

have you tried like below one

Call below Method From the TableView DataSource Method (cellForAtIndexPath) For Doing the same Task

 - (void)setCellBGColorNormalAndSelectedForTableViewCell:(UITableViewCell*)cell cellForRowAtIndexPath:(NSIndexPath*)indexPath { UIImageView *normalCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)]; [normalCellBG setImage:[UIImage imageNamed:@"box_nonselected.png"]];//Set Image for Normal [normalCellBG setBackgroundColor:[UIColor clearColor]]; [cell setBackgroundView:normalCellBG]; UIImageView *selecetedCellBG = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height)]; [selecetedCellBG setImage:[UIImage imageNamed:@"box_selected.png"]];//Set Name for selected Cell [selecetedCellBG setBackgroundColor:[UIColor clearColor]]; [cell setSelectedBackgroundView:selecetedCellBG ]; } 
3006440 0 Xcode File management. What is best practice?

I've been using Xcode for a while now. One thing that always bugs me is the way it handles files. I like to have my files all in nested folders rather than one big physical folder, but when you create a group in Xcode by default it does not create a folder just a virtual folder within the project.

I can see that virtual folders are great for linking code in arbitrary places into your project but once you get beyond a few classes I find the one big folder approach really painful. And then if you try to fix it later it takes ages and is easy to break your build.

Is it possible to change this behaviour so that by default it creates a physical folder? Or am I doing it wrong and trying to cling to some other way of working? How do other people work with files in Xcode?

38052724 0

format is a method of str so you should call that from your string, then pass the result of that into print.

print ("So you are {name} and you are{age}".format(name=my_name,age=my_age)) 
3983809 0

If your goal is to make a game per se with the requirements of developing on OSX and running anywhere it's sounding a lot like Unity3D would be a good match. On this path you'll end up coding in UnityScript and or C# probably. It gives you a lot of tools in a package and it's popular in games development circles. So it sounds like a good match for you too me.

If you just want to learn, you can use whatever language you like. Something fairly popular if you want readily tranferrable skills. I wouldn't worry too much about performance if you're just learning concepts. Languages are a dime a dozen and most will teach you a strong basis to build on.

If you want to become a professional games developer for a big name studio working on consoles you might want to consider learning some C or C++ - particularly to understand memory management, pointers and some other low level concepts.

14044514 0 Can't get data from a codeigniter function with ajax

This is what I've got so far:

This function that returns data from the model:

function get_user2() { $this->load->model('my_model'); $id=$this->input->post('users1'); $users2=$this->my_model->get_relations($id); return $users2; } 

the model function:

function get_relations($usr) { $this->db->where('id',$usr); $rel=$this->db->get('relacion'); if($rel->num_rows!=0) { $relacion=array(); foreach ($rel->result_array() as $row) { $relacion[]=array( 'id'=>$row['id'], 'username1'=>$row['username1'], 'username2'=>$row['username2'], ); } return $relacion; }else{ return false; } } 

and in my view:

<select name="users1" id="drop1"> <?php if($opciones!=false){ foreach ($opciones as $row) { echo '<option value="'.$row['user_id'].'">'.$row['username'].'</option>'; } } ?> </select> <script src="jquery.js"></script> <script type="text/javascript"> $("#drop1").change(function(){ $.ajax({ type: "POST", url: "example.com/CI/index.php/evaluation/get_user2", data: "users1="+$('#drop1').val(), success: function(){ alert('it works!'); } }); }); </script> 

I want to fill a second dropdown with the options returned by the controller function, but the ajax request doesn't do anything so I haven't even got to that part. Can someone help me spot what's wrong? I already tested the controller and model's function and they work. And could you tell me how to fill the second dropdown's options? Thank you very much!

18947308 0 Horizontal manager alignment of its child view?

How can I align a child view in the horizontal LinearLayout? I have two textviews (width height is wrap_content) in the horizontal manager. How I can align one to right and the other one to the left?

3072316 0 how do i receive messages sent to gtalk?

im making an application that needs to get received messages that were sent to google chat. is there an api for working with google chat?

can someone please give me an example in C# how do i receive gtalk messages? im sorry the xmpp documentation is too complex and i do not understand where to start

32187702 0 How to call Pinch and Zoom class on am ImageView?

I am a newbie to android development. Here I am trying to add pinch and zoom an image in my image view. The image is loaded on an activity called FullScreenView

Here is my FullScreenView.java file

public class FullScreenViewActivity extends Activity implements OnClickListener { private static final String TAG = FullScreenViewActivity.class .getSimpleName(); public static final String TAG_SEL_IMAGE = "selectedImage"; private Wallpaper selectedPhoto; private ImageView fullImageView; private LinearLayout llSetWallpaper, llDownloadWallpaper,btShare; private Utils utils; private ProgressBar pbLoader; InterstitialAd mInterstitialAd; // Picasa JSON response node keys private static final String TAG_ENTRY = "entry", TAG_MEDIA_GROUP = "media$group", TAG_MEDIA_CONTENT = "media$content", TAG_IMG_URL = "url", TAG_IMG_WIDTH = "width", TAG_IMG_HEIGHT = "height"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fullscreen_image); //add code AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); mInterstitialAd = new InterstitialAd(this); mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712"); requestNewInterstitial(); fullImageView = (ImageView) findViewById(R.id.imgFullscreen); llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper); llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper); btShare = (LinearLayout) findViewById(R.id.btShare); pbLoader = (ProgressBar) findViewById(R.id.pbLoader); // hide the action bar in fullscreen mode getActionBar().hide(); utils = new Utils(getApplicationContext()); // layout click listeners llSetWallpaper.setOnClickListener(this); llDownloadWallpaper.setOnClickListener(this); btShare.setOnClickListener(this); // setting layout buttons alpha/opacity llSetWallpaper.getBackground().setAlpha(70); llDownloadWallpaper.getBackground().setAlpha(70); btShare.getBackground().setAlpha(70); Intent i = getIntent(); selectedPhoto = (Wallpaper) i.getSerializableExtra(TAG_SEL_IMAGE); // check for selected photo null if (selectedPhoto != null) { // fetch photo full resolution image by making another json request fetchFullResolutionImage(); } else { Toast.makeText(getApplicationContext(), getString(R.string.msg_unknown_error), Toast.LENGTH_SHORT) .show(); } } private void requestNewInterstitial() { AdRequest adRequest = new AdRequest.Builder() .addTestDevice("PFSW5H65PRTS9TTO") .build(); mInterstitialAd.loadAd(adRequest); } /** * Fetching image fullresolution json * */ private void fetchFullResolutionImage() { String url = selectedPhoto.getPhotoJson(); // show loader before making request pbLoader.setVisibility(View.VISIBLE); llSetWallpaper.setVisibility(View.GONE); llDownloadWallpaper.setVisibility(View.GONE); btShare.setVisibility(View.GONE); // volley's json obj request JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, "Image full resolution json: " + response.toString()); try { // Parsing the json response JSONObject entry = response .getJSONObject(TAG_ENTRY); JSONArray mediacontentArry = entry.getJSONObject( TAG_MEDIA_GROUP).getJSONArray( TAG_MEDIA_CONTENT); JSONObject mediaObj = (JSONObject) mediacontentArry .get(0); final String fullResolutionUrl = mediaObj .getString(TAG_IMG_URL); // image full resolution widht and height final int width = mediaObj.getInt(TAG_IMG_WIDTH); final int height = mediaObj.getInt(TAG_IMG_HEIGHT); Log.d(TAG, "Full resolution image. url: " + fullResolutionUrl + ", w: " + width + ", h: " + height); ImageLoader imageLoader = AppController .getInstance().getImageLoader(); // We download image into ImageView instead of // NetworkImageView to have callback methods // Currently NetworkImageView doesn't have callback // methods imageLoader.get(fullResolutionUrl, new ImageListener() { @Override public void onErrorResponse( VolleyError arg0) { Toast.makeText( getApplicationContext(), getString(R.string.msg_wall_fetch_error), Toast.LENGTH_LONG).show(); } @Override public void onResponse( ImageContainer response, boolean arg1) { if (response.getBitmap() != null) { // load bitmap into imageview fullImageView .setImageBitmap(response .getBitmap()); adjustImageAspect(width, height); // hide loader and show set & // download buttons pbLoader.setVisibility(View.GONE); llSetWallpaper .setVisibility(View.VISIBLE); llDownloadWallpaper .setVisibility(View.VISIBLE); btShare .setVisibility(View.VISIBLE); } } }); } catch (JSONException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), getString(R.string.msg_unknown_error), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); // unable to fetch wallpapers // either google username is wrong or // devices doesn't have internet connection Toast.makeText(getApplicationContext(), getString(R.string.msg_wall_fetch_error), Toast.LENGTH_LONG).show(); } }); // Remove the url from cache AppController.getInstance().getRequestQueue().getCache().remove(url); // Disable the cache for this url, so that it always fetches updated // json jsonObjReq.setShouldCache(false); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq); } /** * Adjusting the image aspect ration to scroll horizontally, Image height * will be screen height, width will be calculated respected to height * */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void adjustImageAspect(int bWidth, int bHeight) { LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT , LayoutParams.FILL_PARENT); if (bWidth == 0 || bHeight == 0) return; int sHeight = 0; if (android.os.Build.VERSION.SDK_INT >= 13) { Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); display.getSize(size); sHeight = size.y; } else { Display display = getWindowManager().getDefaultDisplay(); sHeight = display.getHeight(); } int new_width = (int) Math.floor((double) bWidth * (double) sHeight / (double) bHeight); params.width = new_width; params.height = sHeight; Log.d(TAG, "Fullscreen image new dimensions: w = " + new_width + ", h = " + sHeight); //fullImageView.setLayoutParams(params); // fullImageView.setAdjustViewBounds(true); fullImageView.setScaleType(ImageView.ScaleType.FIT_CENTER); } /** * View click listener * */ @Override public void onClick(View v) { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); } //else //{ // beginPlayingGame(); // } Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable()) .getBitmap(); File cache = getApplicationContext().getExternalCacheDir(); File sharefile = new File(cache, "toshare.png"); try { FileOutputStream out = new FileOutputStream(sharefile); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); } catch (IOException e) { } switch (v.getId()) { // button Download Wallpaper tapped case R.id.llDownloadWallpaper: utils.saveImageToSDCard(bitmap); break; // button Set As Wallpaper tapped case R.id.llSetWallpaper: utils.setAsWallpaper(bitmap); break; case R.id.btShare: Intent share = new Intent(android.content.Intent.ACTION_SEND); share.setType("image/*"); share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile)); try { startActivity(Intent.createChooser(share, "Share photo")); } catch (Exception e) { } break; default: break; } } } 

I also create the class for bringing pinch and zoom facility to this.

ZoomableImageView.java

public class ZoomableImageView extends View { //Code goes here } 

How to call this ZoomableImageView java class file to FullScreenViewActivity so that,when i pinch and zoom, it get works...

28844383 0 Deploy Node.js app to AWS elastic beanstalk that contains static assets

I'm having some trouble visualizing how I should handle static assets with my EB Node.js app. It only deploys whats committed in the git repo when you do eb deploy (correct?) but I don't want to commit all our static files. Currently we are uploading to S3 and the app references those (the.s3.url.com/ourbucket/built.js), but now that we are setting up dev, staging, and prod envs we can reference built.js since there can be up to 3 versions of it.

Also, there's a timespan where the files are uploaded and the app is rolling out and the static assets don't work with the two versions up on the servers (i.e. built.js works with app version 0.0.2 but server one is deploy 0.0.1 and server two is running version 0.0.2)

How do keep track of these mismatches or is there a way to just deploy a static assets to the EB instance directly.

37262091 0 Analog timepicker inside scrollView not displaying time chooser

So, in portrait mode is displayed correctly, no matter if timePicker is in scrollView or not.

enter image description here

Landscape mode when is inside scroolView.

enter image description here

Landscape mode when there is no scroolView.

enter image description here

[Edit] Code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.aapps.groupalarmclock.NewAlarmActivity"> <ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:src="@drawable/background" android:alpha="@dimen/background_transparency" android:layout_centerHorizontal="true" /> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="@dimen/toolbar_height" android:layout_alignParentTop="true" android:weightSum="2" android:background="@color/colorToolbar" android:gravity="center_vertical" android:id="@+id/linearLayout"> <RelativeLayout android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/rl_cancle" android:layout_weight="1" android:background="@drawable/click_effect" android:gravity="center"> <ImageView android:layout_width="@dimen/toolbar_icon_size" android:layout_height="@dimen/toolbar_icon_size" android:id="@+id/iv_cancel" android:src="@drawable/cancel" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:layout_marginRight="@dimen/cancel_done_right_margin" android:layout_marginEnd="@dimen/cancel_done_right_margin"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@color/colorText" android:id="@+id/tv_cancel" android:layout_centerVertical="true" android:layout_toRightOf="@+id/iv_cancel" android:layout_toEndOf="@+id/iv_cancel" /> </RelativeLayout> <View android:layout_width="1dp" android:layout_height="@dimen/separator_height" android:background="@color/colorLineSeparator" android:id="@+id/v_cancel_done"> </View> <RelativeLayout android:layout_width="0dp" android:layout_height="match_parent" android:id="@+id/rl_done" android:layout_weight="1" android:background="@drawable/click_effect" android:gravity="center"> <ImageView android:layout_width="@dimen/toolbar_icon_size" android:layout_height="@dimen/toolbar_icon_size" android:id="@+id/iv_done" android:src="@drawable/done" android:layout_centerVertical="true" android:layout_centerHorizontal="true" android:layout_marginRight="@dimen/cancel_done_right_margin" android:layout_marginEnd="@dimen/cancel_done_right_margin"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@color/colorText" android:id="@+id/tv_done" android:layout_centerVertical="true" android:layout_toRightOf="@+id/iv_done" android:layout_toEndOf="@+id/iv_done" /> </RelativeLayout> </LinearLayout> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/scrollView" android:layout_below="@+id/linearLayout" android:layout_centerHorizontal="true" android:fillViewport="true"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/lltp"> <TimePicker tools:targetApi="23" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/timePicker" android:timePickerMode="clock" android:background="#80FFFFFF"/> </RelativeLayout> </ScrollView> 

Anyone know what is wrong?

1274738 0

You could use Traversing/contains also:

$('ul#accordion a').contains(bctext); 
37067215 0

Finally I managed to access it from my computer. I had to modify the configuration file for the operation center, located in /etc/opscenter/opscenterd.conf (only for package installation):

[webserver] port = 8888 interface = 127.0.0.1 

By default the webserver accepts requests only from the localhost. Probably it won't be the best option, but since the operation center allows to configure users, I set interface = 0.0.0.0, allowing any host to contact it.

12780917 0

Your echos are failing;

echo(<p>test1</p>); should be echo('<p>test1</p>');

and echo(<h1>fail</h1>); should be echo('<h1>fail</h1>');

FYI: echo doesn't require brackets, you could do echo '<h1>fail</h1>';

13769307 0

product_size alone will not be a PK and so I cannot reference it

Imagine you have two rows in product_stock table that have the same product_size (and different product_code). Now imagine one of these rows (but not the other) is deleted.

(Similar problems exist for ON DELETE CASCADE / SET NULL and also when UPDATE-ing the PK.)

To avoid these kinds of ambiguities, the DBMS won't let you create a foreign key unless you can uniquely identify parent row, meaning you must use the whole key after the REFERENCES clause of your FK.


That being said, you could create both...

FOREIGN KEY (product_code) REFERENCES product (product_code) 

...and...

FOREIGN KEY (product_code, product_size) REFERENCES product_stock (product_code, product_size) 

Although, if you have the latter, the former is probably redundant.

In fact, (since you already have the FK product_stock -> product), having both FKs would create a "diamond shaped" dependency. BTW, some DMBSes have restrictions on diamond-shaped FKs (MS SQL Server doesn't support cascading referential actions on them).

36168438 0

I just realized that if in eclipse i check "use system default php.ini" under window->preferences->php->phpexecutables it will magically work.

Does anyone know what is "system default php.ini"?

I do a a quick $php --ini and it returns:

Configuration File (php.ini) Path: /etc/php5/cli Loaded Configuration File: /etc/php5/cli/php.ini Scan for additional .ini files in: /etc/php5/cli/conf.d Additional .ini files parsed: /etc/php5/cli/conf.d/05-opcache.ini, /etc/php5/cli/conf.d/10-mysqlnd.ini, /etc/php5/cli/conf.d/10-pdo.ini, /etc/php5/cli/conf.d/20-json.ini, /etc/php5/cli/conf.d/20-mysql.ini, /etc/php5/cli/conf.d/20-mysqli.ini, /etc/php5/cli/conf.d/20-pdo_mysql.ini, /etc/php5/cli/conf.d/20-readline.ini 
4078397 0

I found Scintilla to be very feature-packed, and covered everything I needed. You have to do a bit of work to get all the functionality out of it (ensuring that keyboard short-cuts perform the desired effect, etceteras), but it was incredibly easy to compile, include and get working, though as I said you have to do a bit of legwork to get everything out of it, but this is better than having to tear your hair out getting an "all-purpose" control to stop doing something you don't want to. It is as if the authors have given you a toolbox to work with.

40079467 0

First of all, to check if the number is even just check the modulus by 2, no need to check if the last digit is 2 or 4 or 6 or 8. I would substitute all your checks with next1%2==0, next1%5==0 and next1%10==0, also you need to change every cout<<next2 to cout<<next1 because next2 is modulus of 10 of next1. Also as a good practice I suggest you to read Straustrup C++ book to get the basics of C++.

8294873 0 What is the right way to add invisible text for a resizeable logo

I want to do 2 things:

  1. Know that I am SEO friendly and that I inserted correctly the text (so search engines would know that this is "my logo"
  2. Learn how to resize the logo in case the screen is lower than a specific width (assuming that I know how to work with media-queries)

    <div id="myLogo"> <a href="#"> <img src="css/img/my_logo.png" alt="My Logo"> </a> </div><!--End of #myLogo--> 

What should I do to achieve them both? What should be my CSS and did I wrote the code correctly?

26297202 0

I had the same problem. The only workaround I found was to reduce the number of new Image() to use (ideally one):

function ImageLoader() { var img = new Image(); var queue = []; var lock = false; var lastURL; var lastLoadOk; return { load: load }; function load(url, callback, errorCallback) { if (lock) return queue.push(arguments); lock = true; if (lastURL === url) return lastLoadOk ? onload() : onerror(); lastURL = url; img.onload = onload; img.onerror = onerror; img.src = url; function onload() { lastLoadOk = true; callback(img); oncomplete(); } function onerror() { lastLoadOk = false; if (errorCallback) errorCallback(url); oncomplete(); } } function oncomplete() { lock = false; if (queue.length) load.apply(null, queue.shift()); } } var loader = new ImageLoader(); loader.load(url1, function(img) { // do something }); loader.load(url2, function(img) { // do something }); 

Note that images will be loaded in serie. If if want to load 2 images in parallel, you'll need to instantiate 2 ImageLoader.

40266753 0 Multiple operations in ternary operator

Is it possible to have multiple operations within a ternary operator's if/else?

I've come up with an example below, probably not the best example but I hope you get what I mean.

var totalCount = 0; var oddCount = 0; var evenCount = 0; for(var i = 0; i < arr.length; i++) { if(arr[i] % 2 === 0) { evenCount ++; totalCount ++; } else { oddCount ++; totalCount ++; } } 

into something like:

var totalCount = 0; var oddCount = 0; var evenCount = 0; for(var i = 0; i < arr.length; i++) { arr[i] % 2 === 0? evenCount ++ totalCount ++ : oddCount ++ totalCount ++; } } 
27196026 0
 ALTER TABLE table_name ADD COLUMN column_name datatype 

correct syntax

ALTER TABLE `WeatherCenter` ADD COLUMN BarometricPressure SMALLINT NOT NULL, ADD COLUMN CloudType VARCHAR(70) NOT NULL, ADD COLUMN WhenLikelyToRain VARCHAR(30) NOT NULL; 

check syntax

24260321 0 Work with version control Offline \ Online

How can I change the status from version control work offline to working online using the API?

Can I do it to all of the model or to a particular package?

17908090 0 How to Validate Column with Same Value?

How to validate the column with same value, i try with this code :

protected void ASPxGridView1_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e) { XPQuery<Inventory_Library.Inventory.t_barang_master> q = new XPQuery<Inventory_Library.Inventory.t_barang_master>(ses); List<Inventory_Library.Inventory.t_barang_master> lst = (from o in q where (o.nama_barang == e.OldValues["nama_barang"] && o.kode_barang == e.OldValues["kode_barang"]) select o).ToList<Inventory_Library.Inventory.t_barang_master>(); if (lst.Contains(e.OldValues["nama_barang"])) { e.RowError = "Nama barang yang anda masukkan telah terdaftar dalam sistem"; } else if (lst.Contains(e.OldValues["kode_barang"])) { e.RowError = "Kode barang yang anda masukkan telah terdaftar dalam sistem"; } } 

but that's not work, how to solve this problem, thanks for the answer

34032027 0

I would recommend that you look into breaking this down into parts. For example, do you have the login working on the web portion (rails)? If so then you can begin to try to get it to work on the iOS side. Next I would recommend you look into POST and GET requests as a basic way of talking to a back end. Once you have gotten simple apps to work with that then you might have a better idea of the path that lies ahead.

19697644 0 Successful implementation of user online or not

I have a Java EE 7 application with Spring MVC, which is a web service for mobile application as a final school project. I attribute a Calendar for the last request received and Boolean "Online" for each user. So here's my problem implementer how well a system will change the attribute of the user in my DB if the web service no longer get from the user's request after X minutes?

I need to make a class that implements Runnable and make an infinite loop on my DB looking the Online User and compares how long that has made a request?

If the answer is yes how to do a method that is still running?

Sorry for my english I'm not English.

23498294 0 Linq to Entities SQL Multiple LIKE statements

I have to search an Entity by some values, the ones empty I don't have to consider them but the others I have to use a LIKE statement using Linq to Entities.

The result I want to obtain should be similar to this SQL,

... WHERE (@taxid = '' OR m.taxid LIKE @taxid + '%') AND (@personalid = '' OR m.personalid LIKE @personalid + '%') AND (@certificate = '' OR m.certificate LIKE @certificate + '%') 

My Linq to Entities looks like:

persons = context.Persons.Where(e => e.TaxId.Contains(taxId) && e.PersonalId.Contains(personalId) && e.Certificate.Contains(certificate)).ToList(); 

Any clue?

679088 0

I would go with "from" + confirmation, to avoid forging.

I.e. receive the email, but send a response with auth token in the subject line (or in the body) back to the "from" address. The user either will need reply, or click a link to confirm the submission.

And you post the content only after confirmation.

1688307 0

Start the MonoDevelop program and select "New Solution" and then select the iPhone template.

There are a handful of walk through documents like: http://monotouch.net/Tutorials/MonoDevelop_HelloWorld

Or a complete step-by-step screencast here:

http://www.codesnack.com/blog/2009/9/20/getting-started-with-monotouch.html

Building Hello world: http://tv.falafel.com/iphone/09-09-18/Writing_your_First_IPhone_application_in_C_using_MonoTouch.aspx

4802728 0

Have you looked at ObjectDataSource? You configure it by providing the the names of your C# methods responsible for the CRUD operations. Then in your methods you can do whatever you want.

16239106 0 Finding a row by position

I am getting an error at position 1996250 in my mysql replication. How can I find out what table/row is at that position?

34958453 0

Try to perform the action in a background-queue using the following code:

SwiftSpinner.show("Generating new calendar for \(forYear)", animated: true) dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { let calendar = generateCalendarFor(forYear) print("GENERATED NEW calendar for \(forYear)") dispatch_async(dispatch_get_main_queue(), { SwiftSpinner.show("Saving calendar", animated: false) }) saveNew(calendar, year: forYear) dispatch_async(dispatch_get_main_queue(), { SwiftSpinner.hide() onCompletion(calendar) }) }) 

What you do here:

You should make sure that your UI-buttons etc. are disabled before dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { ... }) gets called and enabled again in onCompletion else the user would be able to press some buttons while your app is working (and maybe change some data used by the queue -> not good).

Why: The UI is updated from the main-queue, but usually not immediately after you call the code to update it; if you block the main-queue, your UI cannot be updated. So we do the work in a background-queue so your main-queue can update the UI.

In detail: You call dispatch_async (from GrandCentralDispatch) which creates a new queue with the priority QOS_CLASS_USER_INITIATED (~normal priority). Then it passes the code in the curly braces to this queue; the OS will execute the queue in a separate thread. Because the UI must only be modified from the main-queue, we pass the code that updates the UI (SwiftSpinner.show("Saving calendar", animated: false)) to the main-queue by using dispatch_async again.

The use of a completion-function is necessary because the code/queue is executed in the background and independently from getOrCreateCalendar; your function probably returns before the queue is completed and the calendar created and saved.

25765221 0 What is the point of splitting up a project into 2 separate projects?

A lot of times I see people splitting up a Project into 2 separate projects, like in this screenshot:

enter image description here

What is the point of seperating Ingot and IngotAPI instead of putting them both in the same project because they get compiled together anyways?

15133470 0

You can have 6 unique games between 4 teams. There are 7 possible pairing hence 42 unique games.

Each player pairs up with every other player only once and play against each one of them 6 times exactly.

List:

Pairs 01: (1,2),(3,4),(5,6),(7,8) PairRound 1: GameRound 01: (1,2) - (3,4) | (5,6) - (7,8) GameRound 02: (1,2) - (7,8) | (3,4) - (5,6) GameRound 03: (1,2) - (5,6) | (3,4) - (7,8) Pairs 02: (1,3),(2,4),(5,7),(6,8) PairRound 2: GameRound 04: (1,3) - (2,4) | (5,7) - (6,8) GameRound 05: (1,3) - (6,8) | (2,4) - (5,7) GameRound 06: (1,3) - (5,7) | (2,4) - (6,8) Pairs 03: (1,4),(2,3),(5,8),(6,7) PairRound 3: GameRound 07: (1,4) - (2,3) | (6,7) - (5,8) GameRound 08: (1,4) - (5,8) | (2,3) - (6,7) GameRound 09: (1,4) - (6,7) | (2,3) - (5,8) Pairs 04: (1,5),(2,6),(3,7),(4,8) PairRound 4: GameRound 10: (1,5) - (2,6) | (3,7) - (4,8) GameRound 11: (1,5) - (4,8) | (2,6) - (3,7) GameRound 12: (1,5) - (3,7) | (2,6) - (4,8) Pairs 05: (1,6),(2,5),(3,8),(4,7) PairRound 5: GameRound 13: (1,6) - (2,5) | (3,8) - (4,7) GameRound 14: (1,6) - (4,7) | (2,5) - (3,8) GameRound 15: (1,6) - (3,8) | (2,5) - (4,7) Pairs 06: (1,7),(2,8),(3,5),(4,6) PairRound 6: GameRound 16: (1,7) - (2,8) | (3,5) - (4,6) GameRound 17: (1,7) - (4,6) | (2,8) - (3,5) GameRound 18: (1,7) - (3,5) | (2,8) - (4,6) Pairs 07: (1,8),(2,7),(3,6),(4,5) PairRound 8: GameRound 19: (1,8) - (2,7) | (3,6) - (4,5) GameRound 20: (1,8) - (4,5) | (2,7) - (3,6) GameRound 21: (1,8) - (3,6) | (2,7) - (4,5) 
26053837 0 ajax function not opening a page

i don't understand why ajax is not working. my code:

<script type="text/javascript" src="js/jquery-1.9.1.js"></script> <script type="text/javascript"> function edit_row(id) { $.ajax({ method:'get', url:'form.php', success:function(data) { $('#form_div').html(data); } }); } 
<?php echo '<td style='.$style.'>'.$status.'<a href="" title="Edit" onClick=edit_row('.$data['type_id'].')><img src="images/pencil.png" width="30px" height="30px"></a></td></tr>'; ?> 

its not opening form.php onclick what is the problem please help me!!!

35972058 0
class Letter { char c; boolean isRevealed; //... getters and setters } Letter[] word = new Letter[MAX_WORD_LENGTH]; private boolean isGuessRight(char chr){ for (int i = 0 ; i < word.length ; i++){ if (word[i].getChar() == chr && word[i].getRevealed() == false){ word[i].reveal(); return true; } else if (word[i] == chr && word[i].getRevealed()){ return false; } } } 
15119711 0

Let's say branches A and B, standing on A, file f was modified (and not checked into A), while B contains another version. If I try to rebase B onto A, the local changes for f are lost. Solution: Commit the changes to f, or stash them away for later, or perhaps discard them by git checkout f.

That is what the message says, in a nutshell.

If you "tried again until it worked", you probably lost changes like the above.

Morals of the story: If you want to do any more complex operation with git (like pulling from upstream, rebasing, changing last commit, ...) make sure everything is tidy. I.e., git status says it is clean, and hopefully no untracked files.

21507914 0 Bad credentials Exception | Spring Security

Trying to use Spring security for authentication process, but getting Bad credentials exception.here is how I have defined things in my spring-security.xml file

<beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> </beans:bean> <beans:bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"> </beans:bean> <authentication-manager id="customerAuthenticationManager"> <authentication-provider user-service-ref="customerDetailsService"> <password-encoder hash="sha" /> </authentication-provider> </authentication-manager> 

customerDetailsService is our own implementation being provided to spring security.In my Java code while registering user, I am encoding provided password before adding password to Database something like

import org.springframework.security.authentication.encoding.PasswordEncoder; @Autowired private PasswordEncoder passwordEncoder; customerModel.setPassword(passwordEncoder.encodePassword(customer.getPwd(), null)); 

When I tried to debug my application, it seems Spring is calling AbstractUserDetailsAuthenticationProvider authenticate method and when its performing additionalAuthenticationCheck with additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication); of DaoAuthenticationProvider, it throwing Bad credential exception at following point

if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); } 

I am not sure where I am doing wrong and what needs to be done here to put things in right place, I already checked customer is there in database and password is encoded.

12095153 0

Is there any way to check a user has like a facebook page without permission request?

Only if your app is running as a page tab app on that Facebook page.

If so, the info is contained inside the signed_request parameter.

30460279 0

following query works fine for delete the record based on current timestamp.

DELETE FROM table WHERE datecolumn = date('Y-m-d h:i A'); //'2012-05-05 10:00PM'

26311715 0 Solving a difficult compilation issue

Good day,

First up, I have a mac running Mavericks, and I am attempting to build PCL (Point Cloud Library) as part of ROS.

This is the command that fails:

cd /Users/X/ros_catkin_ws/build_isolated/pcl_ros && /Users/X/ros_catkin_ws/install_isolated/env.sh cmake -vd /Users/X/ros_catkin_ws/src/perception_pcl/pcl_ros -DCATKIN_DEVEL_PREFIX=/Users/X/ros_catkin_ws/devel_isolated/pcl_ros -DCMAKE_INSTALL_PREFIX=/Users/X/ros_catkin_ws/install_isolated -DCMAKE_BUILD_TYPE=Release 

With:

CMake Error at /usr/local/share/pcl-1.8/PCLConfig.cmake:47 (message): simulation is required but glew was not found Call Stack (most recent call first): /usr/local/share/pcl-1.8/PCLConfig.cmake:500 (pcl_report_not_found) /usr/local/share/pcl-1.8/PCLConfig.cmake:663 (find_external_library) CMakeLists.txt:8 (find_package) 

Now, I have done what I can to debug this. Looking up online, I notice this is happening due to the fact that in Mavericks, there is no longer the GLEW.framework https://github.com/PointCloudLibrary/pcl/issues/492

Hence, I installed it via brew, and yet I still get the same issue. Now, I'm thinking, perhaps cmake cannot find it, so I created my own cmake project, and attempted to add find_package(glew). It seems to have found the package here:

-- Found GLEW: /usr/local/include 

Hence, I included /usr/local/include in my $PATH variable. Yet once again, it seems to fail with the same error. I am kind of at a lost here, and am not sure how to continue. I am speculating that in the command above, it seems that somehow the env.sh there seems to change the environmental variables such that it can't find glew.

Any thoughts?

EDIT: More absurdity. I create a CMake file and included find_package(PCL). It works perfectly. WTF? It even says it found glew

Found Glew: -framework GLEW;-framework Cocoa 

How come it works in my Cmake file, but not in theirs? What might cause this

27850563 0 Call new parameters on a jQuery slider depending on window size

I am using bxslider.js to make a slider on my page. Since my site is responsive, the code I have allows different parameters for the slider depending on the size of the window. For example, when the window is over 768px the slider shows 2 slides. When it is under 768 it shows 1 slide and when it's under 480, the slider function stops completely. All this works fine. However it only works on load. I want it to work on resize too. I've played around the the window.resize function, but I don't have enough of a programing background to really know what I am doing or what the best way to do this is. Can anyone tell me how to get this to work both on load and on resize?

var sliderWidth = $('#testimonialSlider').width(); if ($(window).width() > 768) { doubleslider = $('#testimonialSlider').bxSlider({ minSlides: 2, maxSlides: 2, slideWidth: sliderWidth / 2, auto: false, moveSlides:2, autoHover:true, pager:true }); } else if ($(window).width() < 480) { singleslider.destroySlider(); } else{ singleslider = $('#testimonialSlider').bxSlider({ minSlides: 1, maxSlides: 1, slideWidth: sliderWidth, auto: false, moveSlides:1, autoHover:true, pager:true }); } 
6017914 0

There's no guarantee, but one thing you can do to protect yourself is hide the persistence implementation details behind a well-designed interface. It won't keep you from having to rewrite implementation if you switch, but it will isolate clients from the changes. You'll be able to test implementations separately and swap them in and out in a declarative fashion if you're using a dependency injection engine.

27599571 0 white space below footer

There seems to be random white space after the footer at the bottom of the site. When I try to use inspect element, the white space doesn't seem to fall under any tags. It doesn't seem tied to any footer tags either as removing them didn't change anything.

I'm using Ryan Fait's Sticky Footer solution for my footer.

You can test it at: http://www.edmhunters.com/martin-garrix/

Any ideas what I'm doing wrong?

27513335 0

use this method this vl definitely work 100%.

- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath; { GalleryCell *cell1 = (GalleryCell*)[_resumeCollectionView cellForItemAtIndexPath:indexPath]; cell1= nil; } 
14085705 0

The message is just a warning. You can ignore it. If you're using Xcode, it won't even show you the warning in its Issue Navigator.

Rename your Bison input file to have a .ym extension instead of a .y extension. That tells Xcode that it's a grammar with Objective-C actions.

31869496 0

The version will start after you send it the first request (unless you use Managed VM - https://cloud.google.com/appengine/docs/managed-vms).

29800656 0

The break keyword will always "break-out" of the current block of code. In this case, it is your inner for-loop.

I think you looking for the continue keyword.

36168997 0

This immmediate thing that jumps out at me: this is wrong:

if (section._isInViewport) { 

_isInViewport requires you to pass the element in as an argument, like so:

if (_isInViewport(section)) { 

You also don't need to check the event type in the event handler. Since you're only calling that on scroll, you already know the event type is a scroll event. Instead of thing:

if (event.type === 'scroll') { _getSections(); } 

You want this:

_getSections(); 
32915370 0

This is typically what I do when I want to convert many columns in a data.frame to a different data type:

convNames <- c("NY", "CHI", "LA", "ATL", "MIA") for(name in convNames) { city1[, name] <- as.numeric(as.character((city1[, name])) } 

It's a nice two lines and you just have to add the names of whatever columns you want to coerce to the convNames vector to add a new column to the coercing loop below.

EDIT: Do to a factor issue, do the lapply method above.

19539822 0 Exclude items of one list in another with different object data types, LINQ?

I have two lists filled with their own data. lets say there are two models Human and AnotherHuman. Each model contains different fields, however they have some common fields like LastName, FirstName, Birthday, PersonalID.

List<Human> humans = _unitOfWork.GetHumans(); List<AnotherHuman> anotherHumans = _unitofWork.GetAnotherHumans(); 

I would like to exclude the items from list anotherHumans where LastName, FirstName, Birthday are all equal to the corresponding fields of any item in list humans.

However if any item in anotherHumans list has PersonalID and item in list humans have the same PersonalID, then it is enough to compare Human with AnotherHuman only by this PersonalID, otherwise by LastName, FirstName and Birthday.

I tried to create new list of dublicates and exclude it from anotherHumans:

List<AnotherHuman> duplicates = new List<AnotherHuman>(); foreach(Human human in humans) { AnotherHuman newAnotherHuman = new AnotherHuman(); newAnotherHuman.LastName = human.LastName; newAnotherHuman.Name= human.Name; newAnotherHuman.Birthday= human.Birthday; duplicates.Add(human) } anotherHumans = anotherHumans.Except(duplicates).ToList(); 

But how can I compare PersonalID from both lists if it presents (it is nullable). Is there any way to get rid from creating new instance of AnotherHuman and list of duplicates and use LINQ only?

Thanks in advance!

12917807 0 Simple request using googleapis to freebase

I would like to query freebase, to get some basic information about a celebrity. For example, I would like to get the place of birth, and the gender of Madonna.

I achieved to get Madonna's friends by using:

https://www.googleapis.com/freebase/v1/mqlread?&query={"id":"/en/madonna","name":null,"type":"/base/popstra/celebrity","/base/popstra/celebrity/friendship":[{"participant":[]}]}

But, I'm understanding this request pretty badly. How can I change it to get the information I talked above ?

I was thinking about :

https://www.googleapis.com/freebase/v1/mqlread?&query={"id":"/en/madonna","name":null,"type":"/base/popstra/celebrity","/base/popstra/celebrity/gender":[{"gender":}], "/base/popstra/celebrity/place_of_birth":[{"place of birth":}]}

but it's not working ofc.

12107726 0

Either make the selector more specific:

ul li ul li:first-child{background-color:transparent} 

Or add a class to the UL And select the first child there:

ul.nested li:first-child{background-color: #fff;} ... <li>one <ul class="nested"> <li>two</li> ... 

http://jsfiddle.net/Kyle_Sevenoaks/fX9Gy/15/

1857815 0

You can't use REPLACE to create a comma delimited list for use in an IN clause. To use that as-is, you'd have to utilize MySQL's Prepared Statements (effectively dynamic SQL) - creating the comma separated list first, and inserting that into the SQL query constructed as a string before executing it.

SELECT a.category_id, a.yyyymm, a.cat_balance_ytd FROM GL_VIEW_CAT_BALANCES a JOIN GL_OPTIONS o ON INSTR(o.detail2, a.category_id) AND o.option_id = 'GLREPFUNCJOB01' JOIN (SELECT b.category_id, b.gl_unique_id, MAX(b.yyyymm) 'yyyymm' FROM GL_REPCAT_BALSs b WHERE b.yyyymm <= 200910 GROUP BY b.category_id, b.gl_unique_id) x ON x.category_id = a.category_id AND x.gl_unique_id = a.unique_id AND x.yyyymm = a.yyyymm WHERE a.gl_id = '/JOB//9' AND a.fin_years_ago = 0 

Here's an untested, possible non-dynamic SQL alternative, using FIND_IN_SET:

SELECT a.category_id, a.yyyymm, a.cat_balance_ytd FROM GL_VIEW_CAT_BALANCES a JOIN (SELECT REPLACE(o.detail_2, ' ', ', ') 'detail2_csv' FROM GL_OPTIONS o WHERE o.option_id = 'GLREPFUNCJOB01') y ON FIND_IN_SET(a.category, y.detail2_csv) > 0 JOIN (SELECT b.category_id, b.gl_unique_id, MAX(b.yyyymm) 'yyyymm' FROM GL_REPCAT_BALSs b WHERE b.yyyymm <= 200910 GROUP BY b.category_id, b.gl_unique_id) x ON x.category_id = a.category_id AND x.gl_unique_id = a.unique_id AND x.yyyymm = a.yyyymm WHERE a.gl_id = '/JOB//9' AND a.fin_years_ago = 0 
11582627 1 Python get micro time from certain date

I was browsing the Python guide and some search machines for a few hours now, but I can't really find an answer to my question.

I am writing a switch where only certain files are chosen to be in the a file_list (list[]) when they are modified after a given date.

In my loop I do the following code to get its micro time:

file_time = os.path.getmtime(path + file_name) 

This returns me a nice micro time, like this: 1342715246.0

Now I want to compare if that time is after a certain date-time I give up. So for testing purposes, I used 1790:01:01 00:00:00.

# Preset (outside the class/object) start_time = '1970-01-01 00:00:00' start_time = datetime.datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') start_time = start_time.strftime("%Y-%m-%d %H:%M:%S") # In my Method this check makes sure I only append files to the list # that are modified after the given date if file_time > self.start_time: file_list.append(file_name) 

Of course this does not work, haha :P. What I'm aiming for is to make a micro time format from a custom date. I can only find ClassMethods online that make micro time formats from the current date.

4317703 0

Seems it can't be done with the C preprocessor, at least the gcc docs states it bluntly:

There is no way to convert a macro argument into a character constant.

5326377 0

Using a bit of psychic debugging, I'm going to guess that the strings in your application are pooled in a read-only section.

It's possible that the CreateSysWindowsEx is attempting to write to the memory passed in for the window class or title. That would explain why the calls work when allocated on the heap (SysAllocString) but not when used as constants.

The easiest way to investigate this is to use a low level debugger like windbg - it should break into the debugger at the point where the access violation occurs which should help figure out the problem. Don't use Visual Studio, it has a nasty habit of being helpful and hiding first chance exceptions.

Another thing to try is to enable appverifier on your application - it's possible that it may show something.

3893509 0

My only current solution uses reflection to build the string or paths for the .Expand method.

foo_entitiesctx = new foo_entities(new Uri("http://url/FooService.svc/")); ctx.MergeOption = MergeOption.AppendOnly; var collections = from pi in typeof(TestResult).GetProperties() where IsSubclassOfRawGenericCollection(pi.PropertyType) select pi.Name; var things = ctx.Things.Expand(string.Join(",", collections)); foreach (var item in things) { foreach (var child in item.ChildCollectionProperty1) { //do thing } } 

(The IsSubclassOfRawGenericCollection method is a wrapper around the IsSubclassOfRawGeneric method from Jared Par on SO)

28172523 0

something like this? http://jsfiddle.net/93zb8Lzs/6/

<img src="https://www.google.at/images/srpr/logo11w.png" width="368" height="138" alt="Logo" /> <!-- Nvigationselemente --> <div class="nav"> </div> img { display:block; margin:auto; } 
29633777 0 Syntax Error OledbException delete statement

I can't fugure out what my syntax error is here. Anyone spot it? Or am I going about this all wrong?

Dim myCommand As New OleDb.OleDbCommand("delete * from Team where intPlayerNo='" & txtUniformNo.Text & "'_ strFirstName='" & txtFirstName.Text & "'_ strLastName='" & txtLastName.Text & "'_ strParentName='" & txtParent.Text & "'_ strAddress='" & txtAddress.Text & "'_ strCity='" & txtCity.Text & "'_ strState='" & txtState.Text & "'_ strZipCode='" & txtZip.Text & "'_ strPhone='" & txtPhone.Text & "'_ intAge='" & txtAge.Text & "'", myConnection) 
30484473 0

The error can occur only if there exists a document in the database with some _id, say ID1, and you are trying to insert a new document which has ID1 as its value for _id field.

This can be because of the following:

If the value of _id field is not critical for you, you can just remove that attribute from your objects read from CSV right in your JavaScript code using delete.

Otherwise, you have a conflict, and need to decide what you want to do with duplicate _id documents. If you are ok with overwriting, you can achieve that by having {upsert: 1} option, which will update the document with new values in case if there is one existing with the same _id.

28137764 0

You're passing self twice in the super call. The call to post is a standard method call, so self is always included automatically. It should be:

 super(ClassA, self).post(request, *args, **kwargs) 
2319872 0

Many folks, including Zend, tell programmers to use camel case, but personally I used underscores as word separators for variable names, array keys, class names and function names. Also, all lowercase, except for class names, where I will use capitals.

For example:

class News { private $title; private $summary; private $content; function get_title() { return $this->title; } } $news = new News; 
15356416 0 After I install Wampserver2, while opening phpmyadmin i got error Firefox can't establish a connection to the server at localhost

After I install Wampserver2,

  1. while opening phpmyadmin i got error "Unable to connect Firefox can't establish a connection to the server at localhost. The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer's network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web.
  2. Apache > Service > Test port 80 : Your port 80 is not actually used. also tried Apache > Service > install service : But Apache > Service > Start/resume service is still disabled.

    C:\WINDOWS\system32\drivers\etc\host file has the statement 127.0.0.1 localhost

29165859 0

getDefaultSharedPreferences(Context) in the type PreferenceManager is not applicable for the arguments (DBTools)

Because getDefaultSharedPreferences takes Context object as parameters instead of DBTools.this or any other class context.

To fix this issue create a private Context object as assign value in object inside DBTools class constructor in which you are passing context when creating object of DBTools class:

 private Context mContext; public DBTools(Context applicationContext){ super(applicationContext, "contactbook.db", null, 1); this.mContext=applicationContext; } 

Now, use mContext as parameter to getDefaultSharedPreferences method:

SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(mContext); 
14504560 0

What you are understanding is correct. Here is an example:

string* str_rptr = new string("hello"); string* str2_rptr = str_rptr; str2_rptr->replace(0,5,"goodbye"); std::cout << *str_rptr << std::endl; 

The output of this fragment would print "goodbye" rather than "hello". After the "perfect int" example you gave, this code:

y = 400; std::cout << x << std::endl; 

will print out "200". The important point is that copying a variable does not prevent changes to one from changing the other.

33725788 0 C# Ask user another input

I am creating a soundDex application and I need to ask the user for a second name after they have inputted the first one. I also want "error no input" if the user does not input a second name. How would I do this within my soundDex?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SoundDexFinal { class Program { static void Main(string[] args) { string input = null; bool good = false; Console.WriteLine("SoundDex is a phonetic algorithm which allows a user to encode words which sound the same into digits." + "The program allows the user essentially to enter two names and get an encoded value."); while (!good) // while the boolean is true { Console.WriteLine("Please enter a name -> "); // asks user for an input input = Console.ReadLine(); // Make sure the user entered something good = !string.IsNullOrEmpty(input); // if user enters a string which is null or empty if (!good) // if boolean is true Console.WriteLine("Error! No input."); // displays an error to the user } soundex soundex = new soundex(); // sets new instance variable and assigns from the method Console.WriteLine(soundex.GetSoundex(input)); // gets the method prior to whatever the user enters Console.ReadLine(); // reads the users input } class soundex { public string GetSoundex(string value) { value = value.ToUpper(); // capitalises the string StringBuilder soundex = new StringBuilder(); // Stringbuilder holds the soundex code or digits foreach (char ch in value) // gets the individual chars via a foreach which loops through the chars { if (char.IsLetter(ch)) AddChar(soundex, ch); // When a letter is found this will then add a char } // soundex in (parameter) is for adding the soundex code or digits return soundex.ToString(); //return the value which is then converted into a .String() } private void AddChar(StringBuilder soundex, char character) //encodes letter as soundex char and this then gets appended to the code { string code = GetSoundexValue(character); if (soundex.Length == 0 || code != soundex[soundex.Length - 1].ToString()) soundex.Append(code); } private string GetSoundexValue(char ch) { string chString = ch.ToString(); if ("BFPV".Contains(chString)) // converts this string into a value returned as '1' return "1"; else if ("CGJKQSXZ".Contains(chString)) // converts this string into a value returned as '2' return "2"; else if ("DT".Contains(chString)) // converts this string into a value returned as '3' return "3"; else if ("L".Contains(chString)) // converts this string into a value returned as '4' return "4"; else if ("MN".Contains(chString)) // converts this string into a value returned as '5' return "5"; else if ("R".Contains(chString)) // converts this string into a value returned as '6' return "6"; else return ""; // if it can't do any of these conversions then return nothing } } } } 
1724872 0

The problem was related to the version of the NVelocity assembly I was using.

16746227 0 Generate a random number from another number

In JavaScript, is it possible to generate a random number from another number?

I'm trying to implement a predictable random number generator for one of my fractal terrain generators. I already know that it's possible to generate a random number using Math.random(), but I want to create a random number generator that produces exactly one output for every input. (For example, predictableRandomGenerator(1) would always produce the same result, which would not necessarily be the same as the input.)

So is it possible to generate a random number from another number, where the output is always the same for each input?

32773409 0

Here's a quick function:

myfun <- function(df){ z <- colSums(df) matrix(rowSums(expand.grid(z, z)), ncol = ncol(df)) } 

It first takes the colSums as z. Then we use expand.grid to take all combinations of z to z and takes the rowSums. The output is coerced to a matrix with the correct number of columns.

myfun(df) [,1] [,2] [,3] [,4] [1,] 16 17 19 13 [2,] 17 18 20 14 [3,] 19 20 22 16 [4,] 13 14 16 10 
3791466 0 How do I know if the user clicks the "back" button?

I'm using anchors for dealing with unique urls for an ajaxy website. However, I want to reload the content when the user hits the Browser's "back" button so the contents always matches the url.

How can I achieve this? Is there a jQuery event triggering when user clicks "Back"?

5737426 0

RabbitMQ should fit your bill. The server is free and ready to use. You just need a client side to connect, push/send out message and get/pull notified message

Server: http://www.rabbitmq.com/download.html Do a google for client or implement yourself

Cheers

13673443 0

OpenCV is bar-none the defacto computer vision library. It is packed full of functions to make your life easier.

With respect to image stabilization, Stackoverflow has answered possible approaches to this. Most of the time, you want to extract robust local feature descriptors and use them to perform registration on consecutive image frames.

25982811 0 "No XLIFF language files were found." After updating to MAT 3.1

I have a Windows Store project that I've been developing for quite some time. The Multilingual App Toolkit has been amazing so far. Recently I updated to version 3.1. Unfortunately, this caused the build process to not process my .xlf files that I've been using for a year now.

Based on this entry I took a look at my project file. The resources were defined similarly to how the blog entry suggested they should be. Similar to this:

<ItemGroup> <XliffResource Include="MultilingualResources\MyProject.WinRT_ar.xlf" /> <XliffResource Include="MultilingualResources\MyProject.WinRT_bg-BG.xlf" /> <XliffResource Include="MultilingualResources\MyProject.WinRT_ca-ES.xlf" /> ... 

I tried many things, including adding <Generator> tags. None of it seemed to be working. How can I get the project to see my .xlfs?

9763404 0 SaaS Platform - Different database user for each user or one master account

I have a SaaS platform that I am working on; written in PHP and using a MySQL database (using the PHP PDO class).

The application is already functional and I have decided to use a separate database for each instance.

One of the reasons for using multiple databases is to ensure that client data is separated (and hopefully secure). This also allows us to easily transfer their instance into the on-premise version.

Security is always something that I worry about. I want to ensure this system is as secure as possible before it goes live.

Currently we are using a single MySQL username & password that has access to every database (on that specific MySQL Farm).

Theoretically if there was a security breach then the attacker might be able to access a different database (username & password is unset after the PDO/Database connection is made, but they might be able to run a query such as "use databaseB").

Is this something that I should be concerned about? For example a SaaS platform that simply uses database partitioning is already less secure as a simple SQL error could expose client data.

I've already started looking into using different database usernames & passwords, but it does add to the complexity of the SaaS platform, and keeping things simple is always a good idea.

Thanks!


I have decided to go with different usernames and password for each instance.

This is another layer of security and that cannot hurt.

7180829 0 Generate Multiples XML with PHP

I have a PHP script that is generating an XML file. He reads the contents of the subfolders in the folder X, and generates only one XML with all subfolders and their contents. I'm wanting the same script generates an XML for each subfolder to find it, would someone help me?

<?php $sortorder = $_REQUEST['sortorder']; $indir = '../galleries'; $files = opendir($indir); $outxml = <'xml version=\'1.0\' encoding=\'utf-8\'?>\n\n'; $outxml .= '<galleries>\n\n'; while ($file = readdir($files)) { if(is_dir($indir.'/'.$file)){ if ($file != '.' && $file != '..') { $tmp_outxml[] = $file; } } } if ($sortorder == 'date') { foreach ($tmp_outxml as $k => $v) { $modified = filemtime ($indir.'/'.$v); $moddate[$k] = $modified; } array_multisort ($moddate, $tmp_outxml); } else if ($sortorder == 'random') { shuffle ($tmp_outxml); } else { sort ($tmp_outxml); } foreach ($tmp_outxml as $v) { $outxml .= get_folder_xml($indir.'/'.$v,$v); } $outxml .= "</galleries>"; closedir($files); $fp = fopen('../xml/gallery.xml', 'w'); fwrite($fp, $outxml); fclose($fp); function get_folder_xml($imageDir,$title) { $extensions = array('.jpg', '.jpeg', '.JPG','.JPEG','.gif','.GIF','.swf','.SWF'); $output = ''; if($folder = opendir($imageDir)) { $filenames=array(); while (false !== ($file = readdir($folder))) { $dot = strrchr($file, '.'); if(in_array($dot, $extensions)) { array_push($filenames, $file); } } $spaceTitle = str_replace('_',' ',$title); $newPath = str_replace('../','',$imageDir); $output .= '<gallery>\n'; $output .= '<title>$spaceTitle</title>\n'; $output .= ' <images>\n'; foreach ($filenames as $source) { $imageName = str_replace('mainThumb_','',$source); $finalName = str_replace('_',' ',$imageName); $imageName = str_replace($extensions,'',$finalName); $output .= '\t <image src=\'$newPath/$source\' thumb=\'$newPath/thumbs/$source\'>$imageName</image>\n'; } $output .= ' </images>\n'; $output .= '</gallery>\n\n'; return $output; closedir($folder); } } ?> 

i think i need to modify on this line, but i dont know how...

$fp = fopen('../xml/gallery.xml', 'w'); fwrite($fp, $outxml); fclose($fp); 

ty for help!!

28100899 0 how do i fit unique curves on each unique plot in a for loop

I have written this code (see below) for my data frame kleaf.df to combine multiple plots of variable press_mV with each individual plot for unique ID

I need some help fitting curves to my plots. when i run this code i get the same fitted curve (the curve fitted for the first plot) on ALL the plots where i want each unique fitted curve on each unique plot.

thanks in advance for any help given

f <- function(t,a,b) {a * exp(b * t)} par(mfrow = c(5, 8), mar = c(1,1,1,1), srt = 0, oma = c(1,6,5,1)) for (i in unique(kleaf.df$ID)) { d <- subset(kleaf.df, kleaf.df$ID == i) plot(c(1:length(d$press_mV)),d$press_mV) #----tp:turning point. the last maximum value before the values start to decrease tp <- tail(which( d$press_mV == max(d$press_mV) ),1) #----set the end points(A,B) to fit the curve to A <- tp+5 B <- A+20 #----t = time, p = press_mV # n.b:shift by 5 accomadate for the time before attachment t <- A:B+5 p <- d$press_mV[A:B] fit <- nls(p ~ f(t,a,b), start = c(a=d$press_mV[A], b=-0.01)) #----draw a curve on plot using the above coefficents curve(f(x, a=co[1], b=co[2]), add = TRUE, col="green", lwd=2) } 
7542409 0 C# Linq Expressions - Use String functions for all EF4 class attributes

I have this EF class called COMPONENT

public partial class COMPONENT : INotifyPropertyChanging, INotifyPropertyChanged { private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty); private int _ID; private string _NAME; private string _BRAND; private string _IMAGE; private System.Nullable<double> _PRICE; private string _OBSERVATION; private int _COMPONENT_TYPE_ID; private string _USERNAME; private System.DateTime _CREATE_DATE; 

I want to treat all it's attributes like strings in the predicates of a generic query function using LinqKit PredicateBuilder.
The function is something like this:

 public static List<TEntity> getResults<TEntity>(IList<PredicateFilter> conditions) where TEntity: class { var predicate = PredicateBuilder.True<TEntity>(); foreach (var condition in conditions) { var lambda = createPredicateLambda<TEntity>(condition); predicate = predicate.And(lambda); } DataClassesDataContext db = new DataClassesDataContext(); var components = from com in db.GetTable<TEntity>().Where(predicate) select com; return components.AsExpandable().ToList(); } 

The class PredicateFilter look like this:

 public class PredicateFilter { public string attribute; public string logicOperator; public object value; } 

The problem became in the function createPredicateLambda(condition). This function returns a Expression>. In it's body calls another function called createLambdaExpression

 createLambdaExpression<TEntity>(string methodOperator, ParameterExpression param, MemberExpression attribute, ConstantExpression value) where TEntity : class 

This function, in certain conditions, try to generate a expression where the attribute contains the value (no matter the Type of both the parameter) I want to do something like this but i don't see the solution:

 return Expression.Lambda<Func<TEntity, bool>>(Expression.Contains(Expression.Convert(attribute,typeof(string)),value),param); 

Obviously this wont's compile (The Expression.Convert it's not implemented). However, if i use

 Expression.Lambda<Func<TEntity, bool>>(Expression.Equal(Expression.Convert(attribute,typeof(string)),value),param); 

i get an exception in runtime: "The binary operator Equal is not defined for the types 'System.Int32' and 'System.String'".

Like i said later, i want to compare different data types or use (in certain conditions) the method String.Contains in all the data types. I've tried without any luck... Anyone knows if this can be done?

Thanks in advance!

1389139 0

Compiling MSIL to Native Code Ngen.exe

SUMMARY:

The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and run. When using install-time code generation, the entire assembly that is being installed is converted into native code, taking into account what is known about other assemblies that are already installed.

Take look at - How to compile a .NET application to native code?

3021636 0 how can i execute large mysql queries fast

I have 4 mysql tables and have a single query with JOIN on multiple tables and I am requesting it via jquery ajax, but it takes much too long, from about 1-3 minutes while I want to execute them on average 2-5 seconds.

Is there any special way to execute the queries fast?

35044770 0

I ended up using some jquery in my change events.

'change .edit-status': function(event, template){ var status = event.target.value; if (status === "UnAssigned") { $(".edit-assigned-to").val(""); } return false; }, 'change .edit-assigned-to': function(event, template){ var assignedTo = event.target.value; if (!template.data.assignedTo && assignedTo !== "") { $(".edit-status").val("Not Started"); } if (assignedTo === "") { $(".edit-status").val("UnAssigned"); } return false; } 

I'm not sure if there are better approaches or pitfalls to this solution, but it seems to be meeting my needs.

10788749 0

The NSMutableSet class declares the programmatic interface to an object that manages a mutable set of objects. NSMutableSet provides support for the mathematical concept of a set.

NSMutableSet is “toll-free bridged” with its Core Foundation counterpart, CFMutableSetRef.

Resources:

24928132 0

Actually, I still don't know, why code works as described above. But I have found acceptable method to solve task other way.

Looks like "put a needle into egg, egg into duck, duck into rabbit": ScrollView must contain a ListView component which has a corresponding ListModel and a custom component should act as delegate. Only with ListModel I've got correct automatic scrolling and relative emplacement support.

ScrollView { id: id_scrollView anchors.fill: parent objectName: "ScrollView" frameVisible: true highlightOnFocus: true style: ScrollViewStyle { transientScrollBars: true handle: Item { implicitWidth: 14 implicitHeight: 26 Rectangle { color: "#424246" anchors.fill: parent anchors.topMargin: 6 anchors.leftMargin: 4 anchors.rightMargin: 4 anchors.bottomMargin: 6 } } scrollBarBackground: Item { implicitWidth: 14 implicitHeight: 26 } } ListView { id: id_listView objectName: "ListView" anchors.top: parent.top anchors.left: parent.left anchors.right: parent.right anchors.rightMargin: 11 flickableDirection: Flickable.VerticalFlick boundsBehavior: Flickable.StopAtBounds delegate: view_component model: id_listModel ListModel { id :id_listModel objectName: "ListModel" } //delegate: View_item2.Item Component { id: view_component View_item2 { objectName: name } } } 
30023758 0 Trailing space while using "headertemplate" in asp gridview

I have a gridview which is bounded as

<asp:GridView runat="server" ID="gvShipDetails" AutoGenerateColumns="false" OnRowDataBound="gvShipDetails_RowDataBound"> <Columns> <asp:TemplateField> <HeaderTemplate> Ship name <br /> <asp:TextBox class="search_textbox" runat="server" BorderStyle="None" Width="100%"> </asp:TextBox> </HeaderTemplate> <ItemTemplate> <%#Eval("VesselName")%> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 

The problem is the finally rendered html table td is rendered as

<td> sample vessel name </td> 

A lot of spaces inside td.How is this possible.
If I replace this bound code as

<asp:BoundField HeaderText="vessel name" DataField="vesselname" /> 

Then html is renderd as <td>sample vessel name<td>

Why is it so? I wanted to use headertemplate and i wanted to avoid these trailing spaces. How to do it

Any help will be appreciated

13211993 0 Estimating the variance of eigenvalues of sample covariance matrices in Matlab

I am trying to investigate the statistical variance of the eigenvalues of sample covariance matrices using Matlab. To clarify, each sample covariance matrix is constructed from a finite number of vector snapshots (afflicted with random white Gaussian noise). Then, over a large number of trials, a large number of such matrices are generated and eigendecomposed in order to estimate the theoretical statistics of the eigenvalues.

According to several sources (see, for example, [1, Eq.3] and [2, Eq.11]), the variance of each sample eigenvalue should be equal to that theoretical eigenvalue squared, divided by the number of vector snapshots used for each covariance matrix. However, the results I get from Matlab aren't even close.

Is this an issue with my code? With Matlab? (I've never had such trouble working on similar problems).

Here's a very simple example:

% Data vector length Lvec = 5; % Number of snapshots per sample covariance matrix N = 200; % Number of simulation trials Ntrials = 10000; % Noise variance sigma2 = 10; % Theoretical covariance matrix Rnn_th = sigma2*eye(Lvec); % Theoretical eigenvalues (should all be sigma2) lambda_th = sort(eig(Rnn_th),'descend'); lambda = zeros(Lvec,Ntrials); for trial = 1:Ntrials % Generate new (complex) white Gaussian noise data n = sqrt(sigma2/2)*(randn(Lvec,N) + 1j*randn(Lvec,N)); % Sample covariance matrix Rnn = n*n'/N; % Save sample eigenvalues lambda(:,trial) = sort(eig(Rnn),'descend'); end % Estimated eigenvalue covariance matrix b = lambda - lambda_th(:,ones(1,Ntrials)); Rbb = b*b'/Ntrials % Predicted (approximate) theoretical result Rbb_th_approx = diag(lambda_th.^2/N) 

References:

[1] Friedlander, B.; Weiss, A.J.; , "On the second-order statistics of the eigenvectors of sample covariance matrices," Signal Processing, IEEE Transactions on , vol.46, no.11, pp.3136-3139, Nov 1998 [2] Kaveh, M.; Barabell, A.; , "The statistical performance of the MUSIC and the minimum-norm algorithms in resolving plane waves in noise," Acoustics, Speech and Signal Processing, IEEE Transactions on , vol.34, no.2, pp. 331- 341, Apr 1986

3879203 0 Tab focus granting event

I need to capture tab focus granting event in Firefox browser. Is there any type of listener implement for this event?

24045360 0

Think about what the compiler would have to do to catch the problem you're demonstrating. It would have to look at all callers of test1 to see whether they're passing it a local. Perhaps easy enough, but what if you insert more and more intermediate functions?

int & test1(int & x) { return x; } int & test2(int & x) { return test1(x); } int & test3() { int x = 0; return test2(x); } int main(void){ int & r = test3(); return r; } 

The compiler would have to look not only at all callers of test1, but then also all callers of test2. It would also have to work through test2 (imagine that it's more complex than the example here) to see whether it's passing any of its own locals to test1. Extrapolate that to a truly complex piece of code--keeping track of that sort of thing would be prohibitively complex. The compiler can only do so much to protect us from ourselves.

29159691 0

There are 2 delegate methods of FBLoginView

-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView -(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView 

The first method would inform you whether the user is logged out and the second method would inform you whether the user is logged in and you can perform your action on the basis of that.

For getting the image of the Profile picture u can use users id or objectID from this delegate method which contains all the user information.

-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user { NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=normal",user.id]]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *profileImage = [UIImage imageWithData:data]; } 

where the profileImage would contain the user profile Image and you can use that image to show on your custom button.

29595534 0

First of all, your question is too-broad, and you haven't provided much info, but if you make vague questions, you'll get vague answers, so here we go.

I also developed an app with Laravel 5, and had a pagination with next / previous links. I used AJAX to make a call to the next page, and return the HTML into the current page.

$(document).on("click", ".pagination a", function(e) { e.preventDefault(); url = $(this).attr('href') + " #search_results-listing"; $("#search_results").load(url, function() { setGetParameter('page', '2'); }); }); 
22882485 0 Plot two conditions in one plot

i'm sorry to ask such a dumb question, but i can't find an answer ...

So i have this table called : "linearsep" :

 color x y 1 red 1 1 2 red 1 3 3 red 3 3 4 red 2 4 5 blue 4 1 6 blue 6 3 7 blue 2 -2 8 blue 6 -1 

each line corresponds to a points (1,1 ; 1,3 etc...) , I just want to plot the ''red'' points in red , and the "blue" points in blue.

I know this is pretty dumb : but i just can't find a way to get a vector with the first four line.

I thought it was something like that:

plot(linearsep$color~x, linearsep$color~y)

but obviously it doesn't work ... I've tested some stuff with ggplot:

ggplot(data=a, + aes(x=x, y=y, colour=color)) + geom_point() 

Which works, but seems like a 'hack' , how can i just get the vector i want ? Someone could please help me ... Again sorry for such a dumb question

18644597 0

I'm an FPDF noob myself but have you tried the AcceptPageBreak function?

Something like this (copied from fpdf website):

function AcceptPageBreak() { // Method accepting or not automatic page break if($this->col<2) { // Go to next column $this->SetCol($this->col+1); // Set ordinate to top $this->SetY($this->y0); // Keep on page return false; } else { // Go back to first column $this->SetCol(0); // Page break return true; } } 

As a reference, the fpdf tutorials are really helpful. I suspect this one in particular would help you for what you're doing.

34195319 0 "Warning:mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in?"And after searching I rectified my code as below

DisplayLandlord PHP: I couldn't get the output.The query is not fetching the result

 <?php include("dbconfig.php"); ?> <?php $query = "SELECT * FROM rmuruge4_landlord"; $result = mysqli_query(mysqli_connect(),$query); if ($result === false) {die(mysqli_error(mysqli_connect())); } echo "<div class='bs-example'>"; echo "<table class='table table-striped'>"; echo "<tr><th>LLID</th><th>LName</th><th>Phone</th><th>Address</th></td>"; while($row = mysqli_fetch_array($result)){ echo "<tr><td>" . $row['LLID'] . "</td><td >" . $row['LName'] . "</td><td >". $row['Phone'] . "</td><td >" . $row['Address'] . "</td></tr>"; } echo "</table>"; echo "</div>"; mysqli_close(mysqli_connect()); ?> dbconfig.php: Connection is successful 
25811244 0

These redirects follow your route configuration. The default route is {siteUrl}/{controller}/{action}, which is why when you give it the "Index" action and the "Home" controller, you get the URL you're seeing.

You need to specify a new route similar to this:

MapRoute("CustomRoute", "MyApp/{controller}/{action}"; 

You can then redirect to it like this:

RedirectToRoute("CustomRoute", new {Controller = "Home", Action = "Index" }); 

EDIT to clarify for the comments -

It is also possible to solve this using IIS to make MyApp an application. This is the right solution only if MyApp is the only value you ever want at the beginning of your route for this site. If, for example, you sometimes need MyApp/{controller}/{action} and other times you need OtherSubfolder/{controller}/{action}, you need to use the routes as I have outlined above (or use areas) instead of just updating IIS.

I am assuming you want the solution using MVC, so that is what is here, but you should also consider the IIS application if that's the right solution for you.

7946771 0 UIDocumentInteractionController or QLPreviewController can't zoom PDF on iOS5?

I use QLPreviewController to view PDF files in one of my apps. However, ever since iOS5, users can no longer pinch to zoom in/out of the PDF. This is terrible for iPhone users, as they can't read anything.

I have also tried using UIDocumentInteractionController but have had the same problem.

Anyone know what's going on with this?

29846864 0 Change the app-name sent by docker's syslog driver

I'm using Papertrail to collect my Docker container's logs. Do to that, I used the syslog driver when I created the container:

sudo docker run --name my_container --log-driver=syslog ... 

... and added the following line to my /etc/rsyslog.conf

*.* @logsXXX.papertrailapp.com:YYYY 

At the end, I get on Papertrail logs like this:

Apr 24 13:41:55 ip-10-1-1-86 docker/3b00635360e6: 10.0.0.5 - - [24/Apr/2015:11:41:57 +0000] "GET /healthcheck HTTP/1.1" 200 0 "-" "" "-" 

The problem is that the app-name (see syslog RFC) is docker/container_id

I would rather have the container name (or host). But I don't know how to do. I tried to set a specific hostname to my container like below, but it didn't work better:

sudo docker run --name my_container -h my_container --log-driver=syslog ... 
29411338 0 How to handle OVER_QUERY_LIMIT

I am using google maps to draw the path among various location which are stored in database.

fiddle

While passing 15 geopoints(anything more than 10) am getting status as OVER_QUERY_LIMIT.

I understand that we need to give some milliseconds of time gap when we pass more than 10 geopoints per seconds.

My question is HOW TO DO THAT..Where to add sleep() or setTimeout() or any other time delay code

I've tried all,maximum all possibilities provided at SO but failed.As because they are just saying give some time gap between request but how to do that?

Code Snippet:

 var markers = [ { "title": 'abc', "lat": '17.5061925', "lng": '78.5049901', "description": '1' }, { "title": 'abc', "lat": '17.50165', "lng": '78.5139204', "description": '2' }, . . . . . { "title": 'abc', "lat": '17.4166067', "lng": '78.4853992', "description": '15' } ]; var map; var mapOptions = { center: new google.maps.LatLng(markers[0].lat, markers[0].lng), zoom: 15 , mapTypeId: google.maps.MapTypeId.ROADMAP }; var path = new google.maps.MVCArray(); var service = new google.maps.DirectionsService(); var infoWindow = new google.maps.InfoWindow(); var map = new google.maps.Map(document.getElementById("map"), mapOptions); var poly = new google.maps.Polyline({ map: map, strokeColor: '#000000' }); var lat_lng = new Array(); for (var i = 0; i <= markers.length-1; i++) { var src = new google.maps.LatLng(markers[i].lat, markers[i].lng); var des = new google.maps.LatLng(markers[i+1].lat, markers[i+1].lng); poly.setPath(path); service.route({ origin: src, destination: des, travelMode: google.maps.DirectionsTravelMode.DRIVING }, function (result, status) { if (status == google.maps.DirectionsStatus.OK) { for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) { path.push(result.routes[0].overview_path[i]); } } else{ if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) { document.getElementById('status').innerHTML +="request failed:"+status+"<br>"; } } }); } }); 

RESULT MAP(OVER_QUERY_LIMIT):

OVER_QUERY_LIMIT

28928062 0 Hovercard not displaying in knockoutJS with-binding

I got this hover card and I want to display it inside a sub-menu. It works int the header, but somehow the hover effect does not kick in when inside the sub-menu "with:$root.chosenMenu"-bindings.

This is my code:

HTML:

<div> <span class="previewCard"> <label class="hovercardName" data-bind="text: displayName"></label> <span class="hovercardDetails"> <span data-bind="text: miniBio"></span>.<br/> <a data-bind="attr: { href: webpage, title: webpage }, text: webpage">My blog</a> </span> </span> <br/><br/> <div class="wysClear wysLeft buttonRow"> <a href="#pid1" data-bind="click: function(){$root.chosenMenu('a');return false;}">Panel A</a> <a href="#pid2" data-bind="click: function(){$root.chosenMenu('b');return false;}">Panel B</a> </div> </div> <hr/> <div data-bind="with: $root.chosenMenu"> <div id="pid1" data-bind="visible: $root.chosenMenu() === 'a'"> panel A: <br/><br/> <span class="previewCard"> <label class="hovercardName" data-bind="text: $root.displayName"></label> <span class="hovercardDetails"> <span data-bind="text: $root.miniBio"></span>.<br/> <a data-bind="attr: { href: $root.webpage, title: $root.webpage }, text: $root.webpage">My blog</a> </span> </span> </div> <div id="pid2" data-bind="visible: $root.chosenMenu() === 'b'"> panel B: <br/><br/> <span class="previewCard"> <label class="hovercardName" data-bind="text: $root.displayName"></label> <span class="hovercardDetails"> <span data-bind="text: $root.miniBio"></span>.<br/> <a data-bind="attr: { href: $root.webpage, title: $root.webpage }, text: $root.webpage">My blog</a> </span> </span> </div> </div> 

Javascript:

viewModel = function(){ var self = this; self.chosenMenu = ko.observable(); self.displayName = ko.observable("Asle G"); self.miniBio = ko.observable("Everywhere we go - there you are!"); self.webpage = ko.observable("http://blog.a-changing.com") }; ko.applyBindings( new viewModel() ); // hovercard $(".previewCard").hover(function() { $(this).find(".hovercardDetails").stop(true, true).fadeIn(); }, function() { $(this).find(".hovercardDetails").stop(true, true).fadeOut(); }); 

CSS:

.previewCard { position:relative; } .hovercardName { font-weight:bold; position:relative; z-index:100; /*greater than details, to still appear in card*/ } .hovercardDetails { background:#fff ; border:solid 1px #ddd; position:absolute ; width:300px; left:-10px; top:-10px; z-index:50; /*less than name*/ padding:2em 10px 10px; /*leave enough padding on top for the name*/ display:none; } 

Fiddle: http://jsfiddle.net/AsleG/jb6b61oh/

24731408 0

Filed an issue at jboss jira and the issue is fixed in upcoming release.

A work-around currently is to have the following in your jboss-web.xml:

<?xml version="1.0"?> <jboss-web> <session-config> <cookie-config> <path>/</path> </cookie-config> </session-config> </jboss-web> <xml> 
34895249 0

If you must use a loop, you can do something like

uint64_t text = 0; for (int i = 15; i >= 0; --i) { text <<= 4; text |= a[i] & 0x0f; // Masking in case a[i] have more than the lowest four bits set } 
27795202 0

It's not flushed at this moment, changes kept in memory for a while. If you need to force Grails to update DB exactly at this moment, add flush: true parameter:

person.save(flush: true) 
32102014 0

Yeah, You can use SHOW CREATE TABLE to display the CREATE VIEW statement that created a view.

Link for reference: Hive CREATE VIEW

16393853 0

You don't initialize array and s in the copy constructor.

6995738 0 ASP javascript radiobutton enable disable not included in postback ajax

Here is the problem. I have a radiobutton group (two radiobuttons).

These guys are initialy disabled. When the user clicks a checkbox, I dynamically enable radiobuttons in javascript by setting rbtn.disabled = false; and doing the same for it's parent (span element) so it correctly works in IE. The problem is that these dynamically enabled radiobuttons are not returned on postback (I see rbtn.Checked == false on serverside and request.form does not contain proper value).

Why is this happening? Is there another fix except for a workaround with hidden fields?

Expected answer decribes post-back policy, why/how decides which fields are included in postback and fix to this problem.

21883693 0

Try This:

 int maxNo = 4; //you can change this no and logic works till 9 comboboxes void clearPreceding(ComboBox cmbBox) { int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1)); for (int i = cmbBoxNo; i <= maxNo; i++) { ((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = ""; } } 

You can Subscribe to One EventHandler for all Combobox's SelectedIndexChanges Event as below:

 comboBox1.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; 

and the EventHandler is:

 private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e) { clearPreceding((ComboBox)sender); } 

Complete Code:

public partial class Form1 : Form { int maxNo = 4; public Form1() { InitializeComponent(); comboBox1.SelectedIndexChanged+=AllCombobox_SelectedIndexChanged; comboBox2.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox3.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; comboBox4.SelectedIndexChanged += AllCombobox_SelectedIndexChanged; } private void AllCombobox_SelectedIndexChanged(object sender, EventArgs e) { clearPreceding((ComboBox)sender); } void clearPreceding(ComboBox cmbBox) { int cmbBoxNo = Convert.ToInt32(cmbBox.Name.Substring(cmbBox.Name.Length - 1)); for (int i = cmbBoxNo; i <= maxNo; i++) { ((ComboBox)this.Controls.Find("comboBox" + i, true)[0]).Text = ""; } } } 
16844290 0 Excel Loading via c#

Try to Load an excel file using this code below gives me this error

The Microsoft Access database engine could not find the object 'Sheet Name'. Make sure the object exists and that you spell its name and the path name correctly. If 'Sheet Name' is not a local object, check your network connection or contact the server administrator.

i am sure the Sheet Name is correct.

Any suggestions?

if (strFile.Trim().EndsWith(".xlsx")) { strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile); } else if (strFile.Trim().EndsWith(".xls")) { strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile); } OleDbConnection SQLConn = new OleDbConnection(strConnectionString); SQLConn.Open(); OleDbDataAdapter SQLAdapter = new OleDbDataAdapter(); string sql = "SELECT * FROM [" + sheetName + "]"; OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn); SQLAdapter.SelectCommand = selectCMD; ///error in this line SQLAdapter.Fill(dtXLS); SQLConn.Close(); 
38319846 0

You can use the code like this. I done for you..

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View arg0, boolean hasFocus) { // TODO Auto-generated method stub if(hasFocus){ spinner.setVisibility(View.VISIBLE); } } }); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view,int position, long id) { editText.setText(spinner.getSelectedItem().toString()); //this is taking the first value of the spinner by default. } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } }); 

You can only use OnItemSelectedListener on spinner in android.Red more from Android Developers. Good luck..

17545781 0

As others have said, IE8 does not support the nth-child() selector in CSS.

You have the following options:

  1. Refactor your code to use an alternative method rather than nth-child(). Maybe just add a class to the relevant elements.

  2. Use a javascript polyfill such a IE9.js or Selectivizr, which back-ports the nth-child() selector (and others) to IE8.

  3. Use jQuery or a similar library that supports nth-child() to set the styles rather than doing it in CSS.

  4. Drop support for IE8.

Which of those options you decide to use will depend on what matters to you.

If you've got code that works in other browsers and you need it to work in IE8 with the least amount of additional work, then I would suggest trying out the Selectivizr library. Or IE9.js. But I'd suggest trying Selectivizr first, as IE9.js does a lot of other stuff to the browser that may or may not affect your site.

If you don't want to have to use a Javascript library for this but you still need IE8 support, then you'll need to take option 1, and refactor your code. That may or may not be a lot of work, depending how your code is structured and how much code there is. Bit of a shame to have to make a backward step when the CSS is there.

Option 4 sounds like the worst option, but might be more suitable than it sounds. If the nth-child styling is being used for something like zebra striping, it may not be the end of the world for IE8 users just to not get the stripes. If everything else in the site works okay, they may not even miss it. And if they do miss it, you can tell them to upgrade their browser.

12927929 0 Sorting the report in birt

I have created a column binding in a report(datetime column) using birt. The datetime value that the column binding fetches based on the value of another string type column. Now when I'm sorting the report based on the column binding, the result that I'm getting is initially sorted on the basis of the string column and then on the basis of the column binding.

I want the report to be sorted only on the basis of column binding (datetime) value.

26497171 0

Check if your version of Vim has support for client-server functionality: :echo has('clientserver')

If so, you can write an alias to tell Vim to change its cwd:

In your .bashrc:

alias fg="$VIM --remote-send ':cd $PWD<CR>'; fg" 

Where $VIM is vim or gvim or macvim.

You need the colon and the <CR> because you're sending Vim keystrokes rather than commands (<CR> is a special notation for "Enter")

I'm not sure whether --remote-send works when Vim is suspended - this approach might be better if you use something like screen or tmux to run vim and your shell at the same time.

Otherwise, it's a bit trickier.

There's a :shell command that is similar to suspending and resuming, but I'm assuming it forks a child process instead of returning you to Vim's parent process. If you're ok with that, there's a ShellCmdPost autocmd you can attach to to load information. You can use that in association with an alias that writes the $CWD to a file to load the required directory and change to it.

In your .bashrc:

alias fgv="echo $PWD > ~/.cwd; exit" 

In your .vimrc:

autocmd ShellCmdPost * call LoadCWD() function! LoadCWD() let lines = readfile('~/.cwd') if len(lines) > 0 let cwd = lines[0] execute 'cd' cwd endif endfunction 

Looking through the list of autocommands, I was not able to find any that detect when Vim has been suspended and has just been resumed. You could remap ctrl-z to first set a flag variable then do an unmapped ctrl-z. Then write a shell script like before that writes its $CWD to a specific file. Then you can set up an autocmd to watch that file for modification and in the handler, check the flag variable, and if it's set, reset it, read the file, and change to that directory. A bit complex, but it would work.

That would look like this. You'll have to load the file when you start Vim so that it can monitor it for changes. You may want to set hidden so that you can keep the buffer open but hide it.

In your .bashrc:

alias fg="echo $PWD > ~/.cwd; fg" 

In your .vimrc:

set hidden edit ~/.cwd enew nnoremap <C-Z> :let g:load_cwd = 1<CR><C-Z> autocmd FileChangedShell ~/.cwd call LoadCWD() function! LoadCWD() if g:load_cwd let g:load_cwd = 0 let lines = readfile('~/.cwd') if len(lines) > 0 let cwd = lines[0] execute 'cd' cwd endif endif endfunction 
34993478 0

This is probably late, but editing the permission levels on the site might be easier than removing users access, and your SC admins will still have access.

7231546 0 How to pass Arraylist of Objects to a Procedure using spring mybatis

I want to pass an Arraylist of Objects for e.g.

Arraylist <SomeObject> listOFSomeObject 

Where SomeObject is having two attributes key and value.

On DB side i have a table type of variable i.e.

create or replace type tableTypeVariable is table of SomeType; CREATE OR REPLACE TYPE SomeTypeAS OBJECT (key VARCHAR2(50),value VARCHAR2(50)) 

Now i want to map my each object of type SomeObject from a listOFSomeObject to the tableTypeVariable.

Can any body help me with that ?

30910328 0

The vector handles its memory outside of the structure, in the heap as mentioned in another answer. So resizing or reallocating the vector inside the structure won't change the structure's size at all, not even the vector containing that structure.

http://www.cplusplus.com/reference/vector/vector/

The vector handles its own memory dynamically ( in the heap ).

20334365 0

The problem with your code is that you’re only ever removing one character at a time, and so repeated sequences will be reduced to a single character, but that single character will stick around at the end. For example, your code goes from “xxx” to “xx” to “x”, but since there’s only a single “x” left that “x” is not removed from the string. Adapt your code to remove all of the consecutive repeated characters and your problem will be fixed.

18000537 0

You could use the function eval, but this is very dangerous !

This class might help you : http://www.phpclasses.org/browse/package/2695.html

533014 0 finder_sql for has_many relation

Given the following two (simplified) models:

class Customer < ActiveRecord::Base # finder sql to include global users in the association has_many :users, :dependent => :destroy, :finder_sql => 'SELECT `u`.* FROM `users` `u` WHERE (`u`.`customer_id` = "#{id}" OR `u`.`customer_id` IS NULL)' validates_presence_of :name end class User < ActiveRecord::Base # most users belong to a customer. # however, the customer_id may be NULL # to implement the concept of "global" users. belongs_to :customer validates_presence_of :email end 

At first, this seems to work just fine:

>> Customer.first.users # => Array of users including global users 

But when i try following i get an mysql error:

>> Customer.first.users.find_by_email("test@example.com") ActiveRecord::StatementInvalid: Mysql::Error: Operand should contain 1 column(s): SELECT * FROM `users` WHERE (`users`.`email` = 'test@example.com') AND ( SELECT `u`.* FROM `users` `u` WHERE (`u`.`customer_id` = "1" OR `u`.`customer_id` IS NULL) ORDER BY u.nickname ) LIMIT 1 from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract_adapter.rb:188:in `log' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/mysql_adapter.rb:309:in `execute' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/mysql_adapter.rb:563:in `select' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/connection_adapters/abstract/query_cache.rb:62:in `select_all' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:635:in `find_by_sql' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1490:in `find_every' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1452:in `find_initial' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:587:in `find' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1812:in `find_by_email' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1800:in `send' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:1800:in `method_missing' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_collection.rb:370:in `send' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_collection.rb:370:in `method_missing' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:2003:in `with_scope' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_proxy.rb:202:in `send' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_proxy.rb:202:in `with_scope' from /Library/Ruby/Gems/1.8/gems/activerecord-2.2.2/lib/active_record/associations/association_collection.rb:366:in `method_missing' 

So, Rails is generating an invalid SQL Statement. The reason for that is probably my finder_sql, because the association without finder_sql works as expected.

I've already tried to remove all optional plugins (will_paginate). The thing I'm trying to achieve is actually quite simple: Include all User Models matching the following the condition (users.customer_id = 1 OR users.customer_id IS NULL) in my association.

Appreciate any help!

33034773 0
public class GuessingGame { public static void main(String[] args) { int NumberGuess = 0; Random randomNumber = new Random(); int randomInt = randomNumber.nextInt(51); System.out.println("Guess the number between 0 -50:"); int i = 1; Scanner UserGuess = new Scanner(System.in); while (i <= 7) { NumberGuess = UserGuess.nextInt(); if (NumberGuess == randomInt) { System.out.println("Correct! You win!"); System.out.println("It took you " + i + " guesses."); System.exit(0); } else if (NumberGuess < 0 || NumberGuess > 50) { System.out.println("Invalid Input, please enter numbers between 0 and 50"); } else if (NumberGuess < randomInt) { System.out.println("Guess is too small."); } else if (NumberGuess > randomInt) { System.out.println("Guess is too big."); } System.out.println("You have made " + i + " guesses out of 7"); i++; } System.out.println("Game over!"); System.out.println("All 7 Guesses used!"); System.exit(0); } } 

Also you should not Scanner UserGuess = new Scanner(System.in); use this statement inside the loop. Only one copy of the scanner should be created, outside the loop.

15837920 0 Find all tags and change style attribute

i am trying to find a way to get the tag from a string and remove the style attribute . After that i want to add my own style and keep the following text.. For example, i have:

<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 600px; height: 405px;" /></p><p>&nbsp;</p><p> 

end the endresult should be:

<p><img alt="" src="images/epsth/arismagnisiakos.jpg" style="width: 100%;" /></p><p>&nbsp;</p><p> 

I have unsuccesfully tried regex but it seems like i am too dumb to understand its functionality...

Every help would be appreciated! Greetings from Greece Jim

24452117 0

I just ran into this issue myself, the problem was that syntax coloring was set to C instead of Objective-C.

Click Editor->Syntax Coloring->Objective-C

16701980 0

Please make sure you have the same settings for ansi_null for both your local DB settings and your clients. style like "name is not null" will return the desired result, not like "name =/<> null" that depends on ansi_null settings.

check for ansi_null: http://msdn.microsoft.com/en-us/library/ms188048(v=sql.105).aspx

22203284 0

Python looks for the installed packages in the PYTHON_PATH environment variable. But I am not sure if that is your problem here. The error message suggests that there is a problem with the shared object versions... I would recommend you that you install everything you need with the pip install command on the console...

15428036 0 how to remove 3 lines in row if the first line contain a specific character?

I have a data file (which a matrix with 290 lines and 2 columns) like this:

# RIR1 ABABABABABABABABAA ABABABABABABABABBA # WR ABABABABABABABABAB BABABBABABABABABAA # BR2 ABABABABABABABBABA ABBABABABABABABABA # SL AAABABABABABABBABA AAABBABABABABABABA 

I would like to remove all the data that are for SL and WR (as example). So I will have only:

# RIR1 ABABABABABABABABAA ABABABABABABABABBA # BR2 ABABABABABABABBABA ABBABABABABABABABA 

I know how to remove one line that start or contain something but no idea how to do with 3 lines in row.

this is what I use for one line:

old<-old[!substr(old[1,],1,5)=="# BR2",] old<-old[!substr(old[1,],1,6)=="# RIR1",] 

thanks in advance.

28702920 0

Here's one bash solution (assuming the numbers are in a file, one per line):

sort -n numbers.txt | grep -n . | grep -v -m1 '\([0-9]\+\):\1' | cut -f1 -d: 

The first part sorts the numbers and then adds a sequence number to each one, and the second part finds the first sequence number which doesn't correspond to the number in the array.

Same thing, using sort and awk (bog-standard, no extensions in either):

sort -n numbers.txt | awk '$1!=NR{print NR;exit}' 
10520854 0
$('.className').click(funcName); 

less load as it uses a single jquery object

$('.className').each(function(){ $(this).click(funcName); }); 

more load as it uses the initial instance, and also generates a new instance for each 'eached' element via $(this). If $('.className') contains 50 elements, you now have 51 jQuery objects, versus a single object.

As far as pluggin development, you can use javascript objects and use new for each instance of the plugin. Or you can define a parent object class, and use .each on that to set up instances. I hope this helps, it hard to make a recommendation without knowing what your are cooking.

17199202 0 How to create a mustache without using a file?

I have the template saved as a string somewhere and I want to create the mustache with that. How can I do this? Or is it doable?

8170148 0

Generic info about buttons here

To use image for a button you need an android.widget.ImageButton. Example of drawable selector (put it in res/drawable/):

<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/button_pressed" /> <!-- pressed --> <item android:state_focused="true" android:drawable="@drawable/button_focused" /> <!-- focused --> <item android:drawable="@drawable/button_normal" /> <!-- default --> </selector> 

So you can use different images for various states. To generate buttons on the fly you can define base layout with any layout manager (FrameLayout, RelativeLayout, LinearLayout), find it by id (findViewById()) within your Activity and make it visible:

public void createContainerForImageView() { LinearLayout container = new LinearLayout(this); container.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); container.setOrientation(LinearLayout.HORIZONTAL); ImageView img=(ImageView)findViewById(R.id.ImageView01); Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.sc01); int width=200; int height=200; Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, width, height, true); img.setImageBitmap(resizedbitmap); container.addView(img); // or you can set the visibility of the img } 

Hope this helps.

19733155 0

You would need to use the constructor for Dictionary which accepts a custom IEqualityComparer(Of T) for your key type.

Arrays, without a custom IEqualityComparer(Of T), are not valid object types as keys to a dictionary (or other hash-based collection).

37837741 0 MySQL - How to set auto_increment_increment permanently, to last server restart?

Is it possible to set MySQL auto_increment_increment so that it survives the server restart?

Currently I'm setting it like this:

SET @@auto_increment_increment=2; 

But it loses the value when I:

sudo service mysql restart 

And returns to default value of 1.

I'm on a AWS and I would like to be able to handle possible doomsday errors as easy as possible: by setting up a new instance from an AMI. I would like it to be ready to serve right away when it's up and avoid things like setting the auto_increment_increment -value by hand.

11313935 1 Trying to catch integrity error with SQLAlchemy

I'm having problems with trying to catch an error. I'm using Pyramid/SQLAlchemy and made a sign up form with email as the primary key. The problem is when a duplicate email is entered it raises a IntegrityError, so I'm trying to catch that error and provide a message but no matter what I do I can't catch it, the error keeps appearing.

try: new_user = Users(email, firstname, lastname, password) DBSession.add(new_user) return HTTPFound(location = request.route_url('new')) except IntegrityError: message1 = "Yikes! Your email already exists in our system. Did you forget your password?" 

I get the same message when I tried except exc.SQLAlchemyError (although I want to catch specific errors and not a blanket catch all). I also tried exc.IntegrityError but no luck (although it exists in the API).

Is there something wrong with my Python syntax, or is there something I need to do special in SQLAlchemy to catch it?


I don't know how to solve this problem but I have a few ideas of what could be causing the problem. Maybe the try statement isn't failing but succeeding because SQLAlchemy is raising the exception itself and Pyramid is generating the view so the except IntegrityError: never gets activated. Or, more likely, I'm catching this error completely wrong.

6592841 0

An alternative approach is to just add a few forwarding functions:

T numberedFunction( unsigned int i ) { ... } T single() { return numberedFunction(1); } T halfDozen() { return numberedFunction(6); } 
20520733 0 CSS code a:visited does not work

I have a pretty noob problem, so I hope someone could help me out.

I have a Blogger blog, and I can't get the links to function like I want to.

I want the links in the post content and in the sidebar - the ones that are a purple shade (#8B7083) and underlined - to look the same for both a:link and a:visited. For some reason visited links turn black, even though I don't have that anywhere in my CSS.

Help me, please?

39556966 0

This line:

A[j - 1] = 1; 

Should be:

A[j] = 1; 

So, now should works well:

#include<stdio.h> int A[1000000]; void sieve(int till) { for(int i = 2; i < till; i++) { if(A[i] == 0) { for(int j = i*i; j < till; j+=i) { A[j] = 1; } } } } int main() { int N,i; scanf("%i", &N); for (i = 0;i < N;i++) A[i] = 0; sieve(N); for (i = 2;i < N;i++) if (A[i]) printf("%i is not prime\n",i); else printf("%i is prime\n",i); } 
34104103 0

In BigInt, note /% operation which delivers a pair with the division and the reminder (see API). Note for instance

scala> BigInt(3) /% BigInt(2) (scala.math.BigInt, scala.math.BigInt) = (1,1) scala> BigInt(3) /% 2 (scala.math.BigInt, scala.math.BigInt) = (1,1) 

where the second example involves an implicit conversion from Int to BigInt.

23030942 0

I use this code:

public void getDefaultLauncher() { final Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); PackageManager pm = getPackageManager(); final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0); pm.clearPackagePreferredActivities(getApplicationContext().getPackageName()); for(ResolveInfo ri : list) { if(!ri.activityInfo.packageName.equals(getApplicationContext().getPackageName())) { startSpecificActivity(ri); return; } } } private void startSpecificActivity(ResolveInfo launchable) { ActivityInfo activity=launchable.activityInfo; ComponentName name=new ComponentName(activity.applicationInfo.packageName, activity.name); Intent i=new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_LAUNCHER); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); i.setComponent(name); startActivity(i); } 

Maybe it works for you as well.

23922079 1 How to write unittests for a custom pylint checker?

I have written a custom pylint checker to check for non-i18n'ed strings in python code. I'd like to write some unittests for that code now.

But how? I'd like to have tests with python code as a string, which will get passed through my plugin/checker and check the output?

I'd rather not write the strings out to temporary files and then invoke the pylint binary on it. Is there a cleaner more robust approach, which only tests my code?

35737341 0

You are referencing to the wrong API. The link you have provided is for the Google Play Developer API which is for subscription, in-app purchase and publishing. The API for sharing progress and other in-game API calls is the Google Play Games Services which has a default quota of 50000000 requests/day and in which the user can have 500 requests per second(The quotas can be seen in the Developer's Console). You could also see Managing Quota and Rate Limiting for other info about the quota and limits.

12784538 0

You should try moving your integration test to the top level project. This way it will run after the WAR artifact has been built.

Have you had a look at the Maven Failsafe Plugin? It's designed for the sort of thing you're doing, which is actually an integration test and not a unit test. The page offers some good advice on why you might want to use the integration-test phase for your integration testing.

Namely, it describes why you might want to do start-jetty during pre-integration-test and so on, so that you can tear it all down appropriately.

28584599 0

This is a duplcate of an existing question

See http://stackoverflow.com/a/7661057/2319909

Converted code for reference:

You need to set the button to allow multiple lines. This can be achieved with following P/Invoke code.

Private Const BS_MULTILINE As Integer = &H2000 Private Const GWL_STYLE As Integer = -16 <System.Runtime.InteropServices.DllImport("coredll")> _ Private Shared Function GetWindowLong(hWnd As IntPtr, nIndex As Integer) As Integer End Function <System.Runtime.InteropServices.DllImport("coredll")> _ Private Shared Function SetWindowLong(hWnd As IntPtr, nIndex As Integer, dwNewLong As Integer) As Integer End Function Public Shared Sub MakeButtonMultiline(b As Button) Dim hwnd As IntPtr = b.Handle Dim currentStyle As Integer = GetWindowLong(hwnd, GWL_STYLE) Dim newStyle As Integer = SetWindowLong(hwnd, GWL_STYLE, currentStyle Or BS_MULTILINE) End Sub 

Use it like this:

MakeButtonMultiline(button1) 
11932580 0

I solved this problem by using an activation profile :-

<profiles> <profile> <id>ptest</id> <activation> <property> <name>ptest</name> </property> </activation> <build> <resources> <resource> <directory>src/jmeter</directory> </resource> </resources> <plugins> <plugin> <groupId>com.lazerycode.jmeter</groupId> <artifactId>jmeter-maven-plugin</artifactId> <version>1.4.1</version> <executions> <execution> <id>jmeter-tests</id> <phase>verify</phase> <goals> <goal>jmeter</goal> </goals> </execution> </executions> <configuration> <useOldTestEndDetection>true</useOldTestEndDetection> </configuration> </plugin> </plugins> </build> </profile> </profiles> 

Using this approach you can install once, not using the profile, and then run subsequently with the profile turned on.

19092733 0

You can try and run an exception handler on the occurrence of exception. You can use a flag, I have used the exception for checking the exception occurence itself in the example:

 private static AggregateException exception = null; static void Main(string[] args) { Console.WriteLine("Start"); Task.Factory.StartNew(PrintTime, CancellationToken.None).ContinueWith(HandleException, TaskContinuationOptions.OnlyOnFaulted); for (int i = 0; i < 20; i++) { Console.WriteLine("Master Thread i={0}", i + 1); Thread.Sleep(1000); if (exception != null) { break; } } Console.WriteLine("Finish"); Console.ReadLine(); } private static void HandleException(Task task) { exception = task.Exception; Console.WriteLine(exception); } private static void PrintTime() { for (int i = 0; i < 10; i++) { Console.WriteLine("Inner Thread i={0}", i + 1); Thread.Sleep(1000); } throw new Exception("exception"); } 
21068282 0 Checkbox look like radio buttons on iPad/iPad Mini?

Not sure why this is happening, but couldn't find anything on this. Every input type="checkbox" look like radio buttons on iPads. Has anyone come across this issue and if so, how were you able to fix the problem?

Thank you guys!

<div> <input type="checkbox" name="checkNow">Check Now </div> 
2023342 0

You can achieve this with a DockPanel:

<DockPanel Width="300"> <TextBlock>Left</TextBlock> <Button HorizontalAlignment="Right">Right</Button> </DockPanel> 

The difference is that a StackPanel will arrange child elements into single line (either vertical or horizontally) whereas a DockPanel defines an area where you can arrange child elements either horizontally or vertically, relative to each other (the Dock property changes the position of an element relative to other elements within the same container. Alignment properties, such as HorizontalAlignment, change the position of an element relative to its parent element).

3998888 0

Every valid JSON is also valid JavaScript but not every valid JavaScript is also valid JSON as JSON is a proper subset of JavaScript:

JSON ⊂ JavaScript

JSON requires the names of name/value pairs to be quoted while JavaScript doesn’t (as long as they are not reserved keywords).

So your first example {"active": "yes"} is both valid JSON and valid JavaScript while the second example {active: "yes"} is only valid JavaScript.

24136726 0

You need to send exception about your error, to method fail().

Assert.fail("Some message", new Exception(errorDivs.get(0).getText())); 
14341379 0 Trigger a process (SQL update) when leaving an APEX page

This is a very odd question but i wondered whether it was possible to trigger a process that runs an SQL UPDATE when the user leaves this specific page, either by clicking on the breadcrumb, tabs or back button?

I did setup the process to run on the 'Back' button; however i ran into the problem of: What if s/he clicks on the breadcrumb or a tab instead.

I have searched the net and posting this question was a last resort. I wondered if anyone can point me in the correct direction?

UPDATED POST

Page 1:
Includes a text field and a button. The user enters the category into the text field and clicks on the button to proceed to the next page. The button passes the value in the text field to a text field on Page 2.

Page 2:
Two regions on the page. One region holds information about the category - Category name from the previous page, category description, and the category revision number (which is what i'm trying to get working). The second region is a report that pulls the item name and number that are listed under the category in the category text field. A 'View' link is used on the report to load the edit page for the specific item selected. The 'View' link passes the 'category name' (from the category text field) and the 'item number' from the report to page 3.

Page 3
Two regions are used, first region: Lists the Item number which came from page 2 and name of the item (which i use a simple query to retrieve). In the second region: A report is used with two columns: a list of item properties in column 1, and a text field next to each item property in column 2 to hold the value that can be updated. The 'Apply Changes' button has some PlSql behind which looks for changes and updates where required. It updates the relevant fields that have changed, and it then takes the user back to Page 2 (Page showing user the items listed for the category intitally entered).

I cant increase the category revision on the 'apply changes' button on page 3 because the user may complete edits for items under the same category. So i dont know where i can increase the category revision by 1 per vist to a category. P.s I already increment the revision number for each item by 1 if the info has been changed using the 'apply changes' button on page 3.

21044819 0

You have to create a new serie and then add it to your chart.

Series series1 = new Series("series1"); chart1.Series.Add(series1); 

You can also create them in your .aspx.

<form id="form1" runat="server"> <asp:Chart ID="Chart1" runat="server" ImageType="Png"> <ChartAreas> <asp:ChartArea Name="ChartArea1"></asp:ChartArea> </ChartAreas> <Legends> <asp:Legend Name="Legends1"></asp:Legend> </Legends> <Series> <asp:Series Name="Series0"></asp:Series> <asp:Series Name="Series1"></asp:Series> <asp:Series Name="Series2"></asp:Series> </Series> </asp:Chart> </form> 
7556033 0 Load or functional testing of GWT app using JMeter

I am new to JMeter. I wanted to do some functional testing of my GWT application using JMeter. Does it support GWT testing? For example I would like to write a script that might check if the login module of my GWT application is doing good or not. Please let me know if we have some sort of documentation specific to GWT testing with JMeter.

Thanks a million.

-- Mohyt

4139738 0 Need help with a mIRC macro

I'm trying to make a script that will automatically says "see you later" as soon as one specific handle in a channel says the words "going home". I tried to do it on my own but got lost. Could anyone help me out?

13168565 0

Why not to convert your pseudo-code to real code?

public static class MyExtensions { public static IEnumerable<T> RunMeOnEachItemLater(this IEnumerable<T> sequence, Action<T> action) { foreach(T item in sequence) { action(item); yield return item; } } } 

Now you can execute custom function for each item later using LINQ deferred execution:

IEnumerable<BaseModel> l = Cache[type].Data.Cast<BaseModel>() .RunMeOnEachItemLater(m => m.Init()); 
7257281 0 Using doxygen to create documentation for existing C# code with XML comments

I've read everywhere that doxygen is the way to go for generating documentation for C# code. I've got a single interface that I want to document first (baby steps), and it already has the XML comments (///) present.

Because of the vast number of posts and information available (including doxygen.org) that say these comments are already supported, I'm surprised that when I run doxywizard, I get errors like "warning: Compound Company::Product::MyInterface is not documented".

This leads me to believe that I have somehow misunderstood XML documentation (hopefully not, according to MSDN I am talking about the right thing), or I have misconfigured doxywizard.

I first ran doxywizard via the Wizard tab, and specified that I want to support C#/Java. When I run it, my HTML page is blank, presumably because of the previously-mentioned warnings. I then tried specifying a single file via the Expert tab and ran again -- same behavior.

Can anyone tell me what switch or setting I'm missing to get doxygen to generate the HTML?

Here's an example of what a documented property/method looks like in my interface:

/// <summary> /// Retrieve the version of the device /// </summary> String Version { get; } /// <summary> /// Does something cool or really cool /// </summary> /// <param name="thing">0 = something cool, 1 = something really cool</param> void DoSomething( Int32 thing); 

I do have a comment above the interface, like this:

/// <summary> /// MyInterface /// </summary> public interface MyInterface {...} 
40597239 0

You will have to decide on a library to do API calls. A simple way is to use fetch, which is built-in in modern browsers. There's a polyfill to cover older ones. jQuery's AJAX or SuperAgent are two alternatives. Here's a simple example using fetch. You'll only have to change the URL of the request.

class Example extends React.Component { constructor() { super(); this.state = { data: {} }; } componentDidMount() { var self = this; fetch('http://reqres.in/api/users') .then(function(response) { return response.json() }).then(function(data) { self.setState({ data }, () => console.log(self.state)); }); } render() { return ( <div/> ); } } ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="View"></div>

10164600 0

%p is the format token to show AM/PM

time_tag(time, :format=>'%B %d, %Y %l:%M %p') 
31740599 0

You have error in your query, you are writing select* but there should be a space like so select *

$sql = mysql_query("select * from login where user= '$user' AND pass='$pass' LIMIT 3 ") or die(mysql_error());

EDIT

Also YOU MUST HAVE TO PUT session_start(); as the first line of your code... else it would not work.

So make this as your first lines of code

session_start(); error_reporting(E_ALL); // to see if there is error in code 

And also PHP varialble names are case-sensitive,

Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-sensitive.

So please change

if($user==$username && $pass==$password) 

to

if($user==$UserName && $pass==$Password) 
3896348 0
Seq.initInfinite (fun _ -> Console.ReadLine()) 
10042197 0

It seems your mapper outputs a key-value pair of type ImmutableBytesWritable -> Result but your Reducer reads in a key-value pair of type ImmutableBytesWritable -> Put. This can't work as the output of the mapper must be of the same type the input of the reducer is. You should either

25958074 1 Deleting multiple variables each pass of a loop

In the main loop of my program, I have around a dozen variables that are calculated each time the loop is actioned. At this stage I would prefer a 'NameError' than to have the variables from an earlier pass affect the outcome of a future pass of the loop.

Right now I just have a series of the following statements run at the final step of each loop:

try: del my_var1 except: pass 

I suspect there's a better way to do this?

11281019 0

Third option:

>>> from urlparse import urlparse, parse_qs >>> url = 'http://something.com?blah=1&x=2' >>> urlparse(url).query 'blah=1&x=2' >>> parse_qs(urlparse(url).query) {'blah': ['1'], 'x': ['2']} 
36026699 0 How to know whether Arduino Bluetooth is paired or not?

I am using an Arduino Mega and a Bluetooth module hc-05 zs040. I want to connect an external LED to the Arduino, which will indicate whether Bluetooth is paired or not. I read about the STATE pin and tried to use it but my state always outputs digital 0, no matter whether it is connected or not. Is there any other way to do this (other than soldering)?

25275368 0

Explicitly declare all the variables:

function animate(num, element, transitionUnit, delayUnit) { var delay = 0; var transition = 0; var x = document.getElementById(element).getElementsByTagName("LI"); for (var i = 0; i <= x.length - 1; i++) { x[i].style.WebkitTransform = "translate3d(" + num + "px,0,0)"; x[i].style.transition = transition + "s " + delay + "s ease-in-out"; delay += delayUnit; transition += transitionUnit; if (x[i].querySelectorAll('ul li').length > 0) { x[i].style.background = "rgba(0,0,0,0.35)"; } } } 

Using implicit globals in for loops causes problems.

As aSeptik mentioned, you might be inverting values:

animate(0,"mainNav",0.04,0.02); 
22980046 0 how to solve onTouchListener android

i have problem, I am successfully to display image in alert dialog custom, but when I want to add event onTouchListener to the image, i cannot get problem : the method setonTouchListener in Type View is not applicable. Here my source code :

public class ViewDetailItem extends Activity implements OnTouchListener{ bla bla... onloaditem() } 

here onloaditem() sourcecode :

 imgmain.setImageResource(imgID); imgmain.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub /*Intent MyIntentDetailItem=new Intent(getBaseContext(), ViewDetailItemFullscreen.class); Other_class.setItemCode(timgName); startActivity(MyIntentDetailItem);*/ LayoutInflater li = LayoutInflater.from(ViewDetailItem.this); final View inputdialogcustom = li.inflate(R.layout.activity_view_detail_item_fullscreen2, null); final AlertDialog.Builder alert = new AlertDialog.Builder(ViewDetailItem.this); final ImageView imgmainbig=((ImageView) inputdialogcustom.findViewById(R.id.imgmainbig)); imgID=getBaseContext().getResources().getIdentifier(imgName2+"_1", "drawable", getBaseContext().getPackageName()); imgmainbig.setImageResource(imgID); imgmainbig.setOnTouchListener(this); } } 

The problem refers to imgmainbig.setOnTouchListener(this);

15423760 0

Microsoft tried to do something like that with WinFS but gave up on it. It would be great if they could get it to work.

1765718 0 Android - NPE in BrowserFrame

I get this exception triggered by users occasionally that I cannot reproduce. Since it's issued from looper I suppose it is result of Handler-type callback. I found similar bug on Google code but putting the solution into code didn't solve it. The problem is at this line of code in BrowserFrame:

WebAddress uri = new WebAddress( mCallbackProxy.getBackForwardList().getCurrentItem() .getUrl()); 

Which throws this Exception because I suppose mCallbackProxy is null

java.lang.NullPointerException at android.webkit.BrowserFrame.handleMessage(BrowserFrame.java:348) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:123) at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:471) at java.lang.Thread.run(Thread.java:1060) 

And the questions are - will this forclose the app? And how do I work around this bug?

30478039 1 entering data and displaying entered data using python

I am newbie to python , I am trying to write a program in which i can print the entered data .

here is the program which I tried.

#!"C:\python34\python.exe" import sys print("Content-Type: text/html;charset=utf-8") print() firststring = "bill" secondstring = "cows" thridstring = "abcdef" name = input('Enter your name : ') print ("Hi %s, Let us be friends!" % name) 

The output of this program is only : "Enter your name : " I cannot enter anything from my keyboard. I am running this program using apache in localhost like http://localhost:804/cgi-bin/ex7.py Can anyone plz help me to print the user entered data. Thank you.

17328937 0 Does installing a file automatically register it?

I am creating an MSI installer using WiX. I have several .ocx and .dll files that must be registered on the end user's computer. Does including these files in the installation automatically register them as if the regsvr32 command had been run?

11461733 0 How to embed a property as a string argument in soapUI

I have recently started using soapui to test web services and fairly new. I was wondering how to embed a property value as a string in the request. For example the request is like below

<org:Customer org1:Description="customer" org1:DisplayName="google" org1:Name="google"/> 

Essentially I am looking to do this something like this,

<org:Customer org1:Description=${#Project#orgdesc} org1:DisplayName=${#Project#orgdisplayname} org1:Name=${#Project#orgdisplayname}/> 

I have properties defined for all of the fields above at the project level for parameterizing my test. I am trying to embed these properties within the request. I tried following things but none of them work. Can someone please let me know what I am missing?

Edit#1

I think I am not doing the right thing below. Because in the original request above, Description, DisplayName and Name are the attributes of Customer and I sending the request by making them as child nodes below. It seems fundamentally incorrect. Then how do I embed value of the properties I defined within attributes of a tag?

Attempt 1

 <org:Customer> <arg0> <org1:Description>${#Project#orgdesc}</org1:Description> <org1:DisplayName>${#Project#orgdisplayname}</org1:DisplayName> <org1:Name>${#Project#orgname}</org1:Name> </arg0> </org:Customer> 

Attempt 2

 <org:Customer> <org1:Description> <arg0>${#Project#orgdesc}</arg0> </org1:Description> <org1:DisplayName> <arg0>${#Project#orgdisplayname}</arg0> </org1:DisplayName> <org1:Name> <arg0>${#Project#orgname}</arg0> </org1:Name> </org:Customer> 
38900347 0

There is an event in magento,

sales_quote_collect_totals_after 

This is fired whenever your total is calculated, what you can do is set a flag in session on click on the button to apply discount, and in this above event's observer method, check if it is set then apply discount.

In your config.xml

<global> <events> <sales_quote_collect_totals_after> <observers> <class>Custom_Module_Model_Observer</class> <method>collectTotals</method> </observers> </sales_quote_collect_totals_after> </events> </global> 

Make a Observer.php in

Custom /Module /Model /Observer.php 

Make a function in Observer.php

public function collectTotals(Varien_Event_Observer $observer) { $quote=$observer->getEvent()->getQuote(); $quoteid=$quote->getId(); //check condition here if need to apply Discount if($disocuntApply) $discountAmount =5; if($quoteid) { if($discountAmount>0) { $total=$quote->getBaseSubtotal(); $quote->setSubtotal(0); $quote->setBaseSubtotal(0); $quote->setSubtotalWithDiscount(0); $quote->setBaseSubtotalWithDiscount(0); $quote->setGrandTotal(0); $quote->setBaseGrandTotal(0); $canAddItems = $quote->isVirtual()? ('billing') : ('shipping'); foreach ($quote->getAllAddresses() as $address) { $address->setSubtotal(0); $address->setBaseSubtotal(0); $address->setGrandTotal(0); $address->setBaseGrandTotal(0); $address->collectTotals(); $quote->setSubtotal((float) $quote->getSubtotal() + $address->getSubtotal()); $quote->setBaseSubtotal((float) $quote->getBaseSubtotal() + $address->getBaseSubtotal()); $quote->setSubtotalWithDiscount( (float) $quote->getSubtotalWithDiscount() + $address->getSubtotalWithDiscount() ); $quote->setBaseSubtotalWithDiscount( (float) $quote->getBaseSubtotalWithDiscount() + $address->getBaseSubtotalWithDiscount() ); $quote->setGrandTotal((float) $quote->getGrandTotal() + $address->getGrandTotal()); $quote->setBaseGrandTotal((float) $quote->getBaseGrandTotal() + $address->getBaseGrandTotal()); $quote ->save(); $quote->setGrandTotal($quote->getBaseSubtotal()-$discountAmount) ->setBaseGrandTotal($quote->getBaseSubtotal()-$discountAmount) ->setSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount) ->setBaseSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount) ->save(); if($address->getAddressType()==$canAddItems) { $address->setSubtotalWithDiscount((float) $address->getSubtotalWithDiscount()-$discountAmount); $address->setGrandTotal((float) $address->getGrandTotal()-$discountAmount); $address->setBaseSubtotalWithDiscount((float) $address->getBaseSubtotalWithDiscount()-$discountAmount); $address->setBaseGrandTotal((float) $address->getBaseGrandTotal()-$discountAmount); if($address->getDiscountDescription()){ $address->setDiscountAmount(-($address->getDiscountAmount()-$discountAmount)); $address->setDiscountDescription($address->getDiscountDescription().', Amount Waived'); $address->setBaseDiscountAmount(-($address->getBaseDiscountAmount()-$discountAmount)); }else { $address->setDiscountAmount(-($discountAmount)); $address->setDiscountDescription('Amount Waived'); $address->setBaseDiscountAmount(-($discountAmount)); } $address->save(); }//end: if } //end: foreach //echo $quote->getGrandTotal(); foreach($quote->getAllItems() as $item){ //We apply discount amount based on the ratio between the GrandTotal and the RowTotal $rat=$item->getPriceInclTax()/$total; $ratdisc=$discountAmount*$rat; $item->setDiscountAmount(($item->getDiscountAmount()+$ratdisc) * $item->getQty()); $item->setBaseDiscountAmount(($item->getBaseDiscountAmount()+$ratdisc) * $item->getQty())->save(); } } } } 

collectTotals function will be called, whenever the quote totals is updated, so there is no need to call it explicitly.

Check for how it works here.

Setting magento session variables, check here.

hope it helps!

39225329 0

First one is an example of a nested state which fulfills your requirement for inheriting the scope object. e.g state/sub-state-a, state/sub-state-b The comment above the first snippet you took from the doc reads:

Shows prepended url, inserted template, paired controller, and inherited $scope object.

The second example is a nested view where you can define multiple views per state and use each depending on your use-case. From the docs:

Then each view in views can set up its own templates (template, templateUrl, templateProvider), controllers (controller, controllerProvider).

26493784 0

To get the results you want without changing your existing code too much, you can get the sequence line when you're processing the header line:

while ( my $line = <FILE2> ) { if ($line =~ /^>(\S+)\s+\S+\s+(\d+)\s+(\d+)\s+(\S+)/) { my $cds1 = $1; my $cds2 = $2; my $cds3 = $3; my $cds4 = $4; # fetch the next line from the file -- i.e. the sequence $nextline = <FILE2>; for my $cc22 (@file1list) { if ( $cc22 > $cds2 && $cc22 < $cds3 ) { print "$cc22 $cds2 $cds3 $cds4 $nextline"; } } } } 
5730726 0

The mouse does work for single finger gestures and taps, not sure why it wouldn't work for you except to assume that your code must not be working as you assume :-)

Just for reference, the other way of testing multi-touch is to have a multi-touch enabled monitor

3319559 0

" Is it possible with some code in the controller to define the nested master page and master page?"

Nope. The default view engine only lets you define one level of MasterPages.

See: http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.view.aspx

2420358 0 Why does using a structure in C program cause Link error

I am writing a C program for a 8051 architecture chip and the SDCC compiler.

I have a structure called FilterStructure;

my code looks like this...

#define NAME_SIZE 8 typedef struct { char Name[NAME_SIZE]; } FilterStructure; void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure); int main (void) { FilterStructure testStruct; ReadFilterName('A', 3, &testFilter); ... ... return 0; } void ReadFilterName(U8 WheelID, U8 Filter, FilterStructure* NameStructure) { int StartOfName = 0; int i = 0; ///... do some stuff... for(i = 0; i < 8; i++) { NameStructure->Name[i] = FLASH_ByteRead(StartOfName + i); } return; } 

For some reason I get a link error "?ASlink-Error-Could not get 29 consecutive bytes in internal RAM for area DSEG"

If I comment out the line that says FilterStructure testStruct; the error goes away.

What does this error mean? Do I need to discard the structure when I am done with it?

1351741 0

The answer is no, by default object identity is not preserved via serialization if you are considering 2 separate serializations of a given object/graph. For example, if a I serialize an object over the wire (perhaps I send it from a client to a server via RMI), and then do it again (in separate RMI calls), then the 2 deserialized objects on the server will not be ==.

However, in a "single serialization" e.g. a single client-server message which is a graph containing the same object multiple times then upon deserialization, identity is preserved.

For the first case, you can, however, provide an implementation of the readResolve method in order to ensure that the correct instance is returned (e.g. in the typesafe enum pattern). readResolve is a private method which will be called by the JVM on a de-serialized Java object, giving the object the chance to return a different instance. For example, this is how the TimeUnit enum may have been implemented before enum's were added to the language:

public class TimeUnit extends Serializable { private int id; public TimeUnit(int i) { id = i; } public static TimeUnit SECONDS = new TimeUnit(0); //Implement method and return the relevant static Instance private Object readResolve() throws ObjectStreamException { if (id == 0) return SECONDS; else return this; } } 

.

29765240 0 If without else not running

I have a little code for testing a sprite, that I want to move with the mouse. When I click the screen, the sprite has to move to the clicked point. But something weird is going on.

I'm running it in a thread, called Controls, that extends to Thread and implements MouseListener, and using the following code, the sprite moves.

public void run() { while(true){ if((int)point.getX() > player.getX()){ while((int)point.getX() > player.getX()){ player.moveX(1); } } else{ System.out.println("Nah!"); } } } 

Everything works as expected, but if i do this:

public void run() { while(true){ if((int)point.getX() > player.getX()){ while((int)point.getX() > player.getX()){ player.moveX(1); } } } } 

It doesn't work. If i do this:

public void run() { while(true){ if((int)point.getX() > player.getX()){ while((int)point.getX() > player.getX()){ player.moveX(1); } } else{ } } } 

It doesn't work either. I have no idea of what is going on, any ideas?

28395585 0 Laravel 4.2 returning soft deleted on BelongsToMany results

Hello I just noticed one weird behaviour of softDelete. Basically, when I query for a related set of models, Eloquent returns a collection that also contains soft deleted rows.

I have been following the 4.2 guides on traits usage for softdelete and my code works just fine as long as I get/delete/restore/force delete my models. The issue is triggered with relations.

Consider this scenario: I have a user model that has a belongToMany friendship relation where the friendship status can be accepted/pending/requested/blocked as follows:

public function friends() { return $this->belongsToMany('User', 'friends', 'user_id', 'friend_id')->where('status', 'accepted'); } 

This friends table rows are basically "vectors" where user1->status->user2 and viceversa (user2->status->user1 is on another row). When user1 decides not to be friend with user2 anymore, the 2 friends rows are softdeleted.

Here is the issue: when I query the DB from the controller like this:

$friends = $user->friends; 

even the softdeleted rows show up in the returned collection even though I would have expected these to be hidden from results unless I used ->withTrashed().

I suspect the belongsToMany() method doesn't take into account the deleted_at field on the pivot table.

Did anyone faced a similar issue? Am I doing something wrong with this relation?

Thanks a lot for your help!!!

18988439 0

Method 1: Using list.index:

def match(strs, actual): seen = {} act = actual.split('/') for x in strs.split('/'): if x in seen: #if the item was already seen, so start search #after the previous matched index ind = act.index(x, seen[x]+1) yield ind seen[x] = ind else: ind = act.index(x) yield ind seen[x] = ind ... >>> p1 = '/foo/baz/myfile.txt' >>> p2 = '/bar/foo/myfile.txt' >>> actual = '/foo/bar/baz/myfile.txt' >>> list(match(p1, actual)) #ordered list, so matched [0, 1, 3, 4] >>> list(match(p2, actual)) #unordered list, not matched [0, 2, 1, 4] >>> p1 = '/foo/bar/bar/myfile.txt' >>> p2 = '/bar/bar/baz/myfile.txt' >>> actual = '/foo/bar/baz/bar/myfile.txt' >>> list(match(p1, actual)) #ordered list, so matched [0, 1, 2, 4, 5] >>> list(match(p2, actual)) #unordered list, not matched [0, 2, 4, 3, 5] 

Method 2: Using defaultdict and deque:

from collections import defaultdict, deque def match(strs, actual): indexes_act = defaultdict(deque) for i, k in enumerate(actual.split('/')): indexes_act[k].append(i) prev = float('-inf') for item in strs.split('/'): ind = indexes_act[item][0] indexes_act[item].popleft() if ind > prev: yield ind else: raise ValueError("Invalid string") prev = ind 

Demo:

>>> p1 = '/foo/baz/myfile.txt' >>> p2 = '/bar/foo/myfile.txt' >>> actual = '/foo/bar/baz/myfile.txt' >>> list(match(p1, actual)) [0, 1, 3, 4] >>> list(match(p2, actual)) ... raise ValueError("Invalid string") ValueError: Invalid string >>> p1 = '/foo/bar/bar/myfile.txt' >>> p2 = '/bar/bar/baz/myfile.txt' >>> actual = '/foo/bar/baz/bar/myfile.txt' >>> list(match(p1, actual)) [0, 1, 2, 4, 5] >>> list(match(p2, actual)) ... raise ValueError("Invalid string") ValueError: Invalid string 
34621470 0

I assume, the question reflects an attemtpt to use unique_lock, which OP is saying works. The same example with lock_guard would not work, since std::vector::emplace_back requires the type to be both MoveInsertable and EmplaceConstructible, and std::lock_guard does not suit.

22336760 0

Use:

NodeList nodeList = doc.getElementsByTagName("xLabel"); for (int temp = 0; temp < nodeList.getLength(); temp++) { Node node = nodeList.item(temp); NodeList namexLabelNodes = node.getChildNodes(); for (int i = 0; i < namexLabelNodes.getLength(); i++) { System.out.println(" Name : " + namexLabelNodes.item(i).getTextContent()); } } 

For yLabel will be same code.

22907415 0 Eclipse PHP code formatter removes pipe symbols from @return comments

I'm using Eclipse Kepler (4.3.1) for a PHP project.

I've stumbled across a problem with the eclipse code formatter for PHP regarding PHPDoc's @return with pipe (vertical bar) symbol: When having a comment like this:

<?php /** * * @param string|array The parameter. Either a string or an array. * @return int|string The return value. Either an int or a string. */ function test($param) { } 

Using the format function with [CTRL]+[SHIFT]+[F] results in:

<?php /** * * @param * string|array The parameter. Either a string or an array. * @return int string return value. Either an int or a string. */ function test($param) { } 

As one can see, the pipe symbol between 'int' and 'string' in the '@return' statement has been replaced by a space. But not only that. Also the first word of the description ('The') has been chopped off. On the other hand, it works just fine for the '@param' statement.

phpdoc.org states, that the pipe symbol is used when handling ambigous return values: phpdoc-@return

Somebody also asked a question about this int the Eclipse Community Forums: Forum Post just a few days ago.

Using '@formatter:off' and '@formatter:on' is no option, since this setting is only local and others might not have it set.

Does anyone know how to fix-configure the eclipse php code formatter? Does anybody have a workaround?

38567369 0

Rudy Velthuis's answer explains it perfectly. If I understand correctly what you are trying to do can be done like this.

int pckt_number = 0; // 0 pckt_number |= 0 << 24; // most significant byte, pckt_number |= 1 << 16; // second most significant byte, pckt_number |= 0 << 8; // third most significant byte, pckt_number |= 0; // least significant byte, 
41059077 0

The correct path to use is the platform/google_appengine/ directory, within the google-cloud-sdk installation directory,

29374058 0

All your optionals need to be unwrapped. So lvt should become lvt!

Word of Caution Unwrapping an optional which doesn't have a value will thrown an exception. So it might be a good idea to make sure your lvt isn't nil.

if (lvt != nil) 
38529477 0 Repeating Javascript Animation

I have found a JSFiddle that has some great code to animate a ball - it rotates it through 360 deg. What I would like to do is have the ball constantly rotate through 360 deg - it needs to turn continuously. I have tried to achieve this but have had no success. I would be grateful for any help in adjusting this javascript.

$(document).ready(function(){ var s=$('.ball').position(); var g=s.left; var r=$('.ball').css('margin-left'); $('.ball').css({'margin-left':'0px'}); $('.ball').css({'margin-left':''+r+''}); if(r=="0px") { $('.ball').css({'position':'absolute'}); $('.ball').animate({'left':''+g+'px'}); } $('.ball').css({'transform': 'rotate(360deg)','-webkit-transform': 'rotate(360deg)','-moz-transform': 'rotate(360deg)'}); }); 

This is the JSFiddle I found http://jsfiddle.net/996PJ/5/

7053631 0

You can try to use a different library to load this assembly, like Mono.Cecil.

20149966 1 Python Error: list index out of range

I keep getting the error list index out of range. I'm not sure what I'm doing wrong.

My code:

from scanner import * def small(array): smallest=array[0] for i in range(len(array)): if (array[i]<smallest): smallest=array[i] return smallest def main(): s=Scanner("data.txt") array=[] i=s.readint() while i!="": array.append(i) i=s.readint() s.close() print("The smallest is", small(array)) main() 

The traceback I get:

Traceback (most recent call last): File "file.py", line 21, in <module> main() File "file.py", line 20, in main print("The smallest is", small(array)) File "file.py", line 5, in small smallest=array[0] IndexError: list index out of range 
12503239 0

Use the overload that takes a MidpointRounding

Math.Round(276.5, MidpointRounding.AwayFromZero); 

demo: http://ideone.com/sQ26z

6561284 0
  1. Allocating memory with new/new[]/malloc and not freeing it
  2. Allocating memory to some pointer and overwrite it accidently e.g. p = new int; p = new int[1];
  3. Allocating memory in air. i.e. new int[100]; or cout<<(*new string("hello"))<<endl;
26981858 0

using row number windowed function along with a CTE will do this pretty well. For example:

;With preResult AS ( SELECT TOP(100) [ID] = c.[ID], [Name] = c.[Name], [Keyword] = [colKeyword].[StringVal], [DateAdded] = [colDateAdded].[DateVal], ROW_NUMBER()OVER(PARTITION BY c.ID ORDER BY [colDateAdded].[DateVal]) rn FROM @cards AS c LEFT JOIN @cardindexes AS [colKeyword] ON [colKeyword].[CardID] = c.ID AND [colKeyword].[IndexType] = 1 LEFT JOIN @cardindexes AS [colDateAdded] ON [colDateAdded].[CardID] = c.ID AND [colDateAdded].[IndexType] = 2 WHERE [colKeyword].[StringVal] LIKE 'p%' AND c.[CardTypeID] = 1 ORDER BY [DateAdded] ) SELECT * from preResult WHERE rn = 1 
8643895 0 QTableView - change selection when scrolling

I have a QTableView. I want the selection to be moved when i scroll - so the cursor would be always visible.

enter image description here

There is QTableView.selectRow(rowNo), but do you have a suggestion where to call this?

Ideally i would like upon scrolling the selected row to be in the center.

35714038 0

You have to enable the allowable rotations at the project level and then restrict rotation on all the viewControllers you DON'T want to rotate. i.e. if you have 5 viewControllers, you'll need to restrict rotation on 4 of them and only allow rotation on the Player Controller. You can see more on this here Handling autorotation for one view controller in iOS7

3431255 0

Thanks to advice, I made it! Here is the code.

var foo = function(){}; foo.prototype = { say : function(s){ Queue.enqueue(function(){ alert(s); }); Queue.flush(); return this; }, delay : function(ms){ Queue.enqueue('delay:' + ms); return this; } } Queue = { entries : [], inprocess : null, enqueue : function(entry){ Queue.entries.push(entry); }, flush : function(){ if(Queue.inprocess) return; while (Queue.entries.length){ var entry = Queue.entries.shift(); if(entry.toString().indexOf('delay:') !== -1){ var ms = Number(entry.split(':')[1]); Queue.inprocess = setTimeout(function(){ Queue.inprocess = null; Queue.flush(); }, ms); return; } entry(); } } } 

I prepared a Queue object to manage functions' entries. With this, I can play with a method-chain:

var bar = new foo(); bar.delay(2000).say('Hello, ').delay(3000).say('world!'); 

Many thanks!

23850869 0

Return a pair of values containing the weight and value:

pair<int, int> knapsack(int N, int budget) { if((!N) || (!budget)) return pair<int, int>(0, 0); pair<int, int> local(N, budget); if(hash_memo[local].second) return hash_memo[local]; pair<int, int> b = pair<int, int>(0, 0); pair<int, int> a = knapsack(N-1, budget); if(budget >= arr[N-1].first) { pair<int, int> c = knapsack(N-1, budget - arr[N-1].first); b = pair<int, int>(c.first + arr[N-1].first, c.second + arr[N-1].second); } if(a.second > b.second) { return hash_memo[local] = a; } return hash_memo[local] = b; } 
22752345 0

I'm assuming you left some out, is this the complete code?

public class House { private final House house; public static void main(String[] args) { house = new House("Robinsons"); house.setColor("Red"); } public House(String houseName) { // do something } public void setColor(String color) { // do something } } 

If so, there are a number of problems with this.

  1. a final variable needs to be given a value right on declaration. And to answer your question, once a final variable is given a value (when declaring it), that will be the last time you can modify it. (refer to comments below, thanks exception1!).
  2. House is not a static variable, so it cannot be accessed from inside the main method, either make house a static variable, which I wouldn't recommend. Or declare an instance inside the main method before using it.
14378969 0 Google GCM demo app - Server messages not being received

I am trying to get the Google GCM demo app up and running. My android emulator makes a successful connection to the GCM server and goes on to make successful connection to my own server which is located at http://localhost:8080/gcm-demo-server (ie. the emulator sends the request to http://10.0.2.2:8080/gcm-demo-server).

However when I click 'Send message' on my server's webpage the message doesn't get delivered to the emulator. Nothing shows up in Logcat and my breakpoint in onMessage() in the GCMIntentService class doesn't get hit.

I can't understand how it can successfully register with the server, passing it's registrationId, yet when that registrationId is used to send a message back to the emulator it doesn't get received. I have not altered the demo app code.

Anyone ideas what could be going where or where I could start looking for problems as I don't even know where to start with this.

5721079 0 Issue with transferring of developer certificate and Provisioning Profile under Xcode

I am trying transfer my developer certificate under the keychain to someone. I exported the item. And also send him the provisioning profile which includes his device ID. He installed my certificate to his keychain and also the provisioning profile to his xcode. However, The provisioning profile under his xcode complains of there's no Valid signing Identity. Well I already sent him the certificate.

What's wrong?

15025659 0
if( browser.Button("id").Enabled) Console.Write("Enabled"); else Console.Write("Disabled"); 

you can try this.

10101095 0 Please explain the behaviour of Rails's cache in this case

Imagine I have 5 tags: tag1,tag2...tag5. If I do the following:

Rails.cache.fetch("all.tags") { Tag.all } 

and afterwards I write Rails.cache.fetch("all.tags"), I see the 5 tags. If I add another tag, and I try to fetch from the cache again, the new tag is also loaded. Why is that?

EDIT: Here's my actual code:

Rails.cache.fetch("autocomplete.#{term}") { puts "Cache miss #{term}"; Tag.starting_with(term) } 

Where starting_with is doing a where to find tags starting with certain letters. Here's the behaviour I get in the console:

1.9.3p125 :046 > Rails.cache.read("autocomplete.ta") Tag Load (1.0ms) SELECT "tags".* FROM "tags" WHERE (name like 'ta%') => [#<Tag id: 10, name: "tag1">, #<Tag id: 11, name: "tag2">, #<Tag id: 12, name: "tag3">, #<Tag id: 13, name: "tag4">] 1.9.3p125 :048 > Tag.create(name:"tag5") (0.2ms) begin transaction SQL (1.0ms) INSERT INTO "tags" ("name") VALUES (?) [["name", "tag5"]] (150.9ms) commit transaction => #<Tag id: 14, name: "tag5"> 1.9.3p125 :049 > Rails.cache.read("autocomplete.ta") Tag Load (0.8ms) SELECT "tags".* FROM "tags" WHERE (name like 'ta%') => [#<Tag id: 10, name: "tag1">, #<Tag id: 11, name: "tag2">, #<Tag id: 12, name: "tag3">, #<Tag id: 13, name: "tag4">, #<Tag id: 14, name: "tag5">] 
17066858 0

It is a typo indeed

<? require($_SERVER["DOCUMENT_ROOT"] . '/WestAncroftSettings.php' ); ?> 

should be

<?php require($_SERVER["DOCUMENT_ROOT"] . '/WestAncroftSettings.php' ); ?> 

and later in your code you have the same line again without <?php and your missing quotes around DOCUMENT_ROOT

38098717 0 Running praat on remote ubuntu server

I am working for a web application using praat features. I have written a script for that and it is working fine in ubuntu. But now i want to run these .praat scripts in a remote ubuntu server and I have already installed praat but when I run praat it gives me the following error:

(praat:1364): GLib-GObject-WARNING **: invalid (NULL) pointer instance

(praat:1364): GLib-GObject-CRITICAL **: g_signal_connect_data: assertion 'G_TYPE_CHECK_INSTANCE (instance)' failed

(praat:1364): Gtk-WARNING **: Screen for GtkWindow not set; you must always set a screen for a GtkWindow before using the window

(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_default_colormap: assertion 'GDK_IS_SCREEN (screen)' failed

(praat:1364): Gdk-CRITICAL **: IA__gdk_colormap_get_visual: assertion 'GDK_IS_COLORMAP (colormap)' failed

(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_default_colormap: assertion 'GDK_IS_SCREEN (screen)' failed

(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed

(praat:1364): Gdk-CRITICAL **: IA__gdk_screen_get_root_window: assertion 'GDK_IS_SCREEN (screen)' failed

(praat:1364): Gdk-CRITICAL **: IA__gdk_window_new: assertion 'GDK_IS_WINDOW (parent)' failed Segmentation fault (core dumped)

Please tell me way a that I can run a praat script in remote ubuntu server.

11334903 0

I guess you are not using server side code. If that is the case, I suggest you to read this short tutorial on Javascript and cookies from w3schools:

http://www.w3schools.com/js/js_cookies.asp

26632555 0

I think that instead of build a table of images I would put the first image and I would store the url of the others images ina javascript variable. Then, when you want to load the others images (timer, click event, ...) you just have to change the src parameter of the original image.

39902288 0 Opening a form, closing it, then opening it again in the same location

I have a pop up selector for my main form that comes up when I click a button. After I make my selection the box is closed and I continue my work in the main form. However if I go to click that button again, the pop up will appear slightly under where it had opened up previously. Is there a way to fix this so that every time that form is opened it opens in the same spot?

6968494 0

Perhaps the problem is already at the point where you malloc your data. It gets past around wrong (0x4 isn't plausible) so probably you already have had problems there. A common error is to forget to include the header file and have malloc interpreted as returning int per default rules.

Casting almost always hides a programming or, worse, design error:

3797219 1 object oriented programming basics (python)

Level: Beginner

In the following code my 'samePoint' function returns False where i am expecting True. Any hints?

import math class cPoint: def __init__(self,x,y): self.x = x self.y = y self.radius = math.sqrt(self.x*self.x + self.y*self.y) self.angle = math.atan2(self.y,self.x) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) class pPoint: def __init__(self,r,a): self.radius = r self.angle = a self.x = r * math.cos(a) self.y = r * math.sin(a) def cartesian(self): return (self.x, self.y) def polar(self): return (self.radius, self.angle) def samePoint(p, q): return (p.cartesian == q.cartesian) >>> p = cPoint(1.0000000000000002, 2.0) >>> q = pPoint(2.23606797749979, 1.1071487177940904) >>> p.cartesian() (1.0000000000000002, 2.0) >>> q.cartesian() (1.0000000000000002, 2.0) >>> samePoint(p, q) False >>> 

source: MIT OpenCourseWare http://ocw.mit.edu Introduction to Computer Science and Programming Fall 2008

4612798 0 In SQL Server 2008, how do I check if a varchar parameter can be converted to datatype money?

I've got a stored procedure I use to insert data from a csv. The data itself is a mix of types, some test, some dates, and some money fields. I need to guarantee that this data gets saved, even if it's formatted wrong, so, I'm saving them all to varchars. Later, once the data's been validated and checked off on, it will be moved to another table with proper datatypes.

When I do the insert into the first table, I'd like to do a check that sets a flag (bit column) on the row if it needs attention. For instance, if what should be a money number has letters in it, I need to flag that row and add the column name in an extra errormsg field I've got. I can then use that flag to find and highlight for the users in the interface the fields they need to edit.

The date parameters seem to be easy, I can just use IF ISDATE(@mydate) = '0' to test if that parameter could be converted from varchar to datetime. But, I can't seem to find an ISMONEY(), or anything that's remotely equivalent.

Does anyone know what to call to test if the contents of a varchar can legitimately be converted to money?

EDIT: I haven't tested it yet, but what do you think of a function like this?:

CREATE FUNCTION CheckIsMoney ( @chkCol varchar(512) ) RETURNS bit AS BEGIN -- Declare the return variable here DECLARE @retVal bit SET @chkCol = REPLACE(@chkCol, '$', ''); SET @chkCol = REPLACE(@chkCol, ',', ''); IF (ISNUMERIC(@chkCOl + 'e0') = '1') SET @retVal = '1' ELSE SET @retVal = '0' RETURN @retVal END GO 

Update

Just finished testing the above code, and it works!

27756694 0

To change from a many-to-many relationship to a one-to-one, start by removing the best_friends table.

friends = db.Table('friends', db.Column('user_id', db.Integer, db.ForeignKey('user.id')), db.Column('friend_id', db.Integer, db.ForeignKey('user.id')) ) 

You then want to add a foreign key to User that references another User.

class User(db.Model): id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(50), index=True, unique= True) email = db.Column(db.String(50),index=True, unique= True) bestfriend_id = db.Column(db.Integer, db.ForeignKey('user.id')) bestfriend = db.relationship('User', remote_side=['id'], lazy='dynamic') def are_bestfriends(self, user): return self.best_friend == user def be_bestfriend(self, user): if not self.are_bestfriends(user): self.bestfriend = user user.bestfriend = self return self 
12452961 0 How to get city code weather in AccuWeather?

Have someone ever use AccuWeather to search your country weather? I want to get my city weather code in AccuWeather who can help me? The code generate has form like this: EUR|DE|GM014|TORGAU. I can't find my city code (Phnom Penh, Cambodia)

25054125 0 ASP MVC / EF6 - Automatic logging

Every table of my database has got 2 columns at the end, which allows logging (User who made the action, and Date of the action). EDIT : I use Code-First migrations.
So I would like those two logging columns to be filled automatically :

  1. Each time I insert a new entry in my table (using DbContext.[Model].Add(entry))

  2. OR each time I do a DbContext.SaveChanges() action


I have considered overriding the DbContext.SaveChanges() method, but it didn't work out...

I have also tried overriding the DbSet Add() method, to do the log filling action there. For that I have created a CustomDbSet class which inherits from DbSet :

public class CustomDbSet<TEntity> : DbSet<TEntity> where TEntity : class { public TEntity Add(TEntity entity) { //Do logging action here return base.Add(entity); } } 

But this didn't make it neither.
EDIT : What happens with this CustomDbSet is that any DbContext.[Model] returns null, now (instead of being filled with the content of the database table)

I already have the extension method which will do the logging action, but I don't know where to put it so logging would become an "automatic" action..

public static void EntityLogCreate<T>(this T model, string userName) where T : LogColumns { model.Create_User = userName; model.Create_Date = DateTime.Now; } 

Any idea to achieve that ?

1514725 0

Usually when I have come across this it has been a fatal error in PHP somewhere. Have a look at your PHP-cgi log to see if it is in there. There should be something in the nginx log like this: 104: Connection reset by peer. Depending on your setup this (sorry, link dead) might help but if you're using php-fpm it won't.

13046854 0 jQuery on() method is firing more than one time

I made some jQuery code for preventing users from typing chars but only numbers:

 $("div").on("keydown", ":text", checkKey); function checkKey(e) { var n = e.keyCode; if (n == 13) { $(this).closest("form").submit(); console.log('enter'); } else if (e.shiftKey || e.ctrlKey || e.altKey) { e.preventDefault(); } else { if (!((n == 8) || (n == 46) || (n == 9) || (n >= 35 && n <= 40) || (n >= 48 && n <= 57) || (n >= 96 && n <= 105)) ) { e.preventDefault(); console.log('ok'); } } } 

end in html:

 <div> <input type="text" id="test" /> </div> 

but whenever I type something, it seems it's being fired three times for example for one pressing enter I get three 'enter' in console and for numbers I get three 'ok', why is that? I also replaced it with delegate and live, live worked fine but delegate also was fired three times. thanks.

22503882 0 What does the read call return on earth if there are already both FIN and RST in the TCP buffer?

Assuming that the client and server send packets according to the order of sequence as shown in the figure, the client does not know FIN has arrived.

It sends “hello again” to the server, the server responds to the client with an RST and the RST has arrived. Then if the client is blocking on a read, why it return 0 due to the FIN instead of -1 because the RST? In the 《Effective TCP/IP programming》, it tells us that the core will return ECONNRESET error.

My operating system is Ubuntu 12.10. Is it related with the operating system? Please tell me some TCP’s details on this implementation. Thanks in advance.

enter image description here

25872507 0 Give user input for batch file via c# code

I have a batch file which is asking for some user input text in the middle of that process. I need to run this batch file through c# code. I cannot change the bat file. So the option having command line arguments also is not working for me. Is there any way that i can provide the input when it prompts?

12585443 0

Use mysql_fetch_row()to get the $amount_data.Mysql_query() returns only the resouce id

$amount_data = mysql_query ("SELECT * FROM subscriber WHERE payment_amount = '$payment_amount' AND id = '$id' "); $row = mysql_fetch_row($amount_data); echo $row[0]; 

Check the link http://php.net/manual/en/function.mysql-fetch-row.php

2791931 1 Speed vs security vs compatibility over methods to do string concatenation in Python

Similar questions have been brought (good speed comparison there) on this same subject. Hopefully this question is different and updated to Python 2.6 and 3.0.

So far I believe the faster and most compatible method (among different Python versions) is the plain simple + sign:

text = "whatever" + " you " + SAY 

But I keep hearing and reading it's not secure and / or advisable.

I'm not even sure how many methods are there to manipulate strings! I could count only about 4: There's interpolation and all its sub-options such as % and format and then there's the simple ones, join and +.

Finally, the new approach to string formatting, which is with format, is certainly not good for backwards compatibility at same time making % not good for forward compatibility. But should it be used for every string manipulation, including every concatenation, whenever we restrict ourselves to 3.x only?

Well, maybe this is more of a wiki than a question, but I do wish to have an answer on which is the proper usage of each string manipulation method. And which one could be generally used with each focus in mind (best all around for compatibility, for speed and for security).

Thanks.

edit: I'm not sure I should accept an answer if I don't feel it really answers the question... But my point is that all them 3 together do a proper job.

Daniel's most voted answer is actually the one I'd prefer for accepting, if not for the "note". I highly disagree with "concatenation is strictly using the + operator to concatenate strings" because, for one, join does string concatenation as well, and we can build any arbitrary library for that.

All current 3 answers are valuable and I'd rather having some answer mixing them all. While nobody volunteer to do that, I guess by choosing the one less voted (but fairly broader than THC4k's, which is more like a large and very welcomed comment) I can draw attention to the others as well.

31377154 0

Expand the size of your q1 buffer. scanf("%s", q1) doesn't have enough room to store the input. Remember that C uses a null character '\0' to terminate strings. If you don't account for that, the buffer could overrun into other memory causing undefined behavior. In this instance, it's probably overwriting memory allocated to name, so name ends up pointing to "\0ick". This causes printf(%s), which looks for '\0' to know when to stop printing, to think that the string is shorter than it really is.

The code works perfectly if you expand the buffer:

#include <stdlib.h> #include <stdio.h> #include <string.h> int main(void) { char name[50]; char q1[50]; printf( " What is your name?\n"); scanf("%49s", name); printf( " Hi %s, Do you want to have some fun? [Y/N]\n",name); scanf("%49s",q1); if(strcmp(q1,"Y") == 0||strcmp(q1,"y")==0) { printf("Awesome, let's play!\n"); } else { printf("Fine"); } printf( "So %s, it's time to get started\n", name); getchar(); return 0; } 

Output:

 What is your name? Nick Hi Nick, Do you want to have some fun? [Y/N] y Awesome, let's play! So Nick, it's time to get started 

Note that I've added the qualifier %49s to avoid buffer overruns like this.


You could also circumvent the need for another string entirely by changing char q1[50] and scanf("%49s") to simply char q1 and scanf("%c%*c", &q1) (note the "address of" operator because q1 is no longer a pointer).

You'll probably even get a performance gain from this (albeit small), because strings are notorious memory hoggers. Comparing a single character is usually preferred over comparing strings.

#include <stdlib.h> #include <stdio.h> #include <string.h> int main(void) { char name[50]; char q1; printf( " What is your name?\n"); scanf("%49s%*c", name); printf( " Hi %s, Do you want to have some fun? [Y/N]\n",name); scanf("%c%*c",&q1); if(q1 == 'Y' || q1 == 'y') { printf("Awesome, let's play!\n"); } else { printf("Fine"); } printf( "So %s, it's time to get started\n", name); getchar(); return 0; } if(q1 == 'Y' || q1 == 'y') { printf("Awesome, let's play!\n"); } else { printf("Fine"); } printf( "So %s, it's time to get started\n", name); getchar(); return 0; } 

If you go this route, you have to ignore the enter key using the format specifier %*c because pressing enter sends a key to the stream as well.

6224276 0 Problem comparing extremes

I'm trying to sort trough a list of 32-bit numbers using MIPS assembler and xspim. I've been stepping trough my code to see what fails and noticed that when comparing 0x00000000 with 0xFFFFFFFF it doesn't switch those numbers as it should. At the point where the program fails I got 0x00000000 in $t3 and 0xFFFFFFFF in $t4 and it looks like this.

bge $t3,$t4,lol #So if t3 is greater than or equal I should jump forward else continue. Now the problem is that the program jumps even though t3 is smaller.

28739363 0

I'm not sure where you quoted that from, it doesn't appear in the documentation at all. To actually quote from the documentation:

The HashSet<T> class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the Dictionary<TKey, TValue> or Hashtable collections. In simple terms, the HashSet<T> class can be thought of as a Dictionary<TKey, TValue> collection without values.

So it is a collection, containing actual values. The sentence you quoted there is false.

That being said, you could create an ISet<T> implementation that works that way, e.g. representing numbers in a set as ranges. But trying to do that with a vanilla HashSet<T> will quickly break down.

31699416 0

Use an initializer parameter:

static char calc_crc(char init, unsigned char *data, unsigned len) { for ( int i = 0 ; i < len; i++ ) init = init ^ data[i]; return init; } 

Then you can do result=calc_crc(calc_crc(0,buffer1,buffer1len), buffer2, buffer2len);

17294712 0

I can't quite make out what you're trying to say. Are the folders still empty, or is there content in them now?

Git doesn't track folders, it only tracks files. So you can't add an empty folder into the Git repo, if that's what you're trying to do. If you really want the directory there, the standard practice is to add an empty .gitkeep file into it, so that Git has some content to track there. Then you would git add foldername and commit it.

20225904 0

Have a look at the documentation on the website but pretty sure it should be like below:

has_attached_file :avatar, :styles => { :thumb => ["32x32#", :png] } 

https://github.com/thoughtbot/paperclip

Under post processing

Guess your issue is here:

@format = options[:format] @basename = File.basename(@file.path, @current_format) temp_file = Tempfile.new([@basename, @format].compact.join(".")) 
33630716 0

You installed a jquery module as global module.

Loading local modules

If the module identifier passed to require() is not a native module (e.g. http), and does not begin with '/', '../', or './', then Node.js starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.

If it is not found there, then it moves to the parent directory, and so on, until the root of the file system is reached.

Loading global modules

To make global modules available to the Node.js (and CoffeeScript) REPL, it might be useful to also add the /usr/lib/node_modules folder to the $NODE_PATH environment variable. Since the module lookups using node_modules folders are all relative, and based on the real path of the files making the calls to require(), the packages themselves can be anywhere.

1303660 0

Tough to answer without knowing more. Drupal is not very strong if all you're doing is building [x], where [x] is an online store, blog, forum, rss aggregation site, etc. We recently retooled our company store in Drupal using the Ubercart plugin suite, though, and were able to exercise a lot of control over the final results -- and more importantly, intgrate it better with the rest of our site's content.

That's where the real win is -- if you have lots of existing content and/or community, and you want that integrated smoothly with your store. We can do things like auto-suggest products from the store that match the tags on the articles a user is reading, give people access to private forums on our main site based on purchases they make in the store, etc.

If you aren't already an old hand with Drupal, and you don't need that kind of connection, it's probably better to go with a dedicated solution.

(Random notes: Article about putting up the store, podcast about same)

6681159 0

Instead of messing about with errorformat, just set cscopequickfix and use the normal :cscope commands. eg. (from vim help)

:set cscopequickfix=s-,c-,d-,i-,t-,e- 

Edit

You could also use a filter like the following to reorder the fields

sed -e 's/^\([^ ]\+\) \([^ ]\+\) \([^ ]\+\) \(.*\)$/\1 \3 \4 inside \2/' 

set it to filter your message, then use the efm

errorformat=%f\ %l\ %m 
4693000 0

Your problem is the space after CMD=. This evaluates to CMD=<empty string> "git --version". First, the environment variable CMD is set to an empty string, then the command git --version is called. Notice that due to the "..." the shell really tries to execute a command git --version and not git with argument --version. Simple remove the space between = and " to fix this.

3043018 0

Since CMIS was approved as a standard last month, the new best way to achieve this is probably via CMIS, as explained here.

10330814 0

Use REST; REST is nothing more than using plain HTTP 'better'. Since you are already using HTTP, somehow you are already doing REST like calls and moving these calls to full fledged REST will be easy.

Implementing REST calls is easy. You have two approaches:

Don't use SOAP. The only reason you would want to use SOAP is that you want to contractualise using a WSDL what you are exposing (you can do the same with REST btw, see the Amazon documentation for instance). Trust me, SOAP is way too heavy and confusing for what you are trying to do.

34693184 0

Do I need to include ;WITH CTE_Backup AS at the beginning of the query when I use it in Java code?

Yes you should, otherwise use simple subquery:

SELECT D.name ,ISNULL(CONVERT(VARCHAR,backup_start_date),'No backups') AS last_backup_time ,D.recovery_model_desc ,state_desc, CASE WHEN type ='D' THEN 'Full database' WHEN type ='I' THEN 'Differential database' WHEN type ='L' THEN 'Log' WHEN type ='F' THEN 'File or filegroup' WHEN type ='G' THEN 'Differential file' WHEN type ='P' THEN 'Partial' WHEN type ='Q' THEN 'Differential partial' ELSE 'Unknown' END AS backup_type ,physical_device_name FROM sys.databases D LEFT JOIN ( SELECT database_name,backup_start_date,type,physical_device_name ,Row_Number() OVER(PARTITION BY database_name,BS.type ORDER BY backup_start_date DESC) AS RowNum FROM msdb..backupset BS JOIN msdb.dbo.backupmediafamily BMF ON BS.media_set_id=BMF.media_set_id ) AS CTE ON D.name = CTE.database_name AND RowNum = 1 ORDER BY D.name,type; 

Common Table Expression is nice readable way to introduce derived tables.

14462559 0

One solution is to translate the mesh geometry, and compensate by changing the mesh position, like so:

var offset = objMesh.centroid.clone(); objMesh.geometry.applyMatrix(new THREE.Matrix4().makeTranslation( -offset.x, -offset.y, -offset.z ) ); objMesh.position.copy( objMesh.centroid ); 

updated fiddle: http://jsfiddle.net/Ldt7z/165/

P.S. You do not need to save your fiddle before running it. There is no reason to have so many versions.

three.js r.55

36542725 0

Niknam ansuwer is perfect and I want to add if you use tor just add in your environment

export _JAVA_OPTIONS="-DsocksProxyHost=127.0.0.1 -DsocksProxyPort=9050" 
2651470 0

The most common path is to include a licensing notice at the top of files inside block comments - that's the way most likely to ensure that anyone utilizing the code is aware of the license, since the only possible way for it to be decoupled from the code is someone intentionally removing it.

31319822 0 Modal is coming back undefined in directive

Google is giving me the error: "TypeError: Cannot read property 'open' of undefined" in response to my ui-bootstrap module. I've been using other ui-bootsrap directives fine.

Am I not declaring the modal dependency correctly?

angular.module('ireg').directive('study', function (studyFactory) { return { restrict:'E', scope: { objectid:'@objectid' }, templateUrl: '/ireg/components/study/study.html', link: function (scope, element, attrs, $modal) { scope.openMilestonesDialog = function () { var modalInstance = $modal.open({ animation: $scope.animationsEnabled, templateUrl: '/ireg/components/add-milestones/addMilestonesDialog.html', controller: '/ireg/components/add-milestones/addMilestonesDialogController.js', size: lg }); }; }//end of link } }); angular.module('ireg').controller('addMilestonesDialogController', function ($scope, $modalInstance, studyId) { $scope.ok = function () { $modalInstance.close(); }; }); 
34939698 0

out.println () is a little ugly in terms of readability - but the cost of these calls will be small compared to I/O times.

Using + for String concatenation inside your loop might harm your memory footprint (and it's not the fastest way either). Consider this line you have:

 out.println("<td>"+ rs.getString("FirstName") + " " + rs.getString("LastName") + "</td>"); 

You could gain readability and speed and have less char [] left to be garbage collected by coding with format():

 out.format ("<td>%s %s</td>", rs.getString ("FirstName"), rs.getString ("LastName")); 

More Notes

You create and connect a new database connection every time your servlet is called. This will severly impact your performance and scalability. You should consider using a connection pool from which you fetch pre-connected Connections. The performance you gain will make up for very many String concats or println calls.

3186544 0 iOS4 and audio playback during backgrounding

When my app is backgrounded, the audioplayer continues to play, but i cant hear any sound. When i open my app again, it plays from the point where it would have been had the app not been backgrounded at all. This shows that the app is playing in the background though it is not audible. Why could this be happening?

I have set the audio key in the info.plist for the UIBackgroundModes array. Also my audioplayer is set to the "AVAudioSessionCategoryPlayback" category with an override to allow for audio mixing. So what am i doing wrong that im unable to hear the audio even though it is playing in the background?

Could this be an issue with the simulator alone as i have not been able to test this on a device with iOS4 so iv only been testing it on the simulator.

2633115 0 Java GUI File Menu

I have a GUI with a Menu named file

how do I Add a file open and close function to the program. If the program is in the encrypting mode, it should load/save the cleartext text area. If the program is in decrypting mode, it should load/save the ciphertext area.

40014705 0 How to convert a “String” value to “Type” in Angular 2 TS

This is my current object, Home refers to my import

import { Home } from '../home/home'; arr = [ { name: "Home", root: "Home", icon: "calc" } ]; 

This is what i want to achieve:

 import { Home } from '../home/home'; arr = [ { name: "Home", root: Home, icon: "calc" } ]; 

Im getting a error because "Home" is a string. eval() works but i'm looking for a alternative

Working code:

 for (var i = 0; i < arr.length; i++) { arr[i].root = eval(arr[i].root); } 
13516947 0 how to make a connection to datastore inside jstl tags

I'm making a project on Google App Engine and in one of my jsp files, I want to search an entry in my datastore. I normally do this search by clicking on a button on this jsp page, then I make the connection to datastore in a servlet and then I send the query results to jsp back . Well, I want to query datastore without clicking this button. When I load the page, I want to see the query results on my page. When I was using EL tag lib, I could do that by just typing <% %>, now I'm using jstl tag lib. So is there any way to do ? After using jstl tags, I'm not able to use EL tags.

26092740 0

System.out.println((int)(5.4%((int)5.4)*10));

Basically 5.4 mod 5 gets you .4 * 10 gets you 4.

6604248 0 Unit test which requires a file in Request.Files

I'm writing a unit test and the piece of code its testing requires that a file be in Request.Files.

In my controller I'm calling something called AddDocument(file) and the file is taken from Request.Files.

How do you achieve unit testing this? Isn't the Request only available in the controller?

29722509 0 Foreach loop - three columns(dynamic) table layout

i have the below code, which will create a table with three columns.

<?php $t = array(' 1 ' , ' 2 ' ,' 3 ', ' 4 ' , ' 5 '); $count = 0; $col =3; echo '<table><tr>'; foreach($t AS $r){ $count++; echo '<td> '.$r.' </td>'; if($count == $col){ echo '</tr><tr>'; $count = 0; } } echo '</tr></table>'; ?> 

but what i really want is for the first column to have at least 4 rows before creating a new column and so on. max number of columns is 3 and each column should have at least 4 rows.

10580465 0 How can I populate Viewmodel list collection

How can I populate list collection in ViewModel

Controller:

 SchoolEntities db = new SchoolEntities(); public ActionResult Index() { var student= from s in db.Students select s.Name.ToList(); return View(); } 

ModelView:

 public List<Student>students { get; set;} 
23015705 0

Try this....

ScriptManager.RegisterStartupScript(this, this.GetType(), "onclick", "javascript:window.open( 'SomePage.aspx','_blank','height=600px,width=600px,scrollbars=1');", true); 
9039733 0

I believe it's working the way it's supposed to. If you want arrivingLabelRed to end with it's alpha at 0 you should set it that way in the completion block.

20014967 0 How can remove white screen when page changes one to another page?

I have done my application in iphone using phonegap and jquery mobile. It is major project and it is totally completed. But there is one problem , in application pages load using rel="external" , when page changes one to another page in between 2 to 3 seconds screen display totaly white, that time don't want to display white screen. Anybody idea what can we do for that ? and don't reply with remove rel="external".

9626322 0 Apache + NginX reverse proxy: serving static and proxy files within nested URLs

I have Apache running on my server on port 8080 with NginX running as a reserve proxy on port 80. I am attempting to get NginX to serve static HTML files for specific URLs. I am struggling to write the NginX configuration that does this. I have conflicting directives as my URLs are nested within each other.

Here's what I want to have:

I have set up my nginx.conf file like this:

server { listen 80; server_name localhost; # etc... location / { proxy_pass http://127.0.0.1:8080/; } # etc... 

My attempt to serve the static file at /example/ from NginX went like this:

 location /example/ { alias /path/to/www/; index example-content.html; } 

This works, but it means everything after the /example/ URL (such as /example/images/) is aliased to that local path also.

I would like to use regex instead but I've not found a way to serve up the file specifically, only the folder. What I want to be able to say is something like this:

 location ~ ^/example/$ { alias /path/to/www/example-content.html; } 

This specifically matches the /example/ folder, but using a filename like that is invalid syntax. Using the explicit location = /example/ in any case doesn't work either.

If I write this:

 location ~ ^/example/$ { alias /path/to/www/; index example-content.html; } location ~ /example/(.+) { alias /path/to/www/$1; } 

The second directive attempts to undo the damage of the first directive, but it ends up overriding the first directive and it fails to serve up the static file.

So I'm at a bit of a loss. Any advice at all extremely welcome! Many thanks.

33573673 0 Hiding flyout of a button

I got my DataTemplate for items and within this DataTemplate I have such code:

<Button x:Name="DoneButton" Style="{StaticResource ButtonStyle1}" BorderThickness="1" Margin="0,0,20,0" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="2" Grid.Row="1" Width="50" Height="50" > <Image Source="Images/WPIcons/checked.png" Width="30" Height="30" Margin="-10,0,-10,0" /> <Button.Flyout> <Flyout x:Name="myFly"> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <TextBlock Grid.Row="0" x:Uid="myNote" Text="Note: " Style="{StaticResource myText}" /> <TextBox Grid.Row="1" TextWrapping="Wrap" AcceptsReturn="True" Height="40" x:Name="note" Text="{Binding RecentNote, Mode=TwoWay}" Style="{StaticResource TextBoxStyle1}"/> <Button x:Name="CompletedButton" Command="{Binding CompletedCommand}" CommandParameter="{Binding}" Style="{StaticResource ButtonStyle1}" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="2" Click="CompletedButton_Click" Content="Done" MinWidth="80" Height="40" /> </Grid> </Flyout> </Button.Flyout> </Button> 

After the flyout for the item has been called and user put his data in it I want to hide this flyout as soon as user hits the "Done" button (x:Name="CompletedButton").

I tried to do that in code behind like:

private void CompletedButton_Click(object sender, RoutedEventArgs e) { Button button = (Button)sender; Grid grid = (Grid)VisualTreeHelper.GetParent(button); Flyout fly = (Flyout)VisualTreeHelper.GetParent(grid); fly.Hide(); } 

But I get cast exception with that I can't cast ContentPresenter to Flyout so I guess it's not the way I look for. How I can hide this flyout?

22359144 0

use [[NSDate date] timeIntervalSince1970]

4482058 0

The keyword DISTINCT is used to eliminate duplicate rows from a query result:

SELECT DISTINCT ... FROM A JOIN B ON ... 

However, you can sometimes (possibly even 'often', but not always) avoid the need for it if the tables are organized correctly and you are joining correctly.

To get more information, you are going to have to ask your question more clearly, with concrete examples.

36864836 0 How to register a post type and taxonomy in WordPress and display in a page/single post

I have a question about WordPress register post type:

How can I register a post type like portfolio?

For example: In the WordPress dashboard, I can register a post type and taxonomy. After this I want to create a page to display all the portfolio and taxonomies like (portfolio.php) and display a single portfolio in a (single-portfolio.php).

Can someone explain this for me please?

4254487 0

Try setting up a view in the DB that applies the security filter to the records as needed, and then when retrieving records through L2S. This will ensure that the records that you need will not be returned.

Alternatively, add a .Where() to the query before it is submitted that will apply the security filter. This will allow you to apply the filter programmatically (in case it needs to change based on the scenario).

26187227 0 Is this myFile = SD.open("test.txt", FILE_WRITE); class object usage good/possible in cpp

I have created a class object named myFile for a class File which is present in one of my cpp files (FILE.cpp) which I am calling in another file(SDtrail.cpp) where I am working on.

In SDtrail.cpp file I have defined a statement as shown below myFile = SD.open("test.txt", FILE_WRITE);

So, my doubt is can I declare like above statement or not as I think that this is the root cause of the following errors

error: no match for 'operator=' in 'myFile = SDClass::open(const char*, uint8_t)(((const char*)"test.txt"), 19u)'

error: could not convert 'myFile' to 'bool'

I know that SD.open("test.txt", FILE_WRITE); will provide 1(success) or 0(fail) as output and myFile is an object of my File class ( I have declared it as File myFile). I don't know whether a class object consists of a type declaration. (FYI: myFile = SD.open("test.txt", FILE_WRITE); worked perfectly when I ran that in my Arduino software and when I have printed the myFile variable I got 1 as an output.)

Thanks in advance.

34832022 0

Use another variable:

int dist=fillUps[index].calcDistance(); //or double, depands on the method's returning value fillUps[index].calcMPG(dist); 
25143478 0

Depending on which type of database you are using (SQL, Oracle ect..);To take the Previous days votes you can usually just subtract 1 from the date and it will subtract exactly 1 day:

Where Cast(Posts.modification_date - 1 as Date) = Votes.vote_date 

or if modification_date is already in date format just:

Where Posts.modification_date - 1 = Votes.vote_date 
28354179 1 Why would django fail with server 500 only when Debug=False AND db is set to production database on Heroku?

When we run $ python manage.py runserver --settings=project.settings.local there are 4 different possible combinations:

  1. Debug=True && DB=local => Runs fine
  2. Debug=True && DB=production => Runs fine
  3. Debug=False && DB=local => Runs fine
  4. Debug=False && DB=Production => Server 500 error

The fourth one is simultaneously: the most important, the hardest to debug, and the only one that fails.

Our django settings are setup with this structure:

settings ├── base.py ├── __init__.py ├── local.py └── production.py 

For this test we only used local.py and modified the contents for each run.

For Debug=True and DB=local this is the local.py file:

from project.settings.base import * DEBUG = True TEMPLATE_DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ***, 'USER': ***, 'PASSWORD': ***, 'HOST': 'localhost', 'PORT': '5432', } } 

For Debug=False and DB=production this is the local.py file used:

from project.settings.base import * ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ***, 'USER': ***, 'PASSWORD': ***, 'HOST': '***.amazonaws.com', 'PORT': '5432', } } 

We also ran it with Debug=True and DB=production as well as Debug=False and DB=local, both of which worked.

The DB settings were copied directly from the Heroku configuration and the connection to the database works great as long as Debug is set to True, so we're pretty sure it's not a DB schema or connection problem. We just can't figure out how it's possible that the production DB works when Debug is True, and it runs with DB set to False with the local DB, but for some reason when the two are combined it fails. We've also deployed the code to Heroku and confirmed that it runs with Debug set to True but fails with the same Server 500 error when Debug is set to False.

For reference, this is the contents of our base.py:

import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = *** # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'appname', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'project.urls' WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.6/ref/settings/#databases SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Internationalization # https://docs.djangoproject.com/en/1.6/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.6/howto/static-files/ STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) 

Our googling has come up with a lot of people misconfiguring the ALLOWED_HOSTS variable and ending up with similar symptoms but that doesn't seem to be our problem. Does anybody have any insight as to what could be causing this problem?

As requested, here is production.py, although it should be noted that this settings file was never used in this experiment.

from project.settings.base import * import dj_database_url DEBUG = False TEMPLATE_DEBUG = False ALLOWED_HOSTS = ['*', '.***.com', '.herokuapp.com', 'localhost', '127.0.0.1'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': ***, 'USER': ***, 'PASSWORD': ***, 'HOST': '***.amazonaws.com', 'PORT': '5432', } } STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' 
1164933 0 WPF RibbonControlLibrary

Can anyone tell me how to download Wpf RibbonControlLibrray and how to use it?

26320408 0

You can use that, im not using the prettiest way, but you can write a new accessor that injects that methods.

Classes:

class Container def property=(arg) arg.called_from = self.class @arg = arg end def property @arg end end class SomeClass def container_class @klass end def called_from=(klass) @klass = klass end end 

Spec:

require_relative 'container' describe Container do let(:container) { Container.new } it 'passes message' do container.property = SomeClass.new expect(container.property.container_class).to eq Container end end 
11325145 0 Team City nightly build fails to start

I have a Team City instance running on my PC.

I've set up a nightly build to run at midnight each night, even if there are no checkins to build.

I leave the PC locked at night so assume the build should trigger.

However I keep getting "Unable to collect changes", "Failed to start build", "Failed to collect changes, error: org.tmatesoft.svn.core.SVNException: svn: E210003: Unknown host MySVNServer".

If I set the build to run during the day, it triggers fine, even when the PC is locked.

I have a checkin triggered build, and a couple of others for 1 off ad-hoc builds to the same environment, they all run fine.

Will Team City build fail if I am not "logged in", is the fact the PC is locked causing the issue?

36252837 0 Get parts of string after a certain word? Shell

I have the following variable that contains a string displaying folders in a dir tree:

root/f1/f2/f3/f4/f5 root/f1/f2/f3/f4 root/f1/f2/f3 

How would I go about removing everything that is before f2 so what I'm left with will be:

f2/f3/f4/f5 f2/f3/f4 f2/f3 

?

34221557 0 NodeJS/Express Service down error handling

I have my client which is developed in angular and i am trying to hit my api service[rest-ful].

If my service/server is down, how can i notify my client saying its down?

POST http://localhost:3000/login net::ERR_CONNECTION_REFUSED 

In my console all i am getting is this error message,

api.login(username, password).success(function(response) { }).error(function(response, error){ //i am not getting any error message here. }); 

The login method is just a $http call

login: function (username, password) { return $http.post('http://localhost:8080/login', { username: username, password: password }); } 
22610166 0

You can bind Media Element directly from the view model

in xaml:

<ContentControl Content="{Binding MediaElementObject}"/> 

in ViewModel:

private MediaElement _mediaElementObject; public MediaElement MediaElementObject { get { return _mediaElementObject; } set { _mediaElementObject = value;RaisePropertyChanged(); } } 

And on OnNavigatedTo Override method you can create it's new object & can register it's events.

MediaElementObject=new MediaElement(); 

So that you can do all thing from the viewmodel itself.

35665366 0

Try to clean your project and rebuild it

28979557 0

see this Fiddle

you just need to set hours to midnight 12. You can do it like this d.setHours(0,0,0,0);

var today = true; var d = new Date(), till = new Date(), t, h, m; d.setHours(0, 0, 0, 0); if (today) { till.setDate(d.getDate() + 1); till.setHours(0, 0, 0, 0); while (d <= till) { h = d.getHours(); m = d.getMinutes(); t = h % 12; t = t == 0 ? 12 : t; $('#time').append('<li>' + (t < 10 ? '0' : '') + t + ':' + (m < 10 ? '0' : '') + m + ' ' + (h < 12 || h == 24 ? 'AM' : 'PM') + '</li>'); d.setMinutes(m + 15); } } else { // print full list of time }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="time"></div>

18253824 0 Extracting XML elements which contains a certain string with sed

I have a file like below

 <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show databases"/> <AUDIT_RECORD TIMESTAMP="2013-07-29T17:27:53" NAME="Quit" CONNECTION_ID="12" STATUS="0"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show grants for root@localhost"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="create table stamp like paper"/> 

Here each record begin with <AUDIT_RECORD and end with "/> and the record might spread across multiple lines.

My requirement is to display result like below

 <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show databases"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="show grants for root@localhost"/> <AUDIT_RECORD TIMESTAMP="2013-07-30T17:52:29" NAME="Query" CONNECTION_ID="10" STATUS="0" SQLTEXT="create table stamp like paper"/> 

for that purpose I have used

sed -n "/Query/,/\/>/p" file.txt 

but it is displaying the entire file including the record with the string "Quit".

Can anyone help me regarding this? Also please let me know if it is possible to match exactly string named "Query" ( like grep -w "Query" ).

37749406 0

For example if brand id is 100:

select b.id, sum(h.points),h.brandId from brands b left join histories h on b.id = h.brandid and h.userId = 2866 where b.id=100 group by b.id limit 1; 
27559237 0 Possible arrangements of binary vectors keeping sum fixed in R

Suppose we have fixed row sums for a matrix (say, MAT) of dimension 3 x N which (i.e the row sums) are = (RS,LS,NCS)'. The N column vectors are unknown. There are 3 possible choices for each of the N column vectors - (1,0,0)', (0,1,0)', (0,0,1)'.

So the first question is -

How can we get all possible choices of this matrix MAT by keeping the row sums fixed as (RS,LS,NCS)' using R software ?

For example - Take N=7, RS=sum of first row=2, LS=sum of second row=2 and NCS=sum of third row=3. So (1,0,0)' will appear twice, (0,1,0)' will also appear twice and (0,0,1)' will appear thrice in the set of N columns of that matrix MAT. One possible choice of MAT is -

1 0 0 0 0 1 0

0 1 0 0 0 0 1

0 0 1 1 1 0 0

I think there will be 7!/(2!x2!x3!)=210 possible choices of MAT by keeping the row sum fixed as (2,2,3)'.

But how to get those possible choices of MAT using R software ? It should be an array of dimension 3xNxn, where n is the number of possible choices of MAT.

The second question is-

How the solution mechanism changes in the above problem if the possible choices of each of the N column vectors of that matrix MAT becomes - (1,1,0)', (1,0,0)', (0,1,0)', (0,0,1)' ?

38863310 0 How to jump to an another line of code while executing an Android app

I want to know how to jump to an another line of code while executing an Android app.

Here is my problem in detail.

First of all, here is my code:-.

 listView.setOnItemClickListener (new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { int Current_Song; Songs song = Song.get(i); //If mediaPlayer is not used before, this will make oldsong as present song. if (Old_Song == -326523) { Old_Song = song.getSong(); } Current_Song = song.getSong(); ImageView IVP_P = (ImageView) findViewById(R.id.P_PImage); //If mediaPlayer is paused. if (IsPaused) { P_and_P.setImageResource(R.drawable.ic_pause_white_48dp); //If the song paused is same as the new song. if (Current_Song == Old_Song) { mediaplayer.start(); } //If the song Paused is not the new song. else { if (mediaplayer != null) { mediaplayer.release(); mediaplayer = null; } int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { mediaplayer = mediaplayer.create(SongsListActivity.this, song.getSong()); Old_Song = song.getSong(); NameD.setText(song.getNameOfSong()); RateD.setText(song.getDeveloperRate()); ImageD.setImageResource(song.getImage()); mediaplayer.start(); mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { P_and_P.setImageResource(R.drawable.ic_play_arrow_white_48dp); IsPaused = true; } }); } } IsPaused = false; } else if (mediaplayer != null) { //If mediaPlayer is already Playing a song. if (mediaplayer.isPlaying()) { P_and_P.setImageResource(R.drawable.ic_play_arrow_white_48dp); mediaplayer.pause(); IVP_P.setImageResource(R.drawable.ic_play_arrow_black_24dp); IsPaused = true; } } //If mediaPlayer is used for first time and if mediaPlayer is neither paused else { if (mediaplayer != null) { mediaplayer.release(); mediaplayer = null; } int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { mediaplayer = mediaplayer.create(SongsListActivity.this, song.getSong()); Old_Song = song.getSong(); NameD.setText(song.getNameOfSong()); RateD.setText(song.getDeveloperRate()); ImageD.setImageResource(song.getImage()); mediaplayer.start(); P_and_P.setImageResource(R.drawable.ic_pause_white_48dp); mediaplayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { P_and_P.setImageResource(R.drawable.ic_play_arrow_white_48dp); IsPaused = true; P_and_P.setImageResource(R.drawable.ic_pause_white_48dp); } }); } } } } ); 

Now, whenever the execution enters into any if the onCompletion() method, i want want the execution to start execution from beginning of the onItemClick() method.

What should I do?

For being more detailed:-

Here my app displays a list of songs using ListView and Adapter. The details of songs are stored in a arrayList(As You All Can See).When an item is clicked, it gets the position of that item, then refers to the corresponding element of the arrayList, gets the location of the corresponding song and then plays that song. What I want is that when an song is over, and the method onCompletion() is called, I want to increase to value of i(look in the 4th line of my code) by one and then go to the first line of the onItemClick method.

5349875 0 matlab "arrayfun" function

Consider the following function, which takes a gray image (2D matrix) as input:

function r = fun1(img) r = sum(sum(img)); 

I'm thinking of using arrayfun to process a series of images(3d matrix), thus eliminating the need for a for loop:

arrayfun(@fun1, imgStack); 

But arrayfun tries to treat every element of imgStack as an input to fun1, the result of the previous operation also being a 3D matrix. How can I let arrayfun know that I want to repeat fun1 only on the 3rd dimension of imgStack?

Another question, does arrayfun invoke fun1 in parallel?

4226084 0

Simply adding your CustomPanel to any other JComponent and updating the UI should do the trick. Swing takes care of all the painting for you.

Here is a reslly useful guide to swing painting;
http://java.sun.com/products/jfc/tsc/articles/painting/#paint_process

30860026 0

When you use FileReader and FileWriter, they will use the default encoding for your platform. That's almost always a bad idea.

In your case, it seems that that encoding doesn't support U+0092, which is fairly reasonable given that it's a private use character - many encodings won't support that. I suspect you don't actually want (char) 144 at all. If you really, really want to use that character, you should use an encoding which can encode all of Unicode - I'd recommend UTF-8.

It's important to differentiate between text and binary, however - if you're really just interested in bytes, then you shouldn't use a reader or writer at all - use an InputStream and an OutputStream. Hex editors are typically byte-oriented rather than text-oriented, although they may provide a text view as well (ideally with configurable encoding). If you want to know the exact bytes in the file, you should definitely be using FileInputStream.

40280512 0

You had a wonky join. Try:

select A1.* from Asset A1 left join AuditedItems A2 on A1.asset_number = A2.asset_number where A1.location_id = 15 and A2.asset_number is null 
3291303 0 C#: DataTable conversion row-by-row

In an abstract class (C# 3), there is a virtual method named GetData which returns a DataTable. The algorithm of the method is as following:

  1. Get SQL query string from the class.
  2. Get DataTable from database using above query.
  3. Do transformations on DataTable and return it.

In the 3rd point, I clone the original DataTable in order to change the Type of column (I can't do that on populated table and can't setup this at the 2nd point) and enumerate every row in which I copy and transform data from the original one. Transformations depends on the class, every one has private methods which transforms data on its own.

The question is: How to make a method in a base class which will be based on the following three params: column name which will be converted, Type of new column and action during the transformation. Two first are quite simple but I'm not sure about the third one. I thought about designing a new class which will store these three parameters, and the action will be stored as following delegate:

public delegate object Convert(object objectToConvert); 

The conversion would look something like that:

int rowCounter = 0; foreach(DataRow row in dt.Rows) { foreach(var item in Params) { row[item.ColumnIndex] = item.Convert(originalDataTable.Rows[rowCounter].ItemArray[item.ColumnIndex]); } ++rowCounter; } 

For now, I have to override the method GetData() in every class I want to have a transformations which causes a large duplication of code. The point I want to achieve is to make a base class which will be based on params I mentioned above. Is the above solution good for this problem or is it any other way to do that?

27260020 0 Why are Spock Speck tests so wordy?

Coming from JUnit background I don't really understand the point of all the text in spockD tests, since they don't show on the output from the test.

So for example, if I have a constraint on a field Double foo with constraints foo max:5, nullable:false

And I write tests like this:

void "test constraints" { when: "foo set to > max" foo=6D then: "max validation fails" !foo.validate() when: "foo is null foo=null then: "null validation fails" !foo.validate() } 

The test is well documented in its source, but if the validation fails, the error output doesn't take advantage of all this extra typing I've done to make my tests clear.

All I get is

Failure: | test constraints(com.grapevine.FooSpec) | Condition not satisfied: f.validate() | | | false 

But I can't tell form this report whether it failed the null constraint or the max constraint validation and I then need to check the line number of the failure in the test source.

At least with JUnit I could do

foo=60D; assertFalse("contraints failed to block foo>max", f.validate()); foo=null; assertFalse("contraints failed to block foo=null", f.validate()); 

And then I'd get useful info back from in the failure report. Which seems to both more concise and gives a more informative test failure report.

Is there some way get more robust error reporting out of Spec that take advantage of all this typing of when and then clauses so they show up on failure reports so you know what actually fails? Are these "when" and "then" text descriptors only serving as internal source documentation or are they used somewhere?

15707923 0 Get twitter entity value from json with PHP

I am looping through each tweet in json feed from twitter. The first part of the code works perfectly...

$screen_name = "BandQ"; $count = 10; $urlone = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=BandQ&count=".$count."&page=1"),true); $urltwo = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=BandQ&count=".$count."&page=2"),true); $data = array_merge_recursive( $urlone, $urltwo); // Output tweets //$json = file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&screen_name=".$screen_name."&count=".$count."", true); //$decode = json_decode($json, true); $count = count($data); //counting the number of status $arr = array(); for($i=0;$i<$count;$i++){ $text = $data[$i]["text"]." "; $retweets = $data[$i]["text"]."<br>Retweet Count: ".$data[$i]["retweet_count"]. "<br>Favourited Count: ".$data[$i]["favorite_count"]."<br>".$data[$i]["entities"]["user_mentions"][0]["screen_name"]."<br>"; // $arr[] = $text; $arr[] = $retweets; } // Convert array to string $arr = implode(" ",$arr); print_r($arr); 

but when I try to get entities->user_mentions->screen_name the PHP throws errors...

Notice: Array to string conversion in C:\xampp\htdocs\tweets.php on line 29 Notice: Use of undefined constant user_mentions - assumed 'user_mentions' in C:\xampp\htdocs\tweets.php on line 29 Notice: Use of undefined constant screen_name - assumed 'screen_name' in C:\xampp\htdocs\tweets.php on line 29 

How do I get that screen_name value?

Many thanks

7456037 0
SELECT ACOS(COS(RADIANS(lat)) * COS(RADIANS(lon)) * COS(RADIANS(34.7405350)) * COS(RADIANS(-92.3245120)) + COS(RADIANS(lat)) * SIN(RADIANS(lon)) * COS(RADIANS(34.7405350)) * SIN(RADIANS(-92.3245120)) + SIN(RADIANS(lat)) * SIN(RADIANS(34.7405350))) * 3963.1 AS Distance FROM Stores WHERE 1 HAVING Distance <= 50 

Here's how I use it in PHP:

// Find rows in Stores within 50 miles of $lat,$lon $lat = '34.7405350'; $lon = '-92.3245120'; $sql = "SELECT Stores.*, ACOS(COS(RADIANS(lat)) * COS(RADIANS(lon)) * COS(RADIANS($lat)) * COS(RADIANS($lon)) + COS(RADIANS(lat)) * SIN(RADIANS(lon)) * COS(RADIANS($lat)) * SIN(RADIANS($lon)) + SIN(RADIANS(lat)) * SIN(RADIANS($lat))) * 3963.1 AS Distance FROM Stores WHERE 1 HAVING Distance <= 50"; 
26319502 0 Uncaught ReferenceError: _ is not defined with Browserify

I have a Backbone project that requires a fair amount of shimming for browserify.

I have set it up so that all of my underscore files are concat'd into one file templates.js

In turn I have to shim this into my project:

package.json

"dependencies": { ..... "underscore": "^1.7.0" ..... } ...... "browserify": { "transform": [ "browserify-shim" ] }, "browser": { "//": "SP Core Components", "jst": "./jst/templates", }, "browserify-shim": { "jst" : {"depends": "underscore"} } ..... 

init.js

 var JST = require('jst'); var jsonobject = {}; JST.staffOverview(jsonobject) 

This will generate the following when trying to call :

 Uncaught ReferenceError: _ is not defined 

So my question is, how can I set underscore as a dependency of jst

359241 0

Ok, I found the answer. csl's answer set me on the right path.

pexpect has a "env" option which I thought I could use. like this:

a = pexpect.spawn('program', env = {"TERM": "dumb"}) 

But this spawns a new shell which does not work for me, our development environment depends on a lot of environmental variables :/

But if I do this before spawning a shell:

import os os.environ["TERM"] = "dumb" 

I change the current "TERM" and "dumb" does not support colours, which fixed my issue.

34244587 0

Absolutely:

var View = React.View; /* later... */ propTypes: { ...View.propTypes, myProp: PropTypes.string } 
7819531 0

Try this way:

mProgressDialog.setProgressStyle(android.R.attr.progressBarStyleSmall); 
8982017 0 Design pattern for catching memory leaks in objective-c?

I have read Apple's memory management guide, and think I understand the practices that should be followed to ensure proper memory management in my application.

At present it looks like there are no memory leaks in my code. But as my code grows more complex, I wonder whether there is any particular pattern I should follow to keep track of allocations and deallocations of objects.

Does it make sense to create some kind of global object that is present throughout the execution of the application which contains a count of the number of active objects of a type? Each object could increment the count of their type in their init method, and decrement it in dealloc. The global object could verify at appropriate times if the count of a particular type is zero of not.

EDIT: I am aware of how to use the leaks too, as well as how to analyze the project using Xcode. The reason for this post is to keep track of cases which may not be detected through leaks or analyze easily.

EDIT: Also, it seems to make sense to have something like this so that leaks can be detected in builds early by running unit tests that check the global object. I guess that as an inexperienced objective-c programmer I would benefit from the views of others on this.

8242619 0

standard in any enterprise web application is varchar with 255 length

 varchar(255) 
8290882 0

1) A htaccess is recursive by default

2) You can put some random garbages caracters in htaccess, then call you web page. You should see an error 500 that attest that the htaccess is used. That done, you can add your real configuration to finish.

14488137 0 Unable to execute command on server using j2ssh

I connected to a unix server through ssh and tried to execute a "ls" command and obtain it's output. The code is like this

SessionChannelClient session = client.openSessionChannel(); session.startShell(); String cmd = "ls -l"; session.executeCommand(cmd); ChannelInputStream in = session.getInputStream(); ChannelOutputStream out = session.getOutputStream(); IOStreamConnector input = new IOStreamConnector(System.in, session.getOutputStream()); IOStreamConnector output = new IOStreamConnector(session.getInputStream(), System.out); 

After running I was not getting any output in log file. What I found is that the channel request is failing as shown

1019 [main] INFO com.sshtools.j2ssh.connection.ConnectionProtocol - Channel request succeeded 1020 [main] INFO com.sshtools.j2ssh.session.SessionChannelClient - Requesting command execution 1021 [main] INFO com.sshtools.j2ssh.session.SessionChannelClient - Command is ls -l 1021 [main] INFO com.sshtools.j2ssh.connection.ConnectionProtocol - Sending exec request for the session channel 1021 [main] INFO com.sshtools.j2ssh.transport.TransportProtocolCommon - Sending SSH_MSG_CHANNEL_REQUEST 1021 [main] INFO com.sshtools.j2ssh.connection.ConnectionProtocol - Waiting for channel request reply 1032 [Transport protocol 1] INFO com.sshtools.j2ssh.transport.TransportProtocolCommon - Received SSH_MSG_CHANNEL_EXTENDED_DATA 1033 [ssh-connection 1] DEBUG com.sshtools.j2ssh.transport.Service - Routing SSH_MSG_CHANNEL_EXTENDED_DATA 1033 [ssh-connection 1] DEBUG com.sshtools.j2ssh.transport.Service - Finished processing SSH_MSG_CHANNEL_EXTENDED_DATA 1075 [Transport protocol 1] INFO com.sshtools.j2ssh.transport.TransportProtocolCommon - Received SSH_MSG_CHANNEL_FAILURE 1075 [main] INFO com.sshtools.j2ssh.connection.ConnectionProtocol - Channel request failed

Why is this happening ?

5254808 0

In short, there is no such thing as Foo<String> at runtime due to the type Type Erasure. The type information is lost.

Instead, you can expose Bar as raw Foo with service property typeArg=java.lang.String and use filter when injecting it to the consumer.

Other way is to introduce interfaces FooString extends Foo<String> { }, FooDouble extends Foo<Double> { } and use them instead of Foo.

8429789 0

Have you ever look servicestack ? It's awesome ,totally DTO based and very easy to create API for .net

Please look out my blog post about that

Check this thread for authentication options in ServiceStack.

https://groups.google.com/d/topic/servicestack/U3XH9h7T4K0/discussion

Look at example here

18612637 0

I had this code in a fragment and it was crashing if I try to come back to this fragment

if (mRootView == null) { mRootView = inflater.inflate(R.layout.fragment_main, container, false); } 

after gathering the answers on this thread, I realised that mRootView's parent still have mRootView as child. So, this was my fix.

if (mRootView == null) { mRootView = inflater.inflate(R.layout.fragment_main, container, false); } else { ((ViewGroup) mRootView.getParent()).removeView(mRootView); } 

hope this helps

39145786 0 Create a row with subtotals above data to be added with a Loop through an array in VBA

I need to programmatically format an excel table creating two different subtotals base on changes of values in two specified column (the first and second of the spreadsheet).

I managed to code the routine for the first subtotals but I’m now stuck trying to figure out the second part of the code.

In the second routine I need to create the subtotal row above the data that will be added. I couldn’t manage to insert the calculation in the right row and there is something wrong when I do the loop through the columns included in the array.

Anyone that can see what I’m doing wrong?

Thank you

Public Sub SubtotalTable() Dim RowNumber As Long Dim RangePointer As Range Dim RangeTopRow As Range 'Pointing the column to check Set RangePointer = ActiveSheet.Range("B1") 'Assigning the first row to a range Set RangeTopRow = Rows(2) 'Assigning to long a variable the number of row from which begin checking RowNumber = 3 Do If RangePointer.Offset(RowNumber).Value <> RangePointer.Offset(RowNumber - 1).Value Then Set RangeTopRow = Rows(RowNumber) 'Call the function to insert the row Call InsertRowTotalsAbove(RangePointer.Offset(RowNumber), RangeTopRow, RowNumber) Else RowNumber = RowNumber + 1 End If RowNumber = RowNumber + 1 Loop End Sub Public Function InsertRowTotalsAbove(RangePointer As Range, lastRow As Range, RowNumber As Long) Dim ArrayColumns() As Variant Dim ArrayElement As Variant Dim newRange As Range 'Assigning number of columns to an array ArrayColumns = Array("D", "E", "F", "G") Do If RangePointer.Offset(RowNumber).Value = RangePointer.Offset(RowNumber - 1).Value Then RowNumber = RowNumber - 1 Else ActiveSheet.Cells(RowNumber + 1, 2).Select Set newRange = Range(ActiveCell, ActiveCell.Offset(0, 0)) Rows(newRange.Offset(RowNumber + 1).Row).Insert shift:=xlDown newRange.Offset(RowNumber + 1, 0).Value = "Totale" & " " & newRange.Offset(RowNumber + 2, 0) For Each ArrayElement In ArrayColumns newRange.Cells(RowNumber, ArrayElement).Value = Application.WorksheetFunction.Sum(Range(lastRow.Cells(-1, ArrayElement).Address & ":" & RangePointer.Cells(0, ArrayElement).Address)) Next ArrayElement End If Loop End Function 
19890828 0 How can I do editable listview item?

I have todolist application which includes task,priority,date,status and ı can add new item to list.When click the item another activity run.Here is the problem,ı cant get item's values for new activity and when i click edit button, program add new item without deleting old one.

here setOnItemClickListener

todoListView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent editIntent = new Intent(MainActivity.this, EditItem.class); startActivityForResult(editIntent, EDIT_NOTE); } }); 

and OnActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case ADD_NOTE: String extraName = AddItem.code; ArrayList<String> list = data .getStringArrayListExtra(extraName); todoItems.addAll(list); todoArrayAdapter.notifyDataSetChanged(); break; case EDIT_NOTE: String extraName2 = EditItem.code; ArrayList<String> list2 = data .getStringArrayListExtra(extraName2); todoItems.addAll(list2); todoArrayAdapter.notifyDataSetChanged(); break; default: break; } } super.onActivityResult(requestCode, resultCode, data); } 

and EditItem.java

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.edit_item); editText1 = (EditText) findViewById(R.id.editText1); spinner = (Spinner) findViewById(R.id.prioritySpinner); datePicker = (DatePicker) findViewById(R.id.datePicker); toggleButton = (ToggleButton) findViewById(R.id.statusbutton); editButton = (Button) findViewById(R.id.editButton); cancelButton = (Button) findViewById(R.id.cancelButton); editButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { itemList = new ArrayList<String>(); item = editText1.getText().toString(); priorityLevel = spinner.getSelectedItem().toString(); status = toggleButton.getText().toString(); int day = datePicker.getDayOfMonth(); int month = datePicker.getMonth() + 1; int year = datePicker.getYear(); date = day + "/" + month + "/" + year; itemList.add(new Entry(item, priorityLevel, date, status) .toString()); Intent okIntent = new Intent(); okIntent.putExtra(code, itemList); setResult(Activity.RESULT_OK, okIntent); finish(); } }); 
11680931 0 Nginx/Django Admin POST https only

I've got an Nginx/Gunicorn/Django server deployed on a Centos 6 machine with only the SSL port (443) visible to the outside world. So unless the server is called with the https://, you won't get any response. If you call it with an http://domain:443, you'll merely get a 400 Bad Request message. Port 443 is the only way to hit the server.

I'm using Nginx to serve my static files (CSS, etc.) and all other requests are handled by Gunicorn, which is running Django at http://localhost:8000. So, navigating to https://domain.com works just fine, as do links within the admin site, but when I submit a form in the Django admin, the https is lost on the redirect and I'm sent to http://domain.com/request_uri which fails to reach the server. The POST action does work properly even so and the database is updated.

My configuration file is listed below. The location location / section is where I feel like the solution should be found. But it doesn't seem like the proxy_set_header X-* directives have any effect. Am I missing a module or something? I'm running nginx/1.0.15.

Everything I can find on the internet points to the X-Forwarded-Protocol https like it should do something, but I get no change. I'm also unable to get the debugging working on the remote server, though my next step may have to be compiling locally with debugging enabled to get some more clues. The last resort is to expose port 80 and redirect everything...but that requires some paperwork.

[http://pastebin.com/Rcg3p6vQ](My nginx configure arguments)

server { listen 443 ssl; ssl on; ssl_certificate /path/to/cert.crt; ssl_certificate_key /path/to/key.key; ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:!aNULL:!MD5; server_name example.com; root /home/gunicorn/project/app; access_log /home/gunicorn/logs/access.log; error_log /home/gunicorn/logs/error.log debug; location /static/ { autoindex on; root /home/gunicorn; } location / { proxy_pass http://localhost:8000/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Scheme $scheme; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol https; } } 
30502870 0 Shiny slider on logarithmic scale

I'm using Shiny to build a simple web application with a slider that controls what p-values should be displayed in the output.

How can I make the slider act on a logarithmic, rather than linear, scale?

At the moment I have:

sliderInput("pvalue", "PValue:", min = 0, max = 1e-2, value = c(0, 1e-2) ), 

Thanks!

9444159 0

You should just let GetPassword() return null if the password isn't found. The next problem though is that CompareStringToHash() will fail if you pass in a null password, so instead of

 bool isSame = hasher.CompareStringToHash(txtPassword.Text, hashedPassword); if (isSame==false) { MessageBox.Show("Invalid UserName or Password"); } 

You do

 if (hashedPassword == null || hasher.CompareStringToHash(txtPassword.Text, hashedPassword) { MessageBox.Show("Invalid UserName or Password"); } 

If hashedPassword is null the if statement will be exited before it tries to execute the CompareStringToHash() so you won't get an exception. CompareStringToHash() will only execute if hashedPassword is not null. Then provided you've stored a valid string (which you will have because you are creating it will Encrypto) it should all work - and without a lot of messy if statements :o)

15420146 0

I decided to post an answer to try and explain this situation for anyone else that arrives here from Google.

As David points out, to fix this error...

 uninitialized constant Excel::Iconv 

...you'll have to require "iconv":

require "iconv" require "roo" 

This is because the Roo gem calls Iconv.new in its internal Excel class but Roo forgot to require "iconv" itself, so you're forced to do it. It's a bug. It's no different than calling Set.new without require "set"

Iconv is part of Ruby 1.8 and 1.9's standard library. You don't install it. It's already there.

However, it's worth pointing out that Iconv is deprecated in Ruby 1.9 and removed in Ruby 2.0.

2510502 0

One problem is that you have two AJAX calls - get and load. You don't need both.
Either use load:

$("#content").load('pagination3.php?&category='+ this_id ); 

or get:

$.get("pagination3.php", { category: this_id }, function(data){ $("#content").html(data); }, "html" ); 

(A side note here is that two calls are not necessarily wrong - they might both work. Also, watch out for SQL injection - you are very close..)

11749002 0

CUDA and TBB are optional, it shouldn't matter that they're not there.

.m files are actually plain Matlab source, not anything compiled. In addition to a few .m files, you should end up with a nearest_neighbors.mexa64 (or some other mex extension depending on your platform) in the directory build/matlab/.

This isn't going to be the same directory with the .m and .cpp files -- that's the source directory. You should probably run make install to gather things either in /usr/local, or somewhere else if you do cmake .. -DCMAKE_INSTALL_PREFIX=/wherever. Then you'll have the .m and .mexa64 (but not the .cpp) files in /usr/local/share/flann/matlab/.

25144238 0

Yes, they are both called "Year", but one is a static function and the other a property. You would need to use the "new" keyword added for the compiler to be happy.

public new readonly int Year; 
6629439 0

Variable length array allocation (or any array declaration actually) is done on the stack (assuming GCC compiler). Malloc assigns memory from the heap.

Two advantages to heap vs. stack: 1. Stack is much smaller. There is a decent chance that your variable-size array could cause your stack to overflow. 2. Items allocated on the stack don't survive after the function they were declared in returns.

17187362 0 How to parse below JSON

How to parse below JSON code in javascript where iterators are not identical?

var js= { '7413_7765': { availableColorIds: [ '100', '200' ], listPrice: '$69.00', marketingMessage: '', prdId: '7413_7765', prdName: 'DV by Dolce Vita Archer Sandal', rating: 0, salePrice: '$59.99', styleId: '7765' }, '0417_2898': { availableColorIds: [ '249', '203' ], listPrice: '$24.95', marketingMessage: '', prdId: '0417_2898', prdName: 'AEO Embossed Flip-Flop', rating: 4.5, salePrice: '$19.99', styleId: '2898' }, prod6169041: { availableColorIds: [ '001', '013', '800' ], listPrice: '$89.95', marketingMessage: '', prdId: 'prod6169041', prdName: 'Birkenstock Gizeh Sandal', rating: 5, salePrice: '$79.99', styleId: '7730' } } 

How can i parse this JSON in jvascript? I want the values of 'prdName', 'listprice', 'salePrice' in javascript?

1712345 0

You might need to consider using a different text box control.

Daniel Grunwald has written the Wpf text editor for SharpDevelop completely from scratch. It is called AvalonEdit and a good article is on codeproject:

http://www.codeproject.com/KB/edit/AvalonEdit.aspx

It seems that he has done optimizations for large files.

21158408 0

When references to data are passed around in LabVIEW internally, the data type is always passed around, too. Data is passed around as void pointers and the type is passed along with them. So any time LabVIEW sees your array, it'll also see that the type is a 2d array of int32s. (I work on the LabVIEW team at National Instruments)

25581842 0 Array of File object is empty/null in struts 2 action while uploading multiple files

I am trying to upload multiple files in struts 2 application but every time I am getting File[] fileUpload is empty . I have made several configuration changes in struts.xml but still getting fileUplaod object as either null or empty . Can someone tells me what am i supposed to do to get it working

The corresponding action code is as : In this action I am retrieving the file object array and printing the details

EDIT :

DummyFileUploadAction.java:

package com.cbuddy.common.action; import java.io.File; import com.opensymphony.xwork2.ActionSupport; public class DummyFileUploadAction extends ActionSupport{ private File[] fileUpload; private String fileUploadFileName; private String[] fileUploadContentType; public File[] getFileUpload() { return fileUpload; } public void setFileUpload(File[] fileUpload) { this.fileUpload = fileUpload; } public String getFileUploadFileName() { return fileUploadFileName; } public void setFileUploadFileName(String fileUploadFileName) { this.fileUploadFileName = fileUploadFileName; } public String[] getFileUploadContentType() { return fileUploadContentType; } public void setFileUploadContentType(String[] fileUploadContentType) { this.fileUploadContentType = fileUploadContentType; } @Override public void validate() { if (null == fileUpload) { System.out.println("DummyFileUploadAction.validate()"); } } public String uplaod(){ return "success"; } public String execute() throws Exception{ for (File file: fileUpload) { System.out.println("File :" + file); } for (String fileContentType: fileUploadContentType) { System.out.println("File type : " + fileContentType); } return SUCCESS; } } 

The struts.xml is : I was able to get file object for single file upload with same set of configuration in struts.xml

struts.xml:

<struts> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="true" /> <constant name="struts.custom.i18n.resources" value="ApplicationResources" /> <constant name="struts.multipart.maxSize" value="1000000" /> <package name="default" extends="struts-default,json-default" namespace="/"> <action name="upload" class="com.cbuddy.common.action.DummyFileUploadAction" method="uplaod"> <result name="success">/uplaod.jsp</result> </action> <action name="dummyUpload" class="com.cbuddy.common.action.DummyFileUploadAction" > <interceptor-ref name="fileUpload"> <param name="allowedTypes">image/jpeg,image/gif,image/png</param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> <result name="success">/success.jsp</result> <result name="input">/uplaod.jsp</result> </action> </package> </struts> 

And then success.jsp which will be rendered once files details are successfully printed .

4270843 0 Informix: How to get the rowid of the last insert statement

This is an extension of a question I asked before: C#: How do I get the ID number of the last row inserted using Informix

I am writing some code in C# to insert records into the informix db using the .NET Informix driver. I was able to get the id of the last insert, but in some of my tables the 'serial' attribute is not used. I was looking for a command similar to the following, but to get rowid instead of id.

SELECT DBINFO ('sqlca.sqlerrd1') FROM systables WHERE tabid = 1;

And yes, I do realize working with the rowid is dangerous because it is not constant. However, I plan to make my application force the client apps to reset the data if the table is altered in a way that the rowids got rearranged or the such.

5523027 0

You could make all of the keys lowercase before searching:

array_change_key_case($all_meta, CASE_LOWER)); 
26462091 0 CWnd.wndTopMost usage

What CWnd.wndTopMost is used for?

in definition I found that it is:

static AFX_DATA const CWnd wndTopMost; 

How macro AFX_DATA affects this line?

This code:

this->wndTopMost.SetWindowPos(NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); 

Returns error

'CWnd::SetWindowPos' : cannot convert 'this' pointer from 'const CWnd' to 'CWnd &' 

Why does it needs reference? This method returns to nothing.

8502296 0

Instead of using a 2nd connection object, you could change your connection string and use MARS (Multiple active result set) for this purpose. Add the following statement to your connection string:

MultipleActiveResultSets=True 

EDIT: And like the other's said, use SqlParameters for your parameters and not string concatenation. It's not only a security issue, but also a huge performance hit!

7380869 0 SQL Comma Delimit Problem

I have a small problem. I am getting this error, and I would appreciate if anyone could help me out! All I am trying to do is a comma delimited list.

SET NOCOUNT ON; DECLARE @TypeID Varchar(250) SELECT @TypeID = COALESCE(@TypeID +',' ,'') + TypeID FROM Related RETURN @TypeID 

Conversion failed when converting the varchar value '8,' to data type int.

Does anyone know how to fix, please? I've tried CONVERT(VARCHAR, @TypeID) but this doesn't seem to make any difference!

9160907 0 Selenium RC functionality with java

I am New to selenium RC..already working on selenium IDE. For selenium RC i have chosen java language.also installed selenium rc server. Now i dont have any idea have to go further. Please advice me on same

21510280 0 How can I change hidden input val when add or remove item with using select2 plugin

I use select2 plugin and get values when user typing least 3 character. Get data from php as json like this;

"1":"val1" , "5":"val2" , "19":"val3".... 

I want to store id values of selected items at hidden input and when user remove any selected item, the id of removed item also remove from hidden input. For example;

When val1 and val2 items are selected like below, value of hidden input (id which 'hdn-id') change like below, also.

enter image description here

<input type="hidden" id="hdn-id" val="1,5" /> 

And when val1 is removed, id of this item (1) removed from hidden input like this ;

enter image description here

<input type="hidden" id="hdn-id" val="5" /> 

But I can't do this. My codes;

SELECT2:

function selectAjax(element,url,hiddenElement) { var selectedItemsArray = [] $('#'+element).select2({ multiple: multi, id: function(element) { return element }, ajax: { url: url, dataType: 'json', data: function(term,page) { return { term: term, page_limit: 10 }; }, results: function(data,page) { var titleArr = []; $.each(data, function(k,v){ titleArr.push(k+':'+v); }); return { results: titleArr }; } }, formatResult: formatResult, formatSelection: formatSelection, }); function formatResult(data) { return '<div>'+data.substr(data.indexOf(':')+1)+'</div>' }; function formatSelection(data) { var id = data.split(':',1), text = data.substr(data.indexOf(':')+1), hiddenElementValue = eval([jQuery('#'+hiddenElement).val()]); selectedItemsArray.push(id); jQuery('#'+hiddenElement).val(selectedItemsArray); return '<div data-id="'+id+'" class="y-select2-selected-items">'+text+'</div>'; }; } selectAjax('select2-element','ajx.php','hdn-id'); 

HTML:

<input type="text" id="select2-element" /> <input type="hidden" id="hdn-id" /> 

I can store ids at hidden input with above code but when remove an item I can't remove id from hidden input. Because plugin assign 'return false' to element's onclick event. I handed the job with above codes, I think.How can I be a better solution?

39015172 0

Thanks @vercelli

I got my answer with this query with your help.

Declare @ProdID int set @ProdID=1 DECLARE @columnName VARCHAR(1000) DECLARE @columnVal VARCHAR(1000) DECLARE @Query VARCHAR(1000) --Create dynamic column name SELECT @columnName =COALESCE(@columnName + ', ','')+'['+cast(rn as varchar(10))+'] AS [R'+cast(rn as varchar(10))+']', @columnVal =COALESCE(@columnVal + ',','')+'['+cast(rn as varchar(10))+']' FROM ( select distinct ROW_NUMBER () over (partition By VendorId order by QuotedAmount desc) as rn from tbl_Vendor_Quotation where [ProductRequestID]=@ProdID ) a print @columnName print @columnVal set @Query='select VendorId,'+@columnName+' from ( select VendorId, QuotedAmount, ROW_NUMBER () over (partition By VendorId order by QuotedAmount desc) as rn from tbl_Vendor_Quotation where [ProductRequestID]='+cast(@ProdID as varchar(10))+') t1 PIVOT ( max(QuotedAmount) for rn in ('+@columnVal+')) As PivotTable' exec (@Query) 
23240829 0

Regular Threads can prevent the VM from terminating normally (i.e. by reaching the end of the main method - you are not using System#exit() in your example, which will terminate the VM as per documentation).

For a thread to not prevent a regular VM termination, it must be declared a daemon thread via Thread#setDaemon(boolean) before starting the thread.

In your example - the main thread dies when it reaches the end of it code (after t1.start();), and the VM - including t1- dies when t1 reaches the end of its code (after the while(true) aka never or when abnormally terminating.)

Compare this question, this answer to another similar question and the documentation.

786498 0

I found this info while digging around, and it seems it can be the most cost effective way. I will try it out when I get the guts to dig into assembly. :)

UPDATE

I tested this with my profiler. although a bit faster, it seems I still have tonnes of other overhead :( (I did not bother with timing as I it did not seem to be enough benefit)

14067271 0

Well it depends on your app and the connect, first your app must support background running. Then if the internet connection is GRPS, CDMA or EDGE your connection is dropped and NSURLConnection will receive an error if the connection is not reestablished with the time out period. On 3G and WiFi you can have data and voice at the same time. On LTE all data connection are dropped and the witches back to UMTS(3G) see comment by Codo

37581219 0

You can write your business logic in onchange function as shown below

 <form name="login" action="procesarAdd.do"> <br> <b>CATEGORIA</b> <br> <input type="radio" name="g1" value="per" checked="checked" onchange="product(this.value)"/>PERFUME <input type="radio" name="g1" value="joy" onchange="product(this.value)"/>JOYAS <input type="radio" name="g1" value="car" onchange="product(this.value)"/>BOLSO CARTERAS <table border="1"> <tbody> <tr> <td>ID Producto</td> <td><input type="text" name="id" id ="field1" value="" /></td> </tr> <tr> <td>Nombre</td> <td><input type="text" name="nombre" id ="field2" value="" /></td> </tr> <tr> <td>Stock</td> <td><input type="text" name="stock" id ="field3" value="" /></td> </tr> <tr> <td>Precio</td> <td><input type="text" name="precio" id ="field4" value="" /></td> </tr> </tbody> </table> 


Javascript function:

 function product(x){ alert("Product Name : " +x); if(x=="per"){ document.getElementById("myImg").src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcScKsjtuajfWrNvk2pXTxf4Et2dPoCEsF58XVetpBrVCpDnLmAkVg" } if(x=="joy"){ document.getElementById("myImg").src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcQM3y6qUIwqIr164GbERvTyOXNMBYcWOueodxxwxzug16oFalPldiHJQV1r" } if(x=="car"){ document.getElementById("myImg").src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS3P65pTpiNFx2psFeqOoF6iuXzQErc_gBUmAf6bn1846ghx1TrOw" } } 

codepen URL for your reference: http://codepen.io/nagasai/pen/KMwGMg?editors=1010

Please let me know if you need any further details

35258921 0 multiple apps from one certificate

I have two active projects, my main app and a test app. It seems to be the case that using the "generate" button to run the certificate wizard, I have to generate certificates from scratch each time I switch from one app to the other. The "use existing" option never works. Generating a new cert for one app invalidates the cert for the other app. This doesn't seem right, so what am I doing wrong?

27581465 0

You need to change $chk_group[] to $chk_group in your first line.

In PHP syntax, $chk_group[] = means push the right had value to an array called $chk_group. Your entire array is being stored to $chk_group[0]

What you need instead is:

 $chk_group[] =array( '1' => 'red', '2' => 'thi', '3' => 'aaa', '4' => 'bbb', '5' => 'ccc' ); 
24842599 0 select string with specific character in regular expression

Given the following text of example:

Hello $NAME$ how are you? You are visiting this $LOGIN_PAGE$ page, please fill the form and log in.

I want to select only the following "variable" $LOGIN_PAGE$ without select even the $NAME character.

I made this regex trying to achieve the result but it select both of the string

(\$([A-Z\_])+\$) 

Which part I'm missing in this regex?

21417931 0 jQuery script not working properly on Google Chrome

I have the following code that seems to not work in Google Chrome.

$("#productImg img").click(function() { var img = $(this).attr("src"); var text = $(this).attr("id"); $("#loader").show(); $("#largeImg img").load(function() { $("#loader").hide(); }).attr("src", img.replace('th_', 'si_')); }); 

It works fine in Firefox, but doesn't in Chrome. If i click the first image it makes some kind of loop and never hides the #loader. You can test it here.

Any help is appreciated!

20146345 0 How to rename an IndexedDB database?

I created an IndexedDB databse named "A" by indexedDB.open method.

Now I want to modify the database name to "B", how can I do it?

I dont't want to create a new database with new name and copy all data from old database to new database.

2970040 0

The following code would do what you literally ask (assuming thesocket is a connected stream socket):

with open('thefile.mp3', 'rb') as f: thesocket.sendall(f.read()) 

but of course it's unlikely to be much use without some higher-level protocol to help the counterpart know how much data it's going to receive, what type of data, and so forth.

16226057 0 Recreate original PHP array from print_r output

Let's say I have this output from some source where I don't have access to the original PHP created array:

Array ( [products] => Array ( [name] => Arduino Nano Version 3.0 mit ATMEGA328P [id] => 10005 ) [listings] => Array ( [category] => [title] => This is the first line This is the second line [subtitle] => This is the first subtitle This is the second subtitle [price] => 24.95 [quantity] => [stock] => [shipping_method] => Slow and cheap [condition] => New [defects] => ) [table_count] => 2 [tables] => Array ( [0] => products [1] => listings ) ) 

Now I would like to input that data and have an algorithm recreate the original array that it was printing so I can then use it for my own application.

Currently I am thinking about a sub_str() and regex statements that pull data and place it appropriately. Before I head further, is there a simpler way, via already written code or php plugins that do this for me already out there?

10308265 0

You can create multiple encryption keys (millions) and use separate keys for separate columns. Adding multiple keys is critical for any scenario that requires periodic key rotation. To encrypt data you use ENCRYPTBYKEY and pass in the key name of the desired encryption key, see How to: Encrypt a Column of Data. You decrypt data using DECRYPTBYKEY. Note that you do not specify what decryption key to use, the engine knows. But you have to properly open the decryption key first, see OPEN SYMMETRIC KEY.

1676740 0

Its fun and challenging to go from static image processing to doing analysis in real-time. For example, analyze video from a webcam and have the user play a primitive video game by waving their hands.

Or, if you want to continue with your face recognition idea, try writing software to highlight famous faces in a running video in realtime.

Use google image search to gather training data and then see how well your software can do at identifying the president of the US in different settings , for example. Can you train all of the former presidential candidates and differentiate them all?

Also, look into using OpenCV for fast real time computer vision processing in C.

13335931 0

From the glob module's documentation:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. This is done by using the os.listdir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell.

And if we look the documentation for os.listdir:

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

So glob.glob does not return the files in alphabetical order. It is not stated anywhere in the documentation. Relying on this behaviour is a bug. If you want an ordered sequence you must sort the result. You can then easily imagine that there is no way to make iglob return a sorted result since it does not even have all results available.

If memory is really a problem then you have two choices:

  1. Drop the "aplhabetical order" requirement and just use iglob.
  2. Sort the data using some kind of "bucket sorting", keeping most of the data on disk and loading it into RAM in chunks (such techniques are explained in The Art of Computer Programming, Book 3). This approach will make your program slower and probably much harder to write. But if you really can not hold all the filenames in RAM then you'll have to save them on disk eventually.
1334261 0

Thank you guys for giving me such good advice! Maybe it is just a bad idea to use music, because it is inconvenient.

http://www.larajade.co.uk/high/

That's what I am thinking about - but there are only difficult ways to get it, flash / ajax. Iframes are bad...

Thank you :)

35689257 0

You can use the async package which is great for controlling flow, something like:

 console.log('Recieved the get Request'); var i = 1; var count = 0; while (count < 10) { var url = 'http://www.imdb.com/title/tt' + i + '/'; console.log(url); count = count + 1; i = i + 1; async.waterfall([ function sendRequest (callback) { if (!error) { var $ = cheero.load(html); var json = { title: '', ratings: '', released: '' } } $('.title_wrapper').filter(function() { var data = $(this); json.title = data.children().first().text().trim(); json.released = data.children().last().children().last().text().trim(); }); $('.ratingValue').filter(function() { var data = $(this); json.ratings = parseFloat(data.text().trim()); }); callback(null, JSON.stringify(json, null, 4) + '\n'); }, function appendFile (json, callback) { fs.appendFile('message.txt', json, function(err) { if (err) { callback(err); } callback(); }); } ], function(err) { res.sendFile(__dirname + '/index.js'); }); 
24656338 0

You get this as you cannot cast the IEnumerable to List (This is why LINQ has .ToList() extension). I think what you want is something like this:

public IEnumerable<T> Paginate<T>(IEnumerable<T> list) { return list.Skip(Page * PageSize).Take(PageSize); } 

Which will work with any source that implements IEnumerable (List, T[], IQueryable)

You can then call it like this:

IEnumerable<int> list = someQueryResult; IEnumerable<int> page = class.Paginate<int>(list); 

As pointed out in other answers. IQueryable has it's own set of extension methods. So all though this will work, the paging will not be done as the data-source, as it will use the IEnumerable extensions

25861016 0 50% chance to make a boolean true or not by clicking a button?

I've been stuck on this for a while, I'm trying to figure out how to make a boolean have a 50% chance to be set to true after clicking a button and a 50% chance to keep it false.

Any help would be appreciated.

22387777 0

If you want all results where the Quantity is 20, then all you need to do is specify that in the WHERE clause:

SELECT * FROM Product WHERE Quantity = 20; 

There's no need to include the ORDER BY if you expect the value to be the same throughout. There's also no need to LIMIT unless you want the first number of results where Quantity is 20.

34355272 0

When you declare the function you just have to put a simple name without parentheses and parameters otherwise it will give that error.

enter image description here

See the documentation http://orientdb.com/docs/2.0/orientdb.wiki/Functions.html

38564838 0

OAuth is a concept, and not any library which you can inject, (of course libraries exists to implement that)

So if you want to have OAuth in your application (i.e your application has its own OAuth), you have to setup following things

Check out the OAuth 2.0 Specification to get clear understanding of how it works and how to build your own.

https://tools.ietf.org/html/rfc6749

2748593 0 Authorization in a more purely OOP style

I've never seen this done but I had an idea of doing authorization in a more purely OO way. For each method that requires authorization we associate a delegate. During initialization of the class we wire up the delegates so that they point to the appropriate method (based on the user's rights). For example:

class User { private deleteMemberDelegate deleteMember; public StatusMessage DeleteMember(Member member) { if(deleteMember != null) //in practice every delegate will point to some method, even if it's an innocuous one that just reports 'Access Denied' { deleteMember(member); } } //other methods defined similarly... User(string name, string password) //cstor. { //wire up delegates based on user's rights. //Thus we handle authentication and authorization in the same method. } } 

This way the client code never has to explictly check whether or not a user is in a role, it just calls the method. Of course each method should return a status message so that we know if and why it failed.

Thoughts?

35192629 0 Preventing duplicate REST calls

I'm creating an Android app that calls a PHP bases REST api methods for server side updates.

For example, to add reward points to customer, we can use:

http://example.com/rest/customer/add/1/20

Where 1 is customer id and 20 is reward points.

I was wondering how can I prevent duplicate calls to this URL. If for some reason, this URL is called twice, customer will get 20 more points. There is no such condition that customer cannot get more points on same day.

Also, how to prevent this URL to be executed anonymously?

Is OAuth 2.0 the best solution or there is something better?

Thanks

39782499 0 MySQL: character set utf8 giving error with datetime

I am new to MySQL and wants to create this table after reading tutorial I wrote this command but on MySQL Workbench it shows error for 4 line created_at attribute:

CREATE TABLE tweetMelbourne ( `id` INT(11) NOT NULL AUTO_INCREMENT, `geo_type` VARCHAR(8) CHARACTER SET utf8, `created_at` DATETIME CHARACTER SET utf8 NOT NULL , `geo_coordinates_latitude` decimal(12,9) DEFAULT NULL, `geo_coordinates_longitude` decimal(12,9) DEFAULT NULL, `place_full_name` VARCHAR(35) CHARACTER SET utf8, `place_country` VARCHAR(15) CHARACTER SET utf8, `place_type` VARCHAR(18) CHARACTER SET utf8, `place_bounding_box_type` VARCHAR(10) CHARACTER SET utf8, `place_bounding_box_coordinates_NE_lat` decimal(12,9) DEFAULT NULL, `place_bounding_box_coordinates_NE_long` decimal(12,9) DEFAULT NULL, `place_bounding_box_coordinates_SW_lat` decimal(12,9) DEFAULT NULL, `place_bounding_box_coordinates_SW_long` decimal(12,9) DEFAULT NULL, `place_country_code` VARCHAR(5) CHARACTER SET utf8, `place_name` VARCHAR(17) CHARACTER SET utf8, `text` VARCHAR(140) CHARACTER SET utf8, `user_id` INT, `user_verified` VARCHAR(5) CHARACTER SET utf8, `user_followers_count` INT, `user_listed_count` INT, `user_friends_count` INT, `user_location` VARCHAR(30) CHARACTER SET utf8, `user_following` VARCHAR(5) CHARACTER SET utf8, `user_geo_enabled` VARCHAR(5) CHARACTER SET utf8, `user_lang` VARCHAR(5) CHARACTER SET utf8, PRIMARY KEY (id) ); 

Error is :

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CHARACTER SET utf8 
13459767 0

If the input is within the magnitude range supported by double, and you do not need more than 15 significant digits in the result, convert (a+b) and n to double, use Math.pow, and convert the result back to BigDecimal.

9829667 0

It's because your using an OR clause, you need to use AND. Basically your saying if the textSample is not D then show your message box.

Change it to:

Dim textSample as String = "F" If Not textSample = "D" AND Not textSample = "E" AND Not textSample = "F" Then MessageBox.Show("False") End If 

That should work.

14613725 0 Centered floating logo stuck on right only in IE9

I have a fluid width site with a logo centered in the header area. The logo stays in the center regardless of the window size. Works in all browsers except ie9. In ie9 it is stuck on the right. If I could get it stuck on the left that would be an ok compromise but the right will not do. My best guess is that ie9 does not support the css code:

.logo { width:100%; position:relative; } .logo img { margin-left:auto; margin-right:auto; display:block; }

Here is the website http://www.cyberdefenselabs.org/

Anyone know a workaround for ie9 that will not affect other browsers or involve drastic recode?

33082472 0 My timer increases speed after a single play through of my game why?

I continue to get the error TypeError: Error #1009: Cannot access a property or method of a null object reference. at ChazS1127_win_loose_screen_fla::MainTimeline/updateTime() at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick() and here is my code for my main game

stop(); import flash.events.MouseEvent; import flash.ui.Mouse; import flash.events.TimerEvent; import flash.utils.Timer; var timer:Timer = new Timer(1000, 9999); timer.addEventListener(TimerEvent.TIMER, updateTime); var timeRemaining = 30; timerBox.text = timeRemaining; function updateTime(evt:TimerEvent) { timeRemaining--; timerBox.text = timeRemaining; if(timeRemaining <= 0) { gotoAndStop(1, "Loose Screen"); } } addEventListener(MouseEvent.CLICK, onMouseClick); var score = 0 ; function onMouseClick(evt:MouseEvent) { if(evt.target.name == "playBtn") { texts.visible = false; playBtn.visible = false; backpackss.visible = false; backgrounds.visible = false; timer.start(); } if(evt.target.name == "Backpack") { Backpack.visible = false; message.text = "A backpack is a necessity for carrying all your items."; score = score + 1; scoredisplay.text = "score:" + score; 0 } if(evt.target.name == "Bandage") { Bandage.visible = false; message.text = "Bandages for cuts and scraps and to keep from bleeding out."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Brace") { Brace.visible = false; message.text = "A brace is good for a sprain or even a break in a bone allow you to keep going."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "canned") { canned.visible = false; message.text = "Canned foods are a good resource as food will be scarce in situations."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Compass") { Compass.visible = false; message.text = "Going the wrong direction in a survival situation can be your downfall."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Flashlight") { Flashlight.visible = false; message.text = "A flashlight can help you see at night and help you stay sane."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Iodine") { Iodine.visible = false; message.text = "An ioddine purfication kit can assist in keeping water clean for drinking."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Lighter") { Lighter.visible = false; message.text = "A windproof lighter for even the windest of days to light fires."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Radio") { Radio.visible = false; message.text = "A radio to help keep up to date on news around if it's still brodcasting."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Sewing") { Sewing.visible = false; message.text = "A sewing kit for salvaging clothes and for patching up wounds."; score = score + 1; scoredisplay.text = "score:" + score; } if(evt.target.name == "Tent") { Tent.visible = false; message.text = "A tent can be a home for the night and a home for life."; score = score + 1; scoredisplay.text = "score:" + score; } if(score >= 11) { gotoAndStop(1, "Victory Screen"); } } function removeAllEvents() { removeEventListener(MouseEvent.CLICK, onMouseClick); timer.removeEventListener(TimerEvent.TIMER, updateTime); timer.stop(); } 

and my Victory Screen

stop(); import flash.events.MouseEvent; addEventListener(MouseEvent.CLICK, onMouseClick2); play(); function onMouseClick2(evt:MouseEvent) { if(evt.target.name == "restartButton") { gotoAndStop(1, "Main Game"); removeAllEvents2(); } } function removeAllEvents2() { removeEventListener(MouseEvent.CLICK, onMouseClick2); } 

and my loose screen

stop(); import flash.events.MouseEvent; play(); addEventListener(MouseEvent.CLICK, onMouseClick2); function onMouseClick3(evt:MouseEvent) { if(evt.target.name == "restartButton") { gotoAndStop(1, "Main Game"); removeAllEvents3(); } } function removeAllEvents3() { removeEventListener(MouseEvent.CLICK, onMouseClick3); } 

so why does my game when through one play the timer will speed up and go fast for no reason. After one play through it'll go 2 seconds for every 1 second and so on.

19097912 0 hover works only when entering from outside of container IE

i saw many problems with IE but none was the same as mine. i have a gallery on my site, there are navigation arrows on each pic. i use hover to figure on which half of the picture the user hovers and to show the right arrow accordingly, the problem is that the hover works only when i enter the mouse from outside the div that contains the arrows, when i move form one arrow to another it dosent work. here the code:

<div class="lb-container"> <img class="lb-image" src="http://suburbanfinance.com/wp-content/uploads/2013/04/streetinfo.jpg?973b8a" style="display: block; width: 724px; height: 543px;"> <div class="lb-nav" style="display: block;"> <a class="lb-prev" href="" style="display: block;"></a> <a class="lb-next" href="" style="display: block;"></a> </div> <div class="lb-loader" style="display: none;"><a class="lb-cancel"> </a></div></div> 

and the css:

.lb-next:hover { background: url(../images/next.png) right 48% no-repeat; } .lb-prev:hover { background: url(../images/prev.png) left 48% no-repeat; } 

ideas?

14565675 0 Create Buffer OpenGLES 2

I am having some problem with the creation of frame buffer with opengles. For my application, I create the main frame buffer like this:

glGenFramebuffers( 1, &viewFramebuffer ); glGenRenderbuffers( 1, &viewRenderbuffer ); glBindFramebuffer( GL_FRAMEBUFFER, viewFramebuffer ); glBindRenderbuffer( GL_RENDERBUFFER, viewRenderbuffer ); [ Context renderbufferStorage : GL_RENDERBUFFER fromDrawable : ( CAEAGLLayer* )self.layer ]; glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, viewRenderbuffer ); glGetRenderbufferParameteriv( GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth ); glGetRenderbufferParameteriv( GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight ); if ( itUsesDepthBuffer ) { glGenRenderbuffers( 1, &depthRenderbuffer ); glBindRenderbuffer( GL_RENDERBUFFER, depthRenderbuffer ); glRenderbufferStorage( GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, backingWidth, backingHeight ); glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer ); } if ( glCheckFramebufferStatus( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE ) { NSLog( @"failed to make complete framebuffer object %x", glCheckFramebufferStatus( GL_FRAMEBUFFER ) ); [ self destroyFramebuffer ]; return NO; } 

But the function glGetRenderbufferParameteriv returns 0 either for GL_RENDERBUFFER_WIDTH and GL_RENDERBUFFER_HEIGHT and eventually the glCheckFramebufferStatus returns an error as framebuffer attachment is incomplete.

Do you have any idea why is this happening?

Thank you in advance.

36067450 0 Manipulate scope value with angularjs directive

my model contains some values that I want to modify before showing it to the user. Maybe this is written in the docs and I am to blind to see it.

Lets say I want to display my variable like this

<span decode-directive>{{variable}}</span> 

I want to write the decode-directive and it should display variable + 1234 f.e.

I need this at a few points so I can't code it for only one special object.
I hope you can help me out with this.

14306830 0

use list to store your all objects and iterate the list and check if the condition of search is satisfied or not, in your case it is "billy". If you don't want to use list, use an array of object and then iterate with for loop instead. Hope this has helped. Do tell if you want code for this.

35453865 0

I think you can create nested list groups and by changing their width you can create a responsive design. Using something like:

<div class="col-lg-2 col-md-3 col-sm-12 col-xs-12"> ... </div> 

With this way you can but 6 columns side by side in large screens and only one column for each row in smaller screens.

Bootstrap should be used with 'mobile-first design' approach. So you must design your screen according to smaller screens first and then you should consider larger screen sizes.

I advise you to spend some time in

And here is a couple of demos for nested list groups:

consistent-styling-for-nested-lists-with-bootstrap

nested list group example

I hope this gives you a starting point.

28373213 0

Try the following code

{{ HTML::link(url().'/blog'.$Blog->id, $Blog->BlogTitle)}} 
19224665 0 Why does Object::try work if it's sent to a nil object?

If you try to call a method on a nil object in Ruby, a NoMethodError exception arises with the message:

"undefined method ‘...’ for nil:NilClass" 

However, there is a try method in Rails which just return nil if it's sent to a nil object:

require 'rubygems' require 'active_support/all' nil.try(:nonexisting_method) # no NoMethodError exception anymore 

So how does try work internally in order to prevent that exception?

1808049 0

ever tried SET NOCOUNT ON; as an option?

36602474 0 LINQ to JSON - Query for object or an array

I'm trying to get a list of SEDOL's & ADP values. Below is my json text:

{ "DataFeed" : { "@FeedName" : "AdminData", "Issuer" : [{ "id" : "1528", "name" : "ZYZ.A a Test Company", "clientCode" : "ZYZ.A", "securities" : { "Security" : { "id" : "1537", "sedol" : "SEDOL111", "coverage" : { "Coverage" : [{ "analyst" : { "@id" : "164", "@clientCode" : "SJ", "@firstName" : "Steve", "@lastName" : "Jobs", "@rank" : "1" } }, { "analyst" : { "@id" : "261", "@clientCode" : "BG", "@firstName" : "Bill", "@lastName" : "Gates", "@rank" : "2" } } ] }, "customFields" : { "customField" : [{ "@name" : "ADP Security Code", "@type" : "Textbox", "values" : { "value" : "ADPSC1111" } }, { "@name" : "Top 10 - Select one or many", "@type" : "Dropdown, multiple choice", "values" : { "value" : ["Large Cap", "Cdn Small Cap", "Income"] } } ] } } } }, { "id" : "1519", "name" : "ZVV Test", "clientCode" : "ZVV=US", "securities" : { "Security" : [{ "id" : "1522", "sedol" : "SEDOL112", "coverage" : { "Coverage" : { "analyst" : { "@id" : "79", "@clientCode" : "MJ", "@firstName" : "Michael", "@lastName" : "Jordan", "@rank" : "1" } } }, "customFields" : { "customField" : [{ "@name" : "ADP Security Code", "@type" : "Textbox", "values" : { "value" : "ADPS1133" } }, { "@name" : "Top 10 - Select one or many", "@type" : "Dropdown, multiple choice", "values" : { "value" : ["Large Cap", "Cdn Small Cap", "Income"] } } ] } }, { "id" : "1542", "sedol" : "SEDOL112", "customFields" : { "customField" : [{ "@name" : "ADP Security Code", "@type" : "Textbox", "values" : { "value" : "ADPS1133" } }, { "@name" : "Top 10 - Select one or many", "@type" : "Dropdown, multiple choice", "values" : { "value" : ["Large Cap", "Cdn Small Cap", "Income"] } } ] } } ] } } ] } } 

Here's the code that I have so far:

var compInfo = feed["DataFeed"]["Issuer"] .Select(p => new { Id = p["id"], CompName = p["name"], SEDOL = p["securities"]["Security"].OfType<JArray>() ? p["securities"]["Security"][0]["sedol"] : p["securities"]["Security"]["sedol"] ADP = p["securities"]["Security"].OfType<JArray>() ? p["securities"]["Security"][0]["customFields"]["customField"][0]["values"]["value"] : p["securities"]["Security"]["customFields"]["customField"][0]["values"]["value"] }); 

The error I get is:

Accessed JArray values with invalid key value: "sedol". Int32 array index expected

I think I'm really close to figuring this out. What should I do to fix the code? If there is an alternative to get the SEDOL and ADP value, please do let me know?

[UPDATE1] I've started working with dynamic ExpandoObject. Here's the code that I've used so far:

dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter()); foreach (dynamic element in obj) { Console.WriteLine(element.DataFeed.Issuer[0].id); Console.WriteLine(element.DataFeed.Issuer[0].securities.Security.sedol); Console.ReadLine(); } 

But I'm now getting the error 'ExpandoObject' does not contain a definition for 'DataFeed' and no extension method 'DataFeed' accepting a first argument of type 'ExpandoObject' could be found. NOTE: I understand that this json text is malformed. One instance has an array & the other is an object. I want the code to be agile enough to handle both instances.

[UPDATE2] Thanks to @dbc for helping me with my code so far. I've updated the json text above to closely match my current environment. I'm now able to get the SEDOLs & ADP codes. However, when I'm trying to get the 1st analyst, my code only works on objects and produces nulls for the analysts that are part of an array. Here's my current code:

var compInfo = from issuer in feed.SelectTokens("DataFeed.Issuer").SelectMany(i => i.ObjectsOrSelf()) let security = issuer.SelectTokens("securities.Security").SelectMany(s => s.ObjectsOrSelf()).FirstOrDefault() where security != null select new { Id = (string)issuer["id"], // Change to (string)issuer["id"] if id is not necessarily numeric. CompName = (string)issuer["name"], SEDOL = (string)security["sedol"], ADP = security["customFields"] .DescendantsAndSelf() .OfType<JObject>() .Where(o => (string)o["@name"] == "ADP Security Code") .Select(o => (string)o.SelectToken("values.value")) .FirstOrDefault(), Analyst = security["coverage"] .DescendantsAndSelf() .OfType<JObject>() .Select(jo => (string)jo.SelectToken("Coverage.analyst.@lastName")) .FirstOrDefault(), }; 

What do I need to change to always select the 1st analyst?

357951 0

Because your dropdownlist is contained within another control it may be that you need a recursive findcontrol.

http://weblogs.asp.net/palermo4/archive/2007/04/13/recursive-findcontrol-t.aspx

16527755 0
 if ($("b").has(":contains('Choose a sub category:')").length) { /*Your Stuff Here*/ } 
8656409 0 mongodb map-reduce output doubles

my source database have documents like..

{date:14, month:1, year:2011, name:"abc", item:"A"} {date:14, month:1, year:2011, name:"abc", item:"B"} {date:14, month:1, year:2011, name:"def", item:"A"} {date:14, month:1, year:2011, name:"def", item:"B"} {date:15, month:1, year:2011, name:"abc", item:"A"} {date:16, month:1, year:2011, name:"abc", item:"A"} {date:15, month:1, year:2011, name:"def", item:"A"} {date:16, month:1, year:2011, name:"def", item:"A"} 

and my map reduce is like...

var m = function(){ emit({name:this.name, date:this.date, month:this.month, year:this.year}, {count:1}) } var r = function(key, values) { var total_count = 0; values.forEach(function(doc) { total_count += doc.count; }); return {count:total_count}; }; var res = db.source.mapReduce(m, r, { out : { "merge" : "bb_import_trend" } } ); 

so "myoutput" collection will have counts like this....

{ "_id" : { date : 14, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 2 } }, { "_id" : { date : 14, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 2 } }, { "_id" : { date : 15, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 1 } }, { "_id" : { date : 15, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 1 } }, { "_id" : { date : 16, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 1 } }, { "_id" : { date : 16, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 1 } } 

so total 6 documents

so when aother three documents of date 17 like...

{date:17, month:1, year:2011, name:"abc", item:"A"} {date:17, month:1, year:2011, name:"abc", item:"B"} {date:17, month:1, year:2011, name:"def", item:"A"} 

has been added to my source collection...and again i am running map-reduce it should be jus addition of two documents like...

previous 6 plus

... { "_id" : { date : 17, month : 1, year : 2011, name : "abc" }, "_value" : { "count" : 2 } }, { "_id" : { date : 17, month : 1, year : 2011, name : "def" }, "_value" : { "count" : 1 } } 

but instead of this it duplicates all the previous 6 documents and adds another 2 new ones..so total of 14 documents in my output collection(though i 've used merge in output).

Note > : when i am using another database having same source collection and doing the same procedure it gives me desired output(of only 8 collection).but my database using by my gui is still duplicating the old ones.

20973886 0

The example method you provide

public SomeObject someObjectBehavior(final SomeObject oldSomeObject,final SomeObject newSomeObject) { if(oldSomeObject == null) { oldSomeObject = newSomeObject; //Assignment operation } } 

is a perfect example of why making your parameters final is a Good Idea. Without making your variables final, you might not realize that your method does nothing, since reassigning a parameter reference doesn't change anything outside of your method.

16599422 0 Cannot create new project - There must not already be a project at this location

I am trying to start using the just released Android Studio, I have already established the location for the Android SDK, and the Studio opens correctly.

Now, I want to create a new application project, but I cannot figure out what to select as project location.

Steps followed:

I read a similar question, and I am making sure, as you can tell by the steps I followed, that I am entering the path at the very end, and it still won't work for me.

I really think there must be a silly thing I am missing here, not sure what it may be though.

Any ideas?

38902099 0 Is it necessary to use Static nested class to create a node for linked list

Can you please describe the use of below code and how it works.

class LinkedList { Node head; // head of list static class Node { int data; Node next; Node(int d) { data = d; next=null; } // Constructor } public static void main(String[] args) { LinkedList llist = new LinkedList(); llist.head = new Node(1); Node second = new Node(2); Node third = new Node(3); llist.head.next = second; // Link first node with the second node second.next = third; // Link second node with the third node } } 
7971173 0 Webgrid checkbox selection lost after paging

I have a webgrid

@{ var gdAdminGroup = new WebGrid(source: Model, rowsPerPage: 20, ajaxUpdateContainerId: "tdUserAdminGroup"); } @gdAdminGroup.GetHtml( htmlAttributes: new { id = "tdUserAdminGroup" }, tableStyle: "gd", headerStyle: "gdhead", rowStyle: "gdrow", alternatingRowStyle: "gdalt", columns: gdAdminGroup.Columns( gdAdminGroup.Column(columnName: "Description", header: "Admin Group"), gdAdminGroup.Column(header: "", format: @<text><input name="chkUserAdminGroup" type="checkbox" value="@item.AdminGroupID" @(item.HasAdminGroup == 0? null : "checked") /></text>) ) ) 

If I check some checkboxs and goes to the second page, the selection on the first page will be lost. Can anyone help me with this? Thank you

12179679 0 How to allow read-only binding to the internal properties of a custom control DependencyProperty?

I am developing a CustomControl that exposes the DependencyProperty SearchRange, which is based on the custom class Range.

public class MyCustomControl : Control { public static readonly DependencyProperty SearchRangeProperty = DependencyProperty.Register( "SearchRange", typeof (Range<DateTime>), typeof (VariableBrowser)); // ... public Range<DateTime> SearchRange { get { return (Range<DateTime>)this.GetValue(SearchRangeProperty); } set { this.SetValue(SearchRangeProperty, value); } } // ... } 

The class Range contains two different properties, Minimum and Maximum, and it implements INotifyPropertyChanged.

public class Range<T> : INotifyPropertyChanged where T : IComparable { private T _maximum; private T _minimum; public T Maximum { get { return this._maximum; } set { this._maximum = value; this.OnPropertyChanged("Maximum"); } } public T Minimum { get { return this._minimum; } set { this._minimum = value; this.OnPropertyChanged("Minimum"); } } // ... } 

The specifications that I am following require that an application that uses my Custom control should be able to bind to the SearchRange property only in order to read its inner values (Minimum and Maximum), as these must be handled internally and set just by my CustomControl. The binding target should be updated after any variation to either the SearchRange property or its internal props (Minimum and Maximum), without reassigning the entire SearchRange. Alternatively, I should permit to bind directly to the internal properties (SearchRange.Minimum and SearchRange.Maximum).

I tried many different ways to achieve this result, but none was successful. How could I obtain the required result?

Thanks in advance.

25670049 0 Changing checkbox attributes for multiple rows with single checkbox

Good Morning,

Im working on a larger project but i tried to do a simple page in order to check my work. php/mysql newb here. Sorry! :)

What im trying to accomplish is ultimately having a single user page shown with rows of tasks from a table and a single check mark in order to say if the user has completed the task or not by checking or unchecking the box.

For testing purposes, I have set up a table with rows labled testid, testdata and testcheck. The testid a INT(2)AutoIncrement and Primary and Unique, testdata is a VARCHAR(30) and testcheck is a TINYINT(1). The auto increment isnt really important because I manually populated all the rows. I have 5 rows (for the array sake) consisting of 1-5 testid, "testdata1-5" for testdata and either a 0 or a 1 for testcheck. The table is functioning fine and the database can be queried.

Here is the code for the php start page:

<html> <?php include_once('init.php'); $query = mysql_query("SELECT testid, testdata, testcheck FROM testtable"); ?> <h1>Test form for checkmarks</h1> <form method="POST" action="testover.php"> <table border="1"> <tr> <td> Test ID </td> <td> Test Data </td> <td> Checked </td> <td> Test Check </td> </tr> <?php while ( $row = mysql_fetch_assoc($query)) { ?> <tr> <td> <?php echo $row['testid']; ?> </td> <td> <?php echo $row['testdata']; ?> </td> <td> <center><input type="checkbox" name="<?php $row['testid'] ?>" value="<?php $row['testcheck']; ?>" <?php if($row['testcheck']=='1'){echo 'checked';} ?>></center> </td> <td> <center><?php echo $row['testcheck']; ?></center> </td> </tr> <?php } ?> </table> <input type="submit" name="confirm" value="Confirm Details"> <a href="testcheck.php"><input type="button" value="Home"></a> </form> </html> 

Ive been going back and forth trying to use an array for the inputs name (name="something[]") or the "isset" parameter but that is where my knowledge is failing. Ive read countless articles both here and on other websites and I cant seem to find the right code to use. Most sites have rows with multiple check boxes or a different layout of their table.

I posted here to hopefully be pointed in some direction as to how to update the DB with these values of the check marks.

22401676 0

In object-oriented programming, a constructor in a class is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set member variables required.

So the var catC = new Cat("Fluffy", "White"); creates an new instance of the constructor class Cat

17897551 0 Using databases with Java on Mac

I need to create a simple Java application that connects to a local database file, and will run on a mac.

I've figured that JDBC is a good option, but what file format/drivers should I use? Is .MDB files a possibility?

Thanks for any help!

2568729 0 Android: Create TextView that flashes when clicked

How do I set up a TextView to flash when it is clicked? With flashing I mean that I want to change the background color of the TextView. I essentially want one of the objects that is displayed in a ListActivity, but inside a normal View.

I have tried to do this by adding an OnClickListener, but what I really need is something like adding an On(Un)SelectListener. Using the onClickListener, I can change the TextView background, but obviously the background stays that color. I thought of using a new Handler().postDelayed(new Runnable(){ ... }) kind of thing to reset the backround after some small time, but I did not know if this would be overkill for what I'm trying to do.

What would you recommend?

15656736 0

Your server delivers the resource http://dev.fristil.se/hbh/wp-content/themes/skal/images/video/bubblybeer.webm with the HTTP header Content-Type: text/plain – and therefore Firefox refuses to treat it as anything else.

“Teach” your server to deliver such content as video/webm.

(Same goes for your ogv – your server also says that resource would be text, should be video/ogg instead.)

14007719 0

(Earlier versions) of IE cannot cast a function object to it's source as you request it. Thus, the strings cannot be exchanged that easily.

You can either replace the whole old "_self" function by a new _parent function, e.g.:

$('a[onclick*="_self"]').attr('onclick', function() { _parent-stuff }); 

or - I read your last comment and the second solution won't work for you as it would require changing the HTML of the body.

28401891 0

Check out Array#map.

ids = [ 123, 456 ] connections = ids.map do |id| @graph.get_connections("#{ id }","?fields=posts") end 
10273591 0

getattr()

32906659 0

Just add a dummy column with the source name:

$query = '(SELECT "item" as table, id,name FROM `item` WHERE `accepted` = '1' AND `name` LIKE '%".$search."%') UNION ALL (SELECT "category" AS table, id,name FROM `category` WHERE `name` LIKE '%".$search."%') UNION ALL (SELECT "store" AS table, id,name FROM `store` WHERE `accepted` = '1' AND `name` LIKE '%".$search."%') LIMIT 25 '; 
1600849 0

Look up in the registry to find the DLL associated with the ProgID you have. Once you have its full path, load it as a normal .NET assembly:

var type = Type.GetTypeFromProgID("My.ProgId", true); var regPath = string.Format(@"{0}\CLSID\{1:B}\InProcServer32", Registry.ClassesRoot, type.GUID); var assemblyPath = Registry.GetValue(regPath, "", null); if (!string.IsNullOrEmpty(assemblyPath)) { var assembly = Assembly.LoadFrom(assemblyPath); // Use it as a normal .NET assembly } 
4704472 0 How to set alarm in qt mobility application

Is it possible to set an alarm for a specific time in Qt?

5597109 0

I have an app that does something similar - we use Open ID and OAuth exclusively for logins, and while we store the user's email address (Google Account or Facebook sends it back during authentication) they never login using it and so don't have/need a password.

This is a callback for what happens when a user signs up via Facebook:

 User.create!( :facebook_id => access_token['uid'], :email => data["email"], :name => data["name"], :password => Devise.friendly_token[0,20]) 

The Devise.friendly_token[...] just generates a random 20 character password for the user, and we are using our default User model with devise just fine. Just setting the password in a similar way on your users would be my approach, since you are never going to use their password. Also, if you ever change your mind and want them to be able to login, you can just change a user's password in the database and build a login form, and devise will take care of the rest.

11882692 0

An inline event handler like your onclick='...' can only reference globally scoped variables and functions, but if your variable named global is declared inside a function (inside a document.ready handler, for example) then it is not global and the inline attribute event handler can't see it.

16690380 0 How to get inbox sms in pdu format in android

Can someone let me know if there is a way to get the inbox sms in pdu format?

15984334 0

You can get yourself right to left,

  1. first change all left to something like stackoverflow
  2. Then change right to left
  3. change stackoverflow to right
  4. Now find margin: and padding: , if like margin:0 1px 0 5px change to margin:0 5px 0 1px

Java code may need to be changed, I do not know

18525121 0 How to share data between controllers in angularjs

I'm currently trying to learn angularJS and am having trouble accessing data between controllers.

My first controller pulls a list of currencies from my api and assigns it to $scope.currencies. When I click edit, what is supposed to happen is that it switches the view which uses another controller. now when debugging using batarang, $scope.currencies does show an array of currency objects:

{ currencies: [{ CurrencyCode: HKD Description: HONG KONG DOLLAR ExchangeRateModifier: * ExchangeRate: 1 DecimalPlace: 2 }, { CurrencyCode: USD Description: US DOLLAR ExchangeRateModifier: * ExchangeRate: 7.7 DecimalPlace: 2 }] } 

But when using angular.copy, the $scope.copiedcurrencies result in null.

function CurrencyEditCtrl($scope, $injector, $routeParams) { $injector.invoke(CurrencyCtrl, this, { $scope: $scope }); $scope.copiedcurrencies = angular.copy($scope.currencies); console.log($scope.copiedcurrencies); } 
11233777 0

I've got a functional solution using option #1, but it's such a hack I can't bear to post it publicly. Basically, in serializeData I'm reaching into the model and modifying _relations before and after a call to toJSON. Not thread safe and ugly as heck. Hoping to come back soon and find a proper solution.

40104926 0 Javascript - Does not save into database when i change value in javascript side

My code looks like this:

 document.getElementById("medewerkers").value = mdwString; document.getElementById("medewerkersomschr").value = mdwNaam; $("#medewerkers").val(mdwString); $("#medewerkersomschr").val(mdwNaam); document.getElementById("machines").value = mchString; document.getElementById("machinesomschr").value = mchNaam; $("#machines").val(mchString); $("#machinesomschr").val(mchNaam); 

As u can see i tried two ways to get a value into fields.

This does work for me, but next up when i try to save the values into the database it goes wrong. It looks like the view got updated but not the value of the html itself. Does anyone have an idea what i am doing wrong or what i should change up?

11914152 1 How to send the TAB button using Python In SendKey and PywinAuto Modules

This is the my code which will open the window and send the keys to the window but some screen s are not working

from pywinauto.application import * import time app=Application.Start("Application.exe") app.window_(title="Application") time.sleep(1) app.top_window_().TypeKeys("{TAB 2}") 
11900714 0

On the blog page you can use:

{% for post in site.posts %} … {% endfor %} 

To retrieve all posts and show them all. If you want to filter more (say, you have a third category you wouldn't want to show on this page:

{% for post in site.posts %} {% if post.categories contains 'post' or post.categories contains 'photos' %} ... {% endif %} {% endfor %} 
1657811 0

Subscriptions in the iPhone SDK really are to get around the fact that you cannot sell virtual credits, therefore what you can do is sell a subscription and make the digital content free from within your application assuming the user has a subscription to your service, you are correct in that you have to handle the majority of the logic yourself

23474010 0 Java: How to copy automatically a file each time one is generated in a folder?

I am asking for a Java code.

An ERP generates XML files in a folder, and each one has a different name.

For data extraction, I need to:

If new file is generated:

  1. Copy file from the main folder to a secondary folder

  2. Rename this file under "temp"

  3. Extract data with an ETL (Talend) from "temp"

  4. Delete the file "temp"

My question is: How to capture automaticaly a file with Java in order to copy or rename it each time one is generated?

Thanks

36421576 0 In import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; SimpleImageLoadingLIstneer is not found

I am learning android and new to android. I want to pick multiple images from gallery and then want to show them in gridview and for that i am using UniversalImageLoader library 1.9.5

To Use UniversalImageLoader Library i added the following dependency in build.gradle app module

 compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' 

and then i copied and pasted the solution from some tutorial

In This my mainactivity is like following in which i used universal image loader library

package tainning.infotech.lovely.selectmultipleimagesfromgallery; import java.util.ArrayList; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.provider.MediaStore; import android.util.Log; import android.util.SparseBooleanArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.Toast; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.GridView; import android.widget.ImageView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; /** * @author Paresh Mayani (@pareshmayani) */ public class MainActivity extends BaseActivity { private ArrayList<String> imageUrls; private DisplayImageOptions options; private ImageAdapter imageAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.content_main); final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID }; final String orderBy = MediaStore.Images.Media.DATE_TAKEN; Cursor imagecursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy + " DESC"); this.imageUrls = new ArrayList<String>(); for (int i = 0; i < imagecursor.getCount(); i++) { imagecursor.moveToPosition(i); int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA); imageUrls.add(imagecursor.getString(dataColumnIndex)); System.out.println("=====> Array path => "+imageUrls.get(i)); } options = new DisplayImageOptions.Builder() .showStubImage(R.drawable.stub_image) .showImageForEmptyUri(R.drawable.image_for_empty_url) .cacheInMemory() .cacheOnDisc() .build(); imageAdapter = new ImageAdapter(this, imageUrls); GridView gridView = (GridView) findViewById(R.id.gridview); gridView.setAdapter(imageAdapter); /*gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { startImageGalleryActivity(position); } });*/ } @Override protected void onStop() { imageLoader.stop(); super.onStop(); } public void btnChoosePhotosClick(View v){ ArrayList<String> selectedItems = imageAdapter.getCheckedItems(); Toast.makeText(MainActivity.this, "Total photos selected: "+selectedItems.size(), Toast.LENGTH_SHORT).show(); Log.d(MainActivity.class.getSimpleName(), "Selected Items: " + selectedItems.toString()); } /*private void startImageGalleryActivity(int position) { Intent intent = new Intent(this, ImagePagerActivity.class); intent.putExtra(Extra.IMAGES, imageUrls); intent.putExtra(Extra.IMAGE_POSITION, position); startActivity(intent); }*/ public class ImageAdapter extends BaseAdapter { ArrayList<String> mList; LayoutInflater mInflater; Context mContext; SparseBooleanArray mSparseBooleanArray; public ImageAdapter(Context context, ArrayList<String> imageList) { // TODO Auto-generated constructor stub mContext = context; mInflater = LayoutInflater.from(mContext); mSparseBooleanArray = new SparseBooleanArray(); mList = new ArrayList<String>(); this.mList = imageList; } public ArrayList<String> getCheckedItems() { ArrayList<String> mTempArry = new ArrayList<String>(); for(int i=0;i<mList.size();i++) { if(mSparseBooleanArray.get(i)) { mTempArry.add(mList.get(i)); } } return mTempArry; } @Override public int getCount() { return imageUrls.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = mInflater.inflate(R.layout.row_multiphoto_item, null); } CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1); final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1); imageLoader.displayImage("file://"+imageUrls.get(position), imageView, options, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(Bitmap loadedImage) { Animation anim = AnimationUtils.loadAnimation(MainActivity.this,Animation.START_ON_FIRST_FRAME); imageView.setAnimation(anim); anim.start(); } }); mCheckBox.setTag(position); mCheckBox.setChecked(mSparseBooleanArray.get(position)); mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener); return convertView; } OnCheckedChangeListener mCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked); } }; } } but when i try to build the project it shows me the error following error Error:(26, 53) error: cannot find symbol class SimpleImageLoadingListener and also in following import statement import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; SimpleImageLoadingListener is underlined as red line. and it says cannot find symbol SimpleImageLoadingListener . The BaseActivity.java is following import android.app.Activity; import com.nostra13.universalimageloader.core.ImageLoader; /** * @author Paresh Mayani (@pareshmayani) */ public abstract class BaseActivity extends Activity { protected ImageLoader imageLoader = ImageLoader.getInstance(); } The UilApplication.java is like following package tainning.infotech.lovely.selectmultipleimagesfromgallery; /** * Created by student on 4/5/2016. */ import android.app.Application; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; /** * @author Paresh Mayani (@pareshmayani) */ public class UILApplication extends Application { @Override public void onCreate() { super.onCreate(); // This configuration tuning is custom. You can tune every option, you may tune some of them, // or you can create default configuration by // ImageLoaderConfiguration.createDefault(this); // method. ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()) .threadPoolSize(3) .threadPriority(Thread.NORM_PRIORITY - 2) .memoryCacheSize(1500000) // 1.5 Mb .denyCacheImageMultipleSizesInMemory() .discCacheFileNameGenerator(new Md5FileNameGenerator()) //.enableLogging() // Not necessary in common .build(); // Initialize ImageLoader with configuration. ImageLoader.getInstance().init(config); } } The manifest file is this <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tainning.infotech.lovely.selectmultipleimagesfromgallery" > <!-- Include following permission if you load images from Internet --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Include following permission if you want to cache images on SD card --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Build.gradle(Module:app) is like this apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.2" defaultConfig { applicationId "tainning.infotech.lovely.selectmultipleimagesfromgallery" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5' } Kindly help as soon as possible. 

I searched for the solution of above problem but was not able to find any. I searched as much i can but didn't get the solution.

Thanks in advance 
35106626 1 Implement Neighbors to find the d-neighborhood of a string in Python

Input: A string Pattern and an integer d. Output: The collection of strings Neighbors(Pattern, d).

Sample Input:
ACG 1

Sample Output:
TCG ACG GCG CCG ACA ACT AGG AAG ATG ACC

What is the algorithm to solve this problem?

1316659 0 BLOB data to simple string in DataGridView?

I am using C# & MYSQL to develop a desktop application.

In one of my form I have a DataGridView (dgvBookings) and in my database table I have a table tblBookings which contains a field specialization of type BLOB.

I am selecting data with following query,

SELECT * FROM tblBookings WHERE IsActive=1; 

and then binding the data with DataGridView as,

dgvBookings.DataSource = ds.Tables["allbookings"]; 

BUT after binding the data in gridview it shows Byte[] Array value for all rows of column specialization which is of BLOB type.

How yo solve this problem, I want the data in String format, whatever is written in that column should be show as it is there in the grid.

8912963 0

I'm not sure I understand your question, but you may want to look into the NSNotificationCenter. You can use it to send messages to your controllers, here's an example of triggering a notification:

[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotificationName" object:self userInfo:[NSDictionary dictionaryWithObject:XXXX forKey:@"someObject"]]; 

As you can see, you can even send parameters to it. And in the target controller you just register an observer to respond to those messages:

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(yourMethodHere:) name: @"myNotificationName" object: nil]; 

Regards!

28441260 0 Use ng-model in href

Angular is new to me. I try to make a link which contains a dynamic href attribute.

So far, I read that using ng-href instead of href was a good practice. But, when I try this :

<a target="_blank" data-ng-href="{{myUrl}}">Follow this URL</a> 

(I also tried without the curly brackets)

The href value does not take the value that I put in the controller :

function (data) { console.log("data : %o", data); console.log("url : "+data.url); $scope.myUrl = data.url; } 

Am I doing something wrong?

Here is the value of data as shown is the console :

data : Object requestTokenId: 3405 url: "https://api.twitter.com/oauth/authorize?oauth_token=TBqMIpdz[...]" __proto__: Object 

More background :

I want to create a "twitter authorization" modal :

<div data-ng-controller="myController"> <!-- Some HTML elements on which data-binding works. --> <div class="modal fade" id="authorizationTwitterModal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">Authorization</h4> </div> <div class="modal-body"> <ol> <li>Connect to your account</li> <li id="liAuthorizationTwitterURL"><a target="_blank" ng-href="{{myUrl}}">Follow this URL</a></li> <li>Authorize Ambasdr</li> <li>Copy/Paste the authorization code here :</li> </ol> <p class="text-center"> <input id="verifier" name="value" type="text"> </p> </div> </div> </div> </div> 

Then, when the user wants to authorize twitter, I call my server, which calls twitter then give me the URL that I want to place into the href:

$scope.addTwitterAccount = function(brandId) { console.log("addTwitterAccount"); var popup = wait("Authorization"); //$scope.myUrl = 'http://www.google.fr'; <- This change works! $.doPost("/api/request_token/", { socialMedia: 'TWITTER' }, function (data) { console.log("data : %o", data); console.log("url : "+data.url); $scope.myUrl = data.url; // <- This change does not work! } ); }; 
36458024 0 Git pull -The following untracked working tree files would be overwritten by merge

I am trying to do git pull in master branch and I see this message with a long list of files

The following untracked working tree files would be overwritten by merge: 

I really don't care if these files are over written or not, as I need to get the latest form remote. I have looked into it and I cannot do git fetch, git add * and git reset HARD

When I do git status, it shows me the list of only untracked files. I don't want to commit these files

17389575 0

A pointer is a variable, that store a memory address

The stored address in the pointer is the address of the first-block of the memory-structure of the object it points at

The syntax of a pointer that points at an object of type TYPE:

TYPE * pointer; // define a pointer of type TYPE 

NULL (address 0) denotes a pointer that doesn't point anywhere currently:

pointer = 0; 

To get the memory address of a variable or object:

pointer = &object; // pointer now stores the address of object 

To get the pointed TYPE variable, you de-reference the pointer:

assert(&(*pointer) == &object); // *pointer ~ object 

In example:

int a = 10; // type int int * b = &a; // pointer to int int* * c = &b; // pointer to int* printf(" %d \n ", a ); printf(" %d \n ", *b ); printf(" %d \n ", **c ); char t [256] = "Not Possible ?"; char * x = t; char * y = (x + 4); // address arithmetic printf(" %s \n ", x ); // Not Possible ? printf(" %s \n ", y ); // Possible ? 

void* is a special pointer-type that can store any pointer of any degree, but cannot be used until you cast it to a compatible type ..

void * z = &c; // c holds int** printf(" %d \n ", **((int**)c) ); 
33248746 0

Hoisting moves function declarations and variable declarations to the top, but doesn't move assignments.

Therefore, you first code becomes

var a; function f() { console.log(a.v); } f(); a = {v: 10}; 

So when f is called, a is still undefined.

However, the second code becomes

var a, f; a = {v: 10}; f = function() { console.log(a.v); }; f(); 

So when f is called, a has been assigned.

4031573 0 SQL & Excel 2010

Good morning,

Does anyone know if there is an easy way I can use a SQL query in Excel to select specific data from an Excel spreadsheet without having to use VBA, Access, an SQL database or complicated Excel formula?

Thank you very much.

23442863 0 osx x64 reverse tcp shell code program terminate with success

Been trying to learn some assembler 64 bit on osx and thought a good exercise would be to port a reverse tcp shell code. The program then compiled and linked run fine and listen to the given port 4444, but then I try to connect with nc -nv 127.0.0.1 4444 the shell_code terminate with success and the response back to nc is: Connection to 127.0.0.1 4444 port [tcp/*] succeeded!

It is compiled and linked with:

nasm -g -f macho64 bindshell.s ld -arch x86_64 -macosx_version_min 10.7.0 -lSystem -o bindshell bindshell.o (nasm -v NASM version 2.11.02 compiled on Feb 19 2014) uname -a Darwin MacBook-Pro.local 12.4.0 Darwin Kernel Version 12.4.0: Wed May 1 17:57:12 PDT 2013; root:xnu-2050.24.15~1/RELEASE_X86_64 x86_64 

Been trying to debug it and looked at registers and memory but can't see whats missing, new to 64 bit assembler. The code used is:

BITS 64 section .text global start start: jmp runsh start_shell: dd '/bin//sh', 0 runsh: lea r14, [rel start_shell] ; get address of shell mov rax, 0x2000061 ; call socket(SOCK_STREAM, AF_NET, 0); mov rdi, 2 ; SOCK_STREAM = 2 mov rsi, 1 ; AF_NET = 1 xor rdx, rdx ; protocol, set to 0 syscall mov r12, rax ; save socket from call sock_addr: xor r8, r8 ; clear the value of r8 push r8 ; push r8 to the stack as it's null (INADDR_ANY = 0) push WORD 0x5C11 ; push our port number to the stack (Port = 4444) push WORD 2 ; push protocol argument to the stack (AF_INET = 2) mov r13, rsp ; Save the sock_addr_in into r13 ;bind mov rax, 0x2000068 ; bind(sockfd, sockaddr, addrleng); mov rdi, r12 ; sockfd from socket syscall mov rsi, r13 ; sockaddr mov rdx, 16 ; addrleng the ip address length syscall ;listen mov rax, 0x200006A ; int listen(sockfd, backlog); mov rdi, r12 ; sockfd xor rsi, rsi ; backlog syscall ;accept mov rax, 0x200001E ; int accept(sockfd, sockaddr, socklen); mov rdi, r12 ; sockfd xor rsi, rsi ; sockaddr xor rdx, rdx ; socklen syscall dup: ; dup2 for stdin, stdout and stderr mov rax, 0x200005A ; move the syscall for dup2 into rax mov rdi, r12 ; move the FD for the socket into rdi syscall ; call dup2(rdi, rsi) cmp rsi, 0x2 ; check to see if we are still under 2 inc rsi ; inc rsi jbe dup ; jmp if less than 2 ;execve mov rax, 0x200003B ; execve(char *fname, char **argp, char **envp); mov rdi, r14 ; set the address to shell xor rsi, rsi xor rdx, rdx run_cmd: ; using as break point syscall 
3586871 0 Bold & Non-Bold Text In A Single UILabel?

How would it be possible to include both bold and non-bold text in a uiLabel?

I'd rather not use a UIWebView.. I've also read this may be possible using NSAttributedString but I have no idea how to use that. Any ideas?

Apple achieves this in several of their apps; Examples Screenshot: link text

Thanks! - Dom

8856750 0 How do I sidestep TT_NUMBER from StreamTokenizer

I replaced a call to String.split() with a loop using StreamTokenizer, because my users needed quoting functionality. But now I'm having problems from numbers being converted to numbers instead of left as Strings. In my loop if I get a TT_NUMBER, I convert it back to a String with Double.toString(). But that is not working for some long serial numbers that have to get sent to me; they are being converted to exponential notation.

I can change the way I am converting numbers back into Strings, but I would really like to just not parse numbers in the first place. I see that StreamTokenizer has a parseNumbers() method, that turns on number parsing, but there doesn't seem to be a way to turn it off. What do I have to do to create and configure a parser that is identical to the default but does not parse numbers?

27482844 0

It's a placeholder for formatting. It represents a string.

" %s link.get" % ('href') 

is equivalent to

" " + 'href' + " link.get" 

The placeholders can make things more readable, without cluttering the text with quotes and +. Though in this case, there is no variable, so it is simply

" href link.get" 

However, .format() is preferred to % formatting nowadays, like

" {} link.get".format('href') 
38100821 0 laravel 5 subdomain not working in live

I have a site that can be access in stage.mysite.com now I want to have a subdomain for another page and it can be access at profile.stage.mysite.com.

in my server I have configured the hosting.

ServerAdmin webmaster@localhost ServerName stage.mysite.com ServerAlias *.stage.mysite.com DocumentRoot /var/www/staging.mysite.com/public 

in my routes.php this is the code.

Route::group(['domain' => 'profile.stage.mysite.com'], function() { Route::get('/', 'FrontendController@profile'); }); 

but when I tried to access http://profile.stage.mysite.com returns Server not found error. any ideas how to access my static page into subdomain?

33018837 0 Static array in Julia?

I have functions which are called many times and require temporary arrays. Rather than array allocation happening every time the function is called, I would like the temporary to be statically allocated once.

How do I create a statically allocated array in Julia, with function scope?

3897575 0

With the AudioQueue, I can register for a callback whenever the system needs sound, and respond by filling a buffer with raw audio data.

The closest analogy to this in Android is AudioTrack. Rather than the callback (pull) mechanism you are using, AudioTrack is more of a push model, where you keep writing to the track (presumably in a background thread) using blocking calls.

5536893 0 JQuery Validate and database calls

I am using Jörn Zaefferer's JQuery Validate, but I need to make some database calls to validate some fields (for example to check if a User Name is unique). Is this possible using this plugin, and if so, does someone have some syntax examples? Here is my current code :

$("form").validate({ rules: { txtUserName: { required: true, minlength: 4 }, txtPassword: { required: true }, txtConfirmPassword: { required: true, equalTo: "#txtPassword" }, txtEmailAddress: { required: true, email: true }, txtTelephoneNumber: { required: true, number: true } }, messages: { txtUserName: { required: "Please enter a User Name", minlength: "User Name must be at least 4 characters" }, txtPassword: { required: "Please enter a Password" }, txtConfirmPassword: { required: "Please confirm Password", equalTo: "Confirm Password must match Password" }, txtEmailAddress: { required: "Please enter an Email Address", email: "Please enter a valid Email Address" }, txtTelephoneNumber: { required: "Please enter a Telephone Number", number: "Telephone Number must be numeric" } } }); }); 

EDIT :

I have got this far, but when I do this, I lose the values on my form, presumably because the form has already posted at this point?

$("form").validate({ //errorLabelContainer: $("#divErrors"), rules: { txtUserName: { required: true, minlength: 4 }, txtPassword: { required: true }, txtConfirmPassword: { required: true, equalTo: "#txtPassword" }, txtEmailAddress: { required: true, email: true }, txtTelephoneNumber: { required: true, number: true//, //postalCode:true } }, messages: { txtUserName: { required: "Please enter a User Name", minlength: "User Name must be at least 4 characters" }, txtPassword: { required: "Please enter a Password" }, txtConfirmPassword: { required: "Please confirm Password", equalTo: "Confirm Password must match Password" }, txtEmailAddress: { required: "Please enter an Email Address", email: "Please enter a valid Email Address" }, txtTelephoneNumber: { required: "Please enter a Telephone Number", number: "Telephone Number must be numeric" } }, onValid: addUser() }); }); 

function addUser() {

 alert($('input[name="txtUserName"]').val()); 

}

17269726 0

depending on the state of the resource, if it's constant, you can put them in a enum object. it if's persistent information, you can put in conf/evolution/default/1.sql, and Play will automatically load it when you initialize everything. you can put configuration constants in conf/application.conf, if it's strings, you can put in message file.

21822188 0 Images are not showing in pdf created using velocity template

I create pdf using Velocity template, but i am not able to put images in pdf. I am adding url into context object and accessing that object into eot.vm file, url is going proper but still images are not displaying in pdf.

Thanks & Regards, Tushar

21969883 0

The pure part of algorithm M is quite short indeed:

algorithmM = mapM (\n -> [0..n-1]) 

For example, here's a run in ghci:

> algorithmM [2,3] [[0,0],[0,1],[0,2],[1,0],[1,1],[1,2]] 

It's also quite easy to put an input/output loop around it. For example, we could add

main = readLn >>= mapM_ print . algorithmM 

Compile and run a program containing these two (!) lines, and you will see something like this:

% ./test [2,3] [0,0] [0,1] [0,2] [1,0] [1,1] [1,2] 
4337576 0

The Problem

I'm assuming that you are using JPA to get your data as objects that can be handled by JAXB. If this is the case the JPA objects may be using lazy loading meaning that a query may not realize all the data at once. However as the JAXB implementation traverses the object graph, more and more of it is brought into memory until you run out.

Option #1 - Provide Data in Chunks

One approach is to return your data in chunks and offer a URI like the one below:

These parameters tie in very nicely to JPA query settings:

namedQuery.setFirstResult(10); namedQuery.setMaxResults(100); 

Option #2 - Provide Links to Get More Data

Alternatively, instead of including all the data you can provide links to get more. For example instead of:

<purchase-order> <product id="1"> <name>...</name> <price>...</price> ... </product> <product id="2"> <name>...</name> <price>...</price> ... </product> ... </purchase-order> 

You could return the following, the client can then request details on products using the provided URI. You can map this in JAXB using an XmlAdapter.

<purchase-order> <product>http://www.example.com/products/1</product> <product>http://www.example.com/products/2</product> ... </purchase-order> 

For more information on XmlAdapter see:

29248865 0 Normal.dotm alternative in Excel for referencing the same single VBA code

Just curiosity.

The only way I know so far is to create an add-in with code, put it in some trusted directory and hope it opens when you need it. The drawback is that it sometimes does not open together with application (e.g. I have a custom UDF in the add-in, I use it in the worksheet and an error is what I get, because the addin hasn't started). For this I have a button on my ribbon which calls a sub in the addin which does nothing, but then the addin is activated the UDF works.

Is there any other efficient way to reference code in another workbooks, like in Word we have normal.dotm template?

4949471 0

To hint a browser that it should download a file, make sure you send the Content-Disposition: attachment header from your application.

7060337 0

I think syntactical uniformity is quite important in generic programming. For instance consider,

#include <utility> #include <tuple> #include <vector> template <class T> struct Uniform { T t; Uniform() : t{10, 12} {} }; int main(void) { Uniform<std::pair<int, int>> p; Uniform<std::tuple<int, int>> t; Uniform<int [2]> a; Uniform<std::vector<int>> v; // Uses initializer_list return 0; } 
8808030 0 RequestBody of a REST application

Iam bit new to SpringMVC REST concept. Need a help from experts here to understand/ resolve following issue, I have developed a SpringMVC application, following is a part of a controller class code, and it works perfectly ok with the way it is, meaning it works ok with the JSON type object,

@RequestMapping(method = RequestMethod.POST, value = "/user/register") public ModelAndView addUser( @RequestBody String payload) { try{ ObjectMapper mapper = new ObjectMapper(); CreateNewUserRequest request = mapper.readValue(payload, CreateNewUserRequest.class); UserBusiness userBusiness = UserBusinessImpl.getInstance(); CreateNewUserResponse response = userBusiness.createNewUser(request); return new ModelAndView(ControllerConstant.JASON_VIEW_RESOLVER, "RESPONSE", response); 

and this is my rest-servlet.xml looks like

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean id="jsonViewResolver" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" /> <bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver" /> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jsonConverter" /> </list> </property> </bean> <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes" value="application/json" /> </bean> <bean name="UserController" class="com.tap.mvp.controller.UserController"/> 

My problem is how do i make it work for normal POST request, My controller should not accept JSON type object instead it should work for normal HTTP POST variables. How do i get values from the request?What are the modifications should i need to be done for that. I need to get rid of

ObjectMapper mapper = new ObjectMapper(); CreateNewUserRequest request = mapper.readValue(payload, CreateNewUserRequest.class); 

and instead need to add way to create an instance of

CreateNewUserRequest

class, by invoking its constructor. For that i need to get values from request. How do i do that? Can i treat @RequestBody String payload as a map and get the values? or is there a specific way to get values from the request of HTTP POST method? following values will be in the request,

firstName, lastName, email,password

11148833 0 How to perform element-wise left shift with __m128i?

The SSE shift instructions I have found can only shift by the same amount on all the elements:

These shift all elements, but by the same shift amount.

Is there a way to apply different shifts to the different elements? Something like this:

__m128i a, __m128i b; r0:= a0 << b0; r1:= a1 << b1; r2:= a2 << b2; r3:= a3 << b3; 
30298027 0

If you are not well aware of executor service then the easiest way to achieve this is by using Thread wait and notify mechanism:

private final static Object lock = new Object(); private static DataType type = null; public static String getTypeOfData { new Thread(new Runnable() { @Override public void run() { fetchData(); } }).start(); synchronized (lock) { try { lock.wait(10000);//ensures that thread doesn't wait for more than 10 sec if (type == DataType.partial || type == DataType.temp) { return "partial"; }else{ return "full"; } } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } return "full"; } private static void fetchData() { synchronized (lock) { type = new SelectTypes().getType(); lock.notify(); } } 

You might have to do some little changes to make it work and looks better like instead of creating new thread directly you can use a Job to do that and some other changes based on your requirement. But the main idea remains same that Thread would only wait for max 10 sec to get the response.

5066444 0

I have figured it out! Although I don't know why the Xlinq approach doesn't work... here is the code that worked for me instead of the query:

 public XElement filter(int min = 0, int max = int.MaxValue) { XElement filtered = new XElement("Stock"); foreach (XElement product in xmlFile.Elements("Product")) { if ((int)product.Element("Price") >= min && (int)product.Element("Price") <= max) filtered.Add(product); } return filtered; } 

that would be great if someone gives me an explain. thanks for reading

29527866 0 Jquery-ui autocomplete won't work in a specific only

Been trying for 2 days and appreciate any help. I can get autocomplete to work outside of the div I am trying to make it work in. The specific div, input field, does not work.

I have tried as others mentioned setting the .ui-autocomplete { z-index: 50000 !important; } to the class, but still doesn't work.

Here is a link to the test page. The div is "destinations" front and center. http://www.inidaho.com/responsive/test4.asp

Here is my header code:

<link rel="stylesheet" media="screen" href="css/bootstrap-theme.min.css"> <link rel="stylesheet" media="screen" href="css/bootstrap.min.css"> <link rel="stylesheet" media="screen" href="css/glyphicons.css"> <link rel="stylesheet" media="screen" href="css/iitheme.css"> <link href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900,100italic,300italic,400italic,500italic,700italic,900italic' rel='stylesheet' type='text/css'> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script> <script> $(function() { var availableTags = [ "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran" ]; $("#destination").autocomplete({ source: availableTags }); }); </script> 

and here is the input I am trying to autocomplete

<form id="home-searchform" class="home-searchform"> <div class="col-lg-8 col-med-5 col-sm-4 col-xs-12 text-center ui-widget"> <label for="destination">destination</label> <input id="destination" name="destination" placeholder="Choose Destination"> </div> <div class="col-lg-4 col-med-3 col-sm-3 col-xs-12"> <input type="button" name="submit" value="GO" class="ui-btn med ui-main txt- center"/> </div> </form> 

I have tried to format the code above correctly, but am having trouble so apologize. Any suggestions are appreciated. Best.

17057721 0

Highlighting the code of interest and hitting tab should add another level of indentation. Shift-tab will remove a level of indentation.

35840752 0 How to use unverified custom domains with Google App Engine

I need customers to be able to point their own custom domains to my GAE app.

e.g. customersdomain.com -- CNAME --> myapp.com (which in turn points to myapp.appspot.com)

I know that I can link a domain to my Google account and then use that domain to serve app engine, but this process does not scale and requires that I have direct access to the customer's domain register/DNS. The only other alternative is to force customers to sign up for Google Apps (why!).

Almost all other PaaS make this process painless:

Does anyone know of a workaround for this? Or am I just going to have to manually link hundreds of domains to my account?

36309391 0 SSRS: Calculate the Max Value

I use SQL Server Report Builder.

I have got 20 machines and I calculate the scrap data for these 20 machines. In my query it looks like:

SELECT SUM(case when ScrapName = 'Blown wheel' then scrapUnits else 0 end) AS BlownWheel, Sum(case when ScrapName = 'Blown bell' then scrapUnits else 0 end) AS BlownBell, Sum(case when ScrapName = 'Produced' then scrapUnits else 0 end) AS Produced 

And to get the scrap I did a calculation in SSRS:

=SUM(Fields!BlownWheel.Value) + SUM(Fields!BlownBell.Value) / SUM(Fields!Produced.Value)*100 

This calculation gave me the correct value.

My Problem now is that I must create a new report and in this report I would like to show one of these 20 machines which produced the maximum value of scrap.

I have done this manually in Excel before. And now I would like to create it as a Report.

16838693 0

There are really only a few methods in NSJSONSerialization. Take a look at the documentation.

json_dic_values = [NSJSONSerialization JSONObjectWithData: [response dataUsingEncoding: NSUTF8StringEncoding] options: 0 error: &error]; 
18059 0 Prevent WebBrowser control from swallowing exceptions

I'm using the System.Windows.Forms.WebBrowser, to make a view a-la Visual Studio Start Page. However, it seems the control is catching and handling all exceptions by silently sinking them! No need to tell this is a very unfortunate behaviour.

void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler throw new Exception("OMG!"); } 

The code above will cancel navigation and swallow the exception.

void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler try { e.Cancel = true; if (actions.ContainsKey(e.Url.ToString())) { actions[e.Url.ToString()].Invoke(e.Url, webBrowser.Document); } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } } 

So, what I do (above) is catch all exceptions and pop a box, this is better than silently failing but still clearly far from ideal. I'd like it to redirect the exception through the normal application failure path so that it ultimately becomes unhandled, or handled by the application from the root.

Is there any way to tell the WebBrowser control to stop sinking the exceptions and just forward them the natural and expected way? Or is there some hacky way to throw an exception through native boundaries?

27665884 0 How to create access controls in express/mongoose

I have my project in expressjs and Mongoose(with mongodb). I have multiple roles of users - admin, manager, user

I want few fields of each table to be accessible by manager while others not. by default user would not have any edit access, admin would have full access. One way is to make this controls in each controller function by looking at the role of user. Is there any easy way of doing it such as checking if the user has controls before saving once for each table so as to avoid duplication of business logic.

My ordersschema is as follows. I dont want customer info to be adited without admin permission.

var OrderSchema = new Schema({ order_type: { type: String, trim: true }, customer_phone: { type: String, trim: true } }); var managerAccess = [order_type]; 

My user model is as follows(more fields not added)

var UserSchema = new Schema({ firstName: { type: String, trim: true, default: '', validate: [validateLocalStrategyProperty, 'Please fill in your first name'] }, roles: { type: [{ type: String, enum: ['user', 'admin'] }], default: ['user'] }, }) 
14467546 0

At the begining of your fragment shader source file (the very first line) put this:

#version 140 

This means that you are telling the GLSL compiler that you use the version 1.40 of the shading language (you can, of course, use a higher version - see Wikipedia for details).

Alternatively, if your OpenGL driver (and/or hardware) doesn't support GLSL 1.40 fully (which is part of OpenGL 3.1), but only GLSL 1.30 (OpenGL 3.0), you can try the following:

#version 130 #extension GL_ARB_uniform_buffer_object : require 

However, this one will work only if your OpenGL 3.0 driver supports the GL_ARB_uniform_buffer_object extension.

Hope this helps.

25630404 0 C++ Multiple Static Functions With Same Name But Different Arguments

It appears as though I stumbled across something odd while trying to write my own wrapper for the freeglut api. Basically, I am writing my own little library to make using freeglut easier. One of the first things that I am doing is attempting to implement my own Color class which will be fed into "glClearColor". I am also having it so that you can enter the colors in manually; this means that I will have mutliple static methods with the same name but different parameters/arguments. I tried to compile this afterwards but recieved an error that makes me think that the compiler cant decide which method to use—which is odd considering the two methods in question are still different. One takes a Color3 class and the other a Color4.

Here is some source:

GL.H

#pragma once #include "Vector3.h" #include "Color3.h" #include "Color4.h" #include <string> class GL { public: static void initializeGL(int argc, char* argv); static void initializeDisplayMode(unsigned int displayMode); static void initializeWindowSize(int width, int height); static void createWindow(std::string title); static void mainLoop(); static void translate(const Vector3 &location); static void translate(float x, float y, float z); static void rotate(double rotation, float x, float y, float z); static void rotate(double rotation, const Vector3& axis); static void color3(const Color3 &color); static void color4(const Color4 &color); static void begin(); static void end(); static void pushMatrix(); static void popMatrix(); static void enable(int enableCap); static void viewport(); static void polygonMode(); static void matrixMode(); static void clearColor(const Color3 &color); static void clearColor(float red, float green, float blue); static void clearColor(float red, float green, float blue, float alpha); static void clearColor(const Color4 &color); static void vertex3(const Vector3 &location); static void vertex3(float x, float y, float z); static void loadIdentity(); static void perspective(); static void depthFunction(); }; 

GL.cpp

#include "GL.h" #include "freeglut.h" void GL::clearColor(const Color3 &color) { glClearColor(color.getRed,color.getGreen,color.getBlue, 1.0f); } void GL::clearColor(float red, float green, float blue) { glClearColor(red, green, blue, 1.0f); } void GL::clearColor(float red, float green, float blue, float alpha) { } void GL::clearColor(const Color4 &color) { } 

And here is my compiler error:

1>------ Build started: Project: GameEngineToolkit, Configuration: Debug Win32 ------ 1> Main.cpp 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\main.cpp(47): error C2665: 'GL::clearColor' : none of the 4 overloads could convert all the argument types 1> c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.h(610): could be 'void GL::clearColor(const Color4 &)' 1> c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.h(607): or 'void GL::clearColor(const Color3 &)' 1> while trying to match the argument list '(Color3 *)' 1> GL.cpp 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.cpp(8): error C3867: 'Color3::getRed': function call missing argument list; use '&Color3::getRed' to create a pointer to member 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.cpp(8): error C3867: 'Color3::getGreen': function call missing argument list; use '&Color3::getGreen' to create a pointer to member 1>c:\the capsule\c++\get\gameenginetoolkit\gameenginetoolkit\gl.cpp(8): error C3867: 'Color3::getBlue': function call missing argument list; use '&Color3::getBlue' to create a pointer to member 1> Generating Code... ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== 

As you can see, it seems that the compiler cant decide between using the Color3 function or the color4 function; I dont understand why because it should be obvious which one to choose(the Color3 one is the one I am using in my main).

As per request, here is my Color3 class:

Color3.h

#pragma once class Color3 { public: Color3(); Color3(float red, float green, float blue); void setRed(float red); void setGreen(float green); void setBlue(float blue); float getRed(); float getGreen(); float getBlue(); Color3 getColor(); ~Color3(); private: float red; float green; float blue; }; 

Color3.cpp

#include "Color3.h" Color3::Color3() { } Color3::Color3(float red, float green, float blue) { setRed(red); setGreen(green); setBlue(blue); } Color3::~Color3() { } float Color3::getRed() { return red; } float Color3::getGreen() { return green; } float Color3::getBlue() { return blue; } void Color3::setBlue(float blue) { this->blue = blue; } void Color3::setGreen(float green) { this->green = green; } void Color3::setRed(float red) { this->red = red; } Color3 Color3::getColor() { return *this; } 

The Solution:

Use pointers.

GL.cpp

#include "GL.h" #include "freeglut.h" void GL::clearColor(Color3* color) { glClearColor(color->getRed(),color->getGreen(),color->getBlue(), 1.0f); } void GL::clearColor(float red, float green, float blue) { glClearColor(red, green, blue, 1.0f); } void GL::clearColor(float red, float green, float blue, float alpha) { } void GL::clearColor(Color4* color) { } 

GL.H

#pragma once #include "Vector3.h" #include "Color3.h" #include "Color4.h" #include <string> class GL { public: static void initializeGL(int argc, char* argv); static void initializeDisplayMode(unsigned int displayMode); static void initializeWindowSize(int width, int height); static void createWindow(std::string title); static void mainLoop(); static void translate(const Vector3 &location); static void translate(float x, float y, float z); static void rotate(double rotation, float x, float y, float z); static void rotate(double rotation, const Vector3& axis); static void color3(const Color3 &color); static void color4(const Color4 &color); static void begin(); static void end(); static void pushMatrix(); static void popMatrix(); static void enable(int enableCap); static void viewport(); static void polygonMode(); static void matrixMode(); static void clearColor(Color3* color); // Use pointers instead static void clearColor(float red, float green, float blue); static void clearColor(float red, float green, float blue, float alpha); static void clearColor(Color4* color); // Same thing; no error. =P static void vertex3(const Vector3 &location); static void vertex3(float x, float y, float z); static void loadIdentity(); static void perspective(); static void depthFunction(); }; 
40190814 0 How to save geolocation(displayed with Googlemaps) in local storage and load it later

I have a problem with geolocation and local storage. So this bellow is my code. Excuse me that some of the text is in cyrillic but this is because that is homework of mine and I am from Bulgaria. It is not important what does the text say. You need to know only that first button is Get, second - Save, third one - Load. So I had to make first button to show my location with Google Maps - that's OK. I made it work. The tricky part is next. With the second button "Save" I have to save the data from geolocation into local Storage. And when clicking on the third button Load - the location saved in local Storage should come visible again in the (div id="map). I tried using different suggestions but every time something is not working. Please if someone can help me with an ideal at least. And the most important thing I am not allowed to use JQuery, only Java Script. If you have questions and you don't understand any part of the code please ask me and I'll be happy to explain or rewrite it. I want to thank you in advance for your help. P.S. I am beginner in coding, that's the reason I may ask stupid questions.Please have patience.

var x = document.getElementById("map"); function getLocation() { if (navigator.geolocation) { x.style.visibility = "visible"; navigator.geolocation.getCurrentPosition(showPosition, showError); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { var latlon = position.coords.latitude + "," + position.coords.longitude; var img_url = "https://maps.googleapis.com/maps/api/staticmap?center=" + latlon + "&zoom=14&size=400x300&sensor=false"; document.getElementById("map").innerHTML = "<img src='" + img_url + "'>"; } function showError(error) { switch (error.code) { case error.PERMISSION_DENIED: x.innerHTML = "User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML = "Location information is unavailable." break; case error.TIMEOUT: x.innerHTML = "The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML = "An unknown error occurred." break; } }
#text { width: 100%; margin-bottom: 15px; } #buttons { width: 100%; background-color: #8c8c8c; color: white; border: 2px solid #8c8c8c; padding-top: 2px; } #map { width: 100%; border: 2px solid #8c8c8c; border-bottom-right-radius: 10px; border-bottom-left-radius: 10px; visibility: hidden; background-color: #cccace; } .buttons { border-top-left-radius: 15px; border-bottom-right-radius: 15px; }
<body> <div id="text">Домашна върху HTML5 API &amp; Rounded Corners</div> <div id="buttons"> Местоположение: <input type="button" class="buttons" value="Вземи" onclick="getLocation()" /> <input type="button" class="buttons" value="Запази" onclick="saveLocation" /> <input type="button" class="buttons" value="Зареди" onclick="loadLocation" /> </div> <div id="map"></div> </body>

28702295 0

That code is not very good IMO since it only relies on jQuery instead of using the grid API. You can use the change event to detect row changes, get the selected rows with the select methd and the data items with the dataItem method.

So you can start with something like this:

$("#states").kendoGrid({ selectable: "multiple", dataSource: { data: usStates }, change: function() { var that = this; var html = ""; this.select().each(function() { var dataItem = that.dataItem(this); html += "<option>" + dataItem.name +"</option>"; }); $("#select").html(html); } }); 

(demo)

20203250 0

Presumably you want it to behave with the same fixity as >>=, so if you load up GHCi and type

> :info (>>=) ... infixl 1 >>= 

You could then define your operator as

infixl 1 |>= (|>=) :: Monad m => a -> (a -> m b) -> m b a |>= b = return a >>= b 

But, if your monad preserves the monad laws, this is identical to just doing b a, so there isn't really a need for the operator in the first place.

I'd also suggest using do notation:

naming path = do modTime <- getModificationTime path let str = formatTime defaultTimeLocale "%Y%m%d" modTime name = printf "%s_%s" (takeBaseName path) str replaceBaseName path name 
42174 0

netstat -b is a great answer, you may need to use the -a option as well.

Without -a netstat shows active connections, with -a it shows listening ports with no active clients as well.

8031150 0 How can I pass messages to another thread without using a blocking queue?

I have a pretty straight forward server (using kryonet). The clients are only storing the current state of the car (x,y,angle etc) and are sending requests of acceleration and turning.

The server is receiving the requests and adding them to a ArrayBlockingQueue that the physics thread drains and reads and updates.

When adding another player, the speed of the game slows down by almost double. I have ruled out a lot of things (I have all updates and package sending throttled at 60Hz.)

I am suspecting that using a blocking queue is blocking so much that it is causing the slowdown.

How can I send the client requests to the physics thread without blocking issues?

26511427 0 PL/SQL procedure wont work. Help please?

This is my procedure which compiles fine I am trying to get the release date and duration when i enter the films title:

create or replace PROCEDURE get_films (fname IN film.title%type, r_date OUT film.release_date%type, dur OUT film.f_duration%type) AS BEGIN SELECT release_date, f_duration into r_date, dur FROM FILM WHERE title = fname; EXCEPTION WHEN NO_DATA_FOUND THEN r_date:='';dur:=''; END get_films; 

Its when I call it i get the errors:

set serveroutput on DECLARE ftit FILM.TITLE%type:=&Enter_Film_Title; frdate film.release_date%type; fdur film.f_duration%type; BEGIN GET_FILMS(ftit, frdat, fdur); DBMS_OUTPUT.PUT_LINE('Title Release_date F_Duration'); DBMS_OUTPUT.PUT_LINE(ftit||' '||frdate||' '||fdur); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(SQLCODE||SQLERRM); END; 

errors:

old:EXECUTE GET_FILMS(&Enter_Title) new:EXECUTE GET_FILMS(Interstellar) Error starting at line : 17 in command - EXECUTE GET_FILMS(&Enter_Title) Error report - ORA-06550: line 1, column 17: PLS-00201: identifier 'INTERSTELLAR' must be declared ORA-06550: line 1, column 7: PL/SQL: Statement ignored 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error. *Action: 
21984613 0 Top Navigation disappears with the scroll

I would like to create a navigation menu with the top bar that disappears with the scroll. An example is this

As you can see in this theme, the menu continues to be high but the upper div disappears.

How could I do? Thanks in advance to all

PS: I'm using bootstrap 3

21519313 0 RSS - displaying image, instead of enclosure?

I have made a rss feed for my website, but right now the feed is not really displaying a image but just a link to the image as a enclosure. I would like to know what changes I need to make so I can actually display a image in the rss feed.

echo ' <item> <title>'.html_entity_decode($gag[story], ENT_COMPAT, "UTF-8").' - '.$thesitename.'</title> <description><![CDATA['.html_entity_decode($gag[story], ENT_COMPAT, "UTF-8").']]></description> <link>'.$thebaseurl.'/post/'.$gag[PID].'</link> <guid>'.$thebaseurl.'/post/'.$gag[PID].'/</guid>'; if($gag[pic] != ""){echo ' <enclosure type="image/jpeg" url="'.$thebaseurl.'/pdata/t/'.$gag[pic].'" length="1" />'; } echo ' 
8360275 0

Calling AUGraphClose in the shutdown fixed this. Guess you can't have two open graphs with the same output unit in?

10350373 0 luasoket http request got "connection refused"

I am trying to use luasocket to make http "GET" request to "https://buy.itunes.apple.com/verifyReceipt" , it yields a "connection refused" , while I can access this URL from the the web browser either use python httplib. I doubted it is because the HTTPS protocal , but if i replace url with "https//www.google.com" , it works ok. so any1 has ideas on what the problem is ? much thx for ur answers

This is the code:

local http = require("socket.http") URL = "https://buy.itunes.apple.com/verifyReceipt" local response, httpCode, header = http.request(URL) print(response, httpCode, header) 
319480 0

Have a look at the patterns & practices Application Architecture Guide 2.0 (Beta 2 Release) on Codeplex. The patterns & practices division of Microsoft also has guidelines for naming etc.

9926714 0

Maven is a build/deploy tool. It is similar in use to cmake or ant. It can be plugged in eclipse via plugins, it can be used to deploy wars/jars to tomcat/jboss/websphere etc. It can run test suites and many more.

You should take a look at Maven In 5 Minutes.

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

16598287 0 JSON to NSDictionary literal

I need to build an NSDictionary that I can then parse with NSJSONSerialization in order to get a nice JSON formatted string.

The final output of my JSON needs to be something like:

"Viewport":{ "BottomRight":{ "Latitude":1.26743233E+15, "Longitude":1.26743233E+15 }, "TopLeft":{ "Latitude":1.26743233E+15, "Longitude":1.26743233E+15 } } 

I figured it might be easiest to use NSDictionary literals, but how would I create multi-level nested dictionaries doing it this way?

Also, I will need to be setting the lat and long values when creating the dictionary.

20744549 0 webdriverjs: Expected string got an object

After discovering Mocha and webdriverjs, I wanted to give it a shot, after reading the readme.md in https://github.com/camme/webdriverjs, so i began with a trivial test.

var webdriverjs = require("webdriverjs"), client = webdriverjs.remote(), expect = require("chai").expect; suite('Functional tests', function(done) { setup(function(done) { client.init().url('http://www.google.com', done); }); test('test if you can open a firefox page', function() { var inputType = client.getAttribute('#searchtext_home', 'type'); expect(inputType).to.be.a('string'); console.log(myString); }); teardown(function(done) { client.end(done); //done(); }); }); 

Get the input element of google and expect its type is text. I end up with an object in inputType variable.

AssertionError: expected { Object (sessionId, desiredCapabilities, ...) } to be a string

21219177 0 What does it mean that objc_msgSend() is passed "a pointer to the reciever's data"?

In Apple's ObjC Runtime Guide, it describes what the objc_msgSend() function does for dynamic dispatch:

  1. It first finds the procedure (method implementation) that the selector refers to. Since the same method can be implemented differently by separate classes, the precise procedure that it finds depends on the class of the receiver.
  2. It then calls the procedure, passing it the receiving object (a pointer to its data), along with any arguments that were specified for the method.
  3. Finally, it passes on the return value of the procedure as its own return value.

I was confused in the second step, where it mentioned "receiving object (a pointer to its data)

What is that?

Can somebody give me a illustration to clarify it?

34836598 0

you forgot to render the context

you need:

def index(request): template_name = "index/index.html" is_teamleader = request.user.groups.filter(name='TL').exists() is_employee = request.user.groups.filter(name='Employee').exists() context = { 'is_teamleader': is_teamleader, 'is_employee': is_employee } return render(request, template_name, context) 
31542736 0

You can add float: left to your new element to give it the correct position, but don't forget to the a max-width to your <ul> so it doesn't push the other element out. Also I removed the margin of the new element to make it fit within the black background.

#nav{ background-color: #222; } #nav_wrapper{ width: 960px; margin:0 auto; text-align: right; padding: 0; font-family: Arial; font-size: 18px; /* font: Batang; */ } @font-face { font: Batang; src: url('batang.tff'); } #nav_wrapper .current{ background-color: #333; } #nav ul{ list-style-type: none; padding: 0; margin: 0; max-width: 800px; } #nav ul li{ display: inline-block; } #nav ul li img{ vertical-align: middle; padding-left: 10px; } #nav ul li:hover{ background-color: #333; transition: all 0.4s; } #nav ul li a,visited{ color: #ccc; display: block; padding: 15px; text-decoration: none; } #nav ul li a:hover{ color; #ccc text-decoration: none; } #nav ul li:hover ul{ display: block; } #nav ul ul{ display: none; position: absolute; background-color: #333; border: 5px solid #222; border-top: 0; margin-left: -5px; min-width: 200px; text-align: left; } #nav ul ul li{ display: block; } #nav ul u li a,visited{ color; #ccc; } #nav ul ul li a:hover{ color: #099; transition: all 0.3s; } #nav_wrapper .logo{ position: relative; float: left; color: gold; font-size: 60px; font-family: Batang; margin: 0; }
<div id="nav_wrapper"> <div id="nav"> <p class="logo">IVERSEN</p> <ul> <li><a class="current" href="home.html">Hjem</a></li><li> <a href="#">Om</a></li><li> <a href="#">Kontakt</a></li><li> <a href="#">Projekter<img src="images\arrow.png"/></a> <ul> <li><a href="#">Batch</a></li> <li><a href="#">JavaScript</a></li> <li><a href="#">HTML/CSS</a></li> </ul> </div> </div>

34051383 0 Yii2 Modules in advanced template

I want to create a module (for example Users) in an advanced template application, that I could use it both in the backend (CRUD functionality) and frontend (login, profile)

Which is the right way of doing it, without having to create one module in backend and another in frontend and maybe a model in the common folder?

I want all files in one folder.

11142187 0 How can I match the first unordered list from a string and select the first list items?

I have a content string that starts with an unordered list I want to make a summary of this content on my homepage and I need to match the first unordered list and only show 5 list items in the preview, so I stated with matching the whole ul tag using this regex:

/<\s*ul[^>]*>(.*?)<\s*/\s*ul>/s 

it works fine in regex tester online but I get Unknown modifier '\' and I don't know which one ? also after getting the whole unordered list how can I choose only the first 5 list items for example:

<ul class="mylist"> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> <li>Lorem Ipsum Dolor Sit Amet</li> </ul> 

and I want to create the same one with only the first 5 <li> tags, so should I use regex or some other methods in php ?

and thanks in advance.

12727231 0

Your "myArray.length" is two. Thus the code passes through the inner "for" loop twice. The loop variable "row" is never used inside the inner "for". Thus the same thing is printed twice.

Take out the inner "for".

15151275 0 How to send message to jboss-7 from jboss-5

There are two applications.Earlier both the applications were running in jboss-5. Now one of them is going to get migrated to jboss7

Both the applications communicate with each other via JMS queues . From basic research I understand that we need to access the hornetq in jboss-7 by providing the URL the below way

private static final String PROVIDER_URL = "remote://localhost:4447"; 

Also i understand that in jboss-7 we need to access the queues with username and password ie, SECURITY_PRINCIPAL

But as far as I know these things cannot be achieved in jboss-5 . Please tell me, is there anyway I can send messages to the queue residing in jboss-7, from jboss-5 ??

8051558 0

There are several macros of this kind, but they are not directly available.

The page namespace templates describes how to set up namespace-level template files that automatically substitute some expressions (such as @USER@ or @DATE@) when creating a new page in that directory. It should not be hard to adapt those to the format you desire.

Another choice would be adapt something from the var plugin so that the instructions it generates are converted and saved as text during a page preview or save. It would require converting the plugin from a "syntax" plugin to an "action" plugin.

35329105 0 How to "select" multiple rows that have a certain variable value?

I also want to be able to count/sum the number of these rows.

I can't seem to find this answer anywhere and it's so simple.

In Python it's something like:

df[df[value1]=="<value2>"].count()

How is this done in R?

4284717 0 How do I get my the bottom position of tooltip to appear over my link, using JQuery?

I am working on a dynamic tooltip...I'm stuck on how I can get the bottom position of #MyAuction-BidHistory to appear just above my link a.my-auction-history?

Here is my code so far:

var linkOffset = $('a.my-auction-history').offset().top; $('.my-auction-history').mouseover(function(e){ $.get('/auction/includes/new-bidhistory.asp?lplateid=' + pListedPlatesId + "&xx=" + t, function(data){ $('#MyAuction-BidHistory').css({'display':'block', 'opacity':'0', 'top':linkOffset }).animate({opacity:1}, 200).html(data); }); }); 

I only need to work out the Y co-ordinates as #MyAuction-BidHistory has been position:absolute; & has margin-left:300px;

Any help is greatly appreciated, Thanks

25287926 0 Bootstrap NavBar stopped working
 <!doctype html> <html> <head> <title>Home Page</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="main.css"/> <link rel="stylesheet" href="style.css"/> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <header class ="navbar"> <div class="container navbar-inverse"> <nav role="navigation"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">CASES4U</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">iPhone <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">iPhone 3g/3gs</a></li> <li><a href="#">iPhone 4/4s</a></li> <li><a href="#">iPhone 5/5s</a></li> <li class="divider"></li> <li><a href="#">iPod</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">Samsung <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Galaxy S 3</a></li> <li><a href="#">Galaxy S 4</a></li> <li><a href="#">Galaxy S 5</a></li> <li class="divider"></li> <li><a href="#">Galaxy Tab</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown">HTC <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">HTC Desire</a></li> <li><a href="#">HTC Desire HD</a></li> <li><a href="#">HTC One</a></li> <li class="divider"></li> <li><a href="#">HTC One M8</a></li> </ul> </li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> </nav> </div> </header> </head> <body> <h1 class="cases-of-the-week"><center>Cases Of The Week</center></h1> <div class="container-row"> <div class="row"> <div class="col-sm-4 col-xs-12"> <div class="panel "> <div class="panel-heading"><center>iPhone Case</center></div> <div class="panel-body "> <div class="iPhone-Case-1"> <img src="iPhone-Case-Of-The-Week.png"width="260" height="290" /></div> <b><u><center>XTREME iPhone Case (iPhone 5/5s Case)</center></u></b> It may look like fluorescent armour, but that’s because it kinda is. The XTREME iPhone Case is packed with Reactive Protection Technology, made of XRD foam which stiffens on impact and absorbs 90% of the impact. There’s also a rigid outer polycarbonate shell and an inner shock-absorbing TPE insert, which combine to make this one of the safest havens for your iPhone 5s on the planet. </div> </div> </div> <div class="col-sm-4 col-xs-6"><div class="panel "> <div class="panel-heading"><center>Samsung Case</center></div> <div class="panel-body "> <div class="Samsung-Case-1"> <img src="Samsung-Case-Of-The-Week.png" width="260" height="290" /></div> <b><u><center>Spigen SGP Slim Armour Case (Samsung Galaxy S4 Case)</center></u></b> The Slim Armour case for the Samsung Galaxy S4 has been specifically designed and crafted to offer amazing protection despite being incredibly slim and beautiful in appearance. The TPU case features improved shock absorption on the top, bottom and corners to effectively protect the Galaxy against external impact. </div> </div></div> <div class="col-sm-4 col-xs-6"><div class="panel "> <div class="panel-heading"><center>HTC Case</center></div> <div class="panel-body "> <div class="HTC-Case-1"> <img src="HTC-Case-Of-The-Week.png"width="260" height="290" /></div> <b><u><center>Tough HTC One Case (HTC One Case)</center></u></b> You know the feeling. The heartbreak that immediately sets in as your phone smashes to the ground. Flashes of panic, pools of sweat and buckets of tears overwhelm your body. Protect yourself from future stress with the Tough case, providing dual layers of protection. Built to withstand sudden drops and accidental falls, the Tough case for the HTC One is the epitome of protection. </div> </div> </div> </div> <footer><center>CASES4U Inc</center></footer> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </body> </html> 

I recently started using bootstrap and it was going well. I was learning alot and i started using the navbar they have. I used it and it was going well i even made a quick phone case website everything was going well. Until i checked on my file and saw that my website had changed. I dont understand it was fine a day ago and i didnt touch anything. What website looks like now

31736617 0

I was looking for the a solution to the opposite problem where I needed a fixed width div in the centre and a fluid width div on either side so I came up with the following and thought I'd post it here in case anyone needs it.

HTML:

<div id="wrapper"> <div id="center"> This is fixed width in the centre </div> <div id="left" class="fluid"> This is fluid width on the left </div> <div id="right" class="fluid"> This is fluid width on the right </div> </div> 

CSS:

#wrapper { clear: both; width: 100%; } #wrapper div { display: inline-block; height: 500px; } #center { background-color: green; margin: 0 auto; overflow: auto; width: 500px; } #left { float: left; } #right { float: right; } .fluid { background-color: yellow; width: calc(50% - 250px); } 

If changing the width of the #center element then you need to update the width property of .fluid to:

width: calc(50% - [half of center width]px); 
101915 0

For those working with Windows API, there's a function which allows you to see if any debugger is present using:

if( IsDebuggerPresent() ) { ... } 

Reference: http://msdn.microsoft.com/en-us/library/ms680345.aspx

38614598 0

Please try below code once SELECT FORMAT(275, 'C', 'en-us') Output: $275.00 SELECT FORMAT(275, 'C0', 'en-us') Output: $275

28991910 0

Your fiddle illuminates the actual issue:

content = "<input type='button' value='Add' onclick='addme(\"" + addedTitle + "\")' />" document.getElementById("display").innerHTML = content; 

The problem is that the above code will generate the following:

<input type='button' value='Add' onclick='addme("some'string")' /> 

You'll notice this has a single quote inside of your onclick which is single quoted. This is what is breaking. You can escape the single quote with \.

However, a better approach would be to get rid of the inline onclick and do it this way:

var input = $("<input type='button' value='Add'/>").click(function(){ addme(addedTitle); }); $("#display").append(input); 

http://jsfiddle.net/bxxmhe03/6/

119264 0

I use the http://webthumb.bluga.net service for thumbnail generation. Robust, powerful, easy to use, and very reasonable rates. I have a high traffic production website using this service and it works very well. Given the difficulty of creating a robust web screenshot service, it's nice to have someone else do the hard work.

19386682 0 Count re-Occurrence of a string - VB.NET

What method is best to count the following, Each line is a string created by a loop.

Jane Jane Matt Matt Matt Matt Jane Paul 

In the end i would like to know : Jane = 3, Matt = 4, Paul = 1. Would i use an array or a loop ?

9713623 0

It looks like you want to create an intent and then start an activity with it. You can use the context from "collection" which you are already accessing. Here's some code which should get you going again:

public void onClick(View v) { Context context = collection.getContext(); Intent intent = new Intent(context, DashboardActivity.class); context.startActivity(intent); } 

Note that you'll probably have to make collection become final.

1411472 0

Correct - the positive lookbehinds will not work.

But, just as some general information about regex in Javascript, here's a couple pointers for you.

You don't have to use the RegExp object - you can use pattern literals instead

var regex = /^[a-z\d]+$/i; 

But if you use the RegExp object, you have to escape your backslashes since your pattern is now locked in a string.

var regex = new RegExp( '^[a-z\\d]+$', 'i' ); 

The primary benefit of the RegExp object is if there is a dynamic bit to your pattern, for example

var max = 4; var regex = new RegExp( '\d{1,' + max + '}' ); 
5419977 0

I think it's simply a bug in how the javah outputs its actual classpath. What happens is that it has a bunch of places where it searches for built-in classes, and apart from them, it also uses the stuff in $CLASSPATH. When it prints the actual classpath used, they do something like this (pseudo code, assuming implicitEntries is a list of builtin classpath entries, and explicitEntries is a list of the the directories specified in $CLASSPATH):

print implicitEntries.join(pathSeparator) + explicitEntries.join(pathSeparator) 

where it should have been

print implicitEntries.join(pathSeparator) + pathSeparator + explicitEntries.join(pathSeparator) 

The following works fine for me:

$ ls Sasl.class Sasl.java $ javah -classpath . -o javasasl.h -jni -verbose Sasl [ Search Path: /usr/java/jdk1.6.0/jre/lib/resources.jar:/usr/java/jdk1.6.0/jre/lib/rt.jar:/usr/java/jdk1.6.0/jre/lib/sunrsasign.jar:/usr/java/jdk1.6.0/jre/lib/jsse.jar:/usr/java/jdk1.6.0/jre/lib/jce.jar:/usr/java/jdk1.6.0/jre/lib/charsets.jar:/usr/java/jdk1.6.0/jre/classes/. ] [Creating file javasasl.h] [search path for source files: [.]] [search path for class files: [/usr/java/jdk1.6.0/jre/lib/resources.jar, /usr/java/jdk1.6.0/jre/lib/rt.jar, /usr/java/jdk1.6.0/jre/lib/sunrsasign.jar, /usr/java/jdk1.6.0/jre/lib/jsse.jar, /usr/java/jdk1.6.0/jre/lib/jce.jar, /usr/java/jdk1.6.0/jre/lib/charsets.jar, /usr/java/jdk1.6.0/jre/classes, /usr/java/jdk1.6.0/jre/lib/ext/dnsns.jar, /usr/java/jdk1.6.0/jre/lib/ext/localedata.jar, /usr/java/jdk1.6.0/jre/lib/ext/sunpkcs11.jar, /usr/java/jdk1.6.0/jre/lib/ext/sunjce_provider.jar, .]] [loading ./Sasl.class] [loading /usr/java/jdk1.6.0/lib/ct.sym(META-INF/sym/rt.jar/java/lang/Object.class)] [loading /usr/java/jdk1.6.0/lib/ct.sym(META-INF/sym/rt.jar/java/lang/Throwable.class)] [loading /usr/java/jdk1.6.0/lib/ct.sym(META-INF/sym/rt.jar/java/lang/Class.class)] [done in 585 ms] $ ls javasasl.h Sasl.class Sasl.java 

Now, since the header file generation doesn't seem to work for you... are you sure you have Sasl.class in the current directory? javah works with byte code files, not Java source files.

2877809 0 C# Events and Lambdas, alternative to null check?

Does anybody see any drawbacks? It should be noted that you can't remove anonymous methods from an event delegate list, I'm aware of that (actually that was the conceptual motivation for this).

The goal here is an alternative to:

if (onFoo != null) onFoo.Invoke(this, null); 

And the code:

public delegate void FooDelegate(object sender, EventArgs e); public class EventTest { public EventTest() { onFoo += (p,q) => { }; } public FireFoo() { onFoo.Invoke(this, null); } public event FooDelegate onFoo; 

}

40197537 0

Since you are on UNIX, you can use jot with arguments from bash integer expansion:

jot -r 1 $((10 ** 15)) $((((10 ** 15)) * 2)) 

Generates numbers like:

1595866171875968 
38822670 0

You are using incorrect syntax for batchWrite, try following

$response = $dynamoDb->batchWriteItem([ 'RequestItems' => [ 'mytable' => [ [ 'PutRequest' => [ 'Item' => [ 'id' => array('S' => '123abc'), 'value' => array('N' => '1'), ] ], 'PutRequest' => [ ///Entire PutRequest array need to be repeated not just item array/// 'Item' => [ 'id' => array('S' => '123abc'), 'value' => array('N' => '2'), ] ], ], ], ], ]); 

Apart from that, the difference between single insert and multiple inserts would be the call to connect with DynamoDB, in batchPut you will send entire array at once whereas in single insert it will connect to DB each time it tries to perform any operation.

In general, you can use Batch to process things faster.

Here is the refernce link for batchWrite syntax

Hope that helps.

41069712 0

If you don't like map you can always use a list comprehension:

s = [str(i) for i in x] r = int("".join(s)) 
4749296 0 Best way to allow admin to build objects for Admin

My objective is to allow Admins the right to sign Users up for a Project.

Currently, Users can sign themselves up for Projects.

So I was thinking in order to allow Admin to do this.. do something like this :

haml

= link_to "Project Signup", card_signups_path + "?user=#{user.id}", :class => "button" 

And pass the params[:user] so I can replace this controller with this :

if params[:user] @card_signup = User.find(params[:user]).build_card_signup else @card_signup = current_user.build_card_signup end 

The trouble is though.. this is a 3 part signup process, and its loaded VIA AJAX, so I can't pass the ?user=#{user.id} in any of the steps after the first.. ( at least not by the same convention that I already did, or know how to )

What kind of strategy would you employ in this?

13898280 0

Well to answer my own question, Pear:Cache-Lite does the trick.

1532938 0

I find that typically a repeated CTE gets no performance improvements.

So for instance, if you use a CTE to populate a table and then the same CTE to join to in a later query, no benefit. Unfortunately, CTEs are not snapshots and they literally have to be repeated to be used in two separate statements, so they tend to be evaluated twice.

Instead of CTEs, I often use inline TVFs (which may contain CTEs), which allows proper re-use, and are not any better or worse than CTEs in my SPs.

In addition, I also find that the execution plan can be bad if the first step alters the statistics such that the execution plan for the second step is always inaccurate because it is evaluated before any steps are run.

In this case, I look at manually storing intermediate results, ensuring that they are indexed properly and splitting up the process into multiple SPs and adding WITH RECOMPILE to ensure that later SPs have plans that are good for the data which they are actually going to operate on.

38004638 0 Notify the Service if the Activity is Down

Sometimes my app crashes for some reason and I have no control over it. I want to let the service know when the app crashes and do some other process.

Is it possible to do that?
By the way, starting from Lollipop, getRunningTasks is deprecated.

Thanks.

30308488 0

Upgrade you Calabash-Android version to the latest one. 0.4.20 is a very old release and does not support crosswalk webviews.

11508938 0

how can I make sure that all of the async code in my initializer(s) is complete before doing anything else in the application?

Don't use the initialize:after event. Instead, trigger your own event from the success call, and then bind your app start up code from that one.

MyApp.addInitializer(function (options) { $.ajax({ url: options.apiUrl + '/my-app-api-module', type: 'GET', contentType: 'application/json; charset=utf-8', success: function (results) { MyApp.Resources.urls = results; // trigger custom event here MyApp.vent.trigger("some:event:to:say:it:is:done") } }); }); // bind to your event here, instead of initialize:after MyApp.vent.bind('some:event:to:say:it:is:done', function (options) { // initialization is done...close the modal dialog if (options.initMessageId) { $.noty.close(options.initMessageId); } if (Backbone.history) { Backbone.history.start(); } console.log(MyApp.Resources.urls); }); 

This way you are triggering an event after your async stuff has finished, meaning the code in the handler will not run until after the initial async call has returned and things are set up.

15397551 0

Is there a way to automatically notify the developers of all the super-projects to update the submodule

No.
A submodule is a clone of an upstream repo, nested in a parent repo.
It is a downstream repo compared to the original repo you cloned as a submodule.

And in a distributed environment, you simply don't know of the downstream repos.
You only know of the upstream repo.
See "Definition of “downstream” and “upstream”".

As mentioned in "Update git submodule", you would need to go in the submodule and git pull directly in there in order to update said submodule.

2985568 0

The symbol '>>' is an operator. The writer of the String class included this operator to only take primitive types and of course the String class type.

You have two options:

  1. Convert the char array to a string
  2. Overload the '>>' operator to take char arrays and output it as you like

Look up overloading operator if you really want to have fun.

12322904 0 Liferay: get PortletID and companyID from init()

Maybe trough PortletConfig in init(PortletConfig)

The thing is that using

((PortletConfigImpl) portletConfig).getPortletId(); 

is not allowed anymore because adding portal-impl.jar in package.properties gives throws an exception when trying to execute build ant target, saying that this is not allowed anymore

For companyID I directly have no idea where to start. I am using currently

long companyId = CompanyLocalServiceUtil.getCompanies().get(0).getCompanyId(); 

but as soon as I got more than one company it will fail

If only I could get Portlet object somehow, I think it would be enough to get both portletId and companyId

7235783 0

I broke it down a bit for clarity, but this should do the trick.

$("#checkbox_1").click(function() { var checked = $("#checkbox_1").attr("checked"); var selectVal; if (checked) selectVal = 1; else selectVal = "All"; $("#dropdown").val(selectVal); }); 
31163347 0

Remove MainActivity just use startActivity(i)

39262795 0 fetch associated name of the ID from different table using laravel eloquent relation for chart js

This is the code i am using to extract data in my controller which i am using it in my chartjs:

$startdate = request('startdate') ?: \Carbon\Carbon::now()->startOfYear(); $enddate = request('enddate') ?: \Carbon\Carbon::now(); return complaintRegistrationModel::with('complaintmoderelation') ->select(DB::raw(DB::raw('count(*) as complaints')), DB::raw('modeID')) ->whereBetween('updated_at', array($startdate, $enddate)) ->groupBy('modeID') ->pluck('modeID', 'complaints'); 

As you can see, I am using foreign key modeID from table tblcomplaintregistration ...what i want to do is i want to get the modeName associated with the modeID which is stored in another table call tblmode. So my chart should give modeName in my x-axis instead of modeID. Please help me out. Thank you

UPDATE

ok i was able to solve it by making some changes in the query like this. Hope some might find it useful.

return \App\complaintRegistrationModel::select(\Illuminate\Support\Facades\DB::raw(DB::raw('count(*) as complaints')), \Illuminate\Support\Facades\DB::raw('(select modeName from cr_pltblcomplaintmode where complaintmodeID = modeID) as modeName')) ->whereBetween('updated_at', array($startdate, $enddate)) ->groupBy('modeName') ->pluck('complaints', 'modeName'); 
32735559 0

Ok, I see you need it's recursive.

public static String repeater(int x, String word) { if (x == 0) { return ""; } else { return word.charAt(0) + repeater(x - 1, word); } } 

How is this?

For understanding this recursion, it is working like nested parentheses of Mathematics.

"H" + ("H" + ("H" + ("H" + ("H" + ("H" + ("")))))) 
967264 0 Conditional Routing?

I have a simple partial view. The main part of which is listed below. How can I have the ActionLinks resolve properly when this partial view is rendered on a page that is managed by a different controller. In other words - this partial view shows Project Areas for a given Project. What if this PV shows up on a page being managed by the Project Controller. The Default route behavior here would try to have the code execute the /Project/Edit or Project/Detail . Thats not really what I need. Instead I need it to go to /ProjectArea/Edit for example. How is that accomplished in this case?

 <% foreach (var item in Model) { %> <tr> <td> <%= Html.ActionLink("Edit", "Edit", new { id=item.ProjectAreaId }) %> | <%= Html.ActionLink("Details", "Details", new {id=item.ProjectAreaId })%> </td> <td> <%= Html.Encode(item.Name) %> </td> </tr> <% } %> 
6899758 0

A crude approach (while guessing what you're trying to do):

#!/usr/bin/env python import pprint revisions = [ ['01.02.2010','abc','qwe'], ['02.02.2010','abc','qwe'], ['03.02.2010','aaa','qwe'], ['04.02.2010','aaa','qwe'], ['05.02.2010','aaa','qwe'], ['06.02.2010','aaa','dsa'], ] uniq, seen = [], set() # sets have O(1) membership tests for rev in revisions: if tuple(rev[1:]) in seen: continue else: seen.add(tuple(rev[1:])) uniq.append(rev) pprint.pprint(uniq) # prints: # [['01.02.2010', 'abc', 'qwe'], # ['03.02.2010', 'aaa', 'qwe'], # ['06.02.2010', 'aaa', 'dsa']] 
1067568 0 Determine reason of System.AccessViolationException

We are having nondeterministic System.AccessViolationException thrown from native code. It's hard to reproduce it, but sometimes it happens. I'm not sure if I can "just debug it" since the time needed for access violation is about 2 hours and there is no guarantees that access violation will happen.

The native library is used by managed wrappers. It's used from java through JNI and it's used from .NET through IKVM'ed JNI. The problem was only reproduced during from IKVM'ed code, but the data sets is different and there is no way to test java application with data used by IKVM'ed application.

I have sources for everything, but (if possible) I want to avoid making large number of changes.

I believe native call stack will provide enough information about reason of this access violation.

Is there any effective ways of determining the reason of this access violation?

I think the ideal solution for me is some changes in code or process environment, so it will crash with memory dump in case of this access violation, so I can make that changes and just wait.

20520937 0

if you know how to do it for one data.frame then just use lapply on your list of dats.frames

e.g.

#create your new columns function as it would work for one data.frame foo <- function(DF){ DF$new1 <- distm(x,y)....etc DF$new2 <- .......etc DF$new3 <- cor(x,y).......etc return(DF) } 

Then lapply over the list to return a list of data.frames with the new columns:

DFlist <- list(DF1, DF2, DF3) lapply(DFlist, foo) 
17298862 0 JSP debugging in IntelliJ IDEA using the Tomcat Maven Plugin

We used to have Tomcat run configuration in IntelliJ. This deployed our webapp to a locally installed tomcat instance, and let us debug both java classes and jsp files.

Now we've made the switch to Maven, and we now run our Tomcat instance using the tomcat7 maven plugin with the maven goal: tomcat7:run-war

Debugging our java classes works perfectly, however (due to large amounts of legacy code) we also need to be able to debug JSP files.

Is it possible to debug JSPs in IntelliJ when an embedded Tomcat is launched from the maven plugin?

21266638 0

LocalStorage (in Chrome) is in the %LocalAppData% directory, which is under the user's account. Internet Explorer stores them under %userprofile% Precise location varies among browsers but is always within a user folder.

So no, LocalStorage will not propagate across users.

33053508 0

The reason beyond that is that the bytecode (.class files) used by your Eclipse debugger doesn't contain any information about method parameters name. That's the way the JDK is compiled by default.

The Eclipse debugger implements a workaround for method parameters, naming them "arg0", "arg1", etc. and thus enabling you to inspect them in the "Variables" view. Unfortunately, I don't think there is such a workaround for local method variables...

Some other tickets in StackOverflow advise to rebuild yourself the JRE based on source code of the JDK, e.g.: debugging not able to inspect the variables.

36720519 0

Maybe another solution would be:

#include <iostream> using namespace std; int colonne; int ligne; void initDamier (int **damier, int ligne, int colonne) { for (int i = 0; i < ligne; ++i){ for (int j = 0; j < colonne; ++j){ damier[i][j]=0; //0=case vide } } } 

-

void afficheDamier (int **damier, int ligne, int colonne) { for (int i = 0; i < ligne; ++i) { cout<<endl; for (int j = 0; j < colonne; ++j) { cout<<damier[i][j]<<"|"; } } cout<<endl; } 

-

int main() { int a,b; cout<<"Entrez le nombre de ligne du damier:"<<endl; cin>>a; ligne=a; cout<<"Entrez le nombre de colonne du damier:"<<endl; cin>>b; colonne=b; int** damier = new int*[colonne]; for(int i=0;i<colonne;i++) damier[i] = new int[ligne]; initDamier(damier,ligne, colonne); afficheDamier(damier, ligne, colonne); for(int i=0;i<colonne;i++) delete damier[i]; delete[] damier; return 0; } 
11930250 0

The other answers are technically correct on the compiler error, but miss a subtle point: fun is used incorrectly. It appears to be intended as a local variable that collects results in fun.pairs. However, std::for_each can copy fun instead, and then fun.pairs is not updated.

Correct solution: Fun fun = std::for_each(Packs, Packs + SHARE_PRIZE, Fun());.

19033642 0 Operator '==' cannot be applied to operands of type 'char' and 'string'

I have a registration application which has the "KeyChar" event inside it, and it works great ! but when i give the same lines of code in this application it gives me Operator '=='/'!=' cannot be applied to operands of type 'char' and 'string'

Can't seem to figure out why it works in the other application but not here! Any help is much appreciated !

 private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True"); SqlCommand cmd = new SqlCommand(); Object returnValue; string txtend = textBox1.Text; //string lastChar = txtend.Substring(txtend.Length - 1); if (e.KeyChar == "L") { DBConnection.Open(); } if (DBConnection.State == ConnectionState.Open) { if (textBox1.Text.Length != 7) return; { //cmd.CommandText = ("SELECT last_name +', '+ first_name +'\t ('+major_key+')\t' from name where id =@Name"); cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =@Name"); cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(@"L", ""))); cmd.CommandType = CommandType.Text; cmd.Connection = DBConnection; // sqlConnection1.Open(); returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(@"L", "") + ")"; DBConnection.Close(); if (listBox1.Items.Contains(returnValue)) { for (int n = listBox1.Items.Count - 1; n >= 0; --n) { string removelistitem = returnValue.ToString(); if (listBox1.Items[n].ToString().Contains(removelistitem)) { listBox1.Items.RemoveAt(n); //listBox1.Items.Add(removelistitem+" " +TimeOut+ Time); } } } else listBox1.Items.Add(returnValue); System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName); foreach (object item in listBox1.Items) SaveFile.WriteLine(item.ToString()); SaveFile.Flush(); SaveFile.Close(); textBox1.Clear(); if (listBox1.Items.Count != 0) { DisableCloseButton(); } else { EnableCloseButton(); } Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance."; e.Handled = true; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// else ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// { returnValue = textBox1.Text.Replace(@"*", ""); if (e.KeyChar == "*") return; { if (listBox1.Items.Contains(returnValue)) { for (int n = listBox1.Items.Count - 1; n >= 0; --n) { string removelistitem = returnValue.ToString(); if (listBox1.Items[n].ToString().Contains(removelistitem)) { //listBox1.Items.RemoveAt(n); } } } else listBox1.Items.Add(returnValue); textBox1.Clear(); System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName); foreach (object item in listBox1.Items) SaveFile.WriteLine(item.ToString()); SaveFile.Flush(); SaveFile.Close(); if (listBox1.Items.Count != 0) { DisableCloseButton(); } else { EnableCloseButton(); } Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance."; e.Handled = true; } } } 
39123566 0

Something like this.

select name,math as Grade from your_table union all select name,English as Grade from your_table union all select name,Arts as Grade from your_table 
26590298 0

Is this what you are looking for

var json = {"userid":"12345","cmpyname":"stackoverflow", "starrays": [{"transaction":"7272785","value2":"GOOGLE"}, //Array [0] {"transaction":"85785272","value2":"YAHOO"}, //Array [1] {"transaction":"4774585","value2":"REDIFF"}], //Array [2] "value3":"95345"} if(json["starrays"].length > 0 && (json["starrays"][0].transaction != undefined && json["starrays"][0].value2 != undefined)) { $('#outer').show(); $('#val').html(json["starrays"][0].value2); $('#amt').html(json["starrays"][0].transaction); } 
893757 0 Exporting X.509 certificate WITHOUT private key (.NET C#)

I thought this would be straightforward but apparently it isn't. I have a certificate installed that has a private key, exportable, and I want to programmatically export it with the public key ONLY. In other words, I want a result equivalent to selecting "Do not export the private key" when exporting through certmgr and exporting to .CER.

It seems that all of the X509Certificate2.Export methods will export the private key if it exists, as PKCS #12, which is the opposite of what I want.

Is there any way using C# to accomplish this, or do I need to start digging into CAPICOM?

Thanks,

Aaron

27471858 0

You could set the properties in the controller instead of using the script tag

You´ll have to add a custom button

 <button type="submit" ng-click="pay()" class="stripe-button-el" style="visibility: visible;"><span style="display: block; min-height: 30px;">Pay with Card</span></button> 

And in the controller:

 var handler = StripeCheckout.configure({ image: "https://stripe.com/img/documentation/checkout/marketplace.png", key:'pk_test_' }); $scope.pay = function(){ handler.open({ name: 'Example Product', description: 'Example Product ' + $scope.price, amount: $scope.price * 100 }); e.preventDefault(); }; 

This work as expected:

http://jsfiddle.net/ppq1orso/3/

4427655 0 Keyword BOGUS in php

I'm wondering what the word "BOGUS" means in the following object.

I'm running a script on the command line, sending a object back over SOAP. I expect back:

object(stdClass)#2 (2) { ["distance"]=> string(5) "13726" ["time"]=> string(3) "622" } 

But the first time I ran it, I got this back:

object(stdClass)#2 (2) { ["distance"]=> object(stdClass)#3 (1) { ["BOGUS"]=> string(5) "13726" } ["time"]=> object(stdClass)#4 (1) { ["BOGUS"]=> string(3) "622" } } 

This only happened once, I can't duplicate it. But I'm intrigued and wondering if anyone knows what it means. Thanks.

19591622 0

Already a descusion carried about this please check the link. Delete a particular local notification

28537454 0

I found a solution by thinking a bit different.

This is eventually the function:

public function getPriceLines($pricelinematerial = 0, $year = 0, $week = 0) { if ($year === 0) { $year = (int)date('Y'); } if ($week === 0) { $week = (int)date('W'); } $query = $this->getEntityManager()->createQuery(' SELECT pgp FROM ACME\Bundle\PricelistBundle\Entity\PricelistMaterialPrice pgp WHERE pgp.pricelistmaterial = :pricelistmaterial AND pgp.year <= :year AND pgp.week <= :week ORDER BY pgp.year DESC, pgp.week DESC, pgp.id DESC ')->setParameters(array('pricelistmaterial' => $pricelistmaterial, 'week' => $week, 'year' => $year)); $query->setMaxResults(1); try { $result = $query->getSingleResult(); } catch (\Doctrine\ORM\NoResultException $e) { $result = null; } return $result; } 
21056210 0

Apple already did that: The CLLocationManager property desiredAccuracy with value kCLLocationAccuracyBestForNavigation will "Use the highest possible accuracy and combine it with additional sensor data. This level of accuracy is intended for use in navigation applications that require precise position information at all times and are intended to be used only while the device is plugged in."

18446332 0 how to play two mp4 videos through gstreamer pipeline?

I would like to create a gstreamer pipeline to play two mp4 videos back to back. is it possible to play using gst-launch? can I use multifilesrc for this purpose ?

Please show me path to play two videos back to back.

Thanks in advance !

22338852 0

The reason this is showing in the action menu is because you have android:showAsAction="ifRoom" in your xml file. remove that and you should be good.

32892067 0

You know how to get the RTB.Text vs RTB.Rtf right?

Here is some documentation you might enjoy (or not).

Once you know the difference between those, you get the text, use that to build the rtf string, and then assign that string into the Rtf.

To modify the colors in your rtf string, you should check the documentation on how to format text with rtf. Here is the first google result I found.

Good Luck.

2117755 0

ResolveUrl("~/Resources/R1.png")

Where '~' is used to represent the root of the application in which the current page/control sits.

Or if the resource is external to the current application but is still found within the virtual directory hierarchy, you can use ResolveUrl("/Resources/R1.png")

35599024 0 Varnish 4.0.1, Apache, Centos 7, Plesk 12, Wordpress with w3 total cache - Varnish not caching html

I set up varnish on my site the other day and I don't believe it is working correctly as the age shows as 0:

The url we checked: pbsgroups.deep-image.co.uk HTTP/1.1 200 OK Date: Wed, 24 Feb 2016 09:57:14 GMT Server: Apache Link: <http://pbsgroups.deep-image.co.uk/wp-json/>; rel="https://api.w.org/", <http://pbsgroups.deep-image.co.uk/>; rel=shortlink Expires: Wed, 24 Feb 2016 10:57:15 GMT Pragma: public Cache-Control: max-age=3600, public X-Powered-By: PleskLin X-Pingback: http://pbsgroups.deep-image.co.uk/xmlrpc.php Vary: Accept-Encoding Set-Cookie: iSLuxE=1; expires=Wed, 24-Feb-2016 12:57:14 GMT; Max-Age=10800 Last-Modified: Wed, 24 Feb 2016 09:57:15 GMT Etag: 33984224b175af821c75fc660dbd42a8 X-Mod-Pagespeed: 1.10.33.5-0 Content-Encoding: gzip Content-Length: 7851 Content-Type: text/html; charset=UTF-8 X-Varnish: 655877 Age: 0 Via: 1.1 varnish-v4 Connection: keep-alive 

Static content works perectly:

The url we checked: pbsgroups.deep-image.co.uk/wp-includes/css/dashicons.min.css?ver=4.4.2 HTTP/1.1 200 OK Date: Wed, 24 Feb 2016 09:34:34 GMT Server: Apache Content-Length: 28526 Last-Modified: Thu, 18 Feb 2016 11:04:30 GMT ETag: "b438-52c0954a5d637-gzip" Vary: Accept-Encoding,User-Agent Cache-Control: max-age=31536000, public Expires: Thu, 23 Feb 2017 09:08:56 GMT X-Powered-By: W3 Total Cache/0.9.4.1 Pragma: public X-Original-Content-Length: 46136 Content-Encoding: gzip X-Content-Type-Options: nosniff Content-Type: text/css X-Varnish: 361406 820497 Age: 21 Via: 1.1 varnish-v4 Connection: keep-alive 

This is what isvarnishworking.com has got to say on this:

Varnish appears to be responding at that url, but the Cache-Control header's "max-age" value is less than 1, which means that Varnish will never serve content from cache at this url. 

Here is a copy of my .htaccess (made with w3 total cache):

## EXPIRES CACHING ## ExpiresActive On ExpiresByType image/jpg "access 1 year" ExpiresByType image/jpeg "access 1 year" ExpiresByType image/gif "access 1 year" ExpiresByType image/png "access 1 year" ExpiresByType application/pdf "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month" ExpiresByType image/x-icon "access 1 year" ExpiresDefault "access 2 days" ## EXPIRES CACHING ## # BEGIN W3TC CDN <FilesMatch "\. (asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|wav|wma|wri|woff|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|WAV|WMA|WRI|WOFF|XLA|XLS|XLSX|XLT|XLW|ZIP)$"> <IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule .* - [E=CANONICAL:http://pbsgroups.deep-image.co.uk {REQUEST_URI},NE] RewriteCond %{HTTPS} =on RewriteRule .* - [E=CANONICAL:https://pbsgroups.deep-image.co.uk%{REQUEST_URI},NE] </IfModule> <IfModule mod_headers.c> Header set Link "<%{CANONICAL}e>; rel=\"canonical\"" </IfModule> </FilesMatch> <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css)$"> <IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" </IfModule> </FilesMatch> # END W3TC CDN # BEGIN W3TC Browser Cache <IfModule mod_mime.c> AddType text/css .css AddType text/x-component .htc AddType application/x-javascript .js AddType application/javascript .js2 AddType text/javascript .js3 AddType text/x-js .js4 AddType text/html .html .htm AddType text/richtext .rtf .rtx AddType image/svg+xml .svg .svgz AddType text/plain .txt AddType text/xsd .xsd AddType text/xsl .xsl AddType text/xml .xml AddType video/asf .asf .asx .wax .wmv .wmx AddType video/avi .avi AddType image/bmp .bmp AddType application/java .class AddType video/divx .divx AddType application/msword .doc .docx AddType application/vnd.ms-fontobject .eot AddType application/x-msdownload .exe AddType image/gif .gif AddType application/x-gzip .gz .gzip AddType image/x-icon .ico AddType image/jpeg .jpg .jpeg .jpe AddType application/json .json AddType application/vnd.ms-access .mdb AddType audio/midi .mid .midi AddType video/quicktime .mov .qt AddType audio/mpeg .mp3 .m4a AddType video/mp4 .mp4 .m4v AddType video/mpeg .mpeg .mpg .mpe AddType application/vnd.ms-project .mpp AddType application/x-font-otf .otf AddType application/vnd.ms-opentype .otf AddType application/vnd.oasis.opendocument.database .odb AddType application/vnd.oasis.opendocument.chart .odc AddType application/vnd.oasis.opendocument.formula .odf AddType application/vnd.oasis.opendocument.graphics .odg AddType application/vnd.oasis.opendocument.presentation .odp AddType application/vnd.oasis.opendocument.spreadsheet .ods AddType application/vnd.oasis.opendocument.text .odt AddType audio/ogg .ogg AddType application/pdf .pdf AddType image/png .png AddType application/vnd.ms-powerpoint .pot .pps .ppt .pptx AddType audio/x-realaudio .ra .ram AddType application/x-shockwave-flash .swf AddType application/x-tar .tar AddType image/tiff .tif .tiff AddType application/x-font-ttf .ttf .ttc AddType application/vnd.ms-opentype .ttf .ttc AddType audio/wav .wav AddType audio/wma .wma AddType application/vnd.ms-write .wri AddType application/font-woff .woff AddType application/vnd.ms-excel .xla .xls .xlsx .xlt .xlw AddType application/zip .zip </IfModule> <IfModule mod_expires.c> ExpiresActive On ExpiresByType text/css A31536000 ExpiresByType text/x-component A31536000 ExpiresByType application/x-javascript A31536000 ExpiresByType application/javascript A31536000 ExpiresByType text/javascript A31536000 ExpiresByType text/x-js A31536000 ExpiresByType text/html A3600 ExpiresByType text/richtext A3600 ExpiresByType image/svg+xml A3600 ExpiresByType text/plain A3600 ExpiresByType text/xsd A3600 ExpiresByType text/xsl A3600 ExpiresByType text/xml A3600 ExpiresByType video/asf A31536000 ExpiresByType video/avi A31536000 ExpiresByType image/bmp A31536000 ExpiresByType application/java A31536000 ExpiresByType video/divx A31536000 ExpiresByType application/msword A31536000 ExpiresByType application/vnd.ms-fontobject A31536000 ExpiresByType application/x-msdownload A31536000 ExpiresByType image/gif A31536000 ExpiresByType application/x-gzip A31536000 ExpiresByType image/x-icon A31536000 ExpiresByType image/jpeg A31536000 ExpiresByType application/json A31536000 ExpiresByType application/vnd.ms-access A31536000 ExpiresByType audio/midi A31536000 ExpiresByType video/quicktime A31536000 ExpiresByType audio/mpeg A31536000 ExpiresByType video/mp4 A31536000 ExpiresByType video/mpeg A31536000 ExpiresByType application/vnd.ms-project A31536000 ExpiresByType application/x-font-otf A31536000 ExpiresByType application/vnd.ms-opentype A31536000 ExpiresByType application/vnd.oasis.opendocument.database A31536000 ExpiresByType application/vnd.oasis.opendocument.chart A31536000 ExpiresByType application/vnd.oasis.opendocument.formula A31536000 ExpiresByType application/vnd.oasis.opendocument.graphics A31536000 ExpiresByType application/vnd.oasis.opendocument.presentation A31536000 ExpiresByType application/vnd.oasis.opendocument.spreadsheet A31536000 ExpiresByType application/vnd.oasis.opendocument.text A31536000 ExpiresByType audio/ogg A31536000 ExpiresByType application/pdf A31536000 ExpiresByType image/png A31536000 ExpiresByType application/vnd.ms-powerpoint A31536000 ExpiresByType audio/x-realaudio A31536000 ExpiresByType image/svg+xml A31536000 ExpiresByType application/x-shockwave-flash A31536000 ExpiresByType application/x-tar A31536000 ExpiresByType image/tiff A31536000 ExpiresByType application/x-font-ttf A31536000 ExpiresByType application/vnd.ms-opentype A31536000 ExpiresByType audio/wav A31536000 ExpiresByType audio/wma A31536000 ExpiresByType application/vnd.ms-write A31536000 ExpiresByType application/font-woff A31536000 ExpiresByType application/vnd.ms-excel A31536000 ExpiresByType application/zip A31536000 </IfModule> <IfModule mod_deflate.c> <IfModule mod_setenvif.c> BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html BrowserMatch \bMSI[E] !no-gzip !gzip-only-text/html </IfModule> <IfModule mod_headers.c> Header append Vary User-Agent env=!dont-vary </IfModule> AddOutputFilterByType DEFLATE text/css text/x-component application/x-javascript application/javascript text/javascript text/x-js text/html text/richtext image/svg+xml text/plain text/xsd text/xsl text/xml image/x-icon application/json <IfModule mod_mime.c> # DEFLATE by extension AddOutputFilter DEFLATE js css htm html xml </IfModule> </IfModule> <FilesMatch "\.(css|htc|less|js|js2|js3|js4|CSS|HTC|LESS|JS|JS2|JS3|JS4)$"> FileETag MTime Size <IfModule mod_headers.c> Header set Pragma "public" Header append Cache-Control "public" Header unset Set-Cookie Header set X-Powered-By "W3 Total Cache/0.9.4.1" </IfModule> </FilesMatch> <FilesMatch "\.(html|htm|rtf|rtx|svg|svgz|txt|xsd|xsl|xml|HTML|HTM|RTF|RTX|SVG|SVGZ|TXT|XSD|XSL|XML)$"> FileETag MTime Size <IfModule mod_headers.c> Header set Pragma "public" Header append Cache-Control "public" Header set X-Powered-By "W3 Total Cache/0.9.4.1" </IfModule> </FilesMatch> <FilesMatch "\.(asf|asx|wax|wmv|wmx|avi|bmp|class|divx|doc|docx|eot|exe|gif|gz|gzip|ico|jpg|jpeg|jpe|json|mdb|mid|midi|mov|qt|mp3|m4a|mp4|m4v|mpeg|mpg|mpe|mpp|otf|odb|odc|odf|odg|odp|ods|odt|ogg|pdf|png|pot|pps|ppt|pptx|ra|ram|svg|svgz|swf|tar|tif|tiff|ttf|ttc|wav|wma|wri|woff|xla|xls|xlsx|xlt|xlw|zip|ASF|ASX|WAX|WMV|WMX|AVI|BMP|CLASS|DIVX|DOC|DOCX|EOT|EXE|GIF|GZ|GZIP|ICO|JPG|JPEG|JPE|JSON|MDB|MID|MIDI|MOV|QT|MP3|M4A|MP4|M4V|MPEG|MPG|MPE|MPP|OTF|ODB|ODC|ODF|ODG|ODP|ODS|ODT|OGG|PDF|PNG|POT|PPS|PPT|PPTX|RA|RAM|SVG|SVGZ|SWF|TAR|TIF|TIFF|TTF|TTC|WAV|WMA|WRI|WOFF|XLA|XLS|XLSX|XLT|XLW|ZIP)$"> FileETag MTime Size <IfModule mod_headers.c> Header set Pragma "public" Header append Cache-Control "public" Header unset Set-Cookie Header set X-Powered-By "W3 Total Cache/0.9.4.1" </IfModule> </FilesMatch> # END W3TC Browser Cache # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress 

The only thing that I could see different between the static files and html was that the html pages were sending cookies out, so I tried amending my default.vcl to unset cookies as follows:

sub vcl_recv { if ( !( req.url ~ ^/admin/) ) { unset req.http.Cookie; } } 

I'm completely baffled by this now, so any help would be greatly appreciated

1073610 0

<%= myfunction(); %> would be used to output the return value of myfunction in a page.

<%# myfunction(); %> would be used to output the return value of myfunction in a control that is data bound (for example, inside an asp repeater control).

Take a look at this overview for more information on data binding.

12930378 0 Fluid width for container of inline, non-wrapping elements

I'm having a little CSS trouble.

I have some div elements structured like the following example. There are a dynamic number of class="block" divs, each with a fixed width:

<div class="outer-container"> <div class="inner-container"> <div class="block">text</div> <div class="block">text</div> <div class="block">text</div> <!-- More "block" divs here --> </div> </div> 

My goal is to find a CSS-based solution that will.

  1. Display the class="block" divs inline, without them wrapping to new lines.
  2. Support a variable number of class="inner-container" divs like the one above, each displayed as its own line.
  3. Have the outer container fluidly "shrink-wrap" to match the width of its contents.

Any suggestions?

11075254 0 Passing js array to PHP

Possible Duplicate:
Passing a js array to PHP

i'm stuck jQuery $.post() method, i can't access my through PHP $_POST and I can't figure out why.

Here is the js:

<script type="text/javascript"> var selectedValues; $("td").click(function() { $(this).toggleClass('selectedBox'); selectedValues = $.map($("td.selectedBox"), function(obj) { return $(obj).text(); }); // $.post('/url/to/page', {'someKeyName': variableName}); //exemple $.post('handler.php', {'serializedValues' : JSON.stringify(selectedValues)}, function(data) { //debug } ); }); </script> 

And here is the PHP file:

<?php if(isset($_POST['serializedValues'])) { var_dump($_POST['serializedValues']); $originalValues = json_decode($_POST['serializedValues'], 1); print_r($originalValues); } ?> 

When I issue a console.log(selectedValues) after selecting some of the td element, it return me this for exemple:

 [" 3 ", " 4 "] 

Something else, when I inspect the sent header through XHR, i get this:

 serializedValues:[" 3 "," 4 "] 

And finally, in php var_dump($_POST) still returns me nothing :(

Some hints ? Thanks in advance :)

36102332 0

I am just curious: how is val 2 = 123 understood by Scala?

You can think of val 2 = 123 as:

123 match { case 2 => 2 } 

The variable name part in Scala isn't always a simple name, it can also be a pattern, for example:

val (x, y) = (1, 2) 

Will decompose 1 and 2 to x and y, respectively. In scala, everything which is allowed after a case statement is also allowed after val and is translated to a pattern match.

From the specification (emphasis mine):

Value definitions can alternatively have a pattern as left-hand side. If p is some pattern other than a simple name or a name followed by a colon and a type, then the value definition val p = e is expanded as follows:

(Skipping to the relevant example):

If p has a unique bound variable x:

val x = e match { case p => x } 

This is the reason the compiler doesn't emit a compile time error. There is a lengthy discussion of the subject in this google group question.

23390899 0

I've done the exact same thing few weeks ago. I used the System.DirectoryServices.ActiveDirectory library, and used the Domain and DomainController objects to find what you are looking for.

Here is the code I'm using:

public static class DomainManager { static DomainManager() { Domain domain = null; DomainController domainController = null; try { domain = Domain.GetCurrentDomain(); DomainName = domain.Name; domainController = domain.PdcRoleOwner; DomainControllerName = domainController.Name.Split('.')[0]; ComputerName = Environment.MachineName; } finally { if (domain != null) domain.Dispose(); if (domainController != null) domainController.Dispose(); } } public static string DomainControllerName { get; private set; } public static string ComputerName { get; private set; } public static string DomainName { get; private set; } public static string DomainPath { get { bool bFirst = true; StringBuilder sbReturn = new StringBuilder(200); string[] strlstDc = DomainName.Split('.'); foreach (string strDc in strlstDc) { if (bFirst) { sbReturn.Append("DC="); bFirst = false; } else sbReturn.Append(",DC="); sbReturn.Append(strDc); } return sbReturn.ToString(); } } public static string RootPath { get { return string.Format("LDAP://{0}/{1}", DomainName, DomainPath); } } } 

And then, You simply call DomainManager.DomainPath, everything is initialized once (it avoids resource leaks) or DomainName and so on. Or RootPath, which is very useful to initialize the root DirectoryEntry for DirectorySearcher.

I hope this answers your question and could help.

29483203 0

You have an extra colon in one of your parameter array keys:

$query_params = array( ':username' => $username, ':password' => $password, ':salt' => $salt, ':email' => $email, ':level:' => $level // this should just be ':level' ); 

As a side note - if you individually bind the parameters instead of passing as a whole array, you should get a more discriminating error message:

$query = "...."; $stmt = $db->prepare($query); $stmt->bindParam(":username", $username); ... $result = $stmt->execute(); 
35731063 1 Compare two columns of two different dataframes

Recently, I switched from matlab to python with pandas. It has been working great, but i am stuck at solving the following problem efficiently. For my analysis, I have to dataframes that look somewhat like this:

dfA = NUM In Date 0 2345 we 1 01/03/16 1 3631 we 1 23/02/16 2 2564 we 1 12/02/16 3 8785 sz 2 01/03/16 4 4767 dt 6 01/03/16 5 3452 dt 7 23/02/16 6 2134 sz 2 01/03/16 7 3465 sz 2 01/03/16 

and

dfB In Count_Num 0 we 1 3 1 sz 2 2 2 dt 6 3 3 dt 7 1 

What I would like to perform is a an operation that sums all 'Num' for all "In" in dfA and compares it with the "Count_num" in dfB. Afterwards, I would like to add an column to dfB to return if the comparison is True or False. In the example above, the operation should return this:

dfB In Count_Num Check 0 we 1 3 True 1 sz 2 2 False 2 dt 6 1 True 3 dt 7 1 True 

My approach:

With value_counts() and pd.DataFrame, I constructed the following dfC from dfA dfC =

 In_Number In_Total 0 we 1 4 1 sz 2 3 2 dt 6 1 3 dt 7 1 

Then I merged it with dfB to check it afterwards if the values are the same by comparing the columns within dfB. In this case, I have to end dropping the columns. Is there a better/faster way to do this? I think there is a way to do this very efficiently with one of pandas great functions. I've tried to look into lookup and map, but I can not make it work.

Thanks for the help!

11045699 0

You could use HTTP authentication which uses plain text to send user name and password, so to protect it you could use SSL.

An excellent article could be found here

14922537 0 verilog array referencing

I have this module. The question is gameArray[0][x][y-1] doesn't work. What is the correct way to perform this kind of operation? Basically it is similar to C++ syntax but can not get it to work.

module write_init_copy( input clk, input gameArray [1:0][63:0][127:0], writecell, processedcell, input [5:0] x, input [6:0] y, input initialize, copyover, output reg done_initialize, done_copy, done_writecell); always@(posedge clk) begin if(writecell == 1) begin gameArray[1][x][y] <= processedcell; done_writecell <= 1; end else if(initialize == 1) begin end end endmodule 
37575287 0 How to get data from json file for net-snmp trap?

I have json file and i am exporting file into another file using require i see the data but when i print the value obj.oid from json object it returns undefined any idea why ?

app.js

var snmp = require ("net-snmp"); var session = snmp.createSession ("127.0.0.1", "public"); var oids = require('./oids'); var obj = JSON.stringify(oids); console.log("OIDS",obj.oid) 

oids.json

 { "oid": "1.3.6.1.2.1.1.4.0", "type": "snmp.ObjectType.OctetString", "value": "user.name@domain.name" } 
4571926 0 Cache list of ids to check before querying database

I have a Asp.Net Mvc application that has a default route pattern of /controller/action/id.

This means the user could simply put any ID in the url if they are savy enough to figure it out. I could handle the exceptions, redirect the user to an error page (and I am) or any number of other solutions. There are only about 1200 possible valid IDs. I was considering caching a list of these IDs at the application level to check against before querying the database to save the expense of making a connection and handling the exceptions.

Does anyone have a good argument as to why this is a bad solution?

38313504 0

You can avoid division by zero while maintaining performance by using advanced indexing:

x = np.arange(-500, 500) result = np.empty(x.shape, dtype=float) # set the dtype to whatever is appropriate nonzero = x != 0 result[nonzero] = 1/x[nonzero] result[~nonzero] = 0 
37799934 0

You can do it easily by different view types. For Example -

class MyData{ String text; boolean isHeader; } public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { ArrayList<MyData> allData; class ViewHolder0 extends RecyclerView.ViewHolder { ... } class ViewHolder2 extends RecyclerView.ViewHolder { ... } @Override public int getItemViewType(int position) { // Just as an example, return 0 or 2 depending on list(let assume 0 for header 1 for data // Note that unlike in ListView adapters, types don't have to be contiguous return allData.get(position).isHeader?0:1; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case 0: return new ViewHolder0(header view); case 1: return new ViewHolder2(data view); ... } } } 

And if data is updated then just update your dataList and call notifyDataSetChange() on the adapter.

Hope it will help you :)

30836150 0

This is how I made the above example work, note Im using ember-cli. Instead of creating my store with the DS.RESTAdapter.create(), or in my case, Im using DS.LSAdapter, I create my store in a initializer like this:

app.LsStore = DS.Store.extend({ adapter: '-ls', }); app.register('store:lsstore', app.LsStore); app.register('adapter:-ls', DS.LSAdapter); 

This basically registers a lsstore and a adapter:-ls on the container. Then I can inject my store into the application's route or controller, and this will try to find the adapter using adapter:-ls.

9276418 0

You have probably used the dir attribute/CSS set to rtl instead of proper CSS alignment.

The dir attribute:

This attribute specifies the base direction of directionally neutral text (i.e., text that doesn't have inherent directionality as defined in [UNICODE]) in an element's content and attribute values. It also specifies the directionality of tables.

As you can see this is not limited to alignment.

Use CSS alignment/positioning to align HTML controls.

26367211 0 How to get the terminal leaves of a Wikipedia root category

I want to get only the leaves a wikipedia category but not sure how. I can get all the leaves by

SELECT ?subcat WHERE { ?subcat skos:broader* category:Buildings_and_structures_in_France_by_city . } 

This gives me all intermediate leaves (such as Category:Buildings_and_structures_in_Antibes) but I want to get just the last/bottom leaves of the tree. Leaves that can not be split anymore. How can I do this?

1110786 0

Web Services, in general, are meant to be cross-platform. What would a Java program do with a System.Type from .NET?

Also, what part of Type would you like to see serialized, and how would you like to see it deserialized?

21297062 0 IFrame form submittal opens in frame, needs to open in new window

Trying to resolve an issue using a 3rd party form that unfortunately has to use an iframe to be embedded in the article content. When a user submits their email address, the thank you page opens up in the space taken up by the iframe instead of the page / a new window. I tried using the following JS script to no avail:

<script type="text/javascript"> // If "&_parent=URL" is in this page's URL, then put URL into the top window var match = /_parent=(.+)/.exec(window.location.href); if (match != null) { top.location = match[1]; } </script> 

The page in question:

http://restoringqualityoflifeblog.org/subscribe/

Thanks!

21877273 0

According to hibernate DTD, This should solve your problem

 <natural-id> <component name="location"> <property name="countryISO2"/> <property name="city"/> </component> </natural-id> 

and you should remove <component> that's at bottom of the mapping.

9261189 0

I know there is already an accepted answer for this question, but this same question was asked here:

MouseAdapter: which pattern does it use?

See there for more deatils, but the MouseAdapter adapts the very awkaward MouseListener interface into a more usable form.

4526852 0 Need help implementing a special edge detector

I'm implementing an approach from a research paper. Part of the approach calls for a major edge detector, which the authors describe as follows:

  1. Obtain DC image (effectively downsample by 8 for both width and height)
  2. Calculate Sobel gradient of DC image
  3. Threshold Sobel gradient image (using T=120)
  4. Morphological operations to clean up edge image

Note that this NOT Canny edge detection -- they don't bother with things like non-maximum suppression, etc. I could of course do this with Canny edge detection, but I want to implement things exactly as they are expressed in the paper.

That last step is the one I'm a bit stuck on.

Here is exactly what the authors say about it:

After obtaining the binary edge map from the edge detection process, a binary morphological operation is employed to remove isolated edge pixels, which might cause false alarms during the edge detection

Here's how things are supposed to look like at the end of it all (edge blocks have been filled in black):

alt text

Here's what I have if I skip the last step:

alt text

It seems to be on the right track. So here's what happens if I do erosion for step 4:

alt text

I've tried combinations of erosion and dilation to obtain the same result as they do, but don't get anywhere close. Can anyone suggest a combination of morphological operators that will get me the desired result?

Here's the binarization output, in case anyone wants to play around with it:

alt text

And if you're really keen, here is the source code (C++):

#include <cv.h> #include <highgui.h> #include <stdlib.h> #include <assert.h> using cv::Mat; using cv::Size; #include <stdio.h> #define DCTSIZE 8 #define EDGE_PX 255 /* * Display a matrix as an image on the screen. */ void show_mat(char *heading, Mat const &m) { Mat clone = m.clone(); Mat scaled(clone.size(), CV_8UC1); convertScaleAbs(clone, scaled); IplImage ipl = scaled; cvNamedWindow(heading, CV_WINDOW_AUTOSIZE); cvShowImage(heading, &ipl); cvWaitKey(0); } /* * Get the DC components of the specified matrix as an image. */ Mat get_dc(Mat const &m) { Size s = m.size(); assert(s.width % DCTSIZE == 0); assert(s.height % DCTSIZE == 0); Size dc_size = Size(s.height/DCTSIZE, s.width/DCTSIZE); Mat dc(dc_size, CV_32FC1); cv::resize(m, dc, dc_size, 0, 0, cv::INTER_AREA); return dc; } /* * Detect the edges: * * Sobel operator * Thresholding * Morphological operations */ Mat detect_edges(Mat const &src, int T) { Mat sobelx = Mat(src.size(), CV_32FC1); Mat sobely = Mat(src.size(), CV_32FC1); Mat sobel_sum = Mat(src.size(), CV_32FC1); cv::Sobel(src, sobelx, CV_32F, 1, 0, 3, 0.5); cv::Sobel(src, sobely, CV_32F, 0, 1, 3, 0.5); cv::add(cv::abs(sobelx), cv::abs(sobely), sobel_sum); Mat binarized = src.clone(); cv::threshold(sobel_sum, binarized, T, EDGE_PX, cv::THRESH_BINARY); cv::imwrite("binarized.png", binarized); // // TODO: this is the part I'm having problems with. // #if 0 // // Try a 3x3 cross structuring element. // Mat elt(3,3, CV_8UC1); elt.at<uchar>(0, 1) = 0; elt.at<uchar>(1, 0) = 0; elt.at<uchar>(1, 1) = 0; elt.at<uchar>(1, 2) = 0; elt.at<uchar>(2, 1) = 0; #endif Mat dilated = binarized.clone(); //cv::dilate(binarized, dilated, Mat()); cv::imwrite("dilated.png", dilated); Mat eroded = dilated.clone(); cv::erode(dilated, eroded, Mat()); cv::imwrite("eroded.png", eroded); return eroded; } /* * Black out the blocks in the image that contain DC edges. */ void censure_edge_blocks(Mat &orig, Mat const &edges) { Size s = edges.size(); for (int i = 0; i < s.height; ++i) for (int j = 0; j < s.width; ++j) { if (edges.at<float>(i, j) != EDGE_PX) continue; int row = i*DCTSIZE; int col = j*DCTSIZE; for (int m = 0; m < DCTSIZE; ++m) for (int n = 0; n < DCTSIZE; ++n) orig.at<uchar>(row + m, col + n) = 0; } } /* * Load the image and return the first channel. */ Mat load_grayscale(char *filename) { Mat orig = cv::imread(filename); std::vector<Mat> channels(orig.channels()); cv::split(orig, channels); Mat grey = channels[0]; return grey; } int main(int argc, char **argv) { assert(argc == 3); int bin_thres = atoi(argv[2]); Mat orig = load_grayscale(argv[1]); //show_mat("orig", orig); Mat dc = get_dc(orig); cv::imwrite("dc.png", dc); Mat dc_edges = detect_edges(dc, bin_thres); cv::imwrite("dc_edges.png", dc_edges); censure_edge_blocks(orig, dc_edges); show_mat("censured", orig); cv::imwrite("censured.png", orig); return 0; } 
33454385 0

No. Symbols must be accessed using bracket notation.

Dot notation is only used for string keys that follow certain rule patterns, mostly about being a valid identifier.

Symbols are not strings, they are a whole something else entirely.

Short rational: One of the design goals of symbols is that they can not clash with property names, that makes them safe to use.

So, if you had an object like this

var = { prop1: "Value" }; 

And you created a symbol called prop1, how could you tell the two apart, and access them differently, using just object notation?

15203083 0 4736553 0 How to replace scenes with some action with the help of CCDirector?

I want to replace one scene with another with fade out - fade in effect.(old scene fades out(to the black screen),and then new scene fades in).

i found solution manually to decrease opacity of one scene and then launch

 [[CCDirector sharedDirector] replaceScene:[HelloWorld scene]]; 

But i suppose there is another solution with the use of actions. Please, help me)

23583492 0 GET paramets in CRON job

I have a FOR loop for parsing xml file as parts, but I using a $_GET paramets to receive variable sending at the end of loop in URL (meta http-equiv="Refresh" content="0; url...). In Web browser everything works fine but I want to use CRON job to do it automatically. So it is possible to do something like this? I'll be very grateful for any advice or example

My code:

 $name = 'tmp_add_xml'; if(isset($_GET['file'])){ $xmlfile = 'import/'.$_GET['file'].'.xml'; } else { $xmlfile = 'import/'.$name.'.xml'; $xmlurl = 'URL_XML_FILE'; $downxml = file_get_contents($xmlurl); file_put_contents($xmlfile, $downxml); } $xml = simplexml_load_file($xmlfile); $xml_offer = $xml->xpath("//offer"); $total = count($xml_offer); if(isset($_GET['x']) && isset($_GET['exist']) && isset($_GET['added'])){ $x = $_GET['x']; $product_exist = $_GET['exist']; $product_added = $_GET['added']; } else { $x = $product_exist = $product_added = 0; } $limit = $x+1000; for($z = $x; $z <= $limit; $z++){ $productid = $xml_offer[$z]->id; if(mysql_num_rows(mysql_query("SELECT reference FROM ps_product WHERE reference = '".$productid."'")) > 0){ $product_exist++; } else { $product_added++; } if($z==$total){ echo 'Import 100%'; exit; } elseif($z==$limit){ print '<meta http-equiv="Refresh" content="0; url='.$_SERVER['PHP_SELF'].'?x='.($x+1).'&file='.$name.'&exist='.$product_exist.'&added='.$product_added.'">'; exit; } $x++; } 

URL: script_name.php?x=VARIABLE&file=VARIABLE&exist=VARIABLE&added=VARIABLE

8677069 0

It's typically not a problem unless a) you have a lot of customers frequently making purchases (good for you! :)), and b) you change your prices very frequently

The solution is:

a) change prices (or, more generally, change ANYTHING) off-hours, when customers aren't likely to be using the system

... and/or ...

b) schedule a "maintenance window", during which you lock out user sessions in order to change prices, items and/or schema (the customary approach).

36806947 0 Ng-repeat not updating with array changes

I have looked over this issue for many hours and read many other questions that seem entirely the same and I have tried every one of their solutions, but none seem to work.

I have an array of objects (instructionObj.instructions) and those objects get repeated with ng-repeat and their template is a directive.

<div instruction-directive ng-repeat="i in instructionsObj.instructions"> </div> 

I then allow the items to be sorted using Jquery UI sortable.

var first, second; $( ".sort" ).sortable({ axis: "y", start: function( event, ui ) { first = ui.item.index(); }, stop: function( event, ui ) { second = ui.item.index(); console.log(first + " " + second); rearrange(first, second); $scope.$apply(); } }); 

I then access the start and end index of the object being moved and rearrange the array accordingly:

function rearrange(f, s){ $timeout(function () { $scope.instructionsObj.instructions.splice(s, 0, $scope.instructionsObj.instructions.splice(f, 1)[0]); $scope.$apply(); }); } 

All of this works great most of the time. The one scenario I have found a failure is when rearranging the objects as such (one column is the current position of all objects displayed on the screen):

a | b | c | d | a

b | c | d | c | b

c | d | b | b | d

d | a | a | a | c

The last step should be a, d, c, b. But it changes to a, b, d, c.

wrong configuration

However, when I go back to my previous view and come back the correct configuration is displayed, all is well. As you can see I have tried $timeout and $apply() and many other things, but none seem to work.

I know this is a DOM updating issue because I can log the array and see that it is different (correct) from what the DOM shows (incorrect). Any help would be appreciated.

Update:

I am even using <pre ng-bind="instructionsObj.instructions|json</pre> to show the exact layout of the array and it is always correct. My mind is blown.

14875979 0 Delete (or not insert) the new row in a trgger

I use DB2 Express-C. I have ON INSERT trigger on a table, where I insert the new row into another table. Is there a way not to insert the new row into the table on which the trigger is defined?

Any help is appreciated, thank you

8678839 0

You can do this easily by using regexp to match the string and to replace the corresponding parts. As you mentioned that you'd want to do this with jQuery I am assuming you have jQuery already on your site, but if you don't I wouldn't recommend adding it for this.

Instead of explaining further what to do, I've pasted the code below and commented each step, which should make it quite clear what's going on:

// bind onchange and keypress events to the width and height text boxes $('#txtwidth, #txtheight').bind('change keypress', function(){ // define the regexp to which to test with, edit as needed var re = /\/Content\/Image\/([0-9]+)\/[0-9]+\/[0-9]+\//, // store url and its value to a variable so we won't have to retrieve it multiple times url = $('#url'), val = url.val(); // test if regexp matches the url if (!re.test(val)) { // doesn't match return; } // we got this far, so it did match // replace the variables in the regexo val = val.replace(re, "/Content/Image/$1/" + $("#txtwidth").val() + "/" + $("#txtheight").val() + "/"); // put it back into the input field url.val(val); }); 

example: http://jsfiddle.net/niklasvh/wsAcq/

30807706 0

You can always remove all untracked (and unignored) files with git clean -f. To be safe, run git clean -n first to see which files will be deleted.

40646999 0

That's not a stupid question! I believe what is meant by "strings that it cannot handle" is actually, "strings which are not in a valid format", which I take to mean "strings that contain symbols that we don't know." (I'm going off of slide 14 of this presentation, which I found by just googling Turing 'implicitly reject').

So, if we do use that definition, then we need to simply create a Turing machine that accepts an input if it contains a symbol not in our valid set.

Yes, there are other possible interpretations of "strings that it cannot handle", but I'm fairly sure it means this. It obviously could not be a definition without constraints, or else we could define "strings that it cannot handle" as, say, "strings representing programs that halt", and we'd have solved the halting problem! (Or if you're not familiar with the halting problem, you could substitute in any NP-complete problem, really).

I think the reason that the idea of rejecting strings the Turing machine cannot handle was introduced in the first place is so that the machine can be well defined on all input. So, say, if you have a Turing machine that accepts a binary number if it's divisible by 3, but you pass in input that is not a bianry number (like, say, "apple sauce"), we can still reason about the output of the program.

18592902 0 Writing UART Application

I have been asked to understand the 16550A UART for Linux (3.10 Kernel)and write some test case on its functional blocks.But before that only i am facing lot of troubles in understanding the code flow of the same as it is very big ( I am following kernel 3.10 version) with multiple entry points and exit points.So i thought of writing a UART Application (C Program) having two threads which will transmit and receive characters to the UART port and understand the code flow by printing the log messages. Now I am not getting how to start writing application which would do the same. Also If anyone can help me in getting the first part of the my task (writing test cases) that would be great. And also can you provide me with some of the good links related to UART. Thanks

24831384 0

Looks like I need a couple plugins and something like this will work

http://a-developer-life.blogspot.com/2011/06/jasmine-part-2-spies-and-mocks.html

9273958 0 how can i save "read " error output in shell script?

I write a bash file in which i used read command to read data from a file.

If the file wasn't there I want to save the error into a text file. I tried:

read myVariable < myFile 2> errorFile.txt 

it doesn't work, and many other efforts faild such as:

myVar=`read myVariable < myFile` 
9770210 0

Yes - If I understand your question correctly you should be able to add a mapping in your local hosts file to point that domain at your IIS webserver.

e.g.

10.0.0.x my.example.hostname

(where x is obviously a number)

We use this configuation internally when developing multiple sites on our local machines - each site is bound to a specific hostname and all these hostnames have mappings in the 'hosts' file to 127.0.0.1

The same principal applies here, if I've understood the question correctly :)

12498073 0

I figured out how to solve the issue: in the X class, add this to the to_dict() method:

 ... if value is None: continue if key == 'metaData': array = list() for data in value: array.append(data.to_dict()) output[key] = array elif isinstance(value, SIMPLE_TYPES): output[key] = value ... 

Though I'm not really sure how to automate this case where it's not based off key, but rather whenever it encounters a list of custom objects, it first converts each object in the list to_dict() first.

24938293 0 nodeschool Streams adventure [HTTP SERVER]

I found a bit of intriguing behavior on an exercise about nodejs.

The aim is to transform POST data of a request to uppercase and send back using stream.

My problem is I'm not having the same behavior between these two pieces of code (the transform function just take the buf and queueit to uppercase) :

var server = http.createServer(function (req, res) { var tr = through(transform); if (req.method === 'POST') { req.pipe(tr).pipe(res); } }); 

var tr = through(transform); var server = http.createServer(function (req, res) { if (req.method === 'POST') { req.pipe(tr).pipe(res); } }); 

The first one is correct and gives me :

ACTUAL EXPECTED ------ -------- "ON" "ON" "THEM" "THEM" "BUT," "BUT," ... 

My version with the trvar outside :

ACTUAL EXPECTED ------ -------- "QUICK." "QUICK." "TARK'S" "TARK'S" "QUICK." !== "BIMBOOWOOD" "TARK'S" !== "BIMBOOWOOD" "BIMBOOWOOD" !== "SO" "BIMBOOWOOD" !== "SO" ... 

For info the transform function :

function transform(data) { this.queue(data.toString().toUpperCase()); } 
39923202 0

You should keep in mind that "good OO" is mainly about behavior of objects. Objects (and classes) exist to "map" some "concept out of reality" into the "model" that you make the base of your application.

Thus: you don't use inheritance to save a line of code here or there. You put the "B extends A" tag on B because that is the reasonable thing to do guided by your model.

Given that: your idea of making a tall dog a furniture is a very nice example for people using inheritance for the completely wrong reasons!

Thus: simply forget about this idea; and do as the comments suggest: create reasonable interfaces, and put those classes where they make sense.

4052499 0 Existing List of W3C complient html attribute

It's there a place i can see wich attribute are w3c on all HTML Element, div,p,a,li,hr etc ...

I check on w3cshool but find nothing.

I need a list where they said someting like ... id : (div, a , hr , etc ...), class (div, a , hr , etc) ...

16259845 0 FullCalendar is adding space after events with a URL

I'm using a pretty basic JQuery plugin called FullCalendar to add easy to use calendar to my website. I've mostly had no troubles until now. The main problem is that when you add a url to events in the event object it puts an unnecessary amount of space under it. Further, it works just fine with the url when the title is less than 6 or 7 characters or so. But when you have a a few words it adds the space. I really can't figure this out.

I've imported the stylesheet and js file.

<link rel='stylesheet' type='text/css' href='fullcalendar.css' /> <script type='text/javascript' src='jquery.js'></script> <script type='text/javascript' src='fullcalendar.js'></script> 

I also have a simple script to set up the calendar and to create two events.

$(function() { /* initialize the calendar -----------------------------------------------------------------*/ var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var calendar = $('#calendar').fullCalendar({ buttonText: { prev: '<i class="icon-chevron-left"></i>', next: '<i class="icon-chevron-right"></i>' }, header: { left: 'prev,next today', center: 'title', right: '' }, events: [ { title: 'All', start: new Date(y, m, 1), url: 'single-event.php' }, { title: 'All Day Event', start: new Date(y, m, 1), url: 'index.html' }] }); }) 

Here is a link to the same problem - why is there extra space between url-tagged events?

and to the documentation http://arshaw.com/fullcalendar/docs/usage/

30224687 0

It looks like you are sending two independent events (two calls to tracker.send). One with only custom dimensions and one without custom dimensions. The first event is invalid as it is missing required event category and action so Analytics will ignore it. The second is valid event but its missing the custom dimensions. You should send only one event instead:

tracker.send(new HitBuilders.EventBuilder() .setCategory("customCategory") .setAction("customAction") .setLabel("customLabel") .setCustomMetric(cm.getValue(), metricValue) .setCustomDimension(cd.getValue(), dimensionValue) .build()); 
1908352 0

Well I usually use the object explorer and go to the table I want and then look under Keys. You can widen the object explorer to see the fullname of the key. If it is named properly it probably has the table name of both the primary key and foreign key tables in it. If not you can script it to see. I had to search to find this relationships window you were talking about becasue I would never use the design window as we script all changes.

107502 0

Obviously Google are major users of Grid Computing; all their search service relies on it, and many others.

Engines such as BigTable are based on using lots of nodes for storage and computation. These are commercially very useful because they're a good alternative to a small number of big servers, providing better redundancy and cost effective scaling.

The downside is that the software is fiendishly difficult to write, but Google seem to manage that one ok :)

So anything which requires big storage and/or lots of computation.

18820870 0 Information required regarding Opensip

I am a newbie in programming world.
I want to experiment with sip protocol and make c program.
trying to use opensip from http://www.opensips.org.
but I am not able to install it properly.
I am using ubuntu 13.04 linux system.
Can anybody guide me for its installation, and give me some simple example to understand sip programming more clearly.
So that i will have a right direction to start in.

30857018 0

The code you've posted will run on the Hadoop master node. scaldingTool.run(args) will trigger your job, which would trigger the jobs that execute on task nodes.

13215951 0

Here is some related code which works for me (I have very long file names and paths):

for d in os.walk(os.getcwd()): dirname = d[0] files = d[2] for f in files: long_fname = u"\\\\?\\" + os.getcwd() + u"\\" + dirname + u"\\" + f if op.isdir(long_fname): continue fin = open(long_fname, 'rb') ... 

Note that for me it only worked with a combination of all of the following:

  1. Prepend '\\?\' at the front.

  2. Use full path, not relative path.

  3. Use only backslashes.

  4. In Python, the filename string must be a unicode string, for example u"abc", not "abc".

Also note, for some reason os.walk(..) returned some of the directories as files, so above I check for that.

25024471 0

You are saving your model query results in a specific key(assistiti) inside the array $data, and then you are fetching the whole array in the foreach loop. This way, you got to loop through the specific array, inside the array $data:

foreach($data['assistiti'] as $post){ $nome = $post->nome; $cognome = $post->cognome; $tribunale = $post->tribunale; $tbl .= '<tr><td style="border:1px solid #000;text-align:center">'.$nome.'</td>'; $tbl .= '<td style="border:1px solid #000;text-align:center">'.$cognome.'</td>'; $tbl .= '<td style="border:1px solid #000;text-align:center">'.$tribunale.'</td> </tr>'; ;} $pdf->writeHTML($tbl_header.$tbl.$tbl_footer , true, false, false, false, ''); 
36534009 0

Try launching XCode directly - often after an update XCode will require you to accept a new EULA before it will launch, which can prevent other apps from launching XCode (or its components) automatically.

5236157 0

A reverse_iterator internally stores a normal iterator to the position after its current position. It has to do that, because rend() would otherwise have to return something before begin(), which isn't possible. So you end up accidentally invalidating your base() iterator.

14664111 0 How do I style RootElement

I need a way to style Monotouch Dialogs RootElement. I need to change the background and font color.

I'm have created a custom RootElement as below

public class ActivityRootElement : RootElement { public ActivityRootElement (string caption) : base (caption) { } public ActivityRootElement(string caption, Func<RootElement, UIViewController> createOnSelected) : base (caption, createOnSelected) { } public ActivityRootElement(string caption, int section, int element) : base (caption, section, element) { } public ActivityRootElement(string caption, Group group) : base (caption, group) { } public override UITableViewCell GetCell (UITableView tv) { tv.BackgroundColor = Settings.RootBackgroundColour; return base.GetCell (tv); } protected override void PrepareDialogViewController(UIViewController dvc) { dvc.View.BackgroundColor = Settings.RootBackgroundColour; base.PrepareDialogViewController(dvc); } } 

I am then calling the custom root element as below passing in a custom DialogController

 section.Add (new ActivityRootElement(activity.Name, (RootElement e) => { return new ActivityHistoryDialogViewController (e,true); })); 

The root Element style is not been applied. Any help would be apprciated!!

1385371 0 Comparsion between Pixel Bender(in Flash) and Pixel Shaders(in Silverlight)

Can someone explain the different between Pixel Bender in Flash and Pixel Shader(HLSL) in Silverlight in terms of programming flexibility and run-time performance?

24568329 0 svn: Repository moved permanently please relocate

I was trying to do a svn unlock by giving the below command

svn unlock http://test.server.com/svn/test/server/linux/issue/conf/config.java

svn: Repository moved permanently to 'http://test.server.com/svn/test/server/linux/issue/conf; please relocate 

I think I did a mess. I am not able to access now.

35538912 0 Peewee select with circular dependency

I have two models Room and User. Every user is assigned to exactly one room and one of them is the owner.

DeferredUser = DeferredRelation() class Room(Model): owner = ForeignKeyField(DeferredUser) class User(Model): sessid = CharField() room = ForeignKeyField(Room, related_name='users') DeferredUser.set_model(User) 

Now, having sessid of the owner I'd like to select his room and all assigned users. But when I do:

(Room.select(Room, User) .join(User, on=Room.owner) .where(User.sessid==sessid) .switch(Room) .join(User, on=User.room)) 

It evaluates to:

SELECT "t1".*, "t2".* # skipped column names FROM "room" AS t1 INNER JOIN "user" AS t2 ON ("t1"."owner_id" = "t2"."id") INNER JOIN "user" AS t2 ON ("t1"."id" = "t2"."room_id") WHERE ("t2"."sessid" = ?) [<sessid>] 

and throws peewee.OperationalError: ambiguous column name: t2.id as t2 is defined twice.
What I actually need to do is:

room = (Room.select(Room) .join(User.sessid=sessid) .get()) users = room.users.execute() 

But this is N+1 query and I'd like to resolve it in a single query like:

SELECT t1.*, t3.* FROM room AS t1 INNER JOIN user AS t2 ON t1.owner_id = t2.id INNER JOIN user as t3 ON t3.room_id = t1.id WHERE t2.sessid = ?; 

Is there a peewee way of doing this or I need to enter this SQL query by hand?

7067904 0

Well, you could:

  1. Place it in a common svn repository and check it out through subclipse.
  2. Zip the actual file structure (assuming you aren't doing anything too crazy in .flexProperties et al, this should work fine). Then simply import project from the file system. An fxp is basically a glorified zip anyway, so this shouldn't be terribly difficult.
  3. Copy the files directly (Offers almost 0 benefit over zipping, but it is an option).
36246572 0 How to stop countdown from counting up?

I don't know how to stop my countdown from counting up. I used countdown.js and jquery.min.js attached to my script. What should I add to accomplish this? Here is my sample code:

<?php $query = "select length_queue, extract(year from (ia_time)), extract(month from (ia_time)), extract(day from (ia_time)), ia_time, serving_time, hour(waiting_time), minute(waiting_time), second(waiting_time) from sys_table"; $i = 0; $dsplay = mysql_query($query); while($row = mysql_fetch_row($dsplay)) { $hr = $row[6]; $min = $row[7]; $sec = $row[8]; ?> <tr> <th height="33"><strong><?php echo $row[0]; ?></strong></td> <th><?php echo $row[4]; ?></td> <th><?php echo $row[5]; ?></td> <th><span id="countdown-holder_<?=$i?>" class="ct" ></span></td> </tr> <script type="text/javascript"> $('.ct').each(function(){ var clock = document.getElementById("countdown-holder_<?=$i++?>"), targetDate = new Date(2016, 02, 27, <?php echo $hr;?>, <?php echo $min;?>, <?php echo $sec;?>) ; clock.innerHTML = countdown(targetDate).toString(); setInterval(function(){ clock.innerHTML = countdown(targetDate).toString(); }, 1000); }); // end of function </script> <?php } // END of while loop ?> 
4060332 0

On Android it's best to use AsyncTask to execute tasks in the background while (progressively) updating UI with results from this task.

Edited:

After checking code I think your Handler works correctly. Probably problem is in UpdateDisplay(). Since you are updating display from background thread, make sure you call [view.postInvalidate()][2] after you're done updating your View.

22114703 0

SQLite itself does not require that every parameter is bound explicitly; the default value is NULL.

If the database driver you're using forces you to set all parameters, just set them to NULL.

If index statistics are enabled, SQLite can recompile statements whenever new parameters have been set. In this case, the execution plan might not be the same as you would get for actual parameter values.

4483791 0

You definitely should try Gibraltar. You can combine it with PostSharp and your performantce monitoring will be a piece of cake. Just look into the following code example:

 [GTrace] public Connection ConnectToServer(Server server) { ConnectionStatus connectionStatus = server.TryConnect(); return connectionStatus; } 

And the result in log will look like the following:

Starting method call (you can see passed arguments) alt text

Ending method call

alt text

No crap in code, only thing you need is one attribute. Attrubutes can be used for whole project excluding not needed methods, on namespases, classes or just on any methos you need. Enjoy!

Edit Forgot to mention that Gibraltar has a very rich client and support any metrics you ever need, it's just too powerfull: alt text

32071067 0

I Solved My problem.

Simply add extension=mongo.so in the php.ini file here etc/php5/cli.

36100253 0

You are using the wrong API.

You should be calling _ensureIndex on your collection.

10532652 0

If the Delphi function is declared as being stdcall, why would you declare it in C# as cdecl?

This is the cause of the stack imbalance. Change your C# declaration to use the stdcall convention to match the Delphi declaration.

[UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate double WriteRate(object data); 
22221362 0

we can set an empty array to the Filtering select widgets store.

dijit.byId('widgetId').store.data.splice(0,dijit.byId('widgetId').store.data.length); 

or simply,

dijit.byId('widgetId').store.data = []; 

Or you can set the store itself as null. (But, to add new options after this, you need to recreate the store again, before adding up the new options).

dijit.byId('widgetId').store = null; 
8026669 0

As a reference for future users:

Don't forget to also INSTALL the framework you target! (I, myself, thought that because all the folders (v4.0x, v2.0X, etc.) were there I had all frameworks. NOT! It turns out I only had the .NET 4.0 client profile installed on my system and could not find the System.Web, even though the right framework was targeted.

Anyway, download your needed .net framework here: .NET Frameworks Microsoft Downloads

6312307 0

For the applet to find the libraries, they must be reachable by HTTP. Putting them in the library directory of you web application does not help.

15099432 0

I added a project file and some other small changes which are needed to build ZXing.Net for PCL. You can get it from the source code repository at codeplex. You have to build your own version because at the moment there is no pre built binary. Next version will include it. The restriction of the PCL version is that you have to deal with RGB data. You can't use platform specific classes like Bitmap, WriteableBitmap, BitmapSource or Color32.

13606840 0 VBA MailMerge length > 255

i'm trying to use MailMerge with Word 2010.

I have a TAB delimited file database.dat which looks like the following:

ID Name Street 1 John FooBar 1 2 Smith FooBar 2 

This file is used in Word with the following VBA Code:

ActiveDocument.MailMerge.OpenDataSource Name:="C:/database.dat", _ ConfirmConversions:=False, ReadOnly:=False, LinkToSource:=True, _ AddToRecentFiles:=False, Revert:=False, Format:=wdOpenFormatAuto 

I can use the fields from the file now in the text. So everything works fine.

The Problem:

I need to do some further elaboration with the data in VBA, so I fetch the MergeField Value with:

Function getInfoField(mergefield As String) On Error GoTo MergeFieldNotFound: getInfoField = ActiveDocument.MailMerge.DataSource.DataFields(mergefield).Value GoTo EndFunc MergeFieldNotFound: getInfoField = "" EndFunc: End Function 

But if the length of a merge field value exceeds 255 characters it is cut off. So if I insert

MsgBox Len(ActiveDocument.MailMerge.DataSource.DataFields(mergefield).Value) 

It outputs 255 for a String with e.g. 500 chars.

But directly in the word document, all 500 chars are shown for the merge field.

Question:

How can I get more than 255 chars out of the merge field in VBA?

29677502 0

Perhaps you could simplify and use ng-switch instead.

Something like this:

<ul ng-switch="expression"> <li ng-switch-when="firstThing">my first thing</li> <li ng-switch-when="secondThing">my second thing</li> <li ng-switch-default>default</li> </ul> 

Alternatively, maybe you could use ng-if or ng-show instead of ng-hide, eg:

<p ng-if="HideAddNew">it's here!</p> <p ng-if="!HideAddNew">it's not here.</p> 

Edit

If I understand what you're trying to achieve exactly, I would use ng-show with an ng-click:

Controller:

$scope.addNew = false; 

View:

<button ng-show="!addNew" ng-click="addNew = true">Add New</button> <button ng-show="addNew" ng-click="save()">Save</button> <button ng-show="addNew" ng-click="addNew = false">Cancel</button> 

Example

18162650 0

Here:

struct integer* x= malloc(sizeof(int) * 100);; 

you are allocating memory for the structure (i.e. the pointer and the int), but not for the array.

The moment you try to assign to x->arr[j], you have undefined behaviour.

15155967 0

The relevant part for you is the following one:

You should only grant permission to use the PHP filter to people you trust.

There are always risk of exposing a site to possible attacks when writing code, and in fact the Drupal security team's task is to report security holes to the module maintainers to fix them.
With the PHP filter, the more immediate risk is that users who use it have access to any database table. It would be easy for somebody to change the user account's password, change the ownership of a node, etc.

40796996 0

but i can't find any tutorial which links sql server with cordova app, all i can find is with SQLite or MySQL. I want to connect my local DB with the app directly.

Currently there is no way to connect to sql server directly in Cordova.

You need to implement a service layer for data exposion of your database. You can leverage mssql for node if you are familar with javascript. Alternatively, ASP.Net Web API is a good choice, if you are more familar with .Net.

Whatever the technology you use to build the service layer. It will eventually be consumed by your cordova app through Ajax.

23993911 0

I am not sure whether there is simple way of passing values from View to Controller in Kendo UI Grid. But i have followed the below way in third party MVC Grid to pass the checkbox values. You can bind this function to button click event. It could be too long for simple operation. May be it could be useful for you which you can optimize for your needs.

function PostData(sender, args) { var tempCheckedRecords = new Array(); var gridobj = $find("Grid1"); // getting Grid object. Modify it for KendoUI grid. if (sender.checked == true) { ... //retrieve the records here tempCheckedRecords.push(records[0]); // pass the selected records in the array } var tempRecords = new Array(); $.each(tempCheckedRecords, function (index, element) { var record = {}; record["Column0"] = element.IsSelected; // column names in Grid record["Column1"] = element.TestPointName; // you can get the text box values in the element. record["Column2"] = element.PassThreshold; tempRecords.push(record); }); var params = {}; var visibleColumns = gridobj.get_VisibleColumnName(); $.each(tempRecords, function (i, record) { $.each(visibleColumns, function (j, value) { params["Test[" + i + "]." + this] = record[value]; }); }); $.ajax({ type: 'post', url: "/configuration/testplan/Add", datatype: 'json', data: params, success: function (data) { return data; } }); } 
15266133 0 Why does PMD suggest making fields final?

I created Android application and run static analysis tool PMD on it. And what I don't get is why it is giving me warning and says to declare fields final when possible like in this example.

final City selectedItem = (City) arg0.getItemAtPosition(arg2); new RequestSender(aaa).execute(xxx, selectedItem.getId()); 

It just starts inner AsyncTask instance. Is it good style to declare it final and why? For the sake of readability, I created a new object, but PMD says it should be final.

8603024 0

According to your logic, it is impossible for both conditions to run at the same time. However, I'm sure you've run this script multiple times. Sometimes with IF, sometimes with ELSE. It doesn't seem like you're ever clearing the $_SESSION variables.

Solution: Right after you use the $_SESSION['save'] or $_SESSION['error'] variables, unset them.

unset($_SESSION['save']); 

or

unset($_SESSION['error]'); 
7926733 0
system %x{ wget #{item['src']} } 

Edit: This is assuming you're on a unix system with wget :) Edit 2: Updated code for grabbing the img src from nokogiri.

21804151 0

Long story short: I built my own custom container for that. It provides the ability to switch between tabs, as well as pushing new ViewControllers on each tab. Kind of like a hybrid between UINavigationController and UITabBarController.

If you need a more detailed answer on that please let me know.

22637195 0

Should be like this:

enter image description here

And then this:

enter image description here

It is surprisingly simple. Make sure you've selected the right section.

8024349 0

You should create a custom SearchResult class with a property that returns the full path.
The class should override ToString() and return the text you want to display in the listbox.

You can then put instances of your class directly into the listbox, and cast an item from the listbox back to the class to get the property.

32574686 0

It should be as easy as adding the file to your extension target/project so that both are part of the same module. Same module means internal scope and the constant should be accessible from the other file automatically.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html

18115356 0

You need to check the exit code of every adb statement you are running before moving onto the next

This post here details checking exit codes with bash Bash Beginner Check Exit Status

which includes this (changed for your example)

function test { "$@" status=$? if [ $status -ne 0 ]; then echo "error with $1" exit "$status" fi return $status } test adb shell uiautomator runtest myTest.jar -c com.myTest.TestClass1 test adb shell uiautomator runtest myTest.jar -c com.myTest.TestClass2 

You can also tell Jenkins to use bash by adding a shebang to the first line of your script

#!/bin/bash 
23386742 0 XPath is not finding element

XPath I created:

.//*[@id='stepCongrats']/div[2]/div[3]/div[2]/ul/li[1]/span 

using this xPath I am getting message: NoSuchElementException

Below is my html code:

<div id="stepCongrats"> <div id="ancillary-congratulations"></div> <div id="elephant"></div> <div class="sect"> <div class="s-header"></div> <div class="s-nav"></div> <div class="s-body"> <div class="s-policyholder"></div> <div class="s-policyinfo"> <ul> <li> <h6> Policy number </h6> <span> 247-000-001-13 </span> 
7587080 0

I get mostly 2 calls at the same time (1 for each thread), followed by a one second pause. What is wrong?

That's exactly what you should expect from your implementation. Lets say the time t starts at 0 and the rate is 1:

Thread1 does this:

 lock.acquire() # both threads wait here, one gets the lock current_time = time.time() # we start at t=0 interval = current_time - last_time[0] # so interval = 0 last_time[0] = current_time # last_time = t = 0 if interval < rate: # rate = 1 so we sleep time.sleep(rate - interval) # to t=1 lock.release() # now the other thread wakes up # it's t=1 and we do the job 

Thread2 does this:

 lock.acquire() # we get the lock at t=1 current_time = time.time() # still t=1 interval = current_time - last_time[0] # interval = 1 last_time[0] = current_time if interval < rate: # interval = rate = 1 so we don't sleep time.sleep(rate - interval) lock.release() # both threads start the work around t=1 

My advice is to limit the speed at which the items are put into the queue.

31239515 0

Try the following.

Posts.find({"permalink":"udrskijwddhigfwhecxn"},{fields:{"comments":{"$slice":1‌​0}}}) 

The projection in Meteor is specified by fields.

24001849 0 Dependency Injection / Polymorphism in Objective C

Can I use Objective C protocols the same way I would use Java interfaces for Dependency Injection or Polymorphism?

It seems like I cannot. Note that in (1) below I have to type the property as the implementation rather than as the protocol. I get a compiler error if I use the protocol as the property type.

(1) The object to have dependencies injected into:

#import <Foundation/Foundation.h> #import "FOO_AccountService.h" #import "FOO_BasicAccountService.h" @interface FOO_ServiceManager : NSObject @property (nonatomic, strong) FOO_BasicAccountService <FOO_AccountService> *accountService; ... @end 

(2) The protocol:

#import <Foundation/Foundation.h> #import "FOO_Service.h" @protocol FOO_AccountService <FOO_Service> ... @end 

(3) The implementation:

#import <Foundation/Foundation.h> #import "FOO_BasicService.h" #import "FOO_AccountService.h" @interface FOO_BasicAccountService : FOO_BasicService <FOO_AccountService> ... @end 
37650742 0

You can find the 3d convex hull of all the vertex. Using the points of the convex hull you can form the faces of the convex hull. Then incline one by one all the faces parallel to x-axis. Then find the min x/y/z and max x/y/z along each face rotation.Calculate the volume using min x/y/z and max x/y/z. Find the index corresponding to the minimum volume. Rotate back this volume using the rotation you used for the corresponding face. This problem is similar to the 2d problem of minimum area rectangle. For minimum area rectangle the reference is http://gis.stackexchange.com/questions/22895/how-to-find-the-minimum-area-rectangle-for-given-points

38806433 0 Why cant i use this code to use digital signature on my file?
$lol = system("sudo gpg --clearsign asd.txt;"); 

Is it because I need the password for the gpg??

sudoers:

root ALL=(ALL) NOPASSWD:ALL

apache ALL=(ALL) NOPASSWD:ALL

www-data ALL=(ALL) NOPASSWD:ALL

4557738 0

Function specialization is weird and almost non-existent. It's possible to fully specialize a function, while retaining all types - i.e. you're providing a custom implementation of some specialization of the existing function. You can not partially specialize a templated function.

It's likely that what you're trying to do can be achieved with overloading, i.e.:

template <typename T> T foo(T arg) { return T(); } float foo(int arg) { return 1.f; } 
33080812 0

For a PA to be deterministic it must follow at least the following rule:

If there is an epsilon transition from a state q, there must not be any alphabet transition from that state.

So in your case, if there isn't any other rule, the PA is deterministic.

19692339 0 Java button and listener not working in sync

Trying to add a button to an already made program in JAVA. It converts temperature from Fahrenheit to celsius. My button won't show up. I'm missing something. The idea is that you will be able to both press enter or the button to have a result. There's the main part of the program:

import javax.swing.JFrame; public class Fahrenheit { public static void main (String[] args) { JFrame frame = new JFrame ("Fahrenheit"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); FahrenheitPanel panel = new FahrenheitPanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } } 

Then in a separate file:

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FahrenheitPanel extends JPanel { private JLabel inputLabel, outputLabel, resultLabel; private JButton push; private JTextField fahrenheit; //----------------------------------------------------------------- // Constructor: Sets up the main GUI components. //----------------------------------------------------------------- public FahrenheitPanel() { inputLabel = new JLabel ("Enter Fahrenheit temperature:"); outputLabel = new JLabel ("Temperature in Celsius: "); resultLabel = new JLabel ("---"); fahrenheit = new JTextField (5); fahrenheit.addActionListener (new TempListener()); add (inputLabel); add (fahrenheit); add (outputLabel); add (resultLabel); //Here's some button code push = new JButton ("Push!!!"); push.addActionListener (new ButtonListener()); add (push); setPreferredSize (new Dimension(300, 75)); setBackground (Color.red); } private class ButtonListener implements ActionListener { private class TempListener implements ActionListener { //-------------------------------------------------------------- // Performs the conversion when the enter key is pressed in // the text field. //-------------------------------------------------------------- public void actionPerformed (ActionEvent event) { int fahrenheitTemp, celsiusTemp; String text = fahrenheit.getText(); fahrenheitTemp = Integer.parseInt (text); celsiusTemp = (fahrenheitTemp-32) * 5/9; resultLabel.setText (Integer.toString (celsiusTemp)); } } } } 
33760227 0 How to configure Frag3 to treat packages as Windows packages on a specyfic hosts?

For example I have host addresses: 3.3.3.3 and 3.3.3.33. How to configure Frag3 preprocessor to treat packages that goes to those adressess like/with a typical Windows defragmentation politics?

31141319 0

Fix your gradle file the following way

defaultConfig { applicationId "package.com.app" minSdkVersion 8 //this should be lower than your device targetSdkVersion 21 versionCode 1 versionName "1.0" } 
37652386 0

I have done the same for my application. So here a brief overview what i have done:

Save the data (C#/Kinect SDK):

How to save a depth Image:

 MultiSourceFrame mSF = (MultiSourceFrame)reference; var frame = mSF.DepthFrameReference.AcquireFrame(); if (frame != null ) { using (KinectBuffer depthBuffer = frame.LockImageBuffer()) { Marshal.Copy(depthBuffer.UnderlyingBuffer, targetBuffer,0, DEPTH_IMAGESIZE); } frame.Dispose(); } 

write buffer to file:

File.WriteAllBytes(filePath + fileName, targetBuffer.Buffer); 

For fast saving think about a ringbuffer.

ReadIn the data (Matlab)

how to get z_data:

fid = fopen(fileNameImage,'r'); img= fread(fid[IMAGE_WIDTH*IMAGE_HEIGHT,1],'uint16'); fclose(fid); img= reshape(img,IMAGE_WIDTH,MAGE_HEIGHT); 

how to get XYZ-Data:

For that think about the pinhole-model-formula to convert uv-coordinates to xyz (formula).

To get the cameramatrix K you need to calibrate your camera (matlab calibration app) or get the cameraparameters from Kinect-SDK (var cI= kinectSensor.CoordinateMapper.GetDepthCameraIntrinsics();).

coordinateMapper with the SDK:

The way to get XYZ from Kinect SDK directly is quite easier. For that this link could help you. Just get the buffer by kinect sdk and convert the rawData with the coordinateMapper to xyz. Afterwards save it to csv or txt, so it is easy for reading in matlab.

6462093 0 Reinitialize timeval struct

How can I reinitialize a timeval struct from time.h?

I recognize that I can reset both of the members of the struct to zero, but is there some other method I am overlooking?

27142253 0 Include parent page slug in permalink for posts

I have created a page called Blog and set it as the blog posts page from the wordpress settings.when I create the posts and publish the url structure is like

mysite.com/postname 

i would like it to be like

mysite.com/blog/postname 

so i edited the custom permalink structure to

mysite.com/blog/%postname%/ 

which is working.But i have another custom post type called Work now the permlink structure for work goes like

mysite.com/blog/work/workname 

it was

mysite.com/work/workname 

before i edited the permalink custom structure.

Is there any help to make it the way i want.ie..

mysite.com/blog/postname 

&

 mysite.com/work/workname 

Please help Thanks!!

Edit

my website is

http://jointviews.com/blog/work/best-school-bus-tracking-system/

http://jointviews.com/blog/building-long-term-relationships-with-customers-using-digital-media/

i have register the post type as follows

function work_register() { $labels = array( 'name' => _x('Work', 'post type general name'), 'singular_name' => _x('Work Item', 'post type singular name'), 'add_new' => _x('Add New', 'work item'), 'add_new_item' => __('Add New Work Item'), 'edit_item' => __('Edit Work Item'), 'new_item' => __('New Work Item'), 'view_item' => __('View Work Item'), 'search_items' => __('Search Work'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'menu_icon' => get_stylesheet_directory_uri() . '/article16.png', 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => true, 'menu_position' => null, 'supports' => array('title','editor','thumbnail') ); register_post_type( 'work' , $args ); //register_taxonomy("categories", array("work"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Category", "rewrite" => true)); } 
5362375 0

I am not completely sure what you want to achieve, exactly. But you can do something like:

IsHandled = ev => { ev(this, args); return args.Handled; }; 

Even though I am not sure this is more readable, faster, cleaner, or anything like that. I would just go with something like

if (ErrorConfiguration != null) ErrorConfiguration(this, args); if (!args.Handled) error(this, args); 
38164308 0 Debug mex code using visual studio

Hi I have written a mex file and I would like to debug it using visual studio 2010. I followed steps mentioned in Mathwork website :

http://www.mathworks.com/help/matlab/matlab_external/debugging-on-microsoft-windows-platforms.html

I have also read following posts:

how to debug MATLAB .mex32/.mex64 files with Visual Studio 2010

I should mention that I can compile mex with -g code successfully but when I insert the breakpoint it says: the breakpoint cannot be currently hit. No symbols have been loaded for this document.

Then when I run the mex code from Matlab, it does not create any break point and it does not do the debugging.

According to the following : Fixing "The breakpoint will not currently be hit. No symbols have been loaded for this document." When I go to debug--> windows--> module--> next to matlab says cannot find or open the PDB file. I do not understand what he means when he says

" In normal projects, the assembly and its .pdb file should always have been copied by the IDE into the same folder as your .exe. The bin\Debug folder of your project. Make sure you remove one from the GAC if you've been playing with it."

my Matlab is located in C:\Program Files\MATLAB\R2012a and the mex and pdb file is in C:\Documents\Matlab file but I copied the pdb file (I do not know it is necessary or not) to Matlab workspace. The Matlab current folder that code is running is also C:\Documents\Matlab. Can anyone please help me to solve this problem.

Can anyone please hel me to solve this problem?

16463874 0 Create a larger matrix in special case

I have two vectors:

A=[1 2 3 4] B=[3 5 3 5] 

I want to find a matrix from these vectors like this:

you can suppose that c is a plot matrix, where the x-axis is A and y-axis is B:

c = 0 4 0 4 3 0 3 0 0 0 0 0 0 0 0 0 

or:

 c1= 0 1 0 1 1 0 1 0 0 0 0 0 0 0 0 0 

My question is how to create it automatically because I have large vectors.

36364796 0 __weak typeof(self) weakSelf = self OR __weak MyObject *weakSelf = self?

What is preferable to use here and why?

__weak typeof(self) weakSelf = self; 

or

__weak MyObject *weakSelf = self; 

Obviously, __weak id weakSelf = self; would be the least desirable, as we would not get type checking, is that correct?

However, between the first two... which is desirable and why?

Also, any reason to use __typeof instead of typeof, if clang supports using typeof?

17625315 0

When installing rancid, clogin was placed in /usr/lib/rancid/bin/clogin, which wasn't in my path. It still runs from the command line just fine, though.

I had to create my own ~/.cloginrc file, and chmod 700 ~/.cloginrc before it would let me run the command.

This was on Ubuntu 12.04.

A basic run-through, I installed it via apt-get install rancid. Then I had to add these lines to my (non-existent) ~/cloginrc:

add user 192.168.11.1 admin add password 192.168.11.1 MyPassword 

Then at the command line, I typed:

/usr/lib/rancid/bin/clogin 192.168.11.1 

It performed the login process for me, based on the IP address.

That's pretty much it, though I might point out you could even leave your .cloginrc empty and just type /usr/lib/rancid/bin/clogin -u admin -p MyPassword 192.168.11.1 instead.

Here is a sample ~/.cloginrc from their GitHub:

https://github.com/dotwaffle/rancid-git/blob/master/cloginrc.sample

1356260 0

You can use JavaScript with a little help from jQuery Library to post to an .aspx page. I wrote an example for PHP here http://stackoverflow.com/questions/1353678. The javascript part would stay the same, but on the server side you would have to read the query string to read in the variables using Request.querystring. Also If you want to return JSON data you will have to change the response type to be plain text rather HTML. Like this:

context.Response.ContentType = "text/plain"; 
16030417 0

Forget about performance in this comparison; it would take a truly massive enum for there to be a meaningful performance difference between the two methodologies.

Let's focus instead on maintainability. Suppose you finish coding your Direction enum and eventually move on to a more prestigious project. Meanwhile, another developer is given ownership of your old code including Direction - let's call him Jimmy.

At some point, requirements dictate that Jimmy add two new directions: FORWARD and BACKWARD. Jimmy is tired and overworked and does not bother to fully research how this would affect existing functionality - he just does it. Let's see what happens now:

1. Overriding abstract method:

Jimmy immediately gets a compiler error (actually he probably would've spotted the method overrides right below the enum constant declarations). In any case, the problem is spotted and fixed at compile time.

2. Using a single method:

Jimmy doesn't get a compiler error, or even an incomplete switch warning from his IDE, since your switch already has a default case. Later, at runtime, a certain piece of code calls FORWARD.getOpposite(), which returns null. This causes unexpected behavior and at best quickly causes a NullPointerException to be thrown.

Let's back up and pretend you added some future-proofing instead:

default: throw new UnsupportedOperationException("Unexpected Direction!"); 

Even then the problem wouldn't be discovered until runtime. Hopefully the project is properly tested!

Now, your Direction example is pretty simple so this scenario might seem exaggerated. In practice though, enums can grow into a maintenance problem as easily as other classes. In a larger, older code base with multiple developers resilience to refactoring is a legitimate concern. Many people talk about optimizing code but they can forget that dev time needs to be optimized too - and that includes coding to prevent mistakes.

Edit: A note under JLS Example §8.9.2-4 seems to agree:

Constant-specific class bodies attach behaviors to the constants. [This] pattern is much safer than using a switch statement in the base type... as the pattern precludes the possibility of forgetting to add a behavior for a new constant (since the enum declaration would cause a compile-time error).

7162895 0

You can solve this using MultiDataTriggers. Just make sure that you place them in the correct order, as I recall, the last trigger that meets all criteria takes precedence.

39581342 0 #if - #else - #endif breaking F# Script

Using Visual Studio 2015 Update 3 and fsi.exe from F# v4.0 I' trying to run this script:

//error.fsx #if INTERACTIVE let msg = "Interactive" #else let msg = "Not Interactive" #endif let add x y = x + y printfn "%d" (add 1 2) 

Output: error.fsx(12,15): error FS0039: The value or constructor 'add' is not defined

If I then comment out the #if-#else-#endif block, it works fine:

// fixed.fsx //#if INTERACTIVE // let msg = "Interactive" //#else // let msg = "Not Interactive" //#endif let add x y = x + y printfn "%d" (add 1 2) 

Output: 3

I'm sure I'm doing something wrong (rather than this being a bug) but I can't for the life of me figure out how to make this work.

Thoughts?

33477519 0 Oracle Column Not Allowed Here Default Value

The problem is about the DEFAULT value using a sequence on line 4.

 CREATE OR REPLACE SEQUENCE CHANNEL_SEQ START WITH 1 INCREMENT BY 1; CREATE TABLE "CHANNEL" ( "ID_CHANNEL" NUMBER(18,0) DEFAULT CHANNEL_SEQ.NEXTVAL, "IS_ACTIVE" VARCHAR2(1 CHAR) NOT NULL, "BATCH_SIZE" NUMBER(3,0) NOT NULL, "MAX_DOCS_IN_PROCESS" NUMBER(4,0) NOT NULL, "RECEIVER_ID" NUMBER(18,0) NOT NULL, "LAST_POS_SESSION_TIME" DATE, CONSTRAINT "PK_CHANNEL" PRIMARY KEY ("ID_CHANNEL"), CONSTRAINT "FK_RECEIVER_ID_CHANNEL" FOREIGN KEY ("RECEIVER_ID") REFERENCES "MSG_OUT"("MSG_OUT_ID"), CONSTRAINT "CHK_IS_ACTIVE" CHECK (IS_ACTIVE IN ('Y', 'N')) ); 

The error messages are :

"SQL Error: ORA-00984: column not allowed here"

All help and hints are welcome.

13832020 0

When you put inverted commas round something it makes it into a string, so 'month' means the word this, whereas month means the value in the variable called month.

Your program will stop giving you that particular error if you remove the 's:

D = input() A = ( (14 - month) /12) Y = ( Year - A ) MonthProblem = ( month + 12 * A - 2 ) week = ( (D + Y + Y/4 - Y/100 + Y/400 + 31 * MonthProblem/12) % 7 ) 

Had you defined the values of month etc before?

26200559 0

if max_oms is a parameter (i.e. a constant, and it probably is one) you can do:

CHARACTER(LEN=20) :: filename(max_xoms,2) = RESHAPE(SOURCE=(/'XobsXOM0.txt','XobsXOM1.txt','XobsXOM2.txt','XobsXOM3.txt','XobsXOM4.txt', & 'XobsXOM5.txt','XobsXOM6.txt','XobsXOM7.txt','XobsXOM8.txt','XobsXOM9.txt', & 'XobsXOS0.txt','XobsXOS1.txt','XobsXOS2.txt','XobsXOS3.txt','XobsXOS4.txt', & 'XobsXOS5.txt','XobsXOS6.txt','XobsXOS7.txt','XobsXOS8.txt','XobsXOS9.txt'/), & SHAPE=(/max_xoms,2/)) 

otherwise move

filename = RESHAPE(SOURCE=(/'XobsXOM0.txt','XobsXOM1.txt','XobsXOM2.txt','XobsXOM3.txt','XobsXOM4.txt', & 'XobsXOM5.txt','XobsXOM6.txt','XobsXOM7.txt','XobsXOM8.txt','XobsXOM9.txt', & 'XobsXOS0.txt','XobsXOS1.txt','XobsXOS2.txt','XobsXOS3.txt','XobsXOS4.txt', & 'XobsXOS5.txt','XobsXOS6.txt','XobsXOS7.txt','XobsXOS8.txt','XobsXOS9.txt'/), & SHAPE=(/max_xoms,2/)) 

to the position of a first executable statement.

Generally, avoid DATA in Fortran 90 and later.

34118727 0 using strtok() in c with combined word

I'd like to know how to use strtok to find values, so is this possible to use strtok(mystring, "") or no?

I want split this : mystring --> %3456 I want split into 2 parts : "%" and "3456". Is this possible? how can I do that?

22734714 0 Grep one file and remove contents of the grep with sed -i on a second file

I am trying to grep ip addresses from one file and remove the contents of the grep from a second file with a single command.

The masterfile has

header x.x.x.x header x.x.x.x header2 y.y.y.y header2 y.y.y.y header3 z.z.z.z header3 z.z.z.z 

The tempfile has

x.x.x.x x.x.x.x y.y.y.y y.y.y.y z.z.z.z z.z.z.z 

Attempt

grep "header" masterfile | sed 's/^.* //' | sed -i "" '/$/d' tempfile 

Would also like to remove the empty line after the sed command removes an entry.

18724237 0 Collection was modified error when looping through list and removing items

I have the following:

 tempLabID = lstLab; foreach (string labID in lstLab) { if (fr.GetFileRecipients(fsID).Contains(labID)) { tempLabID.Remove(labID); } } 

When I debug and watch lstLab and I get to tempLabID.remove() it changes lstLab to 0 from 1, and then in turn, when it gets back to the foreach I get an error saying the collection has been modified.

I can't understand why it's happening. I am modifying a different collection.

13469787 0 How to specify page size in dynamically in yii view?

How to specify page size in dynamically in yii view?(not a grid view) In my custom view page there is a search option to find list of users between 2 date i need 2 know how to specify the page size dynamically? If number of rows less than 10 how to hide pagination ?enter image description here

please check screen-shoot

I dont want the page navigation after search it confusing users..

my controller code

 $criteria=new CDbCriteria(); $count=CustomerPayments::model()->count($criteria); $pages=new CPagination($count); // results per page $pages->pageSize=10; $pages->applyLimit($criteria); $paymnt_details=CustomerPayments::model()->findAll($criteria); $this->render('renewal',array('paymnt_details'=>$paymnt_details,'report'=>$report,'branch'=>$branch,'model'=>$model,'pages' => $pages,)); } 

my view Link

27944589 0

if string is: $str = '"World"';

ltrim() function will remove only first Double quote.

Output: World"

So instead of using both these function you should use trim(). Example:

$str = '"World"'; echo trim($str, '"'); 

Output-

World 
6390650 0

It should just work; I believe the problem is that the attributes are inverted (I will take a note to raise a clearer error in this case) - it should be :

[ProtoContract, ProtoInclude(14, typeof(Update))] class Annoucement { } [ProtoContract] class Update : Announcement { } 

i.e. the base needs to know about the descendants. Not I removed the discriminator from serialization, as that is redundant if it relates directly to the object type - it handles this internally via the ProtoInclude and will create the correct type for you. Each type needs to know only about the direct subtypes, i.e.

A - B - C - D - E - F 

here A needs to know about B and D; B needs to know about C; D needs to know about E and F.

Note that a "what is this" enum is a good idea here, but there is no need for it to be a field - a virtual property without a field may be more appropriate. If I have misundersood and the message-type doesn't relate to the object-type, then ignore me ;p

Also: public fields - don't do it. Think of the kittens... It will work, but properties are preferred (in general, I mean; nothing to do with protobuf-net).

10578609 0 Generic extension method for an array does not compile

Populating a request object for a web-service, I need to dynamically add items to some arrays.

I hoped to simplify it by implementing an extension method:

public static class ArrayExtensions<T> where T : class { public static T[] Extend<T>(T[] originalArray, T addItem) { if (addItem == null) { throw new ArgumentNullException("addItem"); } var arr = new[] { addItem }; if (originalArray == null) { return arr; } return originalArray.Concat(arr).ToArray(); } } 

So that this old code:

if (foo.bazArr == null) { foo.bazArr = new[] { baz }; } else { foo.bazArr = new[] { baz }.Concat(foo.bazArr).ToArray(); // (i know this inserts the new item at the beginning, but that's irrelevant, order doesn't matter) } 

could be rewritten as:

foo.bazArr = foo.bazArr.Extend(baz); // won't compile 

The error is: 'System.Array' does not contain a definition for 'Extend' and no extension method 'Extend' accepting a first argument of type 'System.Array' could be found (are you missing a using directive or an assembly reference?)

Whereas calling the extension method directly like so:

foo.bazArr = ArrayExtensions<someService.bazType>.Extend(foo.bazArr, baz); 

compiles fine.

Why is that so? Why can't the compiler infer the type on its own here, if the array is strongly-typed?


EDIT - correct code below:

public static class ArrayExtensions { public static T[] Extend<T>(this T[] originalArray, T addItem) where T : class { if (addItem == null) { throw new ArgumentNullException("addItem"); } var arr = new[] { addItem }; if (originalArray == null) { return arr; } return originalArray.Concat(arr).ToArray(); // although Concat is not recommended for performance reasons, see the accepted answer } } 

For this popular question, here's another good simple example:

public static class Extns { // here's an unbelievably useful array handling extension for games! public static T AnyOne<T>(this T[] ra) where T:class { int k = ra.Length; int r = Random.Range(0,k); return ra[r]; // (add your own check, alerts, etc, to this example code) } } 

and in use ..

someArrayOfSoundEffects.AnyOne().Play(); someArrayOfAnimations.AnyOne().BlendLeft(); winningDisplay.text = successStringsArray.AnyOne() +", " +playerName; SpawnEnormousRobotAt( possibleSafeLocations.AnyOne() ); 

and so on. For any array it will give you one random item. Used constantly in games to randomise effects etc. The array can be any type.

21138303 0

I found out what the problem is: Because I'm using D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, it does notwork with D3DPOOL_MANAGED. I switched it to D3DPOOL_DEFAULT and it worked.

29196717 0

What does your curl call look like? You can use subprocess.call() to run a shell command from a python script.

Here's an example of downloading two images:

script.py

import subprocess data = [ ("homer.jpg", "http://upload.wikimedia.org/wikipedia/en/0/02/Homer_Simpson_2006.png"), ("bart.jpg", "http://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png") ] for datum in data: subprocess.call(["curl", "-o", datum[0], datum[1]]) 

The subprocess.call() function takes a list of arguments so in my example it translates to running the following commands from a terminal:

31826805 0

DS-5 displays only the core registers by default. To display NEON and other system registers, you have to manually add them by either clicking the Browse Button or typing the name of register in the text box beside Browse button.

Detailed documentation is available at http://ds.arm.com/developer-resources/ds-5-documentation/arm-ds-5-debugger-user-guide/registers-view

16675541 0

Marmalade EDK is Extension Development Kit of Marmalade SDK, which is a set of tool to bring native functionality of the platform, on which the application is deployed.
The code is written in native supported language, for example for Android it's Java and for iOS it's Objective C.
EDK is currently supported for Android, iOS, Windows and OSX only. There's no support for Windows phone 8 and BB10 yet.

11930027 0 Compare more than one values with each other

I have about 20 different variables and i want to compare this variables with each other to check weather they are equal or not.

Example

$var1 = 1; $var2 = 2; $var3 = 1; $var4 = 8; . . . $var10 = 2; 

Now i want to check...

if($var1 == $var2 || $var1 == $var3 || $var1 == $var4 || ......... || $var2 == $var3 || $var2 == $var4 || ............. || $var8 = $var9 || $var8 == $var10 ||...) { echo 'At-least two variables have same value'; } 

I am finding for an easy to do this. Any Suggestions?

3458570 0

Put the tags into an array. Each array being respectively called Post A / Post B etc. Then use array_diff_assoc(), to figure out how different the arrays are.

But really, Ivars solution would work better, this is easier to understand though :)

4586806 0

Do this:

$(e).find(".myclass").something(); 

or the slightly shorter, yet less efficient version:

$(".myclass", e).something(); 

The reason you can't use + is that your e is a DOM element, which is not a useful type for concatenation into a selector string, since you end up with something like:

"[object HTMLInputElement] .myclass" 
21955672 0
void move_digits(int a) { int digits = 0; int b = a; while(b / 10 ){ digits++; b = b / 10; } for (int i = 0; i < digits; ++i) { int c = a / 10; int d = a % 10; int res = c + pow(10, digits) * d; printf("%d\n", res); a = res; } printf("\n"); } int main() { move_digits(12345); } 
11269070 0

Assuming you've populated a list of ListIDs (listOfIDs) in a separate query:

var accounts = from a in db.Accounts where !listOfIDs.Contains(a.ListID) select a; db.Accounts.RemoveAll(accounts); db.SubmitChanges(); 
18822891 0

If you don't know on which server your database is stored, there's no way we can know it better than you.

According to your comment, your database is on the machine where your code gets executed. Then HOST = localhost

6657370 0

You essentially need to get the row id from the selected ListView item. Using the row id you can easily delete that row:

String where = "_id = " + _id; db.delete(TABLE_NAME, where, null); 

After deleting the row item make sure you get the ListView adapter cursor and do a requery. If you don't you will not see the updated table, hence updated ListView.

17857348 0 Autofiltering records in grid in asp.net according to keywords

I want to search some items in a grid in asp.net C#. While i search for the records that I want to I don't want to hit the search button and then the grid will get filtered. I want that the grid should get filtered with the records that match the keyword that I am entering. I guess this can be done using html5 or j query. I am not able to exactly phrase my search for google.

Pleas help. Thanks in advance.

40201250 0

The problem was solved after I imported CA certificate in JRE certificate store:

keytool -importcert -alias startssl -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -file ca.der 
2458422 0

Point 1: I think you need at least some quotes around the connection string:

 myProcess.StartInfo.Arguments = "/mode:fullgeneration \"/c:"+cs+"\" project:School ..."; 

But do examine the resulting Arguments string in the debugger to see if everything is allright.

For point 2, see this SO question.

5193297 0 Mail settings in Web.config

Is it possible to set a "to" attribute in the mailSettings element in the Web.config file?

9780589 0

The Excel object model is fully documented on MSDN. Here is the Excel 2010 Application object. Use the links in the left navigator to view properties and members.

http://msdn.microsoft.com/en-us/library/ff194565.aspx

Move up the navigator tree to Reference to see all the objects.

http://msdn.microsoft.com/en-us/library/ff846392.aspx

17354168 0 Scanner class is skipping lines

I'm new to programing and I'm having a problem with my scanner class. This code is in a loop and when the loop comes around the second, third whatever time I have it set to it skips the first title input. I need help please why is it skipping my title scanner input in the beginning?

System.out.println("Title:"); list[i].title=keyboard.nextLine(); System.out.println("Author:"); list[i].author=keyboard.nextLine(); System.out.println("Album:"); list[i].album=keyboard.nextLine(); System.out.println("Filename:"); list[i].filename=keyboard.nextLine(); 
20145535 0

Code -

drop table #a drop table #b select * into #a from [databasename1].information_schema.columns a --where table_name = 'aaa' select * into #b from [databasename2].information_schema.columns b -- add linked server name and db as needed --where table_name = 'bbb' select distinct( a.table_name), b.TABLE_SCHEMA+ '.' + (b.table_name) TableName,b.TABLE_CATALOG DatabaseName from #a a right join #b b on a.TABLE_NAME = b.TABLE_NAME and a.TABLE_SCHEMA = b.TABLE_SCHEMA where a.table_name is null-- and a.table_name not like '%sync%' 
4877342 0
fields: [{name: 'Time', mapping: 'Time', type: 'int'}] fields: [{name: 'Time', type: 'int'}] 

BTW In the case of an identity mapping you can leave it out. These two cases will give you the same results.

15540379 0

Using the Scala debugger through the remote connector works.

But if you want to avoid to go back and forth between sbt and Eclipse, you can load your project in Scala IDE using sbteclipse, and then run your specs2 tests from inside Scala IDE, in debug mode, using the JUnit launcher.

31871649 0

setTimeout(function() { window.location.href = "/NewPage.aspx"; }, 2000);
.wrapper { background-color: red; width: 100%; -webkit-animation-name: example; /* Chrome, Safari, Opera */ -webkit-animation-duration: 2s; /* Chrome, Safari, Opera */ animation-name: example; animation-duration: 2s; } @-webkit-keyframes example { 0% { opacity: 100; filter: alpha(opacity=1000); /* For IE8 and earlier */ } 100% { opacity: 0.0; filter: alpha(opacity=0); /* For IE8 and earlier */ } } /* Standard syntax */ @keyframes example { 0% { opacity: 100; filter: alpha(opacity=1000); /* For IE8 and earlier */ } 100% { opacity: 0.0; filter: alpha(opacity=0); /* For IE8 and earlier */ } }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='wrapper'> <div>Home Page</div> </div>

4196598 0

There's a new project, NLib, which can do this much faster:

if (input.IndexOfNotAny(new char[] { 'y', 'm', 'd', 's', 'h' }, StringComparison.OrdinalIgnoreCase) < 0) { // Valid } 
35867617 0 jqGrid add buttons for add/edit/delete in toolbar not working

I have tried to implement the code for adding buttons in jqGrid toolbar from the example site http://www.guriddo.net/demo/bootstrap/ but I'm surprised to find that it isn't working for me. Searched for a couple of hours but I can't figure it out. Here is my code:

<script type="text/javascript"> $(function () { var gridDataUrl = '@Url.Action("JsonCategories", "AdminNomCategory")' var grid = $("#reportsGrid").jqGrid({ url: gridDataUrl, datatype: "json", mtype: 'POST', colNames: [ '@Html.DisplayNameFor(model => model.CategoryGuid)', '@Html.DisplayNameFor(model => model.CategoryName)', '@Html.DisplayNameFor(model => model.CategoryDescription)' ], colModel: [ { name: 'CategoryGuid', index: 'CategoryGuid', width: 10, align: 'left', classes: "nts-grid-cell", hidden: true }, { name: 'CategoryName', index: 'CategoryName', width: 10, align: 'left', classes: "nts-grid-cell" }, { name: 'CategoryDescription', index: 'CategoryDescription', width: 10, align: 'left', classes: "nts-grid-cell" } ], rowNum: 20, rowList: [10, 20, 30], height: 450, width: 1140, pager: '#pager', /*jQuery('#pager'),*/ sortname: 'CategoryGuid', toolbarfilter: true, viewrecords: true, sortorder: "asc", caption: "Categories", ondblClickRow: function (rowid) { var gsr = jQuery("#reportsGrid").jqGrid('getGridParam', 'selrow'); if (gsr) { var CategoryGuid = grid.jqGrid('getCell', gsr, 'CategoryGuid'); window.location.href = '@Url.Action("Edit", "AdminNomCategory")/' + CategoryGuid } else { alert("Please select Row"); } }, @*onSelectRow: function (rowid) { var gsr = jQuery("#reportsGrid").jqGrid('getGridParam', 'selrow'); if (gsr) { var CategoryGuid = grid.jqGrid('getCell', gsr, 'CategoryGuid'); window.location.href = '@Url.Action("Edit", "AdminNomCategory")/' + CategoryGuid } else { alert("Please select Row"); } }*@ }); //jQuery("#reportsGrid").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true }); var template = "<div style='margin-left:15px;'><div> Customer ID <sup>*</sup>:</div><div> {CustomerID} </div>"; template += "<div> Company Name: </div><div>{CompanyName} </div>"; template += "<div> Phone: </div><div>{Phone} </div>"; template += "<div> Postal Code: </div><div>{PostalCode} </div>"; template += "<div> City:</div><div> {City} </div>"; template += "<hr style='width:100%;'/>"; template += "<div> {sData} {cData} </div></div>"; $('#reportsGrid').navGrid('#pager', // the buttons to appear on the toolbar of the grid { edit: true, add: true, del: true, search: false, refresh: false, view: false, position: "left", cloneToTop: false }, //// options for the Edit Dialog { editCaption: "The Edit Dialog", template: template, errorTextFormat: function (data) { return 'Error: ' + data.responseText } }, // options for the Add Dialog { template: template, errorTextFormat: function (data) { return 'Error: ' + data.responseText } }, // options for the Delete Dailog { errorTextFormat: function (data) { return 'Error: ' + data.responseText } } ); grid.jqGrid('filterToolbar', { searchOnEnter: true, enableClear: false }); jQuery("#pager .ui-pg-selbox").closest("td").before("<td dir='ltr'>Rows per page </td>"); grid.jqGrid('setGridHeight', $(window).innerHeight() - 450); }); $(window).resize(function () { $('#reportsGrid').jqGrid('setGridHeight', $(window).innerHeight() - 450); }); </script> 

I am using jqGrid 4.4.4 and ASP.NET. The thing I noticed, is that on the example page, the buttons are located inside a div with an id like 'jqGridPagerLeft', but on my page, that div has no id. So I went looking inside the jqGrid source but I'm lost and I can't figure out why it doesn't have an id allocated.

Any clues? I just want to add the buttons to the bottom toolbar. Thx!

12756918 0

As Ahmad says, you need to compile your code with API Level 14 in order to use the constant "ICE_CREAM_SANDWICH". The thing is that at compilation time those constants are changed into their respective values. That means that at runtime any device won't see the "ICE_CREAM_SANDWICH" constant but the value 14 (even if it is a device with Froyo 2.2 installed).

In other words, in your code:

Integer version = Build.VERSION_CODES.ICE_CREAM_SANDWICH; 

in the device:

Integer version = 14; 

It is not exactly like that, but you get the idea.

13158927 0

Persistent login are not possible with Apps Script as Apps Script can not interact with browser objects like cookies etc. Apps Script is intended to work only with Google Accounts.

10560872 0

If you really want to do it in Goliath I'd suggest creating a plugin and doing it in there. Create a queue in the config and have the plugin pop items from the queue and send the mail.

36549504 0

The problem is that when more elements are added to a vector it may resize itself. When this happens all elements are moved to a new location and all existing pointers and references to elements get invalidated.

There are containers that do not invalidate iterators when new elements are added, such as std::list and boost::stable_vector.

I.e. boost::stable_vector<Segment> or std::list<Segment> instead of std::stable<Segment> would fix the issue, provided you do not require contiguous storage of Segment elements.

36335069 0

Would a slightly different structure of global app state help you? For example:

const appState = { subApps: { subApp1: {}, subApp2: {}, // etc. }, currentSubApp: 'subApp2', }; const subApp2State = appState.subApps[appState.currentSubApp]; 

On the other hand, if your subApps are completely independent of the parent-app, you could let them use whatever structure they want (their own redux store for example, different from the one of the parent-app) and simply integrate them in React wrapper-components, like this:

import SubApp from '...anywhere...'; const SubAppWrapper = React.createClass({ componentDidMount: function() { this.subApp = new SubApp({ containerElement: this.refs.containerDiv, // other params }); }, componentWillUnmount: function() { this.subApp.destroy(); }, render: function() { return ( <div ref="containerDiv"></div> ); }, }); 
11262031 0 kohana view from what controller?

I have a view that could be called from any of 3 actions from one controller. But, that view should be slightly different depending on what action caused it (it should display 3 icons or 2 or one depending on action called). Can I check in the view what action caused it so I can use if statement to check whether display each icon or not?

Thank you.

36434512 0

you can use ROW_NUMBER

;with cte as ( select x.pt_year, x.pt_month, x.pt_amount, y.fp_earnedprem from ( select sum(a.amount) as pt_amount , va.ACCT_YEAR as pt_year, va.ACCT_MONTHINYEAR as pt_month, ptp.PTRANS_CODE as pt_code from fact_policytransaction a join VDIM_ACCOUNTINGDATE va on a.ACCOUNTINGDATE_ID=va.ACCOUNTINGDATE_ID join DIM_POLICYTRANSACTIONTYPE ptp on a.POLICYTRANSACTIONTYPE_ID=ptp.POLICYTRANSACTIONTYPE_ID group by va.ACCT_YEAR, va.ACCT_MONTHINYEAR, ptp.PTRANS_CODE ) as x join ( select sum(fp.EARNED_PREM_AMT) as fp_earnedprem , dm.MON_YEAR as fp_year, dm.MON_MONTHINYEAR as fp_month from fact_policycoverage fp join dim_month dm on fp.MONTH_ID=dm.MONTH_ID group by dm.MON_YEAR, dm.MON_MONTHINYEAR ) as y on x.pt_year = y.fp_year and x.pt_month = y.fp_month where x.pt_year=2016 and x.pt_month=6 ) , Rn as ( select * , ROW_NUMBER() over (partition by pt_year, pt_month order by pt_year, pt_month) as RoNum from cte ) select pt_year, pt_month, pt_amount , IIF(RoNum = 1, fp_enarnedprem, 0) from Rn order by pt_year, pt_month 

the main part is your own query, I only added below section and a line on top and moved order by to the bottom.

) , Rn as ( select * , ROW_NUMBER() over (partition by pt_year, pt_month order by pt_year, pt_month) as RoNum from cte ) select pt_year, pt_month, pt_amount , IIF(RoNum = 1, fp_enarnedprem, 0) from Rn order by pt_year, pt_month 
24354951 0

The problem with the current code isn't completely clear to me as I don't know what doesn't happen what should happen or vice versa. So I'm still guessing a bit. But I see you are not implementing viewForHeaderInSection which is what I would use to implement custom headers. Also I think you need heightForHeaderInSection set to something different than 0 (obviously).

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { // Simple on the fly generated UIView, you could also return your own subclass of UIView UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)]; [label setFont:[UIFont boldSystemFontOfSize:12]]; label.text = [arrHeaders objectAtIndex:section]; return view; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section; { // Should be same as UIView that you return in previous function return 18.0f; } 
2736978 0

Ok, finally I got it running by making the models closer to what I wanted to present to the user. But related to the topic of the question :

1) Nested forms/formsets are not a built-in Django feature, are a pain to implement by yourself, and are actually not needed... Rather, one should use forms' and formsets' prefixes.

2) Trying to work with forms not based on the models, process the data, then reinject it in the models, is much much more code than modifying the models a little bit to have nice model-based forms. So what I did is I modified the models like that :

class PortConfig(Serializable): port = models.ForeignKey(Port, editable=False) machine = models.ForeignKey("vmm.machine", editable=False) is_open = models.CharField(max_length=16, default="not_open", choices=is_open_choices) class Rule(Serializable): ip_source = models.CharField(max_length=24) port_config = models.ForeignKey(PortConfig) 

Then I simply used a "model formset" for PortConfig, and "model inline formset" for Rule, with a PortConfig as foreign key, and it went perfectly

3) I used this great JS library http://code.google.com/p/django-dynamic-formset/ to put the "add field" and "delete field" links ... you almost have nothing to do.

15932162 0

I believe this works and is the canonical repository of this kind of info. (If it doesn't, the page should be fixed!)

http://www.chromium.org/nativeclient/how-tos/debugging-documentation/debugging-with-debug-stub-recommended/debugging-nacl-apps-in-chrome-os

Yes, you can use gdb remotely.

To see printf output, try chrome:://system and expanding the ui_log.

6097793 0 Can't "unselect" listview item

I was able to get the background changed of an individual listview item in a setOnItemClickListener with

view.setBackgroundResource(R.color.green); 

I only need one selected at a time so when the other list items are clicked, I tried lv.invalidate() and lv.getChildAt(0).invalidate() but neither worked and the second causes null pointer exception. Any ideas for putting the color back?

28968517 0

You can use String#sub to replace it:

'15%'.sub('%', '') #=> '15' 
14079373 0 can we Increase Netty Server performance by using limiting thread pool

Can anybody help me to fix the correct thread pool size a according to the processor and RAM.

Can we fix the limit of worker thread for better performance ?

30513908 0

In Visual Studio 2013, and using googletest with the GoogleTestRunner extension: I couldn't properly debug via the Test Explorer's "Debug this test" menu. I had to debug into the unit test project's executable itself (right click on unit test project, hit Debug).

By "not properly debug" I mean: I was able to stop at a breakpoint, and see a data value by hovering over a variable in the code window - but I didn't get any typical debugger windows (call stack, autos, locals, modules, etc.) nor were there any such windows available under the Debug/Windows menu item!

Not sure if this is your problem, since you didn't specify whether you're using Visual Studio's built-in native C++ unit tests or not. But I believe it might be an issue with running tests inside the Test Explorer.

446336 0

Both of the big OSS DB's (MySQL and PostgreSQL) can scale to extremely large sites. The trick would be to plan from the start such that data can be broken up ("shard") into multiple DB servers and you can quickly find out which server you need to go to.

For example: users having nickname A-G go to server1, H-O to server2, etc. This way you can scale almost infinitely because when a server reaches the limit, you can just split it into smaller pieces.

10240031 0

Per the language spec, section 15.10:

"An array creation expression creates an object that is a new array whose elements are of the type specified by the PrimitiveType or ClassOrInterfaceType. It is a compile-time error if the ClassOrInterfaceType does not denote a reifiable type."

And per the language spec, section 4.7:

Because some type information is erased during compilation, not all types are available at run time. Types that are completely available at run-time are known as reifiable types.

A type is reifiable if and only if one of the following holds:

...

So put simply, "because the language says you can't". I understand the ultimate cause dealt with maintaining backward compatibility, but I'm not familiar with the details.

40453328 0

new_cards = [p if p in usr_card else 'removed' for deck in cards for p in deck] should do it, although may need a bit of tweaking depending what exactly is going on in your code, I'm not too clear.

26834592 0

Let me recommend you a different, more efficient way to easily hook your keyboard:

First, use DllImport and PINvoke inorder to import GetASyncKeyState:

[DllImport("user32.dll")] static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey); 

Then, you can just use the above function as you wish, such as:

public static bool IsKeyPushedDown(System.Windows.Forms.Keys vKey) { return 0 != (GetAsyncKeyState((int)vKey) & 0x8000); } 

More info: PINvoke, MSDN.

Best of luck.

EDIT: btw, If you want to use a barcode reader, you can also create one of your own, or take a look here or here.

14695549 0

Further to Ryan's point, you can see some info on using the bootstrap page on developerworks, you'll want to look at the views example gadget. Unfortunately you can only open a dialog in Connections, the EE style flyout is not available to gadgets on My Page.

39700407 0

Inserting some HTML content into a div makes your arbitrary HTML automatically evaluated. What you should do instead is to parse your HTML string with something like this.

(defn parse-html [html] "Parse an html string into a document" (let [doc (.createHTMLDocument js/document.implementation "mydoc")] (set! (.-innerHTML doc.documentElement) html) doc )) 

This is plain and simple ClojureScript, maybe using the Google Closure library would be more elegant if you want you can dig into the goog.dom namespace or someplace else inside the Google Closure API.

Then you parse your HTML string:

(def html-doc (parse-html "<body><div><p>some of my stuff</p></div></body>")) 

So you can call Enfocus on your document:

(ef/from html-doc :mystuff [:p] (ef/get-text)) 

Result:

{:mystuff "some of my stuff"} 
38193571 0

I'm not exactly sure what would have caused your problem, however is is most likely due to a css/html nesting problem, where multiple css styles interact with the nested elements differently on different browsers? It is better to simply remove the button element in the html and just style the <a> tag to look like a button. By doing this the code is less complicated, you should have fewer problems with styles and nested elements, and this is how most make link buttons anyway. Here is an example of how I made a link button in a recent project, some of the stylings are missing (custom fonts, etc) but it shows that you don't need the button tag, it works better without it, and how to make a button with just the <a> tag.

.btn:link, .btn:visited { display: inline-block; padding: 10px 30px; font-weight: 300; text-decoration: none; color: white; border-radius: 200px; border: 3px solid #1A75BB; margin: 20px 20px 0px 0px; transition: background-color 0.2s, border-color 0.2s, color 0.2s; } .btn:hover, .btn:active { background-color: #14598e; border-color: #14598e; } .btn-full:link, .btn-full:visited { background-color: #1A75BB; margin-right: 20px; } .btn-full:hover, .btn-full:active { background-color: #14598e; } .btn-ghost:link, .btn-ghost:visited { color: black; border-color: #14598e; } .btn-ghost:hover, .btn-ghost:active { color:white; }
<a href="#section-one" class="btn btn-full">Why use AnyMath?</a> <a href="#section-two" class="btn btn-ghost">What problems can AnyMath solve?</a>

19062053 0
$("body")[0]; $("body").get(0); 

Those both should get the DOM object from jQuery.

4006096 0

I don't see you doing anything wrong. I can't test this, don't have the setup right now. Bounds is a bit tricky, there's a bunch of code behind it that ensures that the form can't be displayed off-screen. As an alternative, you could set the Location property instead and override OnLoad() in SnippingTool to set the WindowState property.

11919033 0 Why do I need to call removeView() in order to add a View to my LinearLayout

I am getting this error but I am not sure exactly why:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 

The part where I add the View is the line that the error is pointing to. I am providing my Adapter code in order for you guys to get a better picture of what I am doing and why I am getting this error. Please let me know if anymore info is needed. Thanks in advance.

Adapter

private class InnerAdapter extends BaseAdapter{ String[] array = new String[] {"12\nAM","1\nAM", "2\nAM", "3\nAM", "4\nAM", "5\nAM", "6\nAM", "7\nAM", "8\nAM", "9\nAM", "10\nAM", "11\nAM", "12\nPM", "1\nPM", "2\nPM", "3\nPM", "4\nPM", "5\nPM", "6\nPM", "7\nPM", "8\nPM", "9\nPM", "10\nPM", "11\nPM"}; TextView[] views = new TextView[24]; public InnerAdapter() { TextView create = new TextView(DayViewActivity.this); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 62, getResources().getDisplayMetrics()), 1.0f); params.topMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()); params.bottomMargin = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics()); create.setLayoutParams(params); create.setBackgroundColor(Color.BLUE); create.setText("Test"); views[0] = create; for(int i = 1; i < views.length; i++) { views[i] = null; } } @Override public int getCount() { // TODO Auto-generated method stub return array.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); convertView = inflater.inflate(R.layout.day_view_item, parent, false); } ((TextView)convertView.findViewById(R.id.day_hour_side)).setText(array[position]); LinearLayout layout = (LinearLayout)convertView.findViewById(R.id.day_event_layout); if(views[position] != null) { layout.addView((TextView)views[position], position); } return convertView; } } 

XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="61dp" android:orientation="horizontal" > <LinearLayout android:layout_width="wrap_content" android:layout_height="61dp" android:orientation="vertical"> <TextView android:id="@+id/day_hour_side" android:layout_width="wrap_content" android:layout_height="60dp" android:text="12AM" android:background="#bebebe" android:layout_weight="0" android:textSize="10dp" android:paddingLeft="5dp" android:paddingRight="5dp"/> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:layout_weight="0" android:background="#000000" android:id="@+id/hour_side_divider"/> </LinearLayout> <LinearLayout android:layout_width="0dp" android:layout_height="61dp" android:orientation="vertical" android:layout_weight="1"> <LinearLayout android:id="@+id/day_event_layout" android:layout_width="match_parent" android:layout_height="60dp" android:orientation="horizontal" ></LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="1dp" android:background="#000000" android:id="@+id/event_side_divider" /> </LinearLayout> </LinearLayout> 
26688384 0

It seems to be related to a sort of "IE9 z-index" bug. I found this: http://icreatestuff.co.uk/blog/article/ie9-z-index-stacking-problem-or-something-stranger

and added a transparent 1x1 "fixer.png" to the navbar. Now it works immediately in IE9 without resizing. Glad, that I am using Firefox most of the times. :-)

32053903 0 Rule in firewall for vmware

Should there be some sort of rule in the firewall that lets your vmware host server get out to the internet?

I have changed IP addressees, dns entries and still having an issue.

1568058 1 Django: How do I make fields non-editable by default in an inline model formset?

I have an inline model formset, and I'd like to make fields non-editable if those fields already have values when the page is loaded. If the user clicks an "Edit" button on that row, it would become editable and (using JavaScript) I would replace the original widgets with editable ones. I'd like to do something like this when loading the page:

for field in form.fields: if field.value: # display as text else: # display as my standard editable widget for this field 

I see that inlineformset_factory has an argument called formfield_callback. I suspect that this could be useful, but so for I haven't found any documentation for it. Can anyone point me to some useful documentation for this, and how it can help me solve this problem?

12459293 0

You increment it up to three times in the loop, before comparing against the end.

You erase without saving the new iterator.

Lots of side-effects.

The ordering of if(*it == *(--it)) { isn't defined, so you might end up comparing an element against itself. (== isn't a sequence point, so *it and *(--it) can be evaluated in either order).

You don't check for tableAndHand being empty - you increment it before checking.

32423201 0 undeclared variable in php why through error?

As described in php manual

It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to FALSE, integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array

if so then why its through error (notice) when try to access uninitialized variable? like

echo $x; 

its return even in script following message

Notice: Undefined variable: x...

But When I declare $x as NULL then its not through any notice or error and working nicely

$x = NULL; echo $x; 

Now My Question is Why its through notice if not declare like $x = NULL or $x = '' although undeclared variable initialized as NULL which is clearly mentioned in Manual??

I have a script and many uninitialized variable there and experiencing this issue.

11689684 0

If the code appears again, then the attacker left some script, which, on request, runs the infecting procedure. Usually this script receives an encoded string of the malcode (e.g. in base64), decodes it and executes via eval(). You should find this file (it is most likely a PHP script) and remove it. To find it look at the log and search for suspicious requests (e.g. a single POST request, transmitting base64 string is a very suspicious one).

16954185 0 sling test case SERVER side

I was writing sling unit test case for server side , where my test bundle is run by getting hit into the junit servlet , from the client side using the following piece of code. My test needs a running FTP server for the purpose , which i want to get embed into this function , by using @before and cleaning the dump by @after or any other best possible ways , how to do this with the runnable test class which invokes a junit servlet.

@RunWith(SlingRemoteTestRunner.class) public class FTPImporterTest extends SlingTestBase implements SlingRemoteTestParameters, SlingTestsCountChecker { /** * */ public static final String TEST_SELECTOR = "com.my.proj.FTPImporterTesting.FTPImporterServerTest"; public static final int TESTS_AT_THIS_PATH = 3; /** * */ public int getExpectedNumberOfTests() { return TESTS_AT_THIS_PATH; } public String getJunitServletUrl() { return getServerBaseUrl() + "/system/sling/junit"; } public String getTestClassesSelector() { return TEST_SELECTOR; } public String getTestMethodSelector() { return null; } public void checkNumberOfTests(int i) { Assert.assertEquals(TESTS_AT_THIS_PATH, i); } } 
10779737 0

Hi i think you should like this I check to your code and some modify and created easily code to your navi and logo Please Checked'

Css

.header, .navi, ul, li, a, span{ margin:0; padding:0; } .header{ overflow:hidden; z-index:5; } .logo{ position:relative; z-index:1; height:188px; width:100%; } .navi{ position:absolute; left:40%; right:0; z-index:2; top:148px; list-style:none; } li{ float:left; background:url('http://soteriabrighton.co.uk/test2/nav/images/top.png') no-repeat 10% 0; margin-left:2%; } .navi a{ background:url('http://s16.postimage.org/yqxo6bq6p/navi_left.png') no-repeat left top; padding-left:9px; color:#000; margin-top:27px; text-decoration:none; font-size:22px; float:left; border-radius:5px 0 0 5px; } .navi a span{ background:url('http://s17.postimage.org/ukpot5zcb/navi_right.png') no-repeat right top; padding-right:9px; float:left; line-height:38px; border-radius:0 5px 5px 0; } .navi a:hover span, .navi a:hover{ background:green; color:#fff; border-radius:5px; } 

HTML

<div class="header"> <img src="http://soteriabrighton.co.uk/test2/logo.png" alt="" class="logo" /> <ul class="navi"> <li><a href="#"><span>home</span></a></li> <li><a href="#"><span>news</span></a></li> <li><a href="#"><span>forums</span></a></li> <li><a href="#"><span>articles</span></a></li> <li><a href="#"><span>contact</span></a></li> </ul> </div> 

Live demo here http://jsfiddle.net/Kj2e9/

30412074 0 Clickable links in android using eclipse

I am trying to make strings in the text view clickable.My textview consists of name of various online questions and i want them to redirect the user to the url of the question when clicked.Can anyone recommend changes to my code.

In the following code "result" is the final textview consisting of name of questions .

public class Http extends Activity { TextView httpStuff; HttpClient client; JSONObject json; final static String URL = "http://codeforces.com/api/user.status?handle="; String m = ""; public static String[] sarr = new String[200]; public static String[] name = new String[200]; public static int cnt = 0; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.httpex); httpStuff = (TextView)findViewById(R.id.tvHttp); client = new DefaultHttpClient(); new Read().execute("result"); } public JSONObject lastSub(String username) throws ClientProtocolException, IOException, JSONException { StringBuilder url = new StringBuilder(URL); url.append(username); HttpGet get = new HttpGet(url.toString()); int status = 0; HttpResponse r = client.execute(get); status = r.getStatusLine().getStatusCode(); if(status == 200) { HttpEntity e = r.getEntity(); String data = EntityUtils.toString(e); JSONObject last = new JSONObject(data); //JSONObject last = new JSONObject(data).getJSONArray("result").getJSONObject(0).getJSONObject("problem"); return last; } else { Toast.makeText(Http.this, "error", Toast.LENGTH_SHORT); return null; } } public class Read extends AsyncTask <String, Integer, String> { @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub try { String add = "&from=1&count=100"; String input = (Mainapp.p); input = input.concat(add); json = lastSub(input); JSONArray array = json.getJSONArray("result"); String m1=null, m2=null, m3=null; String n1 = System.getProperty("line.separator"); int flag=0; for(int k=0; k<array.length() && cnt<15; k++) { JSONObject json1 = array.getJSONObject(k).getJSONObject("problem"); JSONObject v = array.getJSONObject(k); if(v.getString("verdict").contentEquals("OK")) { m1 = json1.getString("name"); m2= json1.getString("contestId"); m2= m2.concat("/"); m3= json1.getString("index"); m2 = m2.concat(m3); flag = 0; for(int i=0; i<cnt ; i++) { if (sarr[i].equals(m1)) { flag = 1; } } if(flag == 0) { m = m.concat(m1); m= m.concat(n1); sarr[cnt] = m1; name[cnt] = m2; cnt++; } } } return m; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } return "INVALID USER NAME"; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); httpStuff.setText(result); } } } } 
2698695 0

As noted, K is the loop's label. It allows you to identify a particular loop to aid readability, and also to selectively exit a specific loop from a set of nested enclosing ones (i.e. being a "goto"...shhh! :-)

Here's a contrived example (not compiled checked):

 S : Unbounded_String; F : File_Type; Done_With_Line : Boolean := False; All_Done : Boolean := False; begin Open(F, In_File, "data_file.dat"); File_Processor: while not End_Of_File(F) loop S := Get_Line(F); Data_Processor: for I in 1 .. Length(S) loop Process_A_Character (Data_Char => Element(S, I), -- Mode in Line_Done => Done_With_Line, -- Mode out Finished => All_Done); -- Mode out -- If completely done, leave the outermost (file processing) loop exit File_Processor when All_Done; -- If just done with this line of data, go on to the next one. exit Data_Processor when Done_With_Line; end loop; end loop File_Processor; Close(F); end; 
28910929 0

You have several problems

  1. You don't check if the file opened.

    • After fopen() you must ensure that you can read from the file, if fopen() fails, it returns NULL so a simple

      if (file == NULL) return -1; 

    would prevent problems in the rest of the program.

  2. Your while loop only contains one statement because it lacks braces.

    • Without the braces your while loop is equivalent to

      while (fgets(buf, sizeof(buf), file)) { ptr = strtok(buf, "f"); } 
  3. You don't check that strtok() returned a non NULL value.

    • If the token is not found in the string, strtok() returns NULL, and you passed the returned pointers to atol anyway.

      That would cause undefined behavior, and perhaps a segementation fault.

  4. You don't check if there was an argument passed to the program but you still try to compare it to a string. Also potential undefined behavior.

I don't know if the following program will do what you need since it's your own program, I just made it safer, avoided undefined behavior

#include <ncurses.h> #include <stdlib.h> #include <string.h> #include <stdio.h> int main(int argc, char * argv[]) { char buf[100]; char *ptr; char *ptr2; char *ptr3; char *ptr4; int a; int b; int c; int d; FILE *file; initscr(); cbreak(); noecho(); if (argc > 1) { file = fopen(argv[1], "r"); if (file == NULL) return -1; while (fgets(buf,100,file) != NULL) { ptr = strtok(str,"f"); ptr2 = strtok(NULL," "); ptr3 = strtok(NULL,"f"); ptr4 = strtok(NULL," "); if (ptr != NULL) a = atoi(ptr); if (ptr2 != NULL) b = atoi(ptr2); if (ptr3 != NULL) c = atoi(ptr3); if (ptr4 != NULL) d = atoi(ptr4); } } refresh(); getchar(); endwin(); return 0; } 
18801430 0

Create the class TasksController below in file: app\Controller\TasksController.php

You have called your file tasks_controller.php. Read the error carefully ;-)

The naming convention for controller files was updated in cakephp 2.0. Looks like you are using the old 1.x conventions

39916656 0

Try; /wd:Repository_Document_Reference/wd:ID[contains(@wd:type,"Document_ID")]

25324051 0

One problem is that totalwtax is not being calculated correctly because any items that are zero rated for tax are not included in the total. Changing the else clause to this:

 else { double newprice = Double.parseDouble(price); totalwtax +=newprice; shoppingcart.put(item, price); } 

Produces this output for your test case:

Please enter an item.standard Please enter the price for standard: 12.49 Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.y Please enter an item.music Please enter the price for music: 14.99 Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.y Please enter an item.discount Please enter the price for discount: 0.85 Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.n Your cart contains the following at items with tax{music=16.489, standard=12.49, discount=0.85} Total Tax: 29.829 

This still isn't exactly the same as the expected answer because the expected answer assumes some rounding in the calculation. You would either need to round the values yourself or it might be appropriate to use a Money class so that all the fractions of cents are correctly accounted for.

370459 0 How can I copy files with ASP.Net using Vista and IIS7?

I have a button on a website that creates a directory and copys a file. I developed it using Visual Studio 2008, ASP.Net 3.5. I am running Vista as my OS. The website uses identiy impersonation.

The functionality doesn't work ("Access to Path XYZ is denied") when:

The functionality works fine when [note Visual Studio run with Admin rights]:

I've never seen this behavior before, previously File.Copy type commands only cared that the rights on the folder being copied to were valid etc... (I have Everyone having full control while trying to debug this situation). It seems likely that the issue is having Admin rights or not? Or being logged in to the machine that it is running on?

What is happening here? Why does it work in the development environment and deployed to another machine, but not work when deployed on my own machine? Seems very odd, any help would be appreciated.

EDIT: I've added "Everyone" to all of the relvant directories and give that user Full Control, so there shouldn't be any permission issues?

13554773 0

It is a good way, but. You should not use just except clause, you have to specify the type of the exception you are trying to catch. Also you can catch an error and continue the loop.

def scrape_all_pages(alphabet): try: pages = get_all_urls(alphabet) except IndexError: #IndexError is an example ## LOG THE ERROR IF THAT FAILS. for page in pages: try: scrape_table(page) except IndexError: # IndexError is an example ## LOG THE ERROR IF THAT FAILS and continue this loop 
20276863 0

The solution that uses Set will probably be more readable, and easier to maintain - for example you avoid a whole class of problems when you modify your code like "what happens if I put a false value in the map - will it break my code?".

As a side note, Java's HashSet is quite inefficient memory-wise and actually uses a HashMap under the covers. Still, in most cases it is code readability and maintainability that matters most and not implementation details like this.

3904944 0 fastest way to persist changes

in my web app the database has a blob(an xml file). The user is allowed to change the blob through a web interface. I take the blob show it in a html form, then the user can change some values and save it back. So the user submit request has a db save. Can I save the entry to a cache to speed up the submit request? But then there is a chance of loosing the changes? What is the fastest way to persist the blob in db?

33124843 0 Trouble mounting a folder from host onto my docker image

I am trying to mount a folder from my host system to a docker container. I am aware of the -v attribute of docker commands.

My command is:

docker run -v /home/ubuntu/tools/files/:/root/report -i -t --entrypoint /bin/bash my_image -s 

But this does not seem to work, no files appear at my designated container folder. This is very frustrating as I will need to add files to my docker image at periodic intervals so just adding them to the build file at creation wont cut it.

12871836 0 How to get return value from a function called which executes in another thread in TBB?

In the code:

 #include <tbb/tbb.h> int GetSomething() { int something; // do something return something; } // ... tbb::tbb_thread(GetSomething, NULL); // ... 

Here GetSomething() was called in another thread via its pointer. But can we get return value from GetSomething()? How?

20048184 0 TCPDF remove