Search Results

Search found 20401 results on 817 pages for 'null coalescing operator'.

Page 22/817 | < Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >

  • Should I make the Cells in a Tiledmap as null when my player hits it

    - by Vishal Kumar
    I am making a Tile Based game using Libgdx. I took the idea from SuperKoalio platformer demo by Mario Zencher. When I wanted to implement Collectables in my game , I simply draw the coins using Tiled Map Editor. When my player hits that, I use to set that cell as null. Someday on this site suggested me not to do so... never use null. I agreed. What can be any other way. If I am using layer.setCell(x,y) to set the cell to any other cell... even if an transparent one .. my player seems to be stopped by an invisible object/hurdle. This is my code: for (Rectangle tile : tiles) { if (koalaRect.overlaps(tile)) { TiledMapTileLayer layer = (TiledMapTileLayer) map.getLayers().get(1); try{ type = layer.getCell((int) tile.x, (int) tile.y).getTile().getProperties().get("tileType").toString(); } catch(Exception e){ System.out.print("Exception in Tiles Property"+e); type="nonbreakable"; } //Let us destroy this cell if(("award".equals(type))){ layer.setCell((int) tile.x, (int) tile.y, null); listener.coin(); score+=100; test = ""+layer.getCell(0, 0).getTile().getProperties().get("tileType"); } //DOING THIS GIVES A BAD EFFECT if(("killer".equals(type))){ //player.health--; //layer.setCell((int) tile.x, (int) tile.y, layer.getCell(20,0)); } // we actually reset the player y-position here // so it is just below/above the tile we collided with // this removes bouncing :) if (player.velocity.y > 0) { player.position.y = (tile.y - Player.height); } Is this a right approach? OR I should create separate Sprite Class called Coin.

    Read the article

  • TSQL Help (SQL Server 2005)

    - by Mick Walker
    I have been playing around with a quite complex SQL Statement for a few days, and have gotten most of it working correctly. I am having trouble with one last part, and was wondering if anyone could shed some light on the issue, as I have no idea why it isnt working: INSERT INTO ExistingClientsAccounts_IMPORT SELECT DISTINCT cca.AccountID, cca.SKBranch, cca.SKAccount, cca.SKName, cca.SKBase, cca.SyncStatus, cca.SKCCY, cca.ClientType, cca.GFCID, cca.GFPID, cca.SyncInput, cca.SyncUpdate, cca.LastUpdatedBy, cca.Deleted, cca.Branch_Account, cca.AccountTypeID FROM ClientsAccounts AS cca INNER JOIN (SELECT DISTINCT ClientAccount, SKAccount, SKDesc, SKBase, SKBranch, ClientType, SKStatus, GFCID, GFPID, Account_Open_Date, Account_Update FROM ClientsAccounts_IMPORT) AS ccai ON cca.Branch_Account = ccai.ClientAccount Table definitions follow: CREATE TABLE [dbo].[ExistingClientsAccounts_IMPORT]( [AccountID] [int] NOT NULL, [SKBranch] [varchar](2) NOT NULL, [SKAccount] [varchar](12) NOT NULL, [SKName] [varchar](255) NULL, [SKBase] [varchar](16) NULL, [SyncStatus] [varchar](50) NULL, [SKCCY] [varchar](5) NULL, [ClientType] [varchar](50) NULL, [GFCID] [varchar](10) NULL, [GFPID] [varchar](10) NULL, [SyncInput] [smalldatetime] NULL, [SyncUpdate] [smalldatetime] NULL, [LastUpdatedBy] [varchar](50) NOT NULL, [Deleted] [tinyint] NOT NULL, [Branch_Account] [varchar](16) NOT NULL, [AccountTypeID] [int] NOT NULL ) ON [PRIMARY] CREATE TABLE [dbo].[ClientsAccounts_IMPORT]( [NEWClientIndex] [bigint] NOT NULL, [ClientGroup] [varchar](255) NOT NULL, [ClientAccount] [varchar](255) NOT NULL, [SKAccount] [varchar](255) NOT NULL, [SKDesc] [varchar](255) NOT NULL, [SKBase] [varchar](10) NULL, [SKBranch] [varchar](2) NOT NULL, [ClientType] [varchar](255) NOT NULL, [SKStatus] [varchar](255) NOT NULL, [GFCID] [varchar](255) NULL, [GFPID] [varchar](255) NULL, [Account_Open_Date] [smalldatetime] NULL, [Account_Update] [smalldatetime] NULL, [SKType] [varchar](255) NOT NULL ) ON [PRIMARY] The error message I get is: Msg 8152, Level 16, State 14, Line 1 String or binary data would be truncated. The statement has been terminated.

    Read the article

  • Is there an exponent operator in C#?

    - by Charlie
    For example, does an operator exist to handle this? float Result, Number1, Number2; Number1 = 2; Number2 = 2; Result = Number1 (operator) Number2; In the past the ^ operator has served as an exponential operator in other languages, but in C# it is a bit-wise operator. Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?

    Read the article

  • Join two tables with same # of row but sorted for NULL

    - by VISQL
    I need to join two tables with the same number of rows. Each table has 1 column. There is NO CONNECTING COLUMN to reference for a join. I need to join them side by side because each table was sorted separately so that numeric values are at the top in descinding order. The Table Earners has income values from say 200K down to 0. I cannot just select using 2 cases, because then I will have my first row with Incomes above 100K, but the first 20 or so entries in the second row are NULL. I want the second row to also be sorted descending. I looked up using ORDER BY within CASE but there is no such thing. I have tried to read about row_number() but none of the examples seem to match or make sense. drop table #20plus select case when Income >= 20000 AND Income < 100000 then Income end as 'mula' into #20plus from Earners order by mula desc drop table #100plus select case when Income >= 100000 then Income end as 'dinero' into #100plus from Earners order by dinero desc Select A.dinero, B.mula FROM #100plus as A JOIN #20plus as B ON A.????? = B.????? Since both A and B are sorted descending, moving all NULL to the bottom, what can I reference to join the two tables? Previous output using one SELECT statement with 2 CASE statements dinero mula 2.12688e+007 NULL 1.80031e+007 NULL 1.92415e+006 NULL … … NULL 93530.7 NULL 91000 NULL 84500 Desired output using one SELECT statement after creating two temp TABLES dinero mula 2.12688e+007 93530.7 1.80031e+007 91000 1.92415e+006 84500 … 82500 NULL 82000 NULLNULL NULL This is Microsoft SQL Server 2008. I'm super new to this, so please give an answer as clear and simplified as possible. Thank you.

    Read the article

  • Behavior of <- NULL on lists versus data.frames for removing data

    - by Ananda Mahto
    Many R users eventually figure out lots of ways to remove elements from their data. One way is to use NULL, particularly when you want to do something like drop a column from a data.frame or drop an element from a list. Eventually, a user comes across a situation where they want to drop several columns from a data.frame at once, and they hit upon <- list(NULL) as the solution (since using <- NULL will result in an error). A data.frame is a special type of list, so it wouldn't be too tough to imagine that the approaches for removing items from a list should be the same as removing columns from a data.frame. However, they produce different results, as can be seen in the example below. ## Make some small data--two data.frames and two lists cars1 <- cars2 <- head(mtcars)[1:4] cars3 <- cars4 <- as.list(cars2) ## Demonstration that the `list(NULL)` approach works cars1[c("mpg", "cyl")] <- list(NULL) cars1 # disp hp # Mazda RX4 160 110 # Mazda RX4 Wag 160 110 # Datsun 710 108 93 # Hornet 4 Drive 258 110 # Hornet Sportabout 360 175 # Valiant 225 105 ## Demonstration that simply using `NULL` does not work cars2[c("mpg", "cyl")] <- NULL # Error in `[<-.data.frame`(`*tmp*`, c("mpg", "cyl"), value = NULL) : # replacement has 0 items, need 12 Switch to applying the same concept to a list, and compare the difference in behavior. ## Does not fully drop the items, but sets them to `NULL` cars3[c("mpg", "cyl")] <- list(NULL) # $mpg # NULL # # $cyl # NULL # # $disp # [1] 160 160 108 258 360 225 # # $hp # [1] 110 110 93 110 175 105 ## *Does* drop the `list` items while this would ## have produced an error with a `data.frame` cars4[c("mpg", "cyl")] <- NULL # $disp # [1] 160 160 108 258 360 225 # # $hp # [1] 110 110 93 110 175 105 The main questions I have are, if a data.frame is a list, why does it behave so differently in this scenario? Is there a foolproof way of knowing when an element will be dropped, when it will produce an error, and when it will simply be given a NULL value? Or do we depend on trial-and-error for this?

    Read the article

  • Are null references really a bad thing?

    - by Tim Goodman
    I've heard it said that the inclusion of null references in programming languages is the "billion dollar mistake". But why? Sure, they can cause NullReferenceExceptions, but so what? Any element of the language can be a source of errors if used improperly. And what's the alternative? I suppose instead of saying this: Customer c = Customer.GetByLastName("Goodman"); // returns null if not found if (c != null) { Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!"); } else { Console.WriteLine("There was no customer named Goodman. How lame!"); } You could say this: if (Customer.ExistsWithLastName("Goodman")) { Customer c = Customer.GetByLastName("Goodman") // throws error if not found Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!"); } else { Console.WriteLine("There was no customer named Goodman. How lame!"); } But how is that better? Either way, if you forget to check that the customer exists, you get an exception. I suppose that a CustomerNotFoundException is a bit easier to debug than a NullReferenceException by virtue of being more descriptive. Is that all there is to it?

    Read the article

  • Consistency in placing operator functions

    - by wrongusername
    I have a class like this: class A { ...private functions, variables, etc... public: ...some public functions and variables... A operator * (double); A operator / (double); A operator * (A); ...and lots of other operators } However, I want to also be able to do stuff like 2 * A instead of only being allowed to do A * 2, and so I would need functions like these outside of the class: A operator * (double, A); A operator / (double, A); ...etc... Should I put all these operators outside of the class for consistency, or should I keep half inside and half outside?

    Read the article

  • IN SQL operator in R-Shiny

    - by Piyush
    I am taking multiple selection for component as per below code. selectInput("cmpnt", "Choose Component:", choices = as.character(levels(Material_Data()$CMPNT_NM)),multiple = TRUE) But I am trying to write a sql statement as given below, then its not working. Neither it is throwing any error message. When I was selecting one option at a time (without mutiple = TRUE) then it was working (since I was using "=" operator). But after using "multiple=TRUE" I need to use IN operator, which is not working. Input_Data2 <- fn$sqldf( paste0( "select * from Input_Data1 where MTRL_NBR = '$mtrl1' and CMPNT_NM in ('$cmpnt1')") ) Thanks in advance for any help on this. Thanks jdharrison! Pleasefind the detailed code: # server.R library(RODBC) library(shiny) library(sqldf) Input_Data <- readRDS("InputSource.rds") Mtrl <- factor(Input_Data$MTRL_NBR) Mtrl_List <- levels(Mtrl) shinyServer(function(input, output) { # First UI input (Service column) filter clientData output$Choose_Material <- renderUI({ if (is.null(clientData())) return("No client selected") selectInput("mtrl", "Choose Material:", choices = as.character(levels(clientData()$MTRL_NBR)), selected = input$mtrl ) }) # Second UI input (Rounds column) filter service-filtered clientData output$Choose_Component <- renderUI({ if(is.null(input$mtrl)) return() if (is.null(Material_Data())) return("No service selected") selectInput("cmpnt", "Choose Component:", choices = as.character(levels(Material_Data()$CMPNT_NM)),multiple = TRUE) }) # First data load (client data) clientData <- reactive({ # get(input$Input_Data) return(Input_Data) }) # Second data load (filter by service column) Material_Data <- reactive({ dat <- clientData() if (is.null(dat)) return(NULL) if (!is.null(input$mtrl)) # ! dat <- dat[dat$MTRL_NBR %in% input$mtrl,] dat <- droplevels(dat) return(dat) }) output$Choose_Columns <- renderUI({ if(is.null(input$mtrl)) return() if(is.null(input$cmpnt)) return() colnames <- names(Input_Data) checkboxGroupInput("columns", "Choose Columns To Display The Data:", choices = colnames, selected = colnames) }) output$text <- renderText({ print(input$cmpnt) }) output$data_table <- renderTable({ if(is.null(input$mtrl)) return() if (is.null(input$columns) || !(input$columns %in% names(Input_Data))) return() Input_Data1 <- Input_Data[, input$columns, drop = FALSE] cmpnt1 <- input$cmpnt mtrl1 <- input$mtrl Input_Data2 <- fn$sqldf( paste0( "select * from Input_Data1 where MTRL_NBR = '$mtrl1' and CMPNT_NM in ('$cmpnt1')") ) head(Input_Data2, 10) }) })

    Read the article

  • Implementing a non-public assignment operator with a public named method?

    - by Casey
    It is supposed to copy an AnimatedSprite. I'm having second thoughts that it has the unfortunate side effect of changing the *this object. How would I implement this feature without the side effect? EDIT: Based on new answers, the question should really be: How do I implement a non-public assignment operator with a public named method without side effects? (Changed title as such). public: AnimatedSprite& AnimatedSprite::Clone(const AnimatedSprite& animatedSprite) { return (*this = animatedSprite); } protected: AnimatedSprite& AnimatedSprite::operator=(const AnimatedSprite& rhs) { if(this == &rhs) return *this; destroy_bitmap(this->_frameImage); this->_frameImage = create_bitmap(rhs._frameImage->w, rhs._frameImage->h); clear_bitmap(this->_frameImage); this->_frameDimensions = rhs._frameDimensions; this->CalcCenterFrame(); this->_frameRate = rhs._frameRate; if(rhs._animation != nullptr) { delete this->_animation; this->_animation = new a2de::AnimationHandler(*rhs._animation); } else { delete this->_animation; this->_animation = nullptr; } return *this; }

    Read the article

  • Issue with TagBuilder.MergeAttribute for parameter null

    - by The Yur
    I would like to use Razor's feature not to produce attribute output inside a tag in case when attribute's value is null. So when Razor meets <div class="@var" where @var is null, the output will be mere <div. I've created some Html extension method to write text inside tag. The method takes header text, level (h1..h6), and html attributes as simple object. The code is: public static MvcHtmlString WriteHeader(this HtmlHelper html, string s, int? hLevel = 1, object htmlAttributes = null) { if ((hLevel == null) || (hLevel < 1 || hLevel > 4) || (s.IsNullOrWhiteSpace())) return new MvcHtmlString(""); string cssClass = null, cssId = null, cssStyle = null; if (htmlAttributes != null) { var T = htmlAttributes.GetType(); var propInfo = T.GetProperty("class"); var o = propInfo.GetValue(htmlAttributes); cssClass = o.ToString().IsNullOrWhiteSpace() ? null : o.ToString(); propInfo = T.GetProperty("id"); o = propInfo.GetValue(htmlAttributes); cssId = o.ToString().IsNullOrWhiteSpace() ? null : o.ToString(); propInfo = T.GetProperty("style"); o = propInfo.GetValue(htmlAttributes); cssStyle = o.ToString().IsNullOrWhiteSpace() ? null : o.ToString(); } var hTag = new TagBuilder("h" + hLevel); hTag.MergeAttribute("id", cssId); hTag.MergeAttribute("class", cssClass); hTag.MergeAttribute("style", cssStyle); hTag.InnerHtml = s; return new MvcHtmlString(hTag.ToString()); } I found that in spite of null values for "class" and "style" attributes TagBuilder still puts them as empty strings, like <h1 class="" style="" But for id attribute it surprisingly works, so when id's value is null, there is no id attribute in tag. My question - is such behavior something that should actually happen? How can I achieve absent attributes with null values using TagBuilder? I tried this in VS2013, MVC 5.

    Read the article

  • What is the rationale to non allow overloading of C++ conversions operator with non-member functio

    - by Vicente Botet Escriba
    C++0x has added explicit conversion operators, but they must always be defined as members of the Source class. The same applies to the assignment operator, it must be defined on the Target class. When the Source and Target classes of the needed conversion are independent of each other, neither the Source can define a conversion operator, neither the Target can define a constructor from a Source. Usually we get it by defining a specific function such as Target ConvertToTarget(Source& v); If C++0x allowed to overload conversion operator by non member functions we could for example define the conversion implicitly or explicitly between unrelated types. template < typename To, typename From operator To(const From& val); For example we could specialize the conversion from chrono::time_point to posix_time::ptime as follows template < class Clock, class Duration operator boost::posix_time::ptime( const boost::chrono::time_point& from) { using namespace boost; typedef chrono::time_point time_point_t; typedef chrono::nanoseconds duration_t; typedef duration_t::rep rep_t; rep_t d = chrono::duration_cast( from.time_since_epoch()).count(); rep_t sec = d/1000000000; rep_t nsec = d%1000000000; return posix_time::from_time_t(0)+ posix_time::seconds(static_cast(sec))+ posix_time::nanoseconds(nsec); } And use the conversion as any other conversion. So the question is: What is the rationale to non allow overloading of C++ conversions operator with non-member functions?

    Read the article

  • What's the false operator in C# good for?

    - by Jakub Šturc
    There are two weird operators in C#: the true operator the false operator If I understand this right these operators can be used in types which I want to use instead of a boolean expression and where I don't want to provide an implicit conversion to bool. Let's say I have a following class: public class MyType { public readonly int Value; public MyType(int value) { Value = value; } public static bool operator true (MyType mt) { return mt.Value > 0; } public static bool operator false (MyType mt) { return mt.Value < 0; } } So I can write the following code: MyType mTrue = new MyType(100); MyType mFalse = new MyType(-100); MyType mDontKnow = new MyType(0); if (mTrue) { // Do something. } while (mFalse) { // Do something else. } do { // Another code comes here. } while (mDontKnow) However for all the examples above only the true operator is executed. So what's the false operator in C# good for? Note: More examples can be found here, here and here.

    Read the article

  • Why do not C++11's move constructor/assignment operator act as expected

    - by xmllmx
    #include <iostream> using namespace std; struct A { A() { cout << "A()" << endl; } ~A() { cout << "~A()" << endl; } A(A&&) { cout << "A(A&&)" << endl; } A& operator =(A&&) { cout << "A& operator =(A&&)" << endl; return *this; } }; struct B { // According to the C++11, the move ctor/assignment operator // should be implicitly declared and defined. The move ctor // /assignment operator should implicitly call class A's move // ctor/assignment operator to move member a. A a; }; B f() { B b; // The compiler knows b is a temporary object, so implicitly // defined move ctor/assignment operator of class B should be // called here. Which will cause A's move ctor is called. return b; } int main() { f(); return 0; } My expected output should be: A() A(A&&) ~A() ~A() However, the actual output is: (The C++ compiler is: Visual Studio 2012) A() ~A() ~A() Is this a bug of VC++? or just my misunderstanding?

    Read the article

  • C++ operator lookup rules / Koenig lookup

    - by John Bartholomew
    While writing a test suite, I needed to provide an implementation of operator<<(std::ostream&... for Boost unit test to use. This worked: namespace theseus { namespace core { std::ostream& operator<<(std::ostream& ss, const PixelRGB& p) { return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (int)p.b << ")"); } }} This didn't: std::ostream& operator<<(std::ostream& ss, const theseus::core::PixelRGB& p) { return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (int)p.b << ")"); } Apparently, the second wasn't included in the candidate matches when g++ tried to resolve the use of the operator. Why (what rule causes this)? The code calling operator<< is deep within the Boost unit test framework, but here's the test code: BOOST_AUTO_TEST_SUITE(core_image) BOOST_AUTO_TEST_CASE(test_output) { using namespace theseus::core; BOOST_TEST_MESSAGE(PixelRGB(5,5,5)); // only compiles with operator<< definition inside theseus::core std::cout << PixelRGB(5,5,5) << "\n"; // works with either definition BOOST_CHECK(true); // prevent no-assertion error } BOOST_AUTO_TEST_SUITE_END() For reference, I'm using g++ 4.4 (though for the moment I'm assuming this behaviour is standards-conformant).

    Read the article

  • On C++ global operator new: why it can be replaced

    - by Jimmy
    I wrote a small program in VS2005 to test whether C++ global operator new can be overloaded. It can. #include "stdafx.h" #include "iostream" #include "iomanip" #include "string" #include "new" using namespace std; class C { public: C() { cout<<"CTOR"<<endl; } }; void * operator new(size_t size) { cout<<"my overload of global plain old new"<<endl; // try to allocate size bytes void *p = malloc(size); return (p); } int main() { C* pc1 = new C; cin.get(); return 0; } In the above, my definition of operator new is called. If I remove that function from the code, then operator new in C:\Program Files (x86)\Microsoft Visual Studio 8\VC\crt\src\new.cpp gets called. All is good. However, in my opinion, my implementations of operator new does NOT overload the new in new.cpp, it CONFLICTS with it and violates the one-definition rule. Why doesn't the compiler complain about it? Or does the standard say since operator new is so special, one-definition rule does not apply here? Thanks.

    Read the article

  • Operator+ for a subtype of a template class.

    - by baol
    I have a template class that defines a subtype. I'm trying to define the binary operator+ as a template function, but the compiler cannot resolve the template version of the operator+. #include <iostream> template<typename other_type> struct c { c(other_type v) : cs(v) {} struct subtype { subtype(other_type v) : val(v) {} other_type val; } cs; }; template<typename other_type> typename c<other_type>::subtype operator+(const typename c<other_type>::subtype& left, const typename c<other_type>::subtype& right) { return typename c<other_type>::subtype(left.val + right.val); } // This one works // c<int>::subtype operator+(const c<int>::subtype& left, // const c<int>::subtype& right) // { return c<int>::subtype(left.val + right.val); } int main() { c<int> c1 = 1; c<int> c2 = 2; c<int>::subtype cs3 = c1.cs + c2.cs; std::cerr << cs3.val << std::endl; } I think the reason is because the compiler (g++4.3) cannot guess the template type so it's searching for operator+<int> instead of operator+. What's the reason for that? What elegant solution can you suggest?

    Read the article

  • Operator+ for a subtype of a template classe.

    - by baol
    I have a template class that defines a subtype. I'm trying to define the binary operator+ as a template function, but the compiler cannot resolve the template version of the operator+. #include <iostream> template<typename other_type> struct c { c(other_type v) : cs(v) {} struct subtype { subtype(other_type v) : val(v) {} other_type val; } cs; }; template<typename other_type> typename c<other_type>::subtype operator+(const typename c<other_type>::subtype& left, const typename c<other_type>::subtype& right) { return typename c<other_type>::subtype(left.val + right.val); } // This one works // c<a>::subtype operator+(const c<a>::subtype& left, // const c<a>::subtype& right) // { return c<a>::subtype(left.val + right.val); } int main() { c<int> c1 = 1; c<int> c2 = 2; c<int>::subtype cs3 = c1.cs + c2.cs; std::cerr << cs3.val << std::endl; } I think the reason is because the compiler (g++4.3) cannot guess the template type so it's searching for operator+<int> instead of operator+. What's the reason for that? What elegant solution can you suggest?

    Read the article

  • SQL Server Date Comparison Functions

    - by HighAltitudeCoder
    A few months ago, I found myself working with a repetitive cursor that looped until the data had been manipulated enough times that it was finally correct.  The cursor was heavily dependent upon dates, every time requiring the earlier of two (or several) dates in one stored procedure, while requiring the later of two dates in another stored procedure. In short what I needed was a function that would allow me to perform the following evaluation: WHERE MAX(Date1, Date2) < @SomeDate The problem is, the MAX() function in SQL Server does not perform this functionality.  So, I set out to put these functions together.  They are titled: EarlierOf() and LaterOf(). /**********************************************************                               EarlierOf.sql   **********************************************************/ /**********************************************************   Return the later of two DATETIME variables.   Parameter 1: DATETIME1 Parameter 2: DATETIME2   Works for a variety of DATETIME or NULL values. Even though comparisons with NULL are actually indeterminate, we know conceptually that NULL is not earlier or later than any other date provided.   SYNTAX: SELECT dbo.EarlierOf('1/1/2000','12/1/2009') SELECT dbo.EarlierOf('2009-12-01 00:00:00.000','2009-12-01 00:00:00.521') SELECT dbo.EarlierOf('11/15/2000',NULL) SELECT dbo.EarlierOf(NULL,'1/15/2004') SELECT dbo.EarlierOf(NULL,NULL)   **********************************************************/ USE AdventureWorks GO   IF EXISTS       (SELECT *       FROM sysobjects       WHERE name = 'EarlierOf'       AND xtype = 'FN'       ) BEGIN             DROP FUNCTION EarlierOf END GO   CREATE FUNCTION EarlierOf (       @Date1                              DATETIME,       @Date2                              DATETIME )   RETURNS DATETIME   AS BEGIN       DECLARE @ReturnDate     DATETIME         IF (@Date1 IS NULL AND @Date2 IS NULL)       BEGIN             SET @ReturnDate = NULL             GOTO EndOfFunction       END         ELSE IF (@Date1 IS NULL AND @Date2 IS NOT NULL)       BEGIN             SET @ReturnDate = @Date2             GOTO EndOfFunction       END         ELSE IF (@Date1 IS NOT NULL AND @Date2 IS NULL)       BEGIN             SET @ReturnDate = @Date1             GOTO EndOfFunction       END         ELSE       BEGIN             SET @ReturnDate = @Date1             IF @Date2 < @Date1                   SET @ReturnDate = @Date2             GOTO EndOfFunction       END         EndOfFunction:       RETURN @ReturnDate   END -- End Function GO   ---- Set Permissions --GRANT SELECT ON EarlierOf TO UserRole1 --GRANT SELECT ON EarlierOf TO UserRole2 --GO                                                                                             The inverse of this function is only slightly different. /**********************************************************                               LaterOf.sql   **********************************************************/ /**********************************************************   Return the later of two DATETIME variables.   Parameter 1: DATETIME1 Parameter 2: DATETIME2   Works for a variety of DATETIME or NULL values. Even though comparisons with NULL are actually indeterminate, we know conceptually that NULL is not earlier or later than any other date provided.   SYNTAX: SELECT dbo.LaterOf('1/1/2000','12/1/2009') SELECT dbo.LaterOf('2009-12-01 00:00:00.000','2009-12-01 00:00:00.521') SELECT dbo.LaterOf('11/15/2000',NULL) SELECT dbo.LaterOf(NULL,'1/15/2004') SELECT dbo.LaterOf(NULL,NULL)   **********************************************************/ USE AdventureWorks GO   IF EXISTS       (SELECT *       FROM sysobjects       WHERE name = 'LaterOf'       AND xtype = 'FN'       ) BEGIN             DROP FUNCTION LaterOf END GO   CREATE FUNCTION LaterOf (       @Date1                              DATETIME,       @Date2                              DATETIME )   RETURNS DATETIME   AS BEGIN       DECLARE @ReturnDate     DATETIME         IF (@Date1 IS NULL AND @Date2 IS NULL)       BEGIN             SET @ReturnDate = NULL             GOTO EndOfFunction       END         ELSE IF (@Date1 IS NULL AND @Date2 IS NOT NULL)       BEGIN             SET @ReturnDate = @Date2             GOTO EndOfFunction       END         ELSE IF (@Date1 IS NOT NULL AND @Date2 IS NULL)       BEGIN             SET @ReturnDate = @Date1             GOTO EndOfFunction       END         ELSE       BEGIN             SET @ReturnDate = @Date1             IF @Date2 > @Date1                   SET @ReturnDate = @Date2             GOTO EndOfFunction       END         EndOfFunction:       RETURN @ReturnDate   END -- End Function GO   ---- Set Permissions --GRANT SELECT ON LaterOf TO UserRole1 --GRANT SELECT ON LaterOf TO UserRole2 --GO                                                                                             The interesting thing about this function is its simplicity and the built-in NULL handling functionality.  Its interesting, because it seems like something should already exist in SQL Server that does this.  From a different vantage point, if you create this functionality and it is easy to use (ideally, intuitively self-explanatory), you have made a successful contribution. Interesting is good.  Self-explanatory, or intuitive is FAR better.  Happy coding! Graeme

    Read the article

  • Arraylist is null; I cannot access books in the arraylist

    - by user3701380
    I am a beginner-intermediate java programmer and I am getting a null pointer exception from my arraylist. I am writing a bookstore program for APCS and when i add the book, it is supposed to add to the arraylist in the inventory class. But when i call a method to search for a book (e.g. by title), it shows that there isn't anything in the arraylist. //Here is my inventory class -- it has all methods for adding the book or searching for one The searching methods are in getBookByTitle, getBookByAuthor, and getBookByISBN and the method for adding a book is addBook package webbazonab; //Inventory Class //Bharath Senthil //Ansh Sikka import java.util.ArrayList; public class Inventory{ private ArrayList<Book> allBooks = new ArrayList<Book>(); private String bookTitles; private String bookAuthors; private String bookPrices; private String bookCopies; private String ISBNs; public Inventory() { } //@param double price, int copies, String bookTitle, String Author, String isbnNumber public void addBooks(Book addedBook){ allBooks.add(addedBook); } public boolean isAvailable(){ for(Book myBook : allBooks){ if(myBook.copiesLeft() == 0) return false; } return true; } public String populateTitle(){ for (Book titleBooks : allBooks){ bookTitles = titleBooks.getTitle() + "\n"; return bookTitles; } return bookTitles; } public String populateAuthor(){ for(Book authorBooks : allBooks){ bookAuthors = authorBooks.getAuthor() + "\n"; return bookAuthors; } return bookAuthors; } public String populatePrice(){ for (Book pricedBooks : allBooks){ bookPrices = String.valueOf(pricedBooks.getPrice()) + "\n"; } return "$" + bookPrices; } /** * * @return */ public String populateCopies(){ for (Book amtBooks : allBooks){ bookCopies = String.valueOf(amtBooks.copiesLeft()) + "\n"; return bookCopies; } return bookCopies; } public String populateISBN(){ for (Book isbnNums : allBooks){ ISBNs = isbnNums.getIsbn() + "\n"; return ISBNs; } return ISBNs; } @SuppressWarnings("empty-statement") public Book getBookByTitle(String titleSearch) { for(Book titleBook : allBooks) { if (titleBook.getTitle().equals(titleSearch)) { return titleBook; } } return null; } public Book getBookByISBN(String isbnSearch){ for(Book isbnBookSearches : allBooks){ if(isbnBookSearches.getIsbn().equals(isbnSearch)){ return isbnBookSearches; } } return null; } public Book getBookByAuthor(String authorSearch){ for(Book authorBookSearches : allBooks){ if(authorBookSearches.getAuthor().equals(authorSearch)){ return authorBookSearches; } } return null; } public void sort(){ for(int i = 0; i < allBooks.size(); i++) { for(int k = 0; k < allBooks.size(); k++) { if(((Book) allBooks.get(i)).getIsbn().compareTo(((Book) allBooks.get(k)).getIsbn()) < 1) { Book temp = (Book) allBooks.get(k); allBooks.set(k, allBooks.get(i)); allBooks.set(i, temp); } else if(((Book) allBooks.get(i)).getIsbn().compareTo(((Book) allBooks.get(k)).getIsbn()) > 1) { Book temp = (Book) allBooks.get(i); allBooks.set(i, allBooks.get(k)); allBooks.set(k, temp); } } } } public ArrayList<Book> getBooks(){ return allBooks; } } //The exception occurs when i call the method here (in another class): Inventory lib = new Inventory(); jTextField12.setText(lib.getBookByAuthor(authorSearch).getTitle()); Here is my book class if you need it package webbazonab; //Webbazon AB //Project By: Ansh Sikka and Bharath Senthil public class Book { private double myPrice; private String myTitle; private String bookAuthor; private String isbn; private int myCopies; public Book(double price, int copies, String bookTitle, String Author, String isbnNumber) { myPrice = price; myCopies = copies; myTitle = bookTitle; bookAuthor = Author; isbn = isbnNumber; } public double getPrice() { return myPrice; } public String getIsbn() { return isbn; } public String getTitle() { return myTitle; } public String getAuthor() { return bookAuthor; } public int copiesLeft(){ return myCopies; } public String notFound(){ return "The book you searched for could not be found!"; } public String toString() { return "Title: " + getTitle() + "\nAuthor: " + getAuthor() + "\nNumber of Available Books: " + copiesLeft() + "\nPrice: $" + getPrice(); } } Thanks!

    Read the article

  • How to insert null value for numeric field of a datatable in c#?

    - by Pandiya Chendur
    Consider My dynamically generated datatable contains the following fileds Id,Name,Mob1,Mob2 If my datatable has this it get inserted successfully, Id Name Mob1 Mob2 1 acp 9994564564 9568848526 But when it is like this it gets failed saying, Id Name Mob1 Mob2 1 acp 9994564564 The given value of type String from the data source cannot be converted to type decimal of the specified target column. I generating my datatable by readingt a csv file, CSVReader reader = new CSVReader(CSVFile.PostedFile.InputStream); string[] headers = reader.GetCSVLine(); DataTable dt = new DataTable(); foreach (string strHeader in headers) { dt.Columns.Add(strHeader); } string[] data; while ((data = reader.GetCSVLine()) != null) { dt.Rows.Add(data); } Any suggestion how to insert null value for numeric field during BulkCopy in c#... EDIT: I tried this dt.Columns["Mob2"].AllowDBNull = true; but it doesn't seem to work...

    Read the article

  • MS Access: How to replace blank (null ) values with 0 for all records?

    - by rick
    MS Access: How to replace blank (null ) values with 0 for all records? I guess it has to be done using SQL. I can use Find and Replace to replace 0 with blank, but not the other way around (won't "find" a blank, even if I enter [Ctrl-Spacebar] which inserts a space. So I guess I need to do SQL where I find null values for MyField, then replace all of them with 0. Any help is greatly appreciated. Thanks, The Find & Replace guy.

    Read the article

  • Problems in Binary Search Tree

    - by user2782324
    This is my first ever trial at implementing the BST, and I am unable to get it done. Please help The problem is that When I delete the node if the node is in the right subtree from the root or if its a right child in the left subtree, then it works fine. But if the node is in the left subtree from root and its any left child, then it does not get deleted. Can someone show me what mistake am I doing?? the markedNode here gets allocated to the parent node of the node to be deleted. the minValueNode here gets allocated to a node whose left value child is the smallest value and it will be used to replace the value to be deleted. package DataStructures; class Node { int value; Node rightNode; Node leftNode; } class BST { Node rootOfTree = null; public void insertintoBST(int value) { Node markedNode = rootOfTree; if (rootOfTree == null) { Node newNode = new Node(); newNode.value = value; rootOfTree = newNode; newNode.rightNode = null; newNode.leftNode = null; } else { while (true) { if (value >= markedNode.value) { if (markedNode.rightNode != null) { markedNode = markedNode.rightNode; } else { Node newNode = new Node(); newNode.value = value; markedNode.rightNode = newNode; newNode.rightNode = null; newNode.leftNode = null; break; } } if (value < markedNode.value) { if (markedNode.leftNode != null) { markedNode = markedNode.leftNode; } else { Node newNode = new Node(); newNode.value = value; markedNode.leftNode = newNode; newNode.rightNode = null; newNode.leftNode = null; break; } } } } } public void searchBST(int value) { Node markedNode = rootOfTree; if (rootOfTree == null) { System.out.println("Element Not Found"); } else { while (true) { if (value > markedNode.value) { if (markedNode.rightNode != null) { markedNode = markedNode.rightNode; } else { System.out.println("Element Not Found"); break; } } if (value < markedNode.value) { if (markedNode.leftNode != null) { markedNode = markedNode.leftNode; } else { System.out.println("Element Not Found"); break; } } if (value == markedNode.value) { System.out.println("Element Found"); break; } } } } public void deleteFromBST(int value) { Node markedNode = rootOfTree; Node minValueNode = null; if (rootOfTree == null) { System.out.println("Element Not Found"); return; } if (rootOfTree.value == value) { if (rootOfTree.leftNode == null && rootOfTree.rightNode == null) { rootOfTree = null; return; } else if (rootOfTree.leftNode == null ^ rootOfTree.rightNode == null) { if (rootOfTree.rightNode != null) { rootOfTree = rootOfTree.rightNode; return; } else { rootOfTree = rootOfTree.leftNode; return; } } else { minValueNode = rootOfTree.rightNode; if (minValueNode.leftNode == null) { rootOfTree.rightNode.leftNode = rootOfTree.leftNode; rootOfTree = rootOfTree.rightNode; } else { while (true) { if (minValueNode.leftNode.leftNode != null) { minValueNode = minValueNode.leftNode; } else { break; } } // Minvalue to the left of minvalue node rootOfTree.value = minValueNode.leftNode.value; // The value has been swapped if (minValueNode.leftNode.leftNode == null && minValueNode.leftNode.rightNode == null) { minValueNode.leftNode = null; } else { if (minValueNode.leftNode.leftNode != null) { minValueNode.leftNode = minValueNode.leftNode.leftNode; } else { minValueNode.leftNode = minValueNode.leftNode.rightNode; } // Minvalue deleted } } } } else { while (true) { if (value > markedNode.value) { if (markedNode.rightNode != null) { if (markedNode.rightNode.value == value) { break; } else { markedNode = markedNode.rightNode; } } else { System.out.println("Element Not Found"); return; } } if (value < markedNode.value) { if (markedNode.leftNode != null) { if (markedNode.leftNode.value == value) { break; } else { markedNode = markedNode.leftNode; } } else { System.out.println("Element Not Found"); return; } } } // Parent of the required element found // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (markedNode.rightNode != null) { if (markedNode.rightNode.value == value) { if (markedNode.rightNode.rightNode == null && markedNode.rightNode.leftNode == null) { markedNode.rightNode = null; return; } else if (markedNode.rightNode.rightNode == null ^ markedNode.rightNode.leftNode == null) { if (markedNode.rightNode.rightNode != null) { markedNode.rightNode = markedNode.rightNode.rightNode; return; } else { markedNode.rightNode = markedNode.rightNode.leftNode; return; } } else { if (markedNode.rightNode.value == value) { minValueNode = markedNode.rightNode.rightNode; } else { minValueNode = markedNode.leftNode.rightNode; } if (minValueNode.leftNode == null) { // MinNode has no left value markedNode.rightNode = minValueNode; return; } else { while (true) { if (minValueNode.leftNode.leftNode != null) { minValueNode = minValueNode.leftNode; } else { break; } } // Minvalue to the left of minvalue node if (markedNode.leftNode != null) { if (markedNode.leftNode.value == value) { markedNode.leftNode.value = minValueNode.leftNode.value; } } if (markedNode.rightNode != null) { if (markedNode.rightNode.value == value) { markedNode.rightNode.value = minValueNode.leftNode.value; } } // MarkedNode exchanged if (minValueNode.leftNode.leftNode == null && minValueNode.leftNode.rightNode == null) { minValueNode.leftNode = null; } else { if (minValueNode.leftNode.leftNode != null) { minValueNode.leftNode = minValueNode.leftNode.leftNode; } else { minValueNode.leftNode = minValueNode.leftNode.rightNode; } // Minvalue deleted } } } // //////////////////////////////////////////////////////////////////////////////////////////////////////////////// if (markedNode.leftNode != null) { if (markedNode.leftNode.value == value) { if (markedNode.leftNode.rightNode == null && markedNode.leftNode.leftNode == null) { markedNode.leftNode = null; return; } else if (markedNode.leftNode.rightNode == null ^ markedNode.leftNode.leftNode == null) { if (markedNode.leftNode.rightNode != null) { markedNode.leftNode = markedNode.leftNode.rightNode; return; } else { markedNode.leftNode = markedNode.leftNode.leftNode; return; } } else { if (markedNode.rightNode.value == value) { minValueNode = markedNode.rightNode.rightNode; } else { minValueNode = markedNode.leftNode.rightNode; } if (minValueNode.leftNode == null) { // MinNode has no left value markedNode.leftNode = minValueNode; return; } else { while (true) { if (minValueNode.leftNode.leftNode != null) { minValueNode = minValueNode.leftNode; } else { break; } } // Minvalue to the left of minvalue node if (markedNode.leftNode != null) { if (markedNode.leftNode.value == value) { markedNode.leftNode.value = minValueNode.leftNode.value; } } if (markedNode.rightNode != null) { if (markedNode.rightNode.value == value) { markedNode.rightNode.value = minValueNode.leftNode.value; } } // MarkedNode exchanged if (minValueNode.leftNode.leftNode == null && minValueNode.leftNode.rightNode == null) { minValueNode.leftNode = null; } else { if (minValueNode.leftNode.leftNode != null) { minValueNode.leftNode = minValueNode.leftNode.leftNode; } else { minValueNode.leftNode = minValueNode.leftNode.rightNode; } // Minvalue deleted } } } } // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } } } } } } public class BSTImplementation { public static void main(String[] args) { BST newBst = new BST(); newBst.insertintoBST(19); newBst.insertintoBST(13); newBst.insertintoBST(10); newBst.insertintoBST(20); newBst.insertintoBST(5); newBst.insertintoBST(23); newBst.insertintoBST(28); newBst.insertintoBST(16); newBst.insertintoBST(27); newBst.insertintoBST(9); newBst.insertintoBST(4); newBst.insertintoBST(22); newBst.insertintoBST(17); newBst.insertintoBST(30); newBst.insertintoBST(40); newBst.deleteFromBST(5); newBst.deleteFromBST(4); newBst.deleteFromBST(9); newBst.deleteFromBST(10); newBst.deleteFromBST(13); newBst.deleteFromBST(16); newBst.deleteFromBST(17); newBst.searchBST(5); newBst.searchBST(4); newBst.searchBST(9); newBst.searchBST(10); newBst.searchBST(13); newBst.searchBST(16); newBst.searchBST(17); System.out.println(); newBst.deleteFromBST(20); newBst.deleteFromBST(23); newBst.deleteFromBST(27); newBst.deleteFromBST(28); newBst.deleteFromBST(30); newBst.deleteFromBST(40); newBst.searchBST(20); newBst.searchBST(23); newBst.searchBST(27); newBst.searchBST(28); newBst.searchBST(30); newBst.searchBST(40); } }

    Read the article

  • C++ How do you set an array of pointers to null in an initialiser list like way?

    - by boredjoe
    I am aware you cannot use an initialiser list for an array. However I have heard of ways that you can set an array of pointers to NULL in a way that is similar to an initialiser list. I am not certain how this is done. I have heard that a pointer is set to NULL by default, though I do not know if this is guaranteed/ in the C++ standard. I am also not sure if initialising through the new operator compared to normal allocation can make a difference too.

    Read the article

  • Table Name is null in the sqlite database in android device

    - by Mahe
    I am building a simple app which stores some contacts and retrieves contacts in android phone device. I have created my own database and a table and inserting the values to the table in phone. My phone is not rooted. So I cannot access the files, but I see that values are stored in the table. And tested on a emulator also. Till here it is fine. Display all the contacts in a list by fetching data from table. This is also fine. But the problem is When I am trying to delete the record, it shows the table name is null in the logcat(not an exception), and the data is not deleted. But in emulator the data is getting deleted from table. I am not able to achieve this through phone. This is my code for deleting, public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item .getMenuInfo(); int menuItemIndex = item.getItemId(); String[] menuItems = getResources().getStringArray(R.array.menu); String menuItemName = menuItems[menuItemIndex]; String listItemName = Customers[info.position]; if (item.getTitle().toString().equalsIgnoreCase("Delete")) { Toast.makeText( context, "Selected List item is: " + listItemName + "MenuItem is: " + menuItemName, Toast.LENGTH_LONG).show(); DB = context.openOrCreateDatabase("CustomerDetails.db", MODE_PRIVATE, null); try { int pos = info.position; pos = pos + 1; Log.d("", "customers[pos]: " + Customers[info.position]); Cursor c = DB .rawQuery( "Select customer_id,first_name,last_name from CustomerInfo", null); int rowCount = c.getCount(); DB.delete(Table_name, "customer_id" + "=" + String.valueOf(pos), null); DB.close(); Log.d("", "" + String.valueOf(pos)); Toast.makeText(context, "Deleted Customer", Toast.LENGTH_LONG) .show(); // Customers[info.position]=null; getCustomers(); } catch (Exception e) { Toast.makeText(context, "Delete unsuccessfull", Toast.LENGTH_LONG).show(); } } this is my logcat, 07-02 10:12:42.976: D/Cursor(1560): Database path: CustomerDetails.db 07-02 10:12:42.976: D/Cursor(1560): Table name : null 07-02 10:12:42.984: D/Cursor(1560): Database path: CustomerDetails.db 07-02 10:12:42.984: D/Cursor(1560): Table name : null Don't know the reason why data is not being deleted. Data exists in the table. This is the specification I have given for creating the table public static String customer_id="customer_id"; public static String site_id="site_id"; public static String last_name="last_name"; public static String first_name="first_name"; public static String phone_number="phone_number"; public static String address="address"; public static String city="city"; public static String state="state"; public static String zip="zip"; public static String email_address="email_address"; public static String custlat="custlat"; public static String custlng="custlng"; public static String Table_name="CustomerInfo"; final SQLiteDatabase DB = context.openOrCreateDatabase( "CustomerDetails.db", MODE_PRIVATE, null); final String CREATE_TABLE = "create table if not exists " + Table_name + " (" + customer_id + " integer primary key autoincrement, " + first_name + " text not null, " + last_name + " text not null, " + phone_number+ " integer not null, " + address+ " text not null, " + city+ " text not null, " + state+ " text not null, " + zip+ " integer not null, " + email_address+ " text not null, " + custlat+ " double, " + custlng+ " double " +" );"; DB.execSQL(CREATE_TABLE); DB.close(); Please correct my code. I am struggling from two days. Any help is appreciated!!

    Read the article

< Previous Page | 18 19 20 21 22 23 24 25 26 27 28 29  | Next Page >