Monthly Archives

Articles indexed in November 2013

Page 8/211 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Django model operating on a queryset

    - by jmoz
    I'm new to Django and somewhat to Python as well. I'm trying to find the idiomatic way to loop over a queryset and set a variable on each model. Basically my model depends on a value from an api, and a model method must multiply one of it's attribs by this api value to get an up-to-date correct value. At the moment I am doing it in the view and it works, but I'm not sure it's the correct way to achieve what I want. I have to replicate this looping elsewhere. Is there a way I can encapsulate the looping logic into a queryset method so it can be used in multiple places? I have this atm (I am using django-rest-framework): class FooViewSet(viewsets.ModelViewSet): model = Foo serializer_class = FooSerializer bar = # some call to an api def get_queryset(self): # Dynamically set the bar variable on each instance! foos = Foo.objects.filter(baz__pk=1).order_by('date') for item in foos: item.needs_bar = self.bar return items I would think something like so would be better: def get_queryset(self): bar = # some call to an api # Dynamically set the bar variable on each instance! return Foo.objects.filter(baz__pk=1).order_by('date').set_bar(bar) I'm thinking the api hit should be in the controller and then injected to instances of the model, but I'm not sure how you do this. I've been looking around querysets and managers but still can't figure it out nor decided if it's the best method to achieve what I want. Can anyone suggest the correct way to model this with django? Thanks.

    Read the article

  • How to embed a precharged collection of non-entity forms in symfony2

    - by metalvarez
    I want to embed a collection of precharged non-entity forms, here is the code, first is the parent form buildForm method. public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add("example1")->add("example2"); $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { /*some logic to do before adding the collection of forms*/ $form->add('aclAccess', 'collection', array( 'type' => new ChildFormType(), 'allow_add' => true, 'mapped' => false, 'data' => /* I dont know how to precharge a collection of non-entity forms*/ )); }); } now the child form public function buildForm (FormBuilderInterface $builder, array $options) { $builder->add("test1", "text", array("read_only" => true, "data" => "test")); $builder->->add("test2", "choice", array( 'choices' => array('opt1' => 'Opt1', 'opt2' => 'Opt2'), 'multiple' => true, 'expanded' => true )); } so basicly i want to manage those child options in the test2 field as separated forms, each option group will depend on the value of the test1 field, i know this can be done by coding everythin in twig without form classes but i think having form classes its the best practice to run phpunit test, for maintainability, etc ...

    Read the article

  • How to build Android for Samsung Galaxy Note

    - by Tr?n Ð?i
    I'd like to modify and build my own Android for my Samsung Galaxy Note I've downloaded Android 4.1.2 from http://source.android.com and Samsung open source for my Samsung Galaxy Note. After extract Samsung open source, I get 2 folders: Kernel and Platform, and 2 README text file README_Kernel.txt 1. How to Build - get Toolchain From android git server , codesourcery and etc .. - arm-eabi-4.6 - edit build_kernel.sh edit "CROSS_COMPILE" to right toolchain path(You downloaded). EX) CROSS_COMPILE= $(android platform directory you download)/android/prebuilts/gcc/linux-x86/arm/arm-eabi-4.6/bin/arm-eabi- Ex) CROSS_COMPILE=/usr/local/toolchain/arm-eabi-4.6/bin/arm-eabi- // check the location of toolchain - execute Kernel script $ ./build_kernel.sh 2. Output files - Kernel : arch/arm/boot/zImage - module : drivers/*/*.ko 3. How to Clean $ make clean README_Platform.txt [Step to build] 1. Get android open source. : version info - Android 4.1 ( Download site : http://source.android.com ) 2. Copy module that you want to build - to original android open source If same module exist in android open source, you should replace it. (no overwrite) # It is possible to build all modules at once. 3. You should add module name to 'PRODUCT_PACKAGES' in 'build\target\product\core.mk' as following case. case 1) bluetooth : should add 'audio.a2dp.default' to PRODUCT_PACKAGES case 2) e2fsprog : should add 'e2fsck' to PRODUCT_PACKAGES case 3) libexifa : should add 'libexifa' to PRODUCT_PACKAGES case 4) libjpega : should add 'libjpega' to PRODUCT_PACKAGES case 5) KeyUtils : should add 'libkeyutils' to PRODUCT_PACKAGES case 6) bluetoothtest\bcm_dut : should add 'bcm_dut' to PRODUCT_PACKAGES ex.) [build\target\product\core.mk] - add all module name for case 1 ~ 6 at once PRODUCT_PACKAGES += \ e2fsck \ libexifa \ libjpega \ libkeyutils \ bcm_dut \ audio.a2dp.default 4. In case of 'bluetooth', you should add following text in 'build\target\board\generic\BoardConfig.mk' BOARD_HAVE_BLUETOOTH := true BOARD_HAVE_BLUETOOTH_BCM := true 5. excute build command ./build.sh user What I need to do after followed 2 above files

    Read the article

  • String loops in Python

    - by Steve Hunter
    I have two pools of strings and I would like to do a loop over both. For example, if I want to put two labeled apples in one plate I'll write: basket1 = ['apple#1', 'apple#2', 'apple#3', 'apple#4'] for fruit1 in basket1: basket2 = ['apple#1', 'apple#2', 'apple#3', 'apple#4'] for fruit2 in basket2: if fruit1 == fruit2: print 'Oops!' else: print "New Plate = %s and %s" % (fruit1, fruit2) However, I don't want order to matter -- for example I am considering apple#1-apple#2 equivalent to apple#2-apple#1. What's the easiest way to code this? I'm thinking about making a counter in the second loop to track the second basket and not starting from the point-zero in the second loop every time.

    Read the article

  • Is this OleDbDataAdapter bug

    - by ????
    It doesn't look to me OleDbDataAdapter should throw an exception on trying to fill DataSet for a db table column of type decimal(28,3). The message is "The numerical value is too large to fit into a 96 bit decimal". Could you just check this, I have no significant experience with ADO.NET and OLE DB components? The VB.NET code we have in the application is this: Dim dbDataSet As New DataSet Dim dbDataAdapter As OleDbDataAdapter Dim dbCommand As OleDbCommand Dim conn As OleDbConnection Dim connectionString As String 'parts where connectionString is set conn = New OleDbConnection(connectionString) 'part where sqlQuery is set but it ends up being "SELECT Price As 'Price' From PricebookView" - Price is of type decimal(28,3) dbCommand = New OleDbCommand(sqlQuery, conn) dbCommand.CommandTimeout = cmdTimeout dbDataAdapter = New OleDbDataAdapter(dbCommand) dbDataAdapter.Fill(dbDataSet) The last line is where the exception is thrown and the top of the stack trace is: at System.Data.ProviderBase.DbBuffer.ReadNumeric(Int32 offset) at System.Data.OleDb.ColumnBinding.Value_NUMERIC() at System.Data.OleDb.ColumnBinding.Value() at System.Data.OleDb.OleDbDataReader.GetValues(Object[] values) at System.Data.ProviderBase.DataReaderContainer.CommonLanguageSubsetDataReader.GetValues(Object[] values) at System.Data.ProviderBase.SchemaMapping.LoadDataRow() at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping) at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue) at System.Data.Common.DataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords) at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) ... I am not sure why does it try to set the value to Int32. Thank you for the time !

    Read the article

  • Python built-in id() not consistent:

    - by Dannellyz
    Hoping someone can explain the following discrepancy: >>> s1 = "Cyber security" >>> s2 = "Cyber security" >>> id(s1) == id(s1) True >>> id(s1) == id(s2) False >>> s1 = "cyber" >>> s2 = "cyber" >>> id(s1) == id(s2) True >>> s2 = "cyber " >>> s2 = "cyber " >>> id(s1) == id(s2) False Why does the space make the id() False, yet different variables with no spaces are True?

    Read the article

  • How do I make a SignalR client something when it receives a message?

    - by Ben
    I want to do something when a client receives a message via a SignalR hub. I've put together a basic chat app, but want people to be able to "like" a chat comment. I'm thinking the way to do this is to find the chat message on the client's page and update it using javascript. In the meantime to "prove the concept" I just want to make an alert popup on the client machine to say another user likes the comment. Trouble is, I'm not sure where to put it. (Am struggling to find SignalR documentation to be honest.) can't get my head round what is calling what here. My ChatHub class is as follows: public class ChatHub : Hub { public void Send(string name, string message) { // Call the broadcastMessage method to update clients. Clients.All.broadcastMessage(name, message); } } And my JavaScript is: $(function () { // Declare a proxy to reference the hub. var chat = $.connection.chatHub; // Create a function that the hub can call to broadcast messages. chat.client.broadcastMessage = function (name, message) { // Html encode display name and message. var encodedName = $('<div />').text(name).html(); var encodedMsg = $('<div />').text(message).html(); // Add the message to the page. var divContent = $('#discussion').html(); $('#discussion').html('<div class="container">' + '<div class="content">' + '<p class="username">' + encodedName + '</p>' + '<p class="message">' + encodedMsg + '</p>' + '</div>' + '<div class="slideout">' + '<div class="clickme" onclick="slideMenu(this)"></div>' + '<div class="slidebutton"><img id="imgid" onclick="likeButtonClick(this)" src="Images/like.png" /></div>' + '<div class="slidebutton"><img onclick="commentButtonClick(this)" src="Images/comment.png" /></div>' + '<div class="slidebutton" style="margin-right:0px"><img onclick="redcardButtonClick(this)" src="Images/redcard.png" /></div>' + '</div>' + '</div>' + divContent); }; // Set initial focus to message input box. $('#message').focus(); // Start the connection. $.connection.hub.start().done(function () { $('#sendmessage').click(function () { // Call the Send method on the hub. chat.server.send($('#lblUser').html(), $('#message').val()); // Clear text box and reset focus for next comment. $('#message').val('').focus(); }); });

    Read the article

  • Image re sizing not working after rotation in Html5 canvas

    - by Deepu the Don
    In my HTML 5 + Javascript application, we can drag, re size and rotate image in Html 5 canvas. But after doing rotation, re sizing is not working. (I think it i related to finding dx,dy,not sure). Please help me to fix the code given below. Thanks in advance. <!doctype html> <html> <head> <style> #canvas{ border:red dashed #ccc; } </style> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script> $(function(){ var canvas=document.getElementById("canvas"),ctx=canvas.getContext("2d"),canvasOffset=$("#canvas").offset(); var offsetX=canvasOffset.left,offsetY=canvasOffset.top,startX,startY,isDown=false,pi2=Math.PI*2; var resizerRadius=8,rr=resizerRadius*resizerRadius,draggingResizer={x:0,y:0},imageX=50,imageY=50; var imageWidth,imageHeight,imageRight,imageBottom,draggingImage=false,startX,startY,doRotation=false; var r=0,rotImg = new Image(); rotImg.src="rotation.jpg"; var img=new Image(); img.onload=function(){ imageWidth=img.width; imageHeight=img.height; imageRight=imageX+imageWidth; imageBottom=imageY+imageHeight; w=img.width/2; h=img.height/2; draw(true,false); } img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/facesSmall.png"; function draw(withAnchors,withBorders){ ctx.fillStyle="black"; ctx.clearRect(0,0,canvas.width,canvas.height); ctx.save(); ctx.translate(imageX,imageY); ctx.translate(imageWidth/2,imageHeight/2); ctx.rotate(r); ctx.translate(-imageX,-imageY); ctx.translate(-imageWidth/2,-imageHeight/2); ctx.drawImage(img,0,0,img.width,img.height,imageX,imageY,imageWidth,imageHeight); ctx.restore(); if(withAnchors){ drawDragAnchor(imageX,imageY); drawDragAnchor(imageRight,imageY); drawDragAnchor(imageRight,imageBottom); drawDragAnchor(imageX,imageBottom); } if(withBorders){ ctx.save(); ctx.translate(imageX,imageY); ctx.translate(imageWidth/2,imageHeight/2); ctx.rotate(r); ctx.translate(-imageX,-imageY); ctx.translate(-imageWidth/2,-imageHeight/2); ctx.beginPath(); ctx.moveTo(imageX,imageY); ctx.lineTo(imageRight,imageY); ctx.lineTo(imageRight,imageBottom); ctx.lineTo(imageX,imageBottom); ctx.closePath(); ctx.stroke(); ctx.restore(); } ctx.fillStyle="blue"; ctx.save(); ctx.translate(imageX,imageY); ctx.translate(imageWidth/2,imageHeight/2); ctx.rotate(r); ctx.translate(-imageX,-imageY); ctx.translate(-imageWidth/2,-imageHeight/2); ctx.beginPath(); ctx.moveTo(imageRight+15,imageY-10); ctx.lineTo(imageRight+45,imageY-10); ctx.lineTo(imageRight+45,imageY+20); ctx.lineTo(imageRight+15,imageY+20); ctx.fill(); ctx.closePath(); ctx.restore(); } function drawDragAnchor(x,y){ ctx.save(); ctx.translate(imageX,imageY); ctx.translate(imageWidth/2,imageHeight/2); ctx.rotate(r); ctx.translate(-imageX,-imageY); ctx.translate(-imageWidth/2,-imageHeight/2); ctx.beginPath(); ctx.arc(x,y,resizerRadius,0,pi2,false); ctx.closePath(); ctx.fill(); ctx.restore(); } function anchorHitTest(x,y){ var dx,dy; dx=x-imageX; dy=y-imageY; if(dx*dx+dy*dy<=rr){ return(0); } // top-right dx=x-imageRight; dy=y-imageY; if(dx*dx+dy*dy<=rr){ return(1); } // bottom-right dx=x-imageRight; dy=y-imageBottom; if(dx*dx+dy*dy<=rr){ return(2); } // bottom-left dx=x-imageX; dy=y-imageBottom; if(dx*dx+dy*dy<=rr){ return(3); } return(-1); } function hitImage(x,y){ return(x>imageX && x<imageX+imageWidth && y>imageY && y<imageY+imageHeight); } function handleMouseDown(e){ startX=parseInt(e.clientX-offsetX); startY=parseInt(e.clientY-offsetY); draggingResizer= anchorHitTest(startX,startY); draggingImage= draggingResizer<0 && hitImage(startX,startY); doRotation = draggingResizer<0 && !draggingImage && ctx.isPointInPath(startX,startY); } function handleMouseUp(e){ draggingResizer=-1; draggingImage=false; doRotation=false; draw(true,false); } function handleMouseOut(e){ handleMouseUp(e); } function handleMouseMove(e){ mouseX=parseInt(e.clientX-offsetX); mouseY=parseInt(e.clientY-offsetY); if(draggingResizer>-1){ switch(draggingResizer){ case 0: //top-left imageX=mouseX; imageWidth=imageRight-mouseX; imageY=mouseY; imageHeight=imageBottom-mouseY; break; case 1: //top-right imageY=mouseY; imageWidth=mouseX-imageX; imageHeight=imageBottom-mouseY; break; case 2: //bottom-right imageWidth=mouseX-imageX; imageHeight=mouseY-imageY; break; case 3: //bottom-left imageX=mouseX; imageWidth=imageRight-mouseX; imageHeight=mouseY-imageY; break; } if(imageWidth<25) imageWidth=25; if(imageHeight<25) imageHeight=25; imageRight=imageX+imageWidth; imageBottom=imageY+imageHeight; draw(true,true); }else if(draggingImage){ imageClick=false; var dx=mouseX-startX; var dy=mouseY-startY; imageX+=dx; imageY+=dy; imageRight+=dx; imageBottom+=dy; startX=mouseX; startY=mouseY; draw(false,true); }else if(doRotation){ var dx=mouseX-imageX; var dy=mouseY-imageY; r=Math.atan2(dy,dx); draw(false,true); } } $("#canvas").mousedown(function(e){handleMouseDown(e);}); $("#canvas").mousemove(function(e){handleMouseMove(e);}); $("#canvas").mouseup(function(e){handleMouseUp(e);}); $("#canvas").mouseout(function(e){handleMouseOut(e);}); }); </script> </head> <body> <canvas id="canvas" width=800 height=500></canvas> </body> </html>

    Read the article

  • Parsing a complicated HTML table with PHP

    - by user2944979
    I successfully parsed a dynamic table with the following PHP code: $docH = new DOMDocument(); $docH->loadHTMLFile($url); //get everything inside the body element: $bodyH = $docH->getElementsByTagName('body')->item(0); foreach ($bodyH->childNodes as $childNode) { echo $docH->saveHTML($childNode); } Parsed HTML Table: <table> <tr> <td>5CG </td> <td>aass </td> <td>sxs </td> <td>sx </td> <td>EK </td> <td> </td> <td>72 </td> </tr> <td> </td> <td>samplxs </td> <td>xs </td> <td> </td> <td>xss </td> <td>fkxsx aus</td> <td>s </td> </tr> <td> </td> <td>5AH. </td> <td>ds </td> <td>d </td> <td>sdf </td> <td>sdfsdf aus</td> <td> </td> </tr> <tr> <td>6CG </td> <td>3. </td> <td>sfd </td> <td> </td> <td>scs </td> <td>das aus</td> <td>a </td> </tr> <tr> <td>7DG </td> <td>6. </td> <td>s </td> <td>s </td> <td>sD </td> <td>sdsa.</td> <td> </td> </tr> <td> </td> <td>samplxs </td> <td>xs </td> <td> </td> <td>xss </td> <td>fkxsx aus</td> <td>s </td> </tr> <tr> <td>7DG, 7CG, 7CR </td> <td>6. </td> <td>NsdR </td> <td>s </td> <td>SP </td> <td>fasdlt aus</td> <td>s </td> </tr> <td> </td> <td>samplxs </td> <td>xs </td> <td> </td> <td>xss </td> <td>fkxsx aus</td> <td>s </td> </tr> <tr> <td> 9BR </td> <td>6. </td> <td>FEI </td> <td>sa </td> <td>DE </td> <td>fasdad aus</td> <td> </td> </tr> <tr> <td>9AR, 9BR, 9CR</td> <td>62. </td> <td>BEH </td> <td> </td> <td>sd </td> <td>fasda aus</td> <td> </td> </tr> <tr> <td> </td> <td>6. </td> <td>MLR </td> <td> </td> <td>FdR </td> <td>fsdfaus</td> <td> </td> </tr> <tr> <td>E10C </td> <td>6. </td> <td>sdf </td> <td>d </td> <td>d </td> <td>fsdfs aus</td> <td> </td> </tr> <tr> </table> But my goal is to just show the content of the table the user wants by asking for just the <tr> elements in which the first <td> of the first <tr> includes some text until there is another <tr> which first <td> has a different content. For example: If the user types "9BR" into an input field, I just want him to see: <td> 9BR </td> <td>6. </td> <td>FEI </td> <td>sa </td> <td>DE </td> <td>fasdad aus</td> <td> </td> </tr> <tr> <td>9AR, 9BR, 9CR</td> <td>62. </td> <td>BEH </td> <td> </td> <td>sd </td> <td>fasda aus</td> <td> </td> </tr> <tr> <td> </td> <td>6. </td> <td>MLR </td> <td> </td> <td>FdR </td> <td>fsdfaus</td> <td> </td> </tr> If he types in 5CG: <tr> <td>5CG </td> <td>aass </td> <td>sxs </td> <td>sx </td> <td>EK </td> <td> </td> <td>72 </td> </tr> <td> </td> <td>samplxs </td> <td>xs </td> <td> </td> <td>xss </td> <td>fkxsx aus</td> <td>s </td> </tr> Or if 6CG just: <tr> <td>6CG </td> <td>3. </td> <td>sfd </td> <td> </td> <td>scs </td> <td>das aus</td> <td>a </td> </tr>

    Read the article

  • client-side validation in custom validation attribute - asp.net mvc 4

    - by Giorgos Manoltzas
    I have followed some articles and tutorials over the internet in order to create a custom validation attribute that also supports client-side validation in an asp.net mvc 4 website. This is what i have until now: RequiredIfAttribute.cs [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] //Added public class RequiredIfAttribute : ValidationAttribute, IClientValidatable { private readonly string condition; private string propertyName; //Added public RequiredIfAttribute(string condition) { this.condition = condition; this.propertyName = propertyName; //Added } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { PropertyInfo propertyInfo = validationContext.ObjectType.GetProperty(this.propertyName); //Added Delegate conditionFunction = CreateExpression(validationContext.ObjectType, _condition); bool conditionMet = (bool)conditionFunction.DynamicInvoke(validationContext.ObjectInstance); if (conditionMet) { if (value == null) { return new ValidationResult(FormatErrorMessage(null)); } } return ValidationResult.Success; } private Delegate CreateExpression(Type objectType, string expression) { LambdaExpression lambdaExpression = System.Linq.Dynamic.DynamicExpression.ParseLambda(objectType, typeof(bool), expression); //Added Delegate function = lambdaExpression.Compile(); return function; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var modelClientValidationRule = new ModelClientValidationRule { ValidationType = "requiredif", ErrorMessage = ErrorMessage //Added }; modelClientValidationRule.ValidationParameters.Add("param", this.propertyName); //Added return new List<ModelClientValidationRule> { modelClientValidationRule }; } } Then i applied this attribute in a property of a class like this [RequiredIf("InAppPurchase == true", "InAppPurchase", ErrorMessage = "Please enter an in app purchase promotional price")] //Added "InAppPurchase" public string InAppPurchasePromotionalPrice { get; set; } public bool InAppPurchase { get; set; } So what i want to do is display an error message that field InAppPurchasePromotionalPrice is required when InAppPurchase field is true (that means checked in the form). The following is the relevant code form the view: <div class="control-group"> <label class="control-label" for="InAppPurchase">Does your app include In App Purchase?</label> <div class="controls"> @Html.CheckBoxFor(o => o.InAppPurchase) @Html.LabelFor(o => o.InAppPurchase, "Yes") </div> </div> <div class="control-group" id="InAppPurchasePromotionalPriceDiv" @(Model.InAppPurchase == true ? Html.Raw("style='display: block;'") : Html.Raw("style='display: none;'"))> <label class="control-label" for="InAppPurchasePromotionalPrice">App Friday Promotional Price for In App Purchase: </label> <div class="controls"> @Html.TextBoxFor(o => o.InAppPurchasePromotionalPrice, new { title = "This should be at the lowest price tier of free or $.99, just for your App Friday date." }) <span class="help-inline"> @Html.ValidationMessageFor(o => o.InAppPurchasePromotionalPrice) </span> </div> </div> This code works perfectly but when i submit the form a full post is requested on the server in order to display the message. So i created JavaScript code to enable client-side validation: requiredif.js (function ($) { $.validator.addMethod('requiredif', function (value, element, params) { /*var inAppPurchase = $('#InAppPurchase').is(':checked'); if (inAppPurchase) { return true; } return false;*/ var isChecked = $(param).is(':checked'); if (isChecked) { return false; } return true; }, ''); $.validator.unobtrusive.adapters.add('requiredif', ['param'], function (options) { options.rules["requiredif"] = '#' + options.params.param; options.messages['requiredif'] = options.message; }); })(jQuery); This is the proposed way in msdn and tutorials i have found Of course i have also inserted the needed scripts in the form: jquery.unobtrusive-ajax.min.js jquery.validate.min.js jquery.validate.unobtrusive.min.js requiredif.js BUT...client side validation still does not work. So could you please help me find what am i missing? Thanks in advance.

    Read the article

  • Generic function to handle DataType Conversion

    - by Tommo1977
    I have the following function in C#, that I want to pass a MySQL DataReader value/object. If the value of the object passed is a DBNull I need to handle it and return a Null value of that data type e.g null int. Otherwise I want to convert the returned value like Convert.ToInt32(value) or similar. public static T ConvertFromDB<T>(object value) { return value == DBNull.Value ? default(T) : (T)value; } Can anyone offer any help on this ?

    Read the article

  • DocuSign Connect xsd [on hold]

    - by Brian
    I'm trying to parse xml inbound to our system from the DocuSign Connect service (which publishes status updates to a given web service). I typiclly use jaxb to process xml but as far as I know I need xsd's in order to generate the jaxb. I don't have (or can't find) xsd's from DocuSign in order to do this. I could use other java classes/libraries to parse the xml but without xsd's I'd have to guess at types, restrictions and formats. Is there a way to generate jaxb without having xsd's?

    Read the article

  • Removing elements from heap

    - by user193138
    I made a heap. I am curious if there's something subtley wrong with my remove function: int Heap::remove() { if (n == 0) exit(1); int temp = arr[0]; arr[0] = arr[--n]; heapDown(0); arr[n] = 0; return temp; } void Heap::heapDown(int i) { int l = left(i); int r = right(i); // comparing parent to left/right child // each has an inner if to handle if the first swap causes a second swap // ie 1 -> 3 -> 5 // 3 5 1 5 1 3 if (l < n && arr[i] < arr[l]) { swap(arr[i], arr[l]); heapDown(l); if (r < n && arr[i] < arr[r]) { swap(arr[i], arr[r]); heapDown(r); } } else if (r < n && arr[i] < arr[r]) { swap(arr[i], arr[r]); heapDown(r); if (l < n && arr[i] < arr[l]) { swap(arr[i], arr[l]); heapDown(l); } } } Here's my output i1i2i3i4i5i6i7 p Active heap: 7 4 6 1 3 2 5 r Removed 7 r Removed 6 p Active heap: 5 3 4 1 2 Here's my teacher's sample output: p Active heap : 7 4 6 1 3 2 5 r Removed 7 r Removed 6 p Active heap : 5 4 2 1 3 s Heapsorted : 1 2 3 4 5 While our outputs are completely different, I do seem to hold maxheap principle of having everything left oriented and for all nodes parent child(in every case I tried). I try to do algs like this from scratch, so maybe I'm just doing something really weird and wrong (I would only consider it "wrong" if it's O(lg n), as removes are intended to be for heaps). Is there anything in particular "wrong" about my remove? Thanks, http://ideone.com/PPh4eQ

    Read the article

  • C# Xamarin.IOS / MonoTouch - Toolbar Disappears

    - by Goober
    I have a Xamarin.IOS/Monotouch project with 2 views - MainView and View2. My MainView window has a navigationController at the top, and a toolbar at the bottom. When I call PushViewController(View2,true); - I get pushed from MainView to my second view (View2). View2 also has a navigationController at the top, but it DOES NOT have a toolbar at the bottom - intentionally. When I click the "Back" button on View2 to push back to my MainView, the toolbar at the bottom of MainView has disappeared. Any ideas on how to get around this? Much appreciated.

    Read the article

  • Card emulation via software NFC

    - by user85030
    After reading a lot of questions, i decided to post this one. I read that stock version of android does not support API's for card emulation. Also, we cannot write custom applications to secure element embedded in nfc controllers due to keys managed by google/samsung. I need to emulate a card (mifare or desfire etc). The option i can see is doing it via software. I have a ACR122U reader and i've tested that NFC P2P mode works fine with the Nexus-S that i have. 1) I came across a site that said that nexus s's NFC controller (pn532) can emulate a mifare 4k card. If this is true, can i write/read apdu commands to this emulated card? (Probably if i use a modded rom like cyanogenmod) 2) Can i write a android application that reads apdu commands sent from the reader and generate appropriate responses (if not fully, then upto some extent only). To do so, i searched that we need to patch nexus s with cynagenmod. Has someone tried emulating card via this method? I see that this is possible since we have products from access control companies offering mobile applications via which one can open doors e.g. http://www.assaabloy.com/en/com/Products/seos-mobile-access/

    Read the article

  • AVCam memory low warning

    - by Red Nightingale
    This is less a question and more a record of what I've found around the AVCam sample code provided by Apple for iOS4 and 5 camera manipulation. The symptoms of the problem for me were that my app would crash on launching the AVCamViewController after taking around 5-10 photos. I ran the app through the memory leak profiler and there were no apparent leaks but on inspection with the Activity Monitor I discovered that something called mediaserverd was increasing by 17Mb every time the camera was launched and when it reached ~100Mb the app crashed with multiple low memory warnings.

    Read the article

  • MySQL based authentication with crypt()ed password fails in Apache 2.2

    - by Fester Bestertester
    I'm trying to set up a simple CalDAV/CardDAV server with a Radicale backend and an Apache 2.2 frontend. So far, it's all nice and simple, but I can't get the MySQL based authentication to work. I'd like to authenticate users against an existing MySQL database, and I need the REMOTE_USER variable to be set (pretty much like in the configuration examples for Radicale). I've tried mod_auth_mysql, which authenticated the users nicely, but failed to set the REMOTE_USER variable. The newer alternative seems to be mod_authn_dbd, which doesn't seem to like the crypted passwords in the MySQL database. According to the documentation, crypted passwords should work, so maybe I'm just missing a simple parameter. The configuration looks like this: DBDriver mysql DBDParams "sock=/var/run/mysqld/mysqld.sock dbname=myAuthDB user=myAuthUser pass=myAuthPW <Directory /> AllowOverride None Order allow,deny allow from all AuthName 'CalDav' AuthType Basic AuthBasicProvider dbd require valid-user AuthDBDUserPWQuery "SELECT crypt FROM myAuthTable WHERE id=%s" </Directory> I've tested the query, it works fine. And as mentioned before, mod_auth_mysql worked nicely against the same database, but didn't set the required variables. Am I just missing some configuration parameter? Or is mod_authn_dbd just not the right tool to achieve what I want?

    Read the article

  • Website hosted on IIS is not accessbile

    - by Tola Odejayi
    I have two sites set up in IIS on a remote machine RM; one on regular port 80, and the other on port 5773. From my local machine LM, I can access the site on 80, but I cannot access the one on 5773; I get a status code of 502 and an error code of 10060 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond) when I try to do this. I can access the 5773 site via IIS when I am logged into RM (i.e. by right clicking on a page on the site and going 'Browse'). I can also access pages on the 5773 site via a browser, again when I am logged into RM. I just can't do the same via a browser when I am logged into LM. I have ensured that port 5773 is open for outgoing traffic on LM. Could the problem be that I also need to ensure that port 5773 is open for inbound traffic on RM?

    Read the article

  • Is there a bug with Apache 2.2 and content filters (and maybe mod_proxy)?

    - by asciiphil
    I'm running Apache 2.2.15-29 on RHEL 6 (actually Scientific Linux 6.4) and I'm trying to set up a reverse proxy with content rewriting so all of the links on the proxied web pages are rewritten to reference the proxy host. I'm running into a problem with some of the content rewriting and I'd like to know if this is a bug or if I'm doing something wrong (and how to do it right, if applicable). I'm proxying a subdirectory on an internal host (internal.example.com/foo) onto the root of an external host (external.example.com). I need to rewrite HTML, CSS, and Javascript content to fix all of the URLs. I'm also hosting some content locally on the external host, which I don't think is a problem but I'm mentioning here for completeness. My httpd.conf looks roughly like this: <VirtualHost *:80> ServerName external.example.com ServerAlias example.com # Serve all local content directly, reverse-proxy all unknown URIs. RewriteEngine On RewriteRule ^(/(index.html?)?)?$ http://internal.example.com/foo/ [P] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} -d RewriteRule ^.*$ - [L] RewriteRule ^/~ - [L] RewriteRule ^(.*)$ http://internal.example.com$1 [P] # Standard header rewriting. ProxyPassReverse / http://internal.example.com/foo/ ProxyPassReverseCookieDomain internal.example.com external.example.com ProxyPassReverseCookiePath /foo/ / # Strip any Accept-Encoding: headers from the client so we can process the pages # as plain text. RequestHeader unset Accept-Encoding # Use mod_proxy_html to fix URLs in text/html content. ProxyHTMLEnable On ProxyHTMLURLMap http://internal.example.com/foo/ / ProxyHTMLURLMap http://internal.example.com/foo / ProxyHTMLURLMap /foo/ / ## Use mod_substitute to fix URLs in CSS and Javascript #<Location /> # AddOutputFilterByType SUBSTITUTE text/css # AddOutputFilterByType SUBSTITUTE text/javascript # Substitute "s|http://internal.example.com/foo/|/|nq" #</Location> # Use mod_ext_filter to fix URLs in CSS and Javascript ExtFilterDefine fixurlcss mode=output intype=text/css cmd="/bin/sed -rf /etc/httpd/fixurls" ExtFilterDefine fixurljs mode=output intype=text/javascript cmd="/bin/sed -rf /etc/httpd/fixurls" <Location /> SetOutputFilter fixurlcss;fixurljs </Location> </VirtualHost> The text/html rewriting works just fine. When I use either mod_substitute or mod_ext_filter, the external server sends the pages as Transfer-Encoding: chunked, sends all of the data, and then closes the connection without sending the final, zero-length chunk. Some HTTP clients are unhappy with this. (Chrome won't process any content sent in this way, for example, so the pages don't get CSS applied to them.) Here's a sample wget session: $ wget -O /dev/null -S http://external.example.com/include/jquery.js --2013-11-01 11:36:36-- http://external.example.com/include/jquery.js Resolving external.example.com (external.example.com)... 192.168.0.1 Connecting to external.example.com (external.example.com)|192.168.0.1|:80... connected. HTTP request sent, awaiting response... HTTP/1.1 200 OK Date: Fri, 01 Nov 2013 15:36:36 GMT Server: Apache Last-Modified: Tue, 29 Oct 2013 13:09:10 GMT ETag: "1d60026-187b8-4e9e0ec273e35" Accept-Ranges: bytes Vary: Accept-Encoding X-UA-Compatible: IE=edge,chrome=1 Content-Type: text/javascript;charset=utf-8 Connection: close Transfer-Encoding: chunked Length: unspecified [text/javascript] Saving to: `/dev/null' [ <=> ] 100,280 --.-K/s in 0.005s 2013-11-01 11:36:37 (19.8 MB/s) - Read error at byte 100280 (Success).Retrying. --2013-11-01 11:36:38-- (try: 2) http://external.example.com/include/jquery.js Connecting to external.example.com (external.example.com)|192.168.0.1|:80... connected. HTTP request sent, awaiting response... HTTP/1.1 416 Requested Range Not Satisfiable Date: Fri, 01 Nov 2013 15:36:38 GMT Server: Apache Vary: Accept-Encoding Content-Type: text/html;charset=utf-8 Content-Length: 260 Connection: close The file is already fully retrieved; nothing to do. Am I doing something wrong? Am I hitting some sort of Apache bug? What do I need to do to get it working? (Note that I'd prefer solutions that work within RHEL-6-packaged RPMs and upgrading to Apache 2.4 would be a last resort, as we have a lot of infrastructure built around 2.2 on this system at the moment.)

    Read the article

  • Launching Installer Via Powershell and WinRM and Nothing Happens

    - by Nick DeMayo
    I'm currently working on a Powershell script to run some Microsoft Hotfix installers remotely on several Windows Server 2008 R2 servers that I manage. Basically, the script copies all the appropriate files up to the server, and then runs the installer via Invoke-Command, like so: function InstallCU { Write-Host "Installing June 2013 CU..." Invoke-Command -ComputerName $ServerName -ScriptBlock { Start-Process "c:\aaa\prjcusp2\ubersrvprj2010-kb2817530-fullfile-x64-glb.exe" -ArgumentList "/passive" } } If I run the "Start-Process" command locally on the server, the installer runs properly. However, when trying to run it remotely, nothing happens (actually, I can see the installer start up in Task Manager, but it closes a couple seconds later and doesn't run). I've attempted giving the Invoke-Command -Credentials, I've turned off UAC on the server, and I've ensured that my WinRM settings (running 'winrm quickconfig' and setting TrustedHosts to *) are correct. I've also tried having the Invoke-Command script run a local Powershell script to run the installer and changing the Argument from '/passive' to 'quiet' (in case it can't remotely launch something that has a UI), but again, no dice. Is there anything else I can try, or am I just not going to be able to do this?

    Read the article

  • Why does Google Analytics use two domains?

    - by AKeller
    I'm building a distributed widget that is comparable to Google Analytics. Users will add a <script> tag to their site that references my widget's JavaScript file. The Google Analytics tracking code looks like this: var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']); _gaq.push(['_trackPageview']); (function () { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); Can anyone explain the reasoning behind separate HTTP and HTTPS hostnames? My instinct is to just secure the www address and then use the protocol-less syntax, like //www.google-analytics.com/ga.js. But I'm sure the Google Analytics architects put a lot of thought into this approach. I'd love to understand their logic before I follow/ignore their model.

    Read the article

  • Server 2012 intermittently fails to respond to pings from single host, even with firewall disabled, but responds to non-ICMP requests fine

    - by James Westbury
    This one is kind of weird. I've got the following machines involved: DC01 - 10.1.2.42, Server 2012, domain controller & DNS server, physical machine nagiosv - 10.1.2.35, CentOS 6.4, Nagios, virtual machine CB01 - 10.1.3.81, Ubuntu 12.04 LTS, couchbase server, virtual machine So, I noticed something was wrong while configuring this new Nagios VM. I started seeing DC01's state flapping. I logged into nagiosv when I saw this happening, and attempted to ping DC01, both by FQDN and its IP address. Neither worked. I tried pinging the machine from CB01, which is another VM on the same virtual switch/physical NIC as nagiosv, and that worked fine. Pings still failing from nagiosv at this time. DC01 is also an internal DNS server, so I ran dig google.com from nagiosv, and was able to run a query against DC01 just fine: ;; Query time: 1 msec ;; SERVER: 10.1.2.42#53(10.1.2.42) ;; WHEN: Fri Nov 1 07:53:51 2013 ;; MSG SIZE rcvd: 204 Pings still failing from nagiosv, though. I can ping from DC01 to nagiosv, and that works, and I can still ping from other VMs on the same physical NIC into DC01, and that works. I should mention at this point that I've disabled the firewall on DC01 for testing purposes, and it doesn't make a damned bit of difference. (Even with the firewall enabled, I have a blanket exception for ICMP from the local subnet, so it shouldn't make a difference, but I figured I should test it anyway.) I loaded up Wireshark on DC01 and pinged it from nagiosv again. What I see is a bunch of echo requests coming in and not a single reply going back out. Filtered results here, showing all ICMP traffic during a 15-second period. A few more bits of info: There are no IP conflicts on the network. MAC addresses on the incoming pings match the MAC on the VM. There are no duplicate MACs on the network, as far as I can see. I have absolutely no idea why DC01 is failing to respond, here. Any ideas?

    Read the article

  • Edit email messages in Exchange 2010

    - by vladon
    Is it possible to edit contents of e-mail messages (including headers) in any mailbox stored on Exchange Server (Exchange Server 2010 SP3 UR2 - 14.3.158.1)? Or, alternatively, edit the email messages in the OST file (of MS Outlook), so that they then can be synchronized with the Exchange server? PS. This is necessary for the same functionality as in this email editor in Gmail: Signal Extension for Chrome

    Read the article

  • Can storage-spaces drives be moved to a replacement server when there is a failure

    - by Joe C
    I have tried to search here and Google, but cannot find a case explaining this. Storage spaces is similar to software raid. If the server fails due to motherboard or some other issue, can the drives that comprise that storage spaces config be moved to another win2k12 server without restoring from backup? This can be done in linux software raid. If so, does the storage space config have to be re-created prior to the move, or do the drives hold the config so they are essentially plug and play? Thanks.

    Read the article

  • CPQLOFG XML "Syntax error"

    - by Andrew J. Brehm
    HP Lights-Out Configuration Utility- CPQLOCFG v. 4.00 dated 04/04/2012 Whatever input I use, whether a sample file from the HP Web site, whether an empty file or whether a file just containing <RIBCL VERSION="2.0"> </RIBCL> the HP utility always returns CHECKING XML SYNTAX... 1 - Syntax error: Line #0: syntax error near "" in the line: "" What's wrong with me or the utility? Did anyone ever get this to work?

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >